WinDebugger.cpp 375 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885
  1. #pragma warning(disable:4996)
  2. // TODO: Remove for 64-bit
  3. #pragma warning(disable:4244)
  4. #pragma warning(disable:4267)
  5. #define NTDDI_VERSION 0x06020000
  6. #include "WinDebugger.h"
  7. #include "CPU.h"
  8. #include "DbgModule.h"
  9. #include "DebugVisualizers.h"
  10. #include "MiniDumpDebugger.h"
  11. #include "X86.h"
  12. #include "BeefySysLib/Common.h"
  13. #include "BeefySysLib/util/PerfTimer.h"
  14. #include "BeefySysLib/util/BeefPerf.h"
  15. #include "BeefySysLib/util/CritSect.h"
  16. #include "BeefySysLib/util/UTF8.h"
  17. #include "BeefySysLib/FileStream.h"
  18. #include "BeefySysLib/FileHandleStream.h"
  19. #include "BeefySysLib/util/FileEnumerator.h"
  20. #include <inttypes.h>
  21. #include <windows.h>
  22. #include "DbgExprEvaluator.h"
  23. #include "Compiler/BfSystem.h"
  24. #include "Compiler/BfParser.h"
  25. #include "Compiler/BfReducer.h"
  26. #include "Compiler/BfDemangler.h"
  27. #include "Compiler/BfPrinter.h"
  28. #include <Shlobj.h>
  29. #include "NetManager.h"
  30. #include "DebugManager.h"
  31. #include "X86Target.h"
  32. #include "HotHeap.h"
  33. #include "HotScanner.h"
  34. #include "Profiler.h"
  35. #include <float.h>
  36. #include <psapi.h>
  37. #if !defined BF32 || !defined BF_DBG_64
  38. #define STATUS_WX86_CONTINUE 0x4000001DL
  39. #define STATUS_WX86_SINGLE_STEP 0x4000001EL
  40. #define STATUS_WX86_BREAKPOINT 0x4000001FL
  41. #define STATUS_WX86_EXCEPTION_CONTINUE 0x40000020L
  42. #pragma pack(push, 1)
  43. struct HotJumpOp
  44. {
  45. uint8 mOpCode;
  46. int32 mRelTarget;
  47. };
  48. #pragma pack(pop)
  49. #include "BeefySysLib/util/AllocDebug.h"
  50. #include <limits>
  51. USING_NS_BF_DBG;
  52. static void FilterThreadName(String& name)
  53. {
  54. for (int i = 0; i < (int)name.length(); i++)
  55. {
  56. uint8 c = name[i];
  57. if (c == 0)
  58. {
  59. name.RemoveToEnd(i);
  60. return;
  61. }
  62. if (c < 32)
  63. {
  64. name.Remove(i);
  65. i--;
  66. continue;
  67. }
  68. }
  69. }
  70. //////////////////////////////////////////////////////////////////////////
  71. WdBreakpointCondition::~WdBreakpointCondition()
  72. {
  73. delete mDbgEvaluationContext;
  74. }
  75. //////////////////////////////////////////////////////////////////////////
  76. DbgEvaluationContext::DbgEvaluationContext(WinDebugger* winDebugger, DbgModule* dbgModule, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  77. {
  78. Init(winDebugger, dbgModule, expr, formatInfo, contextValue);
  79. }
  80. DbgEvaluationContext::DbgEvaluationContext(WinDebugger* winDebugger, DbgCompileUnit* dbgCompileUnit, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  81. {
  82. DbgModule* dbgModule = NULL;
  83. if (dbgCompileUnit != NULL)
  84. dbgModule = dbgCompileUnit->mDbgModule;
  85. Init(winDebugger, dbgModule, expr, formatInfo, contextValue);
  86. }
  87. void DbgEvaluationContext::Init(WinDebugger* winDebugger, DbgModule* dbgModule, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  88. {
  89. if (expr.empty())
  90. {
  91. mParser = NULL;
  92. mReducer = NULL;
  93. mPassInstance = NULL;
  94. mDbgExprEvaluator = NULL;
  95. mExprNode = NULL;
  96. return;
  97. }
  98. mParser = new BfParser(winDebugger->mBfSystem);
  99. mParser->mCompatMode = true;
  100. mPassInstance = new BfPassInstance(winDebugger->mBfSystem);
  101. auto terminatedExpr = expr + ";";
  102. mParser->SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  103. mParser->Parse(mPassInstance);
  104. mReducer = new BfReducer();
  105. mReducer->mAlloc = mParser->mAlloc;
  106. mReducer->mSystem = winDebugger->mBfSystem;
  107. mReducer->mPassInstance = mPassInstance;
  108. mReducer->mVisitorPos = BfReducer::BfVisitorPos(mParser->mRootNode);
  109. mReducer->mVisitorPos.MoveNext();
  110. mReducer->mCompatMode = mParser->mCompatMode;
  111. mReducer->mSource = mParser;
  112. mExprNode = mReducer->CreateExpression(mParser->mRootNode->GetFirst());
  113. mParser->Close();
  114. mDbgExprEvaluator = new DbgExprEvaluator(winDebugger, dbgModule, mPassInstance, -1, -1);
  115. if ((formatInfo != NULL) && (mExprNode != NULL) && (mExprNode->GetSrcEnd() < (int) expr.length()))
  116. {
  117. String formatFlags = expr.Substring(mExprNode->GetSrcEnd());
  118. String errorString = "Invalid expression";
  119. if (!winDebugger->ParseFormatInfo(dbgModule, formatFlags, formatInfo, mPassInstance, NULL, NULL, &errorString, contextValue))
  120. {
  121. mPassInstance->FailAt(errorString, mParser->mSourceData, mExprNode->GetSrcEnd(), (int)expr.length() - mExprNode->GetSrcEnd());
  122. formatFlags = "";
  123. }
  124. }
  125. if (formatInfo != NULL)
  126. {
  127. mDbgExprEvaluator->mExplicitThis = formatInfo->mExplicitThis;
  128. mDbgExprEvaluator->mCallStackIdx = formatInfo->mCallStackIdx;
  129. mDbgExprEvaluator->mLanguage = formatInfo->mLanguage;
  130. }
  131. }
  132. bool DbgEvaluationContext::HasExpression()
  133. {
  134. return mExprNode != NULL;
  135. }
  136. DbgEvaluationContext::~DbgEvaluationContext()
  137. {
  138. delete mParser;
  139. delete mReducer;
  140. delete mDbgExprEvaluator;
  141. delete mPassInstance;
  142. }
  143. DbgTypedValue DbgEvaluationContext::EvaluateInContext(DbgTypedValue contextTypedValue)
  144. {
  145. if (mExprNode == NULL)
  146. return DbgTypedValue();
  147. mPassInstance->ClearErrors();
  148. if (contextTypedValue)
  149. {
  150. mDbgExprEvaluator->mExplicitThis = contextTypedValue;
  151. if ((mDbgExprEvaluator->mExplicitThis.mType->IsPointer()) && (mDbgExprEvaluator->mExplicitThis.mType->mTypeParam->WantsRefThis()))
  152. {
  153. mDbgExprEvaluator->mExplicitThis.mType = mDbgExprEvaluator->mExplicitThis.mType->mTypeParam;
  154. mDbgExprEvaluator->mExplicitThis.mSrcAddress = mDbgExprEvaluator->mExplicitThis.mPtr;
  155. mDbgExprEvaluator->mExplicitThis.mPtr = 0;
  156. }
  157. if ((mDbgExprEvaluator->mExplicitThis.mType->IsCompositeType()) && (!mDbgExprEvaluator->mExplicitThis.mType->WantsRefThis()))
  158. {
  159. if (mDbgExprEvaluator->mExplicitThis.mSrcAddress != 0)
  160. {
  161. mDbgExprEvaluator->mExplicitThis.mType = mDbgExprEvaluator->mDbgModule->GetPointerType(mDbgExprEvaluator->mExplicitThis.mType);
  162. mDbgExprEvaluator->mExplicitThis.mPtr = mDbgExprEvaluator->mExplicitThis.mSrcAddress;
  163. mDbgExprEvaluator->mExplicitThis.mSrcAddress = 0;
  164. }
  165. }
  166. }
  167. if (contextTypedValue.mType != NULL)
  168. mDbgExprEvaluator->mDbgCompileUnit = contextTypedValue.mType->mCompileUnit;
  169. DbgTypedValue exprResult;
  170. auto result = mDbgExprEvaluator->Resolve(mExprNode);
  171. return result;
  172. }
  173. bool DbgEvaluationContext::HadError()
  174. {
  175. return mPassInstance->mFailedIdx != 0;
  176. }
  177. String DbgEvaluationContext::GetErrorStr()
  178. {
  179. String errorStr = mPassInstance->mErrors[0]->mError;
  180. if (mExprNode != NULL)
  181. {
  182. errorStr += ": ";
  183. errorStr += mExprNode->ToString();
  184. }
  185. return errorStr;
  186. }
  187. //////////////////////////////////////////////////////////////////////////
  188. typedef HRESULT(WINAPI* SetThreadDescription_t)(HANDLE hThread, PCWSTR lpThreadDescription);
  189. typedef HRESULT(WINAPI* GetThreadDescription_t)(HANDLE hThread, PWSTR* lpThreadDescription);
  190. static SetThreadDescription_t gSetThreadDescription = NULL;
  191. static GetThreadDescription_t gGetThreadDescription = NULL;
  192. static HMODULE gKernelDll = NULL;
  193. static void ImportKernel()
  194. {
  195. if (gKernelDll != NULL)
  196. return;
  197. WCHAR path[MAX_PATH];
  198. GetSystemDirectory(path, MAX_PATH);
  199. wcscat(path, L"\\kernel32.dll");
  200. gKernelDll = GetModuleHandle(path);
  201. if (gKernelDll == NULL)
  202. {
  203. return;
  204. }
  205. gSetThreadDescription = (SetThreadDescription_t)GetProcAddress(gKernelDll, "SetThreadDescription");
  206. gGetThreadDescription = (GetThreadDescription_t)GetProcAddress(gKernelDll, "GetThreadDescription");
  207. }
  208. void WinDebugger::TryGetThreadName(WdThreadInfo* threadInfo)
  209. {
  210. if (threadInfo->mHThread == NULL)
  211. return;
  212. ImportKernel();
  213. PWSTR wStr = NULL;
  214. if (gGetThreadDescription != NULL)
  215. {
  216. gGetThreadDescription(threadInfo->mHThread, &wStr);
  217. if (wStr == NULL)
  218. return;
  219. threadInfo->mName = UTF8Encode(wStr);
  220. FilterThreadName(threadInfo->mName);
  221. LocalFree(wStr);
  222. }
  223. }
  224. static void CreateFilterName(String& name, DbgType* type)
  225. {
  226. CreateFilterName(name, type->mParent);
  227. switch (type->mTypeCode)
  228. {
  229. case DbgType_Namespace:
  230. case DbgType_Struct:
  231. case DbgType_Class:
  232. name += type->mName;
  233. break;
  234. }
  235. }
  236. static void CreateFilterName(String& name, const char* srcStr, DbgLanguage language)
  237. {
  238. int chevronDepth = 0;
  239. const char* cPtr = srcStr;
  240. for (; true; cPtr++)
  241. {
  242. char c = *cPtr;
  243. if (c == 0)
  244. break;
  245. if (c == '>')
  246. chevronDepth--;
  247. bool inGeneric = chevronDepth > 0;
  248. if (c == '<')
  249. chevronDepth++;
  250. if (inGeneric) // Bundle all generic instances together
  251. continue;
  252. if (c == '[') // Bundle all arrays together
  253. name.clear();
  254. if (c == '(')
  255. return; // Start of params
  256. if ((c == ':') && (cPtr[1] == ':') && (language == DbgLanguage_Beef))
  257. {
  258. name.Append('.');
  259. cPtr++;
  260. }
  261. else
  262. name.Append(c);
  263. }
  264. }
  265. static void CreateFilterName(String& name, DbgSubprogram* subprogram)
  266. {
  267. auto language = subprogram->GetLanguage();
  268. if (subprogram->mName == NULL)
  269. {
  270. if (subprogram->mLinkName[0] == '<')
  271. {
  272. name += subprogram->mLinkName;
  273. return;
  274. }
  275. name = BfDemangler::Demangle(subprogram->mLinkName, language);
  276. // Strip off the params since we need to generate those ourselves
  277. int parenPos = (int)name.IndexOf('(');
  278. if (parenPos != -1)
  279. name.RemoveToEnd(parenPos);
  280. return;
  281. }
  282. else if (subprogram->mHasQualifiedName)
  283. {
  284. const char* cPtr = subprogram->mName;
  285. if (strncmp(cPtr, "_bf::", 5) == 0)
  286. {
  287. CreateFilterName(name, cPtr + 5, DbgLanguage_Beef);
  288. name.Replace(".__BfStaticCtor", ".this$static");
  289. name.Replace(".__BfCtorClear", ".this$clear");
  290. name.Replace(".__BfCtor", ".this");
  291. }
  292. else
  293. CreateFilterName(name, subprogram->mName, language);
  294. return;
  295. }
  296. else
  297. {
  298. if (subprogram->mParentType != NULL)
  299. {
  300. String parentName = subprogram->mParentType->ToString();
  301. CreateFilterName(name, parentName.c_str(), language);
  302. if (!name.empty())
  303. {
  304. if (language == DbgLanguage_Beef)
  305. name += ".";
  306. else
  307. name += "::";
  308. }
  309. }
  310. if ((language == DbgLanguage_Beef) && (subprogram->mParentType != NULL) && (subprogram->mParentType->mTypeName != NULL) &&
  311. (strcmp(subprogram->mName, subprogram->mParentType->mTypeName) == 0))
  312. name += "this";
  313. else if ((language == DbgLanguage_Beef) && (subprogram->mName[0] == '~'))
  314. name += "~this";
  315. else if (strncmp(subprogram->mName, "_bf::", 5) == 0)
  316. {
  317. CreateFilterName(name, subprogram->mName + 5, DbgLanguage_Beef);
  318. }
  319. else
  320. {
  321. CreateFilterName(name, subprogram->mName, language);
  322. }
  323. }
  324. if (name.empty())
  325. name += "`anon";
  326. if ((name[name.length() - 1] == '!') || (name[0] == '<'))
  327. {
  328. if (language == DbgLanguage_Beef)
  329. {
  330. // It's a mixin - assert that there's no params
  331. //BF_ASSERT(subprogram->mParams.Size() == 0);
  332. }
  333. return;
  334. }
  335. }
  336. //////////////////////////////////////////////////////////////////////////
  337. DbgPendingExpr::DbgPendingExpr()
  338. {
  339. mThreadId = -1;
  340. mCallStackIdx = -1;
  341. mParser = NULL;
  342. mCursorPos = -1;
  343. mExprNode = NULL;
  344. mIdleTicks = 0;
  345. mExplitType = NULL;
  346. mExpressionFlags = DwEvalExpressionFlag_None;
  347. }
  348. DbgPendingExpr::~DbgPendingExpr()
  349. {
  350. delete mParser;
  351. }
  352. // conversion logic based on table at http://en.wikipedia.org/wiki/Extended_precision
  353. //CDH TODO put this somewhere more general
  354. static double ConvertFloat80ToDouble(const byte fp80[10])
  355. {
  356. uint16 e = *((uint16*)&fp80[8]);
  357. uint64 m = *((uint64*)&fp80[0]);
  358. uint64 bit63 = (uint64)1 << 63;
  359. uint64 bit62 = (uint64)1 << 62;
  360. bool isNegative = (e & 0x8000) != 0;
  361. double s = isNegative ? -1.0 : 1.0;
  362. e &= 0x7fff;
  363. if (!e)
  364. {
  365. // the high bit and mantissa content will determine whether it's an actual zero, or a denormal or
  366. // pseudo-denormal number with an effective exponent of -16382. But since that exponent is so far
  367. // below anything we can handle in double-precision (even accounting for denormal bit shifts), we're
  368. // effectively still dealing with zero.
  369. return s * 0.0;
  370. }
  371. else if (e == 0x7fff)
  372. {
  373. if (m & bit63)
  374. {
  375. if (m & bit62)
  376. {
  377. return std::numeric_limits<double>::quiet_NaN();
  378. }
  379. else
  380. {
  381. if (m == bit63)
  382. return s * std::numeric_limits<double>::infinity();
  383. else
  384. return std::numeric_limits<double>::signaling_NaN();
  385. }
  386. }
  387. else
  388. {
  389. return std::numeric_limits<double>::quiet_NaN();
  390. }
  391. }
  392. else
  393. {
  394. if (!(m & bit63))
  395. return std::numeric_limits<double>::quiet_NaN(); // unnormal (we don't handle these since 80387 and later treat them as invalid operands anyway)
  396. // else is a normalized value
  397. }
  398. int useExponent = (int)e - 16383;
  399. if (useExponent < -1022)
  400. return s * 0.0; // we could technically support e from -1023 to -1074 as denormals, but don't bother with that for now.
  401. else if (useExponent > 1023)
  402. return s * HUGE_VAL;
  403. useExponent += 1023;
  404. BF_ASSERT((useExponent > 0) && (useExponent < 0x7ff)); // assume we've filtered for valid exponent range
  405. BF_ASSERT(m & bit63); // assume we've filtered out values that aren't normalized by now
  406. uint64 result = 0;
  407. if (isNegative)
  408. result |= bit63;
  409. result |= (uint64)useExponent << 52;
  410. result |= (m & ~bit63) >> 11;
  411. return *reinterpret_cast<double*>(&result);
  412. }
  413. addr_target NS_BF_DBG::DecodeTargetDataPtr(const char*& strRef)
  414. {
  415. addr_target val = (addr_target)stouln(strRef, sizeof(intptr_target) * 2);
  416. strRef += sizeof(intptr_target) * 2;
  417. return val;
  418. }
  419. WinDebugger::WinDebugger(DebugManager* debugManager) : mDbgSymSrv(this)
  420. {
  421. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  422. mActiveHotIdx = -1;
  423. mGotStartupEvent = false;
  424. mIsContinuingFromException = false;
  425. mDestroying = false;
  426. mDebugManager = debugManager;
  427. mNeedsRehupBreakpoints = false;
  428. mStepInAssembly = false;
  429. mStepSP = 0;
  430. mStepIsRecursing = false;
  431. mStepStopOnNextInstruction = false;
  432. mDebugTarget = NULL;
  433. mShuttingDown = false;
  434. mBfSystem = new BfSystem();
  435. mAtBreakThread = NULL;
  436. mActiveThread = NULL;
  437. mActiveBreakpoint = NULL;
  438. mSteppingThread = NULL;
  439. mExplicitStopThread = NULL;
  440. mStepSwitchedThreads = false;
  441. mIsDebuggerWaiting = false;
  442. mWantsDebugContinue = false;
  443. mContinueFromBreakpointFailed = false;
  444. mIsStepIntoSpecific = false;
  445. mDbgBreak = false;
  446. mDebuggerWaitingThread = NULL;
  447. mStepType = StepType_None;
  448. mOrigStepType = StepType_None;
  449. mLastValidStepIntoPC = 0;
  450. mActiveSymSrvRequest = NULL;
  451. mStoredReturnValueAddr = 0;
  452. #ifdef BF_DBG_32
  453. mCPU = gX86Target->mX86CPU;
  454. #else
  455. mCPU = gX86Target->mX64CPU;
  456. #endif
  457. mRunState = RunState_NotStarted;
  458. mIsRunning = false;
  459. mSavedAtBreakpointAddress = 0;
  460. mSavedBreakpointAddressContinuing = 0;
  461. mRequestedStackFrameIdx = 0;
  462. mShowPCOverride = 0;
  463. mCurNoInfoStepTries = 0;
  464. mDbgAttachFlags = BfDbgAttachFlag_None;
  465. mDbgProcessHandle = 0;
  466. mDbgThreadHandle = 0;
  467. mDbgProcessId = 0;
  468. mDbgHeapData = NULL;
  469. mIsPartialCallStack = true;
  470. for (int i = 0; i < 4; i++)
  471. {
  472. mFreeMemoryBreakIndices.push_back(i);
  473. }
  474. mMemoryBreakpointVersion = 0;
  475. SYSTEM_INFO systemInfo;
  476. GetSystemInfo(&systemInfo);
  477. mPageSize = systemInfo.dwPageSize;
  478. mEmptyDebugTarget = new DebugTarget(this);
  479. mEmptyDebugTarget->CreateEmptyTarget();
  480. mEmptyDebugTarget->mIsEmpty = true;
  481. mDebugTarget = mEmptyDebugTarget;
  482. mDebugPendingExpr = NULL;
  483. mDebugEvalThreadInfo = WdThreadInfo();
  484. mMemCacheAddr = 0;
  485. mDebuggerThreadId = 0;
  486. }
  487. WinDebugger::~WinDebugger()
  488. {
  489. mDestroying = true;
  490. delete gDbgPerfManager;
  491. gDbgPerfManager = NULL;
  492. if ((mDebugTarget != NULL) && (mDebugTarget != mEmptyDebugTarget))
  493. Detach();
  494. for (auto breakpoint : mBreakpoints)
  495. {
  496. auto checkBreakpoint = breakpoint->mLinkedSibling;
  497. while (checkBreakpoint != NULL)
  498. {
  499. auto nextBreakpoint = checkBreakpoint->mLinkedSibling;
  500. delete checkBreakpoint;
  501. checkBreakpoint = nextBreakpoint;
  502. }
  503. delete breakpoint;
  504. }
  505. delete mEmptyDebugTarget;
  506. delete mBfSystem;
  507. for (auto kv : mPendingProfilerMap)
  508. delete kv.mValue;
  509. for (auto profiler : mNewProfilerList)
  510. delete profiler;
  511. delete mDebugPendingExpr;
  512. }
  513. void WinDebugger::Fail(const StringImpl& error)
  514. {
  515. if (mIsRunning)
  516. mDebugManager->mOutMessages.push_back(StrFormat("error %s", error.c_str()));
  517. }
  518. // Leave active thread unpaused
  519. void WinDebugger::ThreadRestorePause(WdThreadInfo* onlyPauseThread, WdThreadInfo* dontPauseThread)
  520. {
  521. BfLogDbg("ThreadRestorePause %d %d\n", (onlyPauseThread != NULL) ? onlyPauseThread->mThreadId : 0, (dontPauseThread != NULL) ? dontPauseThread->mThreadId : 0);
  522. for (auto threadInfo : mThreadList)
  523. {
  524. if (((threadInfo != dontPauseThread) && (!threadInfo->mIsBreakRestorePaused)) &&
  525. ((onlyPauseThread == NULL) || (threadInfo == onlyPauseThread)))
  526. {
  527. BF_ASSERT(!threadInfo->mIsBreakRestorePaused);
  528. BfLogDbg("SuspendThread %d\n", threadInfo->mThreadId);
  529. ::SuspendThread(threadInfo->mHThread);
  530. threadInfo->mIsBreakRestorePaused = true;
  531. }
  532. }
  533. }
  534. void WinDebugger::ThreadRestoreUnpause()
  535. {
  536. BfLogDbg("ThreadRestoreUnpause\n");
  537. for (auto threadInfo : mThreadList)
  538. {
  539. if (threadInfo->mIsBreakRestorePaused)
  540. {
  541. BfLogDbg("ResumeThread %d\n", threadInfo->mThreadId);
  542. ::ResumeThread(threadInfo->mHThread);
  543. threadInfo->mIsBreakRestorePaused = false;
  544. }
  545. }
  546. }
  547. void WinDebugger::UpdateThreadDebugRegisters(WdThreadInfo* threadInfo)
  548. {
  549. if (threadInfo->mMemoryBreakpointVersion == mMemoryBreakpointVersion)
  550. return;
  551. auto threadId = threadInfo->mHThread;
  552. BF_CONTEXT lcContext;
  553. lcContext.ContextFlags = BF_CONTEXT_DEBUG_REGISTERS;
  554. BF_GetThreadContext(threadId, &lcContext);
  555. for (int memoryBreakIdx = 0; memoryBreakIdx < 4; memoryBreakIdx++)
  556. {
  557. WdMemoryBreakpointBind memoryBreakpointBind = mMemoryBreakpoints[memoryBreakIdx];
  558. WdBreakpoint* wdBreakpoint = memoryBreakpointBind.mBreakpoint;
  559. if (wdBreakpoint == NULL)
  560. {
  561. *(&lcContext.Dr0 + memoryBreakIdx) = 0;
  562. lcContext.Dr7 &= ~((1 << (memoryBreakIdx * 2)) | (1 << (16 + memoryBreakIdx * 4)) | (3 << (18 + memoryBreakIdx * 4)));
  563. }
  564. else
  565. {
  566. int sizeCode = 0;
  567. if (memoryBreakpointBind.mByteCount == 2)
  568. sizeCode = 1;
  569. else if (memoryBreakpointBind.mByteCount == 4)
  570. sizeCode = 3;
  571. else if (memoryBreakpointBind.mByteCount == 8)
  572. sizeCode = 2;
  573. addr_target calcAddr = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress + memoryBreakpointBind.mOfs;
  574. BF_ASSERT(calcAddr == memoryBreakpointBind.mAddress);
  575. *(&lcContext.Dr0 + memoryBreakIdx) = calcAddr;
  576. lcContext.Dr7 |= (1 << (memoryBreakIdx * 2)) | (1 << (16 + memoryBreakIdx * 4)) | (sizeCode << (18 + memoryBreakIdx * 4));
  577. }
  578. }
  579. bool worked = BF_SetThreadContext(threadId, &lcContext) != 0;
  580. BF_ASSERT(worked || (mRunState == RunState_Terminating) || (mRunState == RunState_Terminated));
  581. threadInfo->mMemoryBreakpointVersion = mMemoryBreakpointVersion;
  582. }
  583. void WinDebugger::UpdateThreadDebugRegisters()
  584. {
  585. for (auto threadInfo : mThreadList)
  586. {
  587. ::SuspendThread(threadInfo->mHThread);
  588. UpdateThreadDebugRegisters(threadInfo);
  589. ::ResumeThread(threadInfo->mHThread);
  590. }
  591. }
  592. void WinDebugger::PhysSetBreakpoint(addr_target address)
  593. {
  594. BfLogDbg("PhysSetBreakpoint %p\n", address);
  595. uint8 newData = 0xCC;
  596. // This ensure that we have the orig image data cached
  597. DbgMemoryFlags flags = mDebugTarget->ReadOrigImageData(address, NULL, 1);
  598. if ((flags & DbgMemoryFlags_Execute) == 0)
  599. {
  600. BfLogDbg("Breakpoint ignored - execute flag NOT set in breakpoint address\n", address);
  601. BfLogDbg("Memory Flags = %d\n", gDebugger->GetMemoryFlags(address));
  602. return;
  603. }
  604. // Replace it with Breakpoint
  605. SIZE_T dwReadBytes;
  606. BOOL worked = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, &newData, 1, &dwReadBytes);
  607. if (!worked)
  608. {
  609. int err = GetLastError();
  610. BfLogDbg("SetBreakpoint FAILED %p\n", address);
  611. }
  612. FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, 1);
  613. {
  614. uint8 mem = ReadMemory<uint8>(address);
  615. BfLogDbg("Breakpoint byte %X\n", mem);
  616. }
  617. }
  618. void WinDebugger::SetBreakpoint(addr_target address, bool fromRehup)
  619. {
  620. int* countPtr = NULL;
  621. if (mPhysBreakpointAddrMap.TryAdd(address, NULL, &countPtr))
  622. {
  623. BfLogDbg("SetBreakpoint %p\n", address);
  624. *countPtr = 1;
  625. }
  626. else
  627. {
  628. if (fromRehup)
  629. {
  630. BfLogDbg("SetBreakpoint %p Count: %d. Rehup (ignored).\n", address, *countPtr);
  631. return;
  632. }
  633. (*countPtr)++;
  634. BfLogDbg("SetBreakpoint %p Count: %d\n", address, *countPtr);
  635. return;
  636. }
  637. PhysSetBreakpoint(address);
  638. }
  639. void WinDebugger::SetTempBreakpoint(addr_target address)
  640. {
  641. BfLogDbg("SetTempBreakpoint %p\n", address);
  642. mTempBreakpoint.push_back(address);
  643. SetBreakpoint(address);
  644. }
  645. void WinDebugger::PhysRemoveBreakpoint(addr_target address)
  646. {
  647. BfLogDbg("PhysRemoveBreakpoint %p\n", address);
  648. uint8 origData;
  649. DbgMemoryFlags flags = mDebugTarget->ReadOrigImageData(address, &origData, 1);
  650. if ((flags & DbgMemoryFlags_Execute) == 0)
  651. {
  652. //BF_ASSERT("Failed" == 0);
  653. return;
  654. }
  655. SIZE_T dwReadBytes;
  656. if (!WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, &origData, 1, &dwReadBytes))
  657. {
  658. int err = GetLastError();
  659. BfLogDbg("RemoveBreakpoint FAILED %p\n", address);
  660. }
  661. FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, 1);
  662. }
  663. void WinDebugger::RemoveBreakpoint(addr_target address)
  664. {
  665. int* countPtr = NULL;
  666. mPhysBreakpointAddrMap.TryGetValue(address, &countPtr);
  667. // This can happen when we shutdown and we're continuing from a breakpoint
  668. //BF_ASSERT(*countPtr != NULL);
  669. if (countPtr == NULL)
  670. {
  671. BfLogDbg("RemoveBreakpoint %p FAILED\n", address);
  672. return;
  673. }
  674. BfLogDbg("RemoveBreakpoint %p count: %d\n", address, *countPtr);
  675. if (*countPtr > 1)
  676. {
  677. (*countPtr)--;
  678. return;
  679. }
  680. mPhysBreakpointAddrMap.Remove(address);
  681. PhysRemoveBreakpoint(address);
  682. }
  683. void WinDebugger::SingleStepX86()
  684. {
  685. // In what cases did this catch bugs?
  686. // This caused other failures (caught in tests)
  687. // if (mActiveThread->mIsAtBreakpointAddress != 0)
  688. // {
  689. // ContinueFromBreakpoint();
  690. // return;
  691. // }
  692. BfLogDbg("Setup SingleStepX86 ActiveThread: %d\n", (mActiveThread != NULL) ? mActiveThread->mThreadId : -1);
  693. BF_CONTEXT lcContext;
  694. lcContext.ContextFlags = BF_CONTEXT_ALL;
  695. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  696. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  697. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  698. }
  699. bool WinDebugger::IsInRunState()
  700. {
  701. return (mRunState == RunState_Running) || (mRunState == RunState_Running_ToTempBreakpoint);
  702. }
  703. bool WinDebugger::ContinueFromBreakpoint()
  704. {
  705. if (mDebuggerWaitingThread->mFrozen)
  706. {
  707. BfLogDbg("ContinueFromBreakpoint bailout on frozen thread\n");
  708. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  709. mDebuggerWaitingThread->mIsAtBreakpointAddress = 0;
  710. return true;
  711. }
  712. mActiveThread = mDebuggerWaitingThread;
  713. mActiveBreakpoint = NULL;
  714. BfLogDbg("ContinueFromBreakpoint. ActiveThread: %d\n", (mActiveThread != NULL) ? mActiveThread->mThreadId : -1);
  715. BfLogDbg("ResumeThread %d\n", mActiveThread->mThreadId);
  716. BOOL success = ::ResumeThread(mActiveThread->mHThread);
  717. if (success)
  718. {
  719. // It's possible the active thread is suspended - possibly by the GC, so we would deadlock if we
  720. // attempted to pause the other threads
  721. BfLogDbg("SuspendThread %d\n", mActiveThread->mThreadId);
  722. BfLogDbg("Thread already paused!\n");
  723. ::SuspendThread(mActiveThread->mHThread);
  724. return false;
  725. }
  726. ThreadRestorePause(NULL, mActiveThread);
  727. PhysRemoveBreakpoint(mActiveThread->mIsAtBreakpointAddress);
  728. BF_CONTEXT lcContext;
  729. lcContext.ContextFlags = BF_CONTEXT_ALL;
  730. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  731. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  732. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  733. mActiveThread->mStoppedAtAddress = 0;
  734. mActiveThread->mBreakpointAddressContinuing = mActiveThread->mIsAtBreakpointAddress;
  735. mActiveThread->mIsAtBreakpointAddress = 0;
  736. BfLogDbg("ContinueFromBreakpoint set mIsAtBreakpointAddress = 0\n");
  737. return true;
  738. }
  739. void WinDebugger::ValidateBreakpoints()
  740. {
  741. HashSet<addr_target> usedBreakpoints;
  742. std::function<void(WdBreakpoint*)> _AddBreakpoint = [&](WdBreakpoint* breakpoint)
  743. {
  744. if (breakpoint->mAddr != 0)
  745. {
  746. usedBreakpoints.Add(breakpoint->mAddr);
  747. WdBreakpoint* foundBreakpoint = NULL;
  748. auto itr = mBreakpointAddrMap.Find(breakpoint->mAddr);
  749. bool found = false;
  750. while (itr != mBreakpointAddrMap.end())
  751. {
  752. WdBreakpoint* foundBreakpoint = itr->mValue;
  753. found |= foundBreakpoint == breakpoint;
  754. itr.NextWithSameKey(breakpoint->mAddr);
  755. }
  756. BF_ASSERT(found);
  757. }
  758. auto checkSibling = (WdBreakpoint*)breakpoint->mLinkedSibling;
  759. while (checkSibling != NULL)
  760. {
  761. _AddBreakpoint(checkSibling);
  762. checkSibling = (WdBreakpoint*)checkSibling->mLinkedSibling;
  763. }
  764. };
  765. for (auto breakpoint : mBreakpoints)
  766. _AddBreakpoint(breakpoint);
  767. for (auto& entry : mBreakpointAddrMap)
  768. {
  769. BF_ASSERT(usedBreakpoints.Contains(entry.mKey));
  770. }
  771. }
  772. Breakpoint* WinDebugger::FindBreakpointAt(intptr address)
  773. {
  774. #ifdef _DEBUG
  775. //ValidateBreakpoints();
  776. #endif
  777. WdBreakpoint* breakpoint = NULL;
  778. mBreakpointAddrMap.TryGetValue(address, &breakpoint);
  779. return breakpoint;
  780. }
  781. Breakpoint* WinDebugger::GetActiveBreakpoint()
  782. {
  783. if ((mActiveBreakpoint != NULL) && (mActiveBreakpoint->mHead != NULL))
  784. return mActiveBreakpoint->mHead;
  785. return mActiveBreakpoint;
  786. }
  787. void WinDebugger::DebugThreadProc()
  788. {
  789. BpSetThreadName("DebugThread");
  790. BfpThread_SetName(NULL, "DebugThread", NULL);
  791. mDebuggerThreadId = GetCurrentThreadId();
  792. if (!IsMiniDumpDebugger())
  793. {
  794. if (!DoOpenFile(mLaunchPath, mArgs, mWorkingDir, mEnvBlock))
  795. {
  796. if (mDbgProcessId != 0)
  797. OutputRawMessage("error Unable to attach to process");
  798. else
  799. OutputRawMessage(StrFormat("error Failed to launch: %s", mLaunchPath.c_str()));
  800. mShuttingDown = true;
  801. mRunState = RunState_Terminated;
  802. }
  803. }
  804. while (!mShuttingDown)
  805. {
  806. DoUpdate();
  807. }
  808. mIsRunning = false;
  809. for (int i = 0; i < (int) mBreakpoints.size(); i++)
  810. {
  811. WdBreakpoint* wdBreakpoint = mBreakpoints[i];
  812. if (wdBreakpoint->mAddr != 0)
  813. mBreakpointAddrMap.Remove(wdBreakpoint->mAddr, wdBreakpoint);
  814. wdBreakpoint->mAddr = 0;
  815. wdBreakpoint->mLineData = DbgLineDataEx();
  816. wdBreakpoint->mSrcFile = NULL;
  817. if (wdBreakpoint->mLinkedSibling != NULL)
  818. {
  819. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  820. wdBreakpoint->mLinkedSibling = NULL;
  821. }
  822. }
  823. if (!IsMiniDumpDebugger())
  824. {
  825. while (true)
  826. {
  827. if (!mIsDebuggerWaiting)
  828. {
  829. if (!WaitForDebugEvent(&mDebugEvent, 0))
  830. break;
  831. }
  832. if (mDebuggerWaitingThread != NULL)
  833. {
  834. BF_ASSERT_REL((mDebuggerWaitingThread->mIsAtBreakpointAddress == 0) || (mShuttingDown));
  835. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_CONTINUE);
  836. BfLogDbg("::ContinueDebugEvent startup ThreadId:%d\n", mDebuggerWaitingThread->mThreadId);
  837. }
  838. mIsDebuggerWaiting = false;
  839. mDebuggerWaitingThread = NULL;
  840. }
  841. }
  842. mDebuggerThreadId = 0;
  843. }
  844. static void DebugThreadProcThunk(void* winDebugger)
  845. {
  846. ((WinDebugger*) winDebugger)->DebugThreadProc();
  847. }
  848. int WinDebugger::GetAddrSize()
  849. {
  850. return sizeof(addr_target);
  851. }
  852. bool WinDebugger::CanOpen(const StringImpl& fileName, DebuggerResult* outResult)
  853. {
  854. FILE* fp = fopen(fileName.c_str(), "rb");
  855. if (fp == NULL)
  856. {
  857. *outResult = DebuggerResult_CannotOpen;
  858. return false;
  859. }
  860. FileStream fs;
  861. fs.mFP = fp;
  862. *outResult = DebuggerResult_Ok;
  863. bool canRead = DbgModule::CanRead(&fs, outResult);
  864. fclose(fp);
  865. return canRead;
  866. }
  867. void WinDebugger::OpenFile(const StringImpl& launchPath, const StringImpl& targetPath, const StringImpl& args, const StringImpl& workingDir, const Array<uint8>& envBlock)
  868. {
  869. BF_ASSERT(!mIsRunning);
  870. mLaunchPath = launchPath;
  871. mTargetPath = targetPath;
  872. mArgs = args;
  873. mWorkingDir = workingDir;
  874. mEnvBlock = envBlock;
  875. mDebugTarget = new DebugTarget(this);
  876. }
  877. bool WinDebugger::Attach(int processId, BfDbgAttachFlags attachFlags)
  878. {
  879. BF_ASSERT(!mIsRunning);
  880. mDbgAttachFlags = attachFlags;
  881. mDbgProcessHandle = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)processId);
  882. if (mDbgProcessHandle == 0)
  883. return false;
  884. BOOL is32Bit = false;
  885. if (!IsWow64Process(mDbgProcessHandle, &is32Bit))
  886. {
  887. mDbgProcessHandle = 0;
  888. ::CloseHandle(mDbgProcessHandle);
  889. return false;
  890. }
  891. bool want32Bit = sizeof(intptr_target) == 4;
  892. if (want32Bit != (is32Bit != 0))
  893. {
  894. mDbgProcessHandle = 0;
  895. ::CloseHandle(mDbgProcessHandle);
  896. return false;
  897. }
  898. HMODULE mainModule = 0;
  899. DWORD memNeeded = 0;
  900. ::EnumProcessModules(mDbgProcessHandle, &mainModule, sizeof(HMODULE), &memNeeded);
  901. WCHAR fileName[MAX_PATH] = {0};
  902. GetModuleFileNameExW(mDbgProcessHandle, mainModule, fileName, MAX_PATH);
  903. mLaunchPath = UTF8Encode(fileName);
  904. mTargetPath = mLaunchPath;
  905. mDbgProcessId = processId;
  906. mDbgProcessHandle = 0;
  907. ::CloseHandle(mDbgProcessHandle);
  908. mDebugTarget = new DebugTarget(this);
  909. return true;
  910. }
  911. void WinDebugger::Run()
  912. {
  913. mIsRunning = true;
  914. DWORD localThreadId;
  915. HANDLE hThread = ::CreateThread(NULL, 64 * 1024, (LPTHREAD_START_ROUTINE) &DebugThreadProcThunk, (void*)this, 0, &localThreadId);
  916. CloseHandle(hThread);
  917. }
  918. void WinDebugger::HotLoad(const Array<String>& objectFiles, int hotIdx)
  919. {
  920. AutoCrit autoCrit(mDebugManager->mCritSect);
  921. if (mDebugTarget->mTargetBinary == NULL)
  922. {
  923. Fail("Hot swapping failed because the hot target binary has not yet been loaded.");
  924. return;
  925. }
  926. if (mDebugTarget->mHotHeap == NULL)
  927. {
  928. Fail("There is no hot heap space available for hot swapping.");
  929. return;
  930. }
  931. BfLogDbg("WinDebugger::HotLoad Start %d\n", hotIdx);
  932. SetAndRestoreValue<int> prevHotIdx(mActiveHotIdx, hotIdx);
  933. BF_ASSERT(mHotThreadStates.empty());
  934. mHotThreadStates.Resize(mThreadList.size());
  935. for (int threadIdx = 0; threadIdx < (int)mThreadList.size(); threadIdx++)
  936. {
  937. WdThreadInfo* threadInfo = mThreadList[threadIdx];
  938. SetAndRestoreValue<WdThreadInfo*> prevActiveThread(mActiveThread, threadInfo);
  939. BfLogDbg("SuspendThread %d\n", threadInfo->mThreadId);
  940. ::SuspendThread(threadInfo->mHThread);
  941. mHotThreadStates[threadIdx].mThreadId = threadInfo->mThreadId;
  942. PopulateRegisters(&mHotThreadStates[threadIdx].mRegisters);
  943. }
  944. for (auto address : mTempBreakpoint)
  945. RemoveBreakpoint(address);
  946. mTempBreakpoint.Clear();
  947. mStepBreakpointAddrs.Clear();
  948. for (auto breakpoint : mBreakpoints)
  949. {
  950. DetachBreakpoint(breakpoint);
  951. }
  952. int startingModuleIdx = (int)mDebugTarget->mDbgModules.size();
  953. bool failed = false;
  954. for (auto fileName : objectFiles)
  955. {
  956. BfLogDbg("WinDebugger::HotLoad: %s\n", fileName.c_str());
  957. DbgModule* newBinary = mDebugTarget->HotLoad(fileName, hotIdx);
  958. if ((newBinary != NULL) && (newBinary->mFailed))
  959. failed = true;
  960. }
  961. for (int moduleIdx = startingModuleIdx; moduleIdx < (int)mDebugTarget->mDbgModules.size(); moduleIdx++)
  962. {
  963. auto dbgModule = mDebugTarget->mDbgModules[moduleIdx];
  964. BF_ASSERT(dbgModule->IsObjectFile());
  965. BF_ASSERT(dbgModule->mHotIdx == hotIdx);
  966. dbgModule->FinishHotSwap();
  967. }
  968. for (auto dwarf : mDebugTarget->mDbgModules)
  969. dwarf->RevertWritingEnable();
  970. int blockAllocSinceClean = mDebugTarget->mHotHeap->mBlockAllocIdx - mDebugTarget->mLastHotHeapCleanIdx;
  971. // Clean up the hot heap every 64MB
  972. int blocksBetweenCleans = (64 * 1024 * 1024) / HotHeap::BLOCK_SIZE;
  973. #ifdef _DEBUG
  974. //TODO: This is just for testing
  975. blocksBetweenCleans = 1;
  976. #endif
  977. //TODO: Put this back after we fix the cleanup
  978. if (blockAllocSinceClean >= blocksBetweenCleans)
  979. CleanupHotHeap();
  980. mDebugTarget->RehupSrcFiles();
  981. for (int breakIdx = 0; breakIdx < (int)mBreakpoints.size(); breakIdx++)
  982. {
  983. auto breakpoint = mBreakpoints[breakIdx];
  984. CheckBreakpoint(breakpoint);
  985. }
  986. for (int hotThreadIdx = 0; hotThreadIdx < (int)mHotThreadStates.size(); hotThreadIdx++)
  987. {
  988. auto& hotThreadState = mHotThreadStates[hotThreadIdx];
  989. WdThreadInfo* threadInfo = NULL;
  990. if (!mThreadMap.TryGetValue((uint32)hotThreadState.mThreadId, &threadInfo))
  991. continue;
  992. BfLogDbg("ResumeThread %d\n", threadInfo->mThreadId);
  993. ::ResumeThread(threadInfo->mHThread);
  994. }
  995. mHotThreadStates.Clear();
  996. if (IsPaused())
  997. {
  998. ClearCallStack();
  999. UpdateCallStack();
  1000. }
  1001. }
  1002. void WinDebugger::InitiateHotResolve(DbgHotResolveFlags flags)
  1003. {
  1004. AutoCrit autoCrit(mDebugManager->mCritSect);
  1005. delete mHotResolveData;
  1006. mHotResolveData = NULL;
  1007. mHotResolveData = new DbgHotResolveData();
  1008. DbgHotScanner* hotScanner = new DbgHotScanner(this);
  1009. hotScanner->Scan(flags);
  1010. delete hotScanner;
  1011. }
  1012. intptr WinDebugger::GetDbgAllocHeapSize()
  1013. {
  1014. if (mDbgHeapData == NULL)
  1015. {
  1016. Beefy::String memName = StrFormat("BFGC_stats_%d", mProcessInfo.dwProcessId);
  1017. mDbgHeapData = new WinDbgHeapData();
  1018. mDbgHeapData->mFileMapping = ::OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, memName.c_str());
  1019. if (mDbgHeapData->mFileMapping == 0)
  1020. {
  1021. delete mDbgHeapData;
  1022. mDbgHeapData = NULL;
  1023. return 0;
  1024. }
  1025. mDbgHeapData->mStats = (WinDbgHeapData::Stats*)MapViewOfFile(mDbgHeapData->mFileMapping, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(WinDbgHeapData::Stats));
  1026. }
  1027. if (mDbgHeapData->mStats == NULL)
  1028. return 0;
  1029. return mDbgHeapData->mStats->mHeapSize;
  1030. }
  1031. String WinDebugger::GetDbgAllocInfo()
  1032. {
  1033. AutoCrit autoCrit(mDebugManager->mCritSect);
  1034. for (auto threadInfo : mThreadList)
  1035. ::SuspendThread(threadInfo->mHThread);
  1036. delete mHotResolveData;
  1037. mHotResolveData = NULL;
  1038. mHotResolveData = new DbgHotResolveData();
  1039. DbgHotScanner* hotScanner = new DbgHotScanner(this);
  1040. hotScanner->Scan(DbgHotResolveFlag_Allocations);
  1041. delete hotScanner;
  1042. String result;
  1043. if (mHotResolveData != NULL)
  1044. {
  1045. DbgExprEvaluator exprEvaluator(this, NULL, NULL, -1, -1);
  1046. exprEvaluator.mDebugTarget = mDebugTarget;
  1047. String typeName;
  1048. result += ":types\n";
  1049. for (int typeId = 0; typeId < mHotResolveData->mTypeData.size(); typeId++)
  1050. {
  1051. auto& typeData = mHotResolveData->mTypeData[typeId];
  1052. if (typeData.mCount > 0)
  1053. {
  1054. auto type = exprEvaluator.GetBeefTypeById(typeId);
  1055. typeName.Clear();
  1056. exprEvaluator.BeefTypeToString(type, typeName);
  1057. if (typeName.IsEmpty())
  1058. typeName = StrFormat("Type #%d", typeId);
  1059. result += StrFormat("type\t%d\t%s\t%lld\t%lld\n", typeId, typeName.c_str(), typeData.mCount, typeData.mSize);
  1060. }
  1061. }
  1062. }
  1063. for (auto threadInfo : mThreadList)
  1064. ::ResumeThread(threadInfo->mHThread);
  1065. return result;
  1066. }
  1067. bool WinDebugger::DoOpenFile(const StringImpl& fileName, const StringImpl& args, const StringImpl& workingDir, const Array<uint8>& envBlock)
  1068. {
  1069. BP_ZONE("WinDebugger::DoOpenFile");
  1070. AutoCrit autoCrit(mDebugManager->mCritSect);
  1071. //gDbgPerfManager->StartRecording();
  1072. STARTUPINFOW si;
  1073. ZeroMemory(&si, sizeof(si));
  1074. si.cb = sizeof(si);
  1075. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  1076. if (mDbgProcessId != 0)
  1077. {
  1078. BOOL success = ::DebugActiveProcess(mDbgProcessId);
  1079. if (!success)
  1080. return false;
  1081. mProcessInfo.dwProcessId = mDbgProcessId;
  1082. }
  1083. else
  1084. {
  1085. BP_ZONE("DoOpenFile_CreateProcessW");
  1086. UTF16String envW;
  1087. DWORD flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS | CREATE_DEFAULT_ERROR_MODE;
  1088. void* envPtr = NULL;
  1089. if (!envBlock.IsEmpty())
  1090. {
  1091. //UTF16?
  1092. if (envBlock[1] == 0)
  1093. {
  1094. envPtr = (void*)&envBlock[0];
  1095. flags |= CREATE_UNICODE_ENVIRONMENT;
  1096. }
  1097. else
  1098. {
  1099. String str8((char*)&envBlock[0], (int)envBlock.size());
  1100. envW = UTF8Decode(str8);
  1101. envPtr = (void*)envW.c_str();
  1102. flags |= CREATE_UNICODE_ENVIRONMENT;
  1103. }
  1104. }
  1105. String cmdLine = "\"";
  1106. cmdLine += fileName;
  1107. cmdLine += "\"";
  1108. if (!args.IsEmpty())
  1109. {
  1110. cmdLine += " ";
  1111. cmdLine += args;
  1112. }
  1113. BOOL worked = CreateProcessW(NULL, (WCHAR*)UTF8Decode(cmdLine).c_str(), NULL, NULL, FALSE,
  1114. flags, envPtr, (WCHAR*)UTF8Decode(workingDir).c_str(), &si, &mProcessInfo);
  1115. if (!worked)
  1116. {
  1117. auto lastError = ::GetLastError();
  1118. if (lastError == ERROR_DIRECTORY)
  1119. {
  1120. mDebugManager->mOutMessages.push_back(StrFormat("error Unable to locate specified working directory '%s'", SlashString(workingDir, false, false).c_str()));
  1121. }
  1122. return false;
  1123. }
  1124. WdThreadInfo* threadInfo = new WdThreadInfo();
  1125. threadInfo->mProcessId = mProcessInfo.dwProcessId;
  1126. threadInfo->mThreadId = mProcessInfo.dwThreadId;
  1127. threadInfo->mHThread = mProcessInfo.hThread;
  1128. threadInfo->mThreadLocalBase = NULL;
  1129. threadInfo->mStartAddress = NULL;
  1130. mThreadMap[mProcessInfo.dwThreadId] = threadInfo;
  1131. mThreadList.push_back(threadInfo);
  1132. }
  1133. mRunState = RunState_Running;
  1134. while (true)
  1135. {
  1136. BP_ZONE("DoOpenFile_WaitForImageBase");
  1137. autoCrit.mCritSect->Unlock();
  1138. DoUpdate();
  1139. autoCrit.mCritSect->Lock();
  1140. ContinueDebugEvent();
  1141. if ((mDebugTarget->mLaunchBinary != NULL) && (mDebugTarget->mLaunchBinary->mOrigImageData != NULL))
  1142. break;
  1143. }
  1144. RehupBreakpoints(true);
  1145. //gDbgPerfManager->StopRecording();
  1146. //gDbgPerfManager->DbgPrint();
  1147. return true;
  1148. }
  1149. void WinDebugger::StopDebugging()
  1150. {
  1151. AutoCrit autoCrit(mDebugManager->mCritSect);
  1152. BfLogDbg("WinDebugger::Terminate\n");
  1153. if (mActiveSymSrvRequest != NULL)
  1154. mActiveSymSrvRequest->Cancel();
  1155. if ((mRunState == RunState_NotStarted) || (mRunState == RunState_Terminated) || (mRunState == RunState_Terminating))
  1156. return;
  1157. if ((mDbgProcessId != 0) && ((mDbgAttachFlags & BfDbgAttachFlag_ShutdownOnExit) == 0))
  1158. {
  1159. for (auto address : mTempBreakpoint)
  1160. RemoveBreakpoint(address);
  1161. for (auto breakpoint : mBreakpoints)
  1162. DetachBreakpoint(breakpoint);
  1163. BfLogDbg("StopDebugging\n");
  1164. ::DebugActiveProcessStop(mDbgProcessId);
  1165. mRunState = RunState_Terminated;
  1166. BfLogDbg("mRunState = RunState_Terminated\n");
  1167. }
  1168. else
  1169. {
  1170. TerminateProcess(mProcessInfo.hProcess, 0);
  1171. mRunState = RunState_Terminating;
  1172. BfLogDbg("mRunState = RunState_Terminating\n");
  1173. }
  1174. }
  1175. void WinDebugger::Terminate()
  1176. {
  1177. AutoCrit autoCrit(mDebugManager->mCritSect);
  1178. BfLogDbg("WinDebugger::Terminate\n");
  1179. if (mActiveSymSrvRequest != NULL)
  1180. mActiveSymSrvRequest->Cancel();
  1181. if ((mRunState == RunState_NotStarted) || (mRunState == RunState_Terminated) || (mRunState == RunState_Terminating))
  1182. return;
  1183. TerminateProcess(mProcessInfo.hProcess, 0);
  1184. mRunState = RunState_Terminating;
  1185. BfLogDbg("mRunState = RunState_Terminating\n");
  1186. }
  1187. static int gDebugUpdateCnt = 0;
  1188. void WinDebugger::Detach()
  1189. {
  1190. BfLogDbg("Debugger Detach\n");
  1191. mDebugManager->mNetManager->CancelAll();
  1192. while ((mIsRunning) || (mDebuggerThreadId != 0))
  1193. {
  1194. mShuttingDown = true;
  1195. Sleep(1);
  1196. }
  1197. for (auto profiler : mProfilerSet)
  1198. profiler->Stop();
  1199. BfLogDbg("Debugger Detach - thread finished\n");
  1200. mPendingProfilerMap.Clear();
  1201. for (auto profiler : mNewProfilerList)
  1202. delete profiler;
  1203. mNewProfilerList.Clear();
  1204. mPendingImageLoad.Clear();
  1205. mPendingDebugInfoLoad.Clear();
  1206. RemoveTempBreakpoints();
  1207. mContinueEvent.Reset();
  1208. if (mDebugTarget != mEmptyDebugTarget)
  1209. delete mDebugTarget;
  1210. mDebugTarget = mEmptyDebugTarget;
  1211. mShuttingDown = false;
  1212. mStepSP = 0;
  1213. ClearCallStack();
  1214. mRunState = RunState_NotStarted;
  1215. mStepType = StepType_None;
  1216. mHadImageFindError = false;
  1217. mIsPartialCallStack = true;
  1218. delete mDebugPendingExpr;
  1219. mDebugPendingExpr = NULL;
  1220. for (auto threadPair : mThreadMap)
  1221. {
  1222. auto threadInfo = threadPair.mValue;
  1223. delete threadInfo;
  1224. }
  1225. mThreadMap.Clear();
  1226. mThreadList.Clear();
  1227. mHotTargetMemory.Clear();
  1228. // We don't need to close the hThread when we have attached to a process
  1229. if (mDbgProcessId == 0)
  1230. {
  1231. CloseHandle(mProcessInfo.hThread);
  1232. CloseHandle(mProcessInfo.hProcess);
  1233. }
  1234. for (auto breakpoint : mBreakpoints)
  1235. {
  1236. if (!mDestroying)
  1237. {
  1238. BF_FATAL("Breakpoints should be deleted already");
  1239. }
  1240. if (breakpoint->mMemoryBreakpointInfo != NULL)
  1241. {
  1242. DetachBreakpoint(breakpoint);
  1243. }
  1244. }
  1245. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  1246. mStepBreakpointAddrs.Clear();
  1247. mIsRunning = false;
  1248. mDbgAttachFlags = BfDbgAttachFlag_None;
  1249. mDbgProcessId = 0;
  1250. delete mDbgHeapData;
  1251. mDbgHeapData = NULL;
  1252. mDbgProcessHandle = 0;
  1253. ClearCallStack();
  1254. mWantsDebugContinue = false;
  1255. mAtBreakThread = NULL;
  1256. mActiveThread = NULL;
  1257. mActiveBreakpoint = NULL;
  1258. mSteppingThread = NULL;
  1259. mExplicitStopThread = NULL;
  1260. mIsContinuingFromException = false;
  1261. mGotStartupEvent = false;
  1262. mIsDebuggerWaiting = false;
  1263. mPhysBreakpointAddrMap.Clear();
  1264. mBreakpointAddrMap.Clear();
  1265. gDebugUpdateCnt = 0;
  1266. }
  1267. Profiler* WinDebugger::StartProfiling()
  1268. {
  1269. return new DbgProfiler(this);
  1270. }
  1271. Profiler* WinDebugger::PopProfiler()
  1272. {
  1273. AutoCrit autoCrit(mDebugManager->mCritSect);
  1274. if (mNewProfilerList.IsEmpty())
  1275. return NULL;
  1276. auto profiler = (DbgProfiler*)mNewProfilerList[0];
  1277. mNewProfilerList.erase(mNewProfilerList.begin());
  1278. return profiler;
  1279. }
  1280. void WinDebugger::AddProfiler(DbgProfiler * profiler)
  1281. {
  1282. AutoCrit autoCrit(mDebugManager->mCritSect);
  1283. mProfilerSet.Add(profiler);
  1284. }
  1285. void WinDebugger::RemoveProfiler(DbgProfiler * profiler)
  1286. {
  1287. AutoCrit autoCrit(mDebugManager->mCritSect);
  1288. mProfilerSet.Remove(profiler);
  1289. }
  1290. void WinDebugger::ReportMemory(MemReporter* memReporter)
  1291. {
  1292. mEmptyDebugTarget->ReportMemory(memReporter);
  1293. if (mDebugTarget != mEmptyDebugTarget)
  1294. mDebugTarget->ReportMemory(memReporter);
  1295. }
  1296. void WinDebugger::ModuleChanged(DbgModule* dbgModule)
  1297. {
  1298. mDebugManager->mOutMessages.push_back(String("dbgInfoLoaded ") + dbgModule->mFilePath);
  1299. }
  1300. bool WinDebugger::DoUpdate()
  1301. {
  1302. if ((mDbgProcessId != 0) && ((mDbgAttachFlags & BfDbgAttachFlag_ShutdownOnExit) == 0))
  1303. ::DebugSetProcessKillOnExit(FALSE);
  1304. else
  1305. ::DebugSetProcessKillOnExit(TRUE);
  1306. //
  1307. {
  1308. AutoCrit autoCrit(mDebugManager->mCritSect);
  1309. auto _ModuleChanged = [&](DbgModule* dbgModule)
  1310. {
  1311. ModuleChanged(dbgModule);
  1312. ClearCallStack(); // We may have actual dbgSubprograms and stuff now...
  1313. };
  1314. for (auto dbgModule : mPendingImageLoad)
  1315. {
  1316. dbgModule->PreCacheImage();
  1317. }
  1318. for (auto kv : mPendingDebugInfoLoad)
  1319. {
  1320. kv.mKey->PreCacheDebugInfo();
  1321. }
  1322. while (!mPendingImageLoad.IsEmpty())
  1323. {
  1324. auto dbgModule = mPendingImageLoad.back();
  1325. mPendingImageLoad.pop_back();
  1326. dbgModule->RequestImage();
  1327. _ModuleChanged(dbgModule);
  1328. }
  1329. if (!mPendingDebugInfoLoad.IsEmpty())
  1330. {
  1331. Array<DbgPendingDebugInfoLoad> pendingList;
  1332. for (auto kv : mPendingDebugInfoLoad)
  1333. pendingList.Add(kv.mValue);
  1334. mPendingDebugInfoLoad.Clear();
  1335. for (auto& entry : pendingList)
  1336. {
  1337. auto dbgModule = entry.mModule;
  1338. entry.mModule->RequestDebugInfo(entry.mAllowRemote);
  1339. // We do a "_ModuleChanged" even if the load failed, so we rehup the callstack and stop
  1340. // saying "<Loading...>"
  1341. _ModuleChanged(entry.mModule);
  1342. }
  1343. }
  1344. }
  1345. if (IsMiniDumpDebugger())
  1346. {
  1347. //
  1348. {
  1349. AutoCrit autoCrit(mDebugManager->mCritSect);
  1350. if (mRunState == RunState_Terminating)
  1351. {
  1352. mRunState = RunState_Terminated;
  1353. return false;
  1354. }
  1355. }
  1356. Sleep(20);
  1357. return false;
  1358. }
  1359. if (mIsDebuggerWaiting)
  1360. {
  1361. if ((IsInRunState()) || (mRunState == RunState_Terminating) || (mRunState == RunState_DebugEval))
  1362. ContinueDebugEvent();
  1363. if (mContinueEvent.WaitFor(8))
  1364. {
  1365. BF_ASSERT(!mWantsDebugContinue); // mWantsDebugContinue should already been reset
  1366. BfLogDbg("::ContinueDebugEvent 1 ThreadId:%d\n", mDebuggerWaitingThread->mThreadId);
  1367. BF_ASSERT_REL(mDebuggerWaitingThread->mIsAtBreakpointAddress == 0);
  1368. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, mIsContinuingFromException ? DBG_EXCEPTION_NOT_HANDLED : DBG_CONTINUE);
  1369. mIsContinuingFromException = false;
  1370. mIsDebuggerWaiting = false;
  1371. mDebuggerWaitingThread = NULL;
  1372. }
  1373. else
  1374. return false;
  1375. }
  1376. if (!WaitForDebugEvent(&mDebugEvent, 8))
  1377. return false;
  1378. gDebugUpdateCnt++;
  1379. static const char* eventNames[] = { "DBG_EVENT ?",
  1380. "EXCEPTION_DEBUG_EVENT",
  1381. "CREATE_THREAD_DEBUG_EVENT",
  1382. "CREATE_PROCESS_DEBUG_EVENT",
  1383. "EXIT_THREAD_DEBUG_EVENT",
  1384. "EXIT_PROCESS_DEBUG_EVENT",
  1385. "LOAD_DLL_DEBUG_EVENT",
  1386. "UNLOAD_DLL_DEBUG_EVENT",
  1387. "OUTPUT_DEBUG_STRING_EVENT",
  1388. "RIP_EVENT"};
  1389. BfLogDbg("WaitForDebugEvent %s ThreadId:%d\n", eventNames[mDebugEvent.dwDebugEventCode], mDebugEvent.dwThreadId);
  1390. BP_ZONE(eventNames[mDebugEvent.dwDebugEventCode]);
  1391. AutoCrit autoCrit(mDebugManager->mCritSect);
  1392. mActiveBreakpoint = NULL;
  1393. mIsDebuggerWaiting = true;
  1394. mWantsDebugContinue = true;
  1395. mRequestedStackFrameIdx = 0;
  1396. mBreakStackFrameIdx = 0;
  1397. mShowPCOverride = 0;
  1398. WdThreadInfo* threadInfo = NULL;
  1399. mThreadMap.TryGetValue(mDebugEvent.dwThreadId, &threadInfo);
  1400. mDebuggerWaitingThread = threadInfo;
  1401. mExplicitStopThread = mDebuggerWaitingThread;
  1402. switch (mDebugEvent.dwDebugEventCode)
  1403. {
  1404. case CREATE_PROCESS_DEBUG_EVENT:
  1405. {
  1406. if (threadInfo == NULL)
  1407. {
  1408. BF_ASSERT(mThreadMap.size() == 0);
  1409. WdThreadInfo* newThreadInfo = new WdThreadInfo();
  1410. newThreadInfo->mProcessId = mDebugEvent.dwProcessId;
  1411. newThreadInfo->mThreadId = mDebugEvent.dwThreadId;
  1412. newThreadInfo->mHThread = mDebugEvent.u.CreateProcessInfo.hThread;
  1413. newThreadInfo->mThreadLocalBase = mDebugEvent.u.CreateProcessInfo.lpThreadLocalBase;
  1414. newThreadInfo->mStartAddress = (void*)mDebugEvent.u.CreateProcessInfo.lpStartAddress;
  1415. BF_CONTEXT lcContext;
  1416. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1417. BF_GetThreadContext(newThreadInfo->mHThread, &lcContext);
  1418. newThreadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1419. mThreadMap[mDebugEvent.dwThreadId] = newThreadInfo;
  1420. mDebuggerWaitingThread = newThreadInfo;
  1421. mThreadList.push_back(mDebuggerWaitingThread);
  1422. UpdateThreadDebugRegisters();
  1423. OutputMessage(StrFormat("Creating thread from CREATE_PROCESS_DEBUG_EVENT %d\n", mDebugEvent.dwThreadId));
  1424. threadInfo = mDebuggerWaitingThread;
  1425. mProcessInfo.dwThreadId = threadInfo->mThreadId;
  1426. mProcessInfo.hThread = threadInfo->mHThread;
  1427. mProcessInfo.hProcess = mDebugEvent.u.CreateProcessInfo.hProcess;
  1428. }
  1429. else
  1430. {
  1431. threadInfo->mThreadLocalBase = mDebugEvent.u.CreateProcessInfo.lpThreadLocalBase;
  1432. threadInfo->mStartAddress = (void*)mDebugEvent.u.CreateProcessInfo.lpStartAddress;
  1433. }
  1434. BF_CONTEXT lcContext;
  1435. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1436. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1437. threadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1438. DbgModule* launchBinary = mDebugTarget->Init(mLaunchPath, mTargetPath, (addr_target)(intptr)mDebugEvent.u.CreateProcessInfo.lpBaseOfImage);
  1439. addr_target gotImageBase = (addr_target)(intptr)mDebugEvent.u.CreateProcessInfo.lpBaseOfImage;
  1440. if (launchBinary->mImageBase != gotImageBase)
  1441. {
  1442. BF_FATAL("Image base didn't match");
  1443. }
  1444. launchBinary->mImageBase = gotImageBase;
  1445. launchBinary->mImageSize = (int)launchBinary->GetImageSize();
  1446. launchBinary->mOrigImageData = new DbgModuleMemoryCache(launchBinary->mImageBase, launchBinary->mImageSize);
  1447. if (launchBinary == mDebugTarget->mTargetBinary)
  1448. mDebugTarget->SetupTargetBinary();
  1449. if (mDebugEvent.u.CreateProcessInfo.hFile != NULL)
  1450. CloseHandle(mDebugEvent.u.CreateProcessInfo.hFile);
  1451. mDbgProcessHandle = mDebugEvent.u.CreateProcessInfo.hProcess;
  1452. mDbgThreadHandle = mDebugEvent.u.CreateProcessInfo.hThread;
  1453. mGotStartupEvent = true;
  1454. mDebugManager->mOutMessages.push_back("modulesChanged");
  1455. }
  1456. break;
  1457. case EXIT_PROCESS_DEBUG_EVENT:
  1458. {
  1459. BfLogDbg("EXIT_PROCESS_DEBUG_EVENT\n");
  1460. DWORD exitCode = mDebugEvent.u.ExitProcess.dwExitCode;
  1461. String exitMessage;
  1462. switch (exitCode)
  1463. {
  1464. case STATUS_DLL_NOT_FOUND:
  1465. exitMessage = "STATUS_DLL_NOT_FOUND";
  1466. break;
  1467. case STATUS_DLL_INIT_FAILED:
  1468. exitMessage = "STATUS_DLL_INIT_FAILED";
  1469. break;
  1470. case STATUS_ENTRYPOINT_NOT_FOUND:
  1471. exitMessage = "STATUS_ENTRYPOINT_NOT_FOUND";
  1472. break;
  1473. }
  1474. String exitCodeStr;
  1475. if ((exitCode >= 0x10000000) && (exitCode <= 0xF7000000))
  1476. exitCodeStr = StrFormat("0x%X", exitCode);
  1477. else
  1478. exitCodeStr = StrFormat("%d", exitCode);
  1479. if (!exitMessage.IsEmpty())
  1480. OutputMessage(StrFormat("Process terminated. ExitCode: %s (%s).\n", exitCodeStr.c_str(), exitMessage.c_str()));
  1481. else
  1482. OutputMessage(StrFormat("Process terminated. ExitCode: %s.\n", exitCodeStr.c_str()));
  1483. mRunState = RunState_Terminated;
  1484. mDebugManager->mOutMessages.push_back("modulesChanged");
  1485. }
  1486. break;
  1487. case LOAD_DLL_DEBUG_EVENT:
  1488. {
  1489. WCHAR moduleNameStr[MAX_PATH] = { 0 };
  1490. GetFinalPathNameByHandleW(mDebugEvent.u.LoadDll.hFile, moduleNameStr, MAX_PATH, FILE_NAME_NORMALIZED);
  1491. std::wstring wow64Dir;
  1492. std::wstring systemDir;
  1493. PWSTR wow64DirPtr = NULL;
  1494. SHGetKnownFolderPath(FOLDERID_SystemX86, KF_FLAG_NO_ALIAS, NULL, &wow64DirPtr);
  1495. if (wow64DirPtr != NULL)
  1496. {
  1497. wow64Dir = wow64DirPtr;
  1498. CoTaskMemFree(wow64DirPtr);
  1499. }
  1500. PWSTR systemDirPtr = NULL;
  1501. SHGetKnownFolderPath(FOLDERID_System, KF_FLAG_NO_ALIAS, NULL, &systemDirPtr);
  1502. if (systemDirPtr != NULL)
  1503. {
  1504. systemDir = systemDirPtr;
  1505. CoTaskMemFree(systemDirPtr);
  1506. }
  1507. if ((mDebugEvent.u.LoadDll.lpImageName != 0) && (mDebugEvent.u.LoadDll.fUnicode))
  1508. {
  1509. addr_target strAddr = ReadMemory<addr_target>((addr_target)(intptr)mDebugEvent.u.LoadDll.lpImageName);
  1510. for (int i = 0; i < MAX_PATH - 1; i++)
  1511. {
  1512. WCHAR c = ReadMemory<WCHAR>(strAddr + i*2);
  1513. moduleNameStr[i] = (WCHAR)c;
  1514. if (c == 0)
  1515. break;
  1516. }
  1517. }
  1518. String origModuleName = UTF8Encode(moduleNameStr);
  1519. String moduleName = origModuleName;
  1520. String loadMsg;
  1521. HANDLE altFileHandle = INVALID_HANDLE_VALUE;
  1522. if (moduleName != origModuleName)
  1523. {
  1524. loadMsg = StrFormat("Loading DLL: %s(%s) @ %s", origModuleName.c_str(), moduleName.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.LoadDll.lpBaseOfDll, true).c_str());
  1525. altFileHandle = ::CreateFileW(UTF8Decode(moduleName).c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  1526. }
  1527. else
  1528. {
  1529. loadMsg = StrFormat("Loading DLL: %s @ %s", moduleName.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.LoadDll.lpBaseOfDll, true).c_str());
  1530. }
  1531. BfLogDbg("LOAD_DLL_DEBUG_EVENT %s\n", moduleName.c_str());
  1532. bool skipLoad = false;
  1533. #ifdef BF_DBG_32
  1534. if (((uintptr)mDebugEvent.u.LoadDll.lpBaseOfDll & 0xFFFFFFFF00000000LL) != 0)
  1535. {
  1536. skipLoad = true;
  1537. loadMsg += " - Skipped";
  1538. }
  1539. #endif
  1540. if (!skipLoad)
  1541. {
  1542. FileHandleStream stream;
  1543. stream.mFileHandle = mDebugEvent.u.LoadDll.hFile;
  1544. if (altFileHandle != INVALID_HANDLE_VALUE)
  1545. stream.mFileHandle = altFileHandle;
  1546. if (mDebugTarget->SetupDyn(moduleName, &stream, (intptr)mDebugEvent.u.LoadDll.lpBaseOfDll) == NULL)
  1547. loadMsg += " - Failed to load";
  1548. stream.mFileHandle = 0;
  1549. }
  1550. OutputMessage(loadMsg + "\n");
  1551. if (altFileHandle != INVALID_HANDLE_VALUE)
  1552. ::CloseHandle(altFileHandle);
  1553. ::CloseHandle(mDebugEvent.u.LoadDll.hFile);
  1554. // Try to bind any breakpoints tied to this DLL
  1555. RehupBreakpoints(true);
  1556. mDebugManager->mOutMessages.push_back("modulesChanged");
  1557. }
  1558. break;
  1559. case UNLOAD_DLL_DEBUG_EVENT:
  1560. {
  1561. bool needsBreakpointRehup = false;
  1562. String name = "???";
  1563. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress((addr_target)(intptr)mDebugEvent.u.UnloadDll.lpBaseOfDll);
  1564. if (dbgModule != NULL)
  1565. {
  1566. name = dbgModule->mFilePath;
  1567. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  1568. {
  1569. auto breakpoint = mBreakpoints[i];
  1570. auto checkBreakpoint = breakpoint;
  1571. bool hasAddr = false;
  1572. while (checkBreakpoint != NULL)
  1573. {
  1574. if ((checkBreakpoint->mAddr >= dbgModule->mImageBase) && (checkBreakpoint->mAddr < dbgModule->mImageBase + dbgModule->mImageSize))
  1575. hasAddr = true;
  1576. checkBreakpoint = (WdBreakpoint*)checkBreakpoint->mLinkedSibling;
  1577. }
  1578. if (hasAddr)
  1579. {
  1580. DetachBreakpoint(breakpoint);
  1581. needsBreakpointRehup = true;
  1582. }
  1583. }
  1584. mDebugTarget->UnloadDyn(dbgModule->mImageBase);
  1585. if (needsBreakpointRehup)
  1586. RehupBreakpoints(true);
  1587. mPendingDebugInfoLoad.Remove(dbgModule);
  1588. mPendingDebugInfoRequests.Remove(dbgModule);
  1589. mDebugManager->mOutMessages.push_back("modulesChanged");
  1590. }
  1591. if (!name.empty())
  1592. OutputMessage(StrFormat("Unloading DLL: %s @ %0s\n", name.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.UnloadDll.lpBaseOfDll, true).c_str()));
  1593. BfLogDbg("UNLOAD_DLL_DEBUG_EVENT %s\n", name.c_str());
  1594. }
  1595. break;
  1596. case OUTPUT_DEBUG_STRING_EVENT:
  1597. {
  1598. const int maxChars = 1024 * 1024;
  1599. int len = BF_MIN(maxChars, (int)mDebugEvent.u.DebugString.nDebugStringLength); // 1MB max
  1600. char* message = new char[len + 1];
  1601. message[0] = 0;
  1602. message[len] = 0;
  1603. ReadMemory((addr_target)(intptr)mDebugEvent.u.DebugString.lpDebugStringData, len, message);
  1604. if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId == mDebugEvalThreadInfo.mThreadId))
  1605. mDebugManager->mOutMessages.push_back(String("dbgEvalMsg ") + message);
  1606. else
  1607. mDebugManager->mOutMessages.push_back(String("msg ") + message);
  1608. BfLogDbg("OUTPUT_DEBUG_STRING_EVENT (BreakAddr:%@): %s\n", threadInfo->mIsAtBreakpointAddress, message);
  1609. BF_ASSERT_REL(threadInfo->mIsAtBreakpointAddress == 0);
  1610. delete [] message;
  1611. }
  1612. break;
  1613. case CREATE_THREAD_DEBUG_EVENT:
  1614. {
  1615. WdThreadInfo* threadInfo = new WdThreadInfo();
  1616. threadInfo->mProcessId = mDebugEvent.dwProcessId;
  1617. threadInfo->mThreadId = mDebugEvent.dwThreadId;
  1618. threadInfo->mHThread = mDebugEvent.u.CreateThread.hThread;
  1619. threadInfo->mThreadLocalBase = mDebugEvent.u.CreateThread.lpThreadLocalBase;
  1620. threadInfo->mStartAddress = (void*)mDebugEvent.u.CreateThread.lpStartAddress;
  1621. BF_CONTEXT lcContext;
  1622. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1623. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1624. threadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1625. mThreadMap[mDebugEvent.dwThreadId] = threadInfo;
  1626. mDebuggerWaitingThread = threadInfo;
  1627. mThreadList.push_back(mDebuggerWaitingThread);
  1628. UpdateThreadDebugRegisters();
  1629. OutputMessage(StrFormat("Creating thread %d\n", mDebugEvent.dwThreadId));
  1630. }
  1631. break;
  1632. case EXIT_THREAD_DEBUG_EVENT:
  1633. {
  1634. OutputMessage(StrFormat("Exiting thread %d\n", mDebugEvent.dwThreadId));
  1635. if (mSteppingThread == threadInfo)
  1636. {
  1637. // We were attempting stepping on this thread, but not anymore!
  1638. ClearStep();
  1639. }
  1640. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_CONTINUE);
  1641. mIsDebuggerWaiting = false;
  1642. mWantsDebugContinue = false;
  1643. if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId == mDebugEvalThreadInfo.mThreadId))
  1644. {
  1645. // Thread terminated while evaluating! Is there a more graceful way of handling this?
  1646. CleanupDebugEval(false);
  1647. mRunState = RunState_Running;
  1648. }
  1649. mThreadList.Remove(mDebuggerWaitingThread);
  1650. delete mDebuggerWaitingThread;
  1651. mDebuggerWaitingThread = NULL;
  1652. mThreadMap.Remove(mDebugEvent.dwThreadId);
  1653. return true;
  1654. }
  1655. break;
  1656. case RIP_EVENT:
  1657. OutputMessage("RIP Event\n");
  1658. break;
  1659. case EXCEPTION_DEBUG_EVENT:
  1660. {
  1661. auto exceptionRecord = &mDebugEvent.u.Exception.ExceptionRecord;
  1662. switch (exceptionRecord->ExceptionCode)
  1663. {
  1664. case STATUS_WX86_BREAKPOINT:
  1665. case EXCEPTION_BREAKPOINT:
  1666. {
  1667. if (mRunState == RunState_Terminating)
  1668. {
  1669. BfLogDbg("Ignoring event because of RunState_Terminating\n");
  1670. break;
  1671. }
  1672. mAtBreakThread = threadInfo;
  1673. mActiveThread = mAtBreakThread;
  1674. bool isHighAddr = false;
  1675. #ifdef BF_DBG_32
  1676. if (((uintptr)exceptionRecord->ExceptionAddress & 0xFFFFFFFF00000000) != 0)
  1677. {
  1678. if (mActiveThread == mThreadList.front())
  1679. {
  1680. // Skip the initial Wow64 ntdll.dll!LdrpDoDebuggerBreak
  1681. mRunState = RunState_Running;
  1682. break;
  1683. }
  1684. isHighAddr = true;
  1685. }
  1686. #endif
  1687. addr_target pcAddress = (addr_target)(intptr)exceptionRecord->ExceptionAddress;
  1688. if (isHighAddr)
  1689. pcAddress = (addr_target)-1;
  1690. //mStoppedAtAddress = pcAddress;
  1691. bool isStepOut = false;
  1692. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto))
  1693. {
  1694. isStepOut = mStepBreakpointAddrs.Contains(pcAddress);
  1695. }
  1696. BF_CONTEXT lcContext;
  1697. lcContext.ContextFlags = BF_CONTEXT_ALL;
  1698. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1699. BfLogDbg("EXCEPTION_BREAKPOINT Thread:%d %p SP:%p\n", mActiveThread->mThreadId, pcAddress, BF_CONTEXT_SP(lcContext));
  1700. uint8 origImageData = 0xCC;
  1701. mDebugTarget->ReadOrigImageData(pcAddress, &origImageData, 1);
  1702. bool wasDebugBreakpoint = origImageData != 0xCC;
  1703. DbgSubprogram* dwSubprogram = NULL;
  1704. DbgLineData* dwLineData = NULL;
  1705. if (!isStepOut)
  1706. {
  1707. dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  1708. if (dwSubprogram == NULL)
  1709. dwSubprogram = mDebugTarget->FindSubProgram(pcAddress, DbgOnDemandKind_LocalOnly);
  1710. }
  1711. bool isLineStart = (dwLineData != NULL) && (dwSubprogram->GetLineAddr(*dwLineData) == pcAddress);
  1712. bool isNonDebuggerBreak = false;
  1713. if (wasDebugBreakpoint)
  1714. {
  1715. // Go ahead and set EIP back one instruction
  1716. BF_CONTEXT_IP(lcContext)--;
  1717. BF_SetThreadContext(threadInfo->mHThread, &lcContext);
  1718. if ((dwSubprogram != NULL) && (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid) &&
  1719. (pcAddress == dwSubprogram->mBlock.mLowPC))
  1720. {
  1721. BfLogDbg("Hit HotReplaceKind_Invalid breakpoint\n");
  1722. mRunState = RunState_Paused;
  1723. mDebugManager->mOutMessages.push_back("error This lambda was replaced by a new version that has incompatible captures. A program restart is required.");
  1724. PhysRemoveBreakpoint(pcAddress);
  1725. break;
  1726. }
  1727. }
  1728. else
  1729. {
  1730. // This was an actual "break" instruction
  1731. BfLogDbg("Non-debugger break\n");
  1732. isNonDebuggerBreak = true;
  1733. auto prevState = mRunState;
  1734. // Make it an "auto" stop, so for example when we have an assert/retry we won't stop inside assembly
  1735. mRequestedStackFrameIdx = -2;
  1736. mRunState = RunState_Paused;
  1737. CheckNonDebuggerBreak();
  1738. if (IsInRunState())
  1739. {
  1740. BF_ASSERT((prevState == RunState_Running) || (prevState == RunState_DebugEval));
  1741. mRunState = prevState;
  1742. break; // Continue as if nothing happened
  1743. }
  1744. if (prevState == RunState_DebugEval)
  1745. mRequestedStackFrameIdx = -1; // Don't show a rolled back stack idx if a debug eval fails
  1746. ClearStep();
  1747. }
  1748. if (threadInfo->mIsBreakRestorePaused)
  1749. {
  1750. // The thread is supposed to be paused, but the IP has been reset
  1751. // so just break here so we'll hit that breakpoint again once we're
  1752. // actually unpaused properly
  1753. BfLogDbg("Ignoring EXCEPTION_BREAKPOINT\n", threadInfo->mThreadId);
  1754. break;
  1755. }
  1756. if ((mRunState == RunState_DebugEval) || (mRunState == RunState_HotStep))
  1757. {
  1758. // If we hit a breakpoint while doing a debug eval, we just remove the breakpoint
  1759. // and expect to reinstate it during a rehup after the evaluation has completed
  1760. WdBreakpoint* breakpoint = (WdBreakpoint*)FindBreakpointAt((uintptr_t) exceptionRecord->ExceptionAddress);
  1761. if (breakpoint != NULL)
  1762. {
  1763. mNeedsRehupBreakpoints = true;
  1764. RemoveBreakpoint(breakpoint->mLineData.GetAddress());
  1765. }
  1766. break;
  1767. }
  1768. bool isDeeper = false;
  1769. int stepBreakAddrIdx = (int)mStepBreakpointAddrs.IndexOf(pcAddress);
  1770. WdBreakpoint* breakpoint = NULL;
  1771. bool ignoreBreakpoint = false;
  1772. if ((mStepType != StepType_None) && (mSteppingThread == mAtBreakThread))
  1773. {
  1774. if (mStepType == StepType_ToTempBreakpoint)
  1775. {
  1776. RemoveTempBreakpoints();
  1777. mRunState = RunState_Paused;
  1778. break;
  1779. }
  1780. if (mContinueFromBreakpointFailed)
  1781. {
  1782. BfLogDbg("Continuing from ContinueFromBreakpointFailed\n");
  1783. SetupStep(mStepType);
  1784. mRunState = RunState_Running;
  1785. break;
  1786. }
  1787. if (!isStepOut)
  1788. breakpoint = (WdBreakpoint*)FindBreakpointAt(pcAddress);
  1789. // Ignore breakpoint if it's on the line we're stepping off of
  1790. if ((breakpoint != NULL) && (breakpoint->mAddr == mStepPC) &&
  1791. (mStepSP == BF_CONTEXT_SP(lcContext)))
  1792. {
  1793. ignoreBreakpoint = true;
  1794. }
  1795. else if ((breakpoint != NULL) && (stepBreakAddrIdx == -1) && (!CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress)))
  1796. {
  1797. ignoreBreakpoint = true;
  1798. }
  1799. if ((stepBreakAddrIdx == -1) && (breakpoint == NULL) && (!isNonDebuggerBreak))
  1800. {
  1801. // If a breakpoint is removed in a prior thread
  1802. BfLogDbg("Ignoring step break (old breakpoint)\n");
  1803. if ((mSteppingThread == mAtBreakThread) && (mStepSwitchedThreads))
  1804. {
  1805. SetupStep(mStepType);
  1806. }
  1807. break;
  1808. }
  1809. if ((stepBreakAddrIdx != -1) && (breakpoint == NULL) && (mSteppingThread != mActiveThread))
  1810. {
  1811. BfLogDbg("Ignoring break (wrong thread)\n");
  1812. ThreadRestorePause(mSteppingThread, mActiveThread);
  1813. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1814. break;
  1815. }
  1816. isDeeper = mStepSP > BF_CONTEXT_SP(lcContext);
  1817. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto))
  1818. {
  1819. isDeeper = mStepSP >= BF_CONTEXT_SP(lcContext);
  1820. BfLogDbg("StepOut Iteration SP:%p StartSP:%p IsDeeper:%d\n", BF_CONTEXT_SP(lcContext), mStepSP, isDeeper);
  1821. }
  1822. if (((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto)) && (breakpoint == NULL) && (isDeeper))
  1823. {
  1824. // We're encountered recursion
  1825. // Make sure we don't already have one of these stored
  1826. BF_ASSERT(mStoredReturnValueAddr == 0);
  1827. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1828. break; // Don't fall through, we don't want to set mIsAtBreakpointAddress
  1829. }
  1830. if (isStepOut)
  1831. {
  1832. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1833. if (mStepType == StepType_StepOut_ThenInto)
  1834. {
  1835. dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  1836. if ((dwLineData != NULL) && (pcAddress == dwSubprogram->GetLineAddr(*dwLineData)))
  1837. {
  1838. // Our step out from a filtered function put us at the start of a new line. Stop here
  1839. // <do nothing>
  1840. }
  1841. else
  1842. {
  1843. // .. otherwise keep going until we get to the start of a new line
  1844. SetupStep(StepType_StepInto);
  1845. mRunState = RunState_Running;
  1846. break;
  1847. }
  1848. }
  1849. if (!mStepInAssembly)
  1850. {
  1851. // Keep stepping out until we find a frame that we have source for
  1852. DbgSubprogram* dwSubprogram = NULL;
  1853. DbgLineData* dwLineData = FindLineDataAtAddress(BF_CONTEXT_IP(lcContext), &dwSubprogram);
  1854. if (dwLineData == NULL)
  1855. {
  1856. SetupStep(StepType_StepOut);
  1857. break;
  1858. }
  1859. if ((dwLineData->mColumn == -1) && (!dwSubprogram->HasValidLines()))
  1860. {
  1861. // This is a method we don't actually want to be in, it has no valid lines!
  1862. SetupStep(StepType_StepOut);
  1863. break;
  1864. }
  1865. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  1866. {
  1867. // We've stepped out, but right into the start of an inlined method, so step out of this inlined method now...
  1868. SetupStep(StepType_StepOut);
  1869. break;
  1870. }
  1871. }
  1872. ClearStep();
  1873. mRunState = RunState_Paused;
  1874. threadInfo->mStoppedAtAddress = pcAddress;
  1875. break;
  1876. }
  1877. mRunState = RunState_Paused;
  1878. if (breakpoint != NULL)
  1879. {
  1880. // While stepping we hit a legit breakpoint
  1881. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  1882. // Ignore breakpoint on return statement if we're return-stepping
  1883. mRunState = RunState_Breakpoint;
  1884. }
  1885. if ((mStepType == StepType_StepInto) && (dwSubprogram != NULL))
  1886. {
  1887. // Don't filter out the current subprogram (would break cases where we explicitly stepped into or hit breakpoint in a filtered subprogram)
  1888. bool isInStartSubprogram = (mStepStartPC >= dwSubprogram->mBlock.mLowPC) && (mStepStartPC < dwSubprogram->mBlock.mHighPC);
  1889. if ((!isInStartSubprogram) && (IsStepFiltered(dwSubprogram, dwLineData)))
  1890. {
  1891. BfLogDbg("Hit step filter\n");
  1892. mRunState = RunState_Running;
  1893. SetupStep(StepType_StepOut_ThenInto);
  1894. break;
  1895. }
  1896. }
  1897. if ((mStepType == StepType_StepOver) && (stepBreakAddrIdx == 0) && (mStepBreakpointAddrs[0] != 0) && (mStepBreakpointAddrs.size() > 1))
  1898. {
  1899. // Break was on the 'call' instruction, not the instruction after it -- means recursion
  1900. BfLogDbg("StepOver detected recursing\n");
  1901. mStepIsRecursing = true;
  1902. if (mTempBreakpoint.Remove(mStepBreakpointAddrs[0]))
  1903. {
  1904. RemoveBreakpoint(mStepBreakpointAddrs[0]);
  1905. }
  1906. mStepBreakpointAddrs[0] = 0;
  1907. mRunState = RunState_Running;
  1908. break;
  1909. }
  1910. if ((mStepType == StepType_StepOver) && (stepBreakAddrIdx > 0) && (mStepBreakpointAddrs[0] != 0) && (isDeeper))
  1911. {
  1912. // This is the first time we've hit the target breakpoint.
  1913. if (HasSteppedIntoCall())
  1914. {
  1915. mStepIsRecursing = true;
  1916. RemoveBreakpoint(mStepBreakpointAddrs[0]);
  1917. mStepBreakpointAddrs[0] = 0;
  1918. //mStepBreakpointAddrs.erase(mStepBreakpointAddrs.begin());
  1919. }
  1920. }
  1921. if ((mStepType == StepType_StepOver) && (mStepIsRecursing) && (stepBreakAddrIdx != -1) && (isDeeper))
  1922. {
  1923. // Decrement so the equality test on "step out" marks us as not being deeper when we
  1924. // hit the expected SP
  1925. BfLogDbg("Converting StepOver to StepOut\n");
  1926. mStepSP--;
  1927. mStepType = StepType_StepOut_ThenInto;
  1928. //SetupStep(StepType_StepOut);
  1929. mRunState = RunState_Running;
  1930. break;
  1931. }
  1932. if ((mStepType == StepType_StepOver) && (!ignoreBreakpoint) && (breakpoint == NULL) && (!mStepInAssembly))
  1933. {
  1934. // Test for stepping over inline method
  1935. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  1936. // mTempBreakpoints will have 2 entries if we are on a 'call' line. If we have an inlined call immediately following a call, then we
  1937. // assume we're hitting a return break
  1938. /*if ((dwSubprogram != NULL) && (dwSubprogram->mInlineParent != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC) && (mTempBreakpoint.size() < 2))
  1939. {
  1940. BfLogDbg("Attempting StepOver of inlined method\n");
  1941. SetupStep(StepType_StepOut);
  1942. mRunState = RunState_Running;
  1943. break;
  1944. } */
  1945. //TODO: The previous logic with the "(mTempBreakpoint.size() < 2)" was causing Try!(Method()); stepovers to enter into Try!. What did we mean by
  1946. // "assume we're hitting a return break"?
  1947. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  1948. {
  1949. RemoveTempBreakpoints();
  1950. BfLogDbg("Attempting StepOver of inlined method\n");
  1951. SetupStep(StepType_StepOut);
  1952. mRunState = RunState_Running;
  1953. break;
  1954. }
  1955. }
  1956. if (mStepType == StepType_StepOut_Inline)
  1957. {
  1958. if (mOrigStepType == StepType_StepOver)
  1959. {
  1960. // For the step over, if we are still inside the source line after an inline then step over again...
  1961. DbgSubprogram* origSubprogram = NULL;
  1962. auto origLineData = FindLineDataAtAddress(mStepStartPC, &origSubprogram);
  1963. DbgSubprogram* curSubprogram = NULL;
  1964. auto curLineData = FindLineDataAtAddress(pcAddress, &curSubprogram);
  1965. if ((origLineData != NULL) &&
  1966. ((origLineData == curLineData) ||
  1967. ((origSubprogram == curSubprogram) && (origLineData->mLine == curLineData->mLine))))
  1968. {
  1969. mRunState = RunState_Running;
  1970. SetupStep(StepType_StepOver);
  1971. break;
  1972. }
  1973. }
  1974. ClearStep();
  1975. break;
  1976. }
  1977. if ((mStepType != StepType_None) && (ignoreBreakpoint) && (!mStepInAssembly) && (stepBreakAddrIdx == -1))
  1978. {
  1979. // Ignore breakpoint by just continuing...
  1980. mRunState = RunState_Running;
  1981. break;
  1982. }
  1983. RemoveTempBreakpoints();
  1984. if ((mStepType != StepType_None) && (!mStepInAssembly) && (!isLineStart) && (stepBreakAddrIdx != -1))
  1985. {
  1986. SetupStep(mStepType);
  1987. mRunState = RunState_Running;
  1988. }
  1989. else
  1990. {
  1991. //if (mStepType != StepType_Return)
  1992. if (stepBreakAddrIdx != -1)
  1993. {
  1994. // Even if we've detected we're at a breakpoint, we mark ourselves as just stepping if we also
  1995. // have a step breakpoint here
  1996. StepLineTryPause(pcAddress, true);
  1997. }
  1998. if (mRunState == RunState_Paused)
  1999. ClearStep();
  2000. }
  2001. if (ignoreBreakpoint)
  2002. {
  2003. SetupStep(mStepType);
  2004. mRunState = RunState_Running;
  2005. }
  2006. if ((mRunState == RunState_Paused) && (breakpoint != NULL))
  2007. {
  2008. // Just do the 'check' here so we can do the logging/condition stuff
  2009. CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress);
  2010. }
  2011. }
  2012. else
  2013. {
  2014. breakpoint = (WdBreakpoint*)FindBreakpointAt((uintptr_t)exceptionRecord->ExceptionAddress);
  2015. if ((breakpoint != NULL) && (!CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress)))
  2016. {
  2017. ClearCallStack();
  2018. BfLogDbg("Skipping conditional breakpoint. Setting mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  2019. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  2020. mRunState = RunState_Running;
  2021. break;
  2022. }
  2023. if (breakpoint != NULL)
  2024. {
  2025. BfLogDbg("Breakpoint hit. mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  2026. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  2027. mRunState = RunState_Breakpoint;
  2028. }
  2029. else if ((stepBreakAddrIdx != -1) || (isNonDebuggerBreak))
  2030. {
  2031. if (mRunState != RunState_DebugEval)
  2032. {
  2033. // Was in mStepBreakpointAddrs list
  2034. if ((isNonDebuggerBreak) || (mStepType == StepType_None) || (mSteppingThread == mAtBreakThread))
  2035. {
  2036. BfLogDbg("Hit mStepBreakpointAddrs breakpoint\n");
  2037. mRunState = RunState_Paused;
  2038. }
  2039. else
  2040. {
  2041. BfLogDbg("Ignored mStepBreakpointAddrs breakpoint (wrong thread)\n");
  2042. mRunState = RunState_Running;
  2043. }
  2044. }
  2045. }
  2046. else
  2047. {
  2048. BfLogDbg("Ignoring break (old or ignored breakpoint)\n");
  2049. mRunState = RunState_Running;
  2050. }
  2051. }
  2052. if ((breakpoint != NULL) && (!ignoreBreakpoint))
  2053. {
  2054. mActiveBreakpoint = breakpoint;
  2055. mBreakStackFrameIdx = -1;
  2056. }
  2057. if ((mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint))
  2058. threadInfo->mStoppedAtAddress = pcAddress;
  2059. }
  2060. break;
  2061. case STATUS_WX86_SINGLE_STEP:
  2062. case EXCEPTION_SINGLE_STEP:
  2063. {
  2064. if (mRunState == RunState_Terminating)
  2065. {
  2066. BfLogDbg("Ignoring event because of RunState_Terminating\n");
  2067. break;
  2068. }
  2069. if ((mStepSwitchedThreads) && (mActiveThread == mSteppingThread) && (mActiveThread->mIsAtBreakpointAddress != NULL))
  2070. {
  2071. ContinueFromBreakpoint();
  2072. break;
  2073. }
  2074. if (mRunState == RunState_HotStep)
  2075. {
  2076. BF_ASSERT(mActiveThread == mDebuggerWaitingThread);
  2077. mRunState = RunState_Paused;
  2078. break;
  2079. }
  2080. mActiveThread = mDebuggerWaitingThread;
  2081. BF_CONTEXT lcContext;
  2082. lcContext.ContextFlags = BF_CONTEXT_ALL;
  2083. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  2084. addr_target pcAddress = BF_CONTEXT_IP(lcContext);
  2085. bool wasUnfilteredStep = mStepType == StepType_StepInto_Unfiltered;
  2086. if (mStepType == StepType_StepInto_UnfilteredSingle)
  2087. {
  2088. wasUnfilteredStep = true;
  2089. mStepType = StepType_StepInto;
  2090. mStepStartPC = pcAddress;
  2091. }
  2092. BfLogDbg("EXCEPTION_SINGLE_STEP Thread:%d PC:%p\n", mActiveThread->mThreadId, exceptionRecord->ExceptionAddress);
  2093. if (lcContext.Dr6 & 0x0F) // Memory breakpoint hit
  2094. {
  2095. WdBreakpoint* foundBreakpoint = NULL;
  2096. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  2097. {
  2098. if ((lcContext.Dr6 & ((intptr_target)1 << memoryWatchSlot)) != 0)
  2099. {
  2100. foundBreakpoint = mMemoryBreakpoints[memoryWatchSlot].mBreakpoint;
  2101. break;
  2102. }
  2103. }
  2104. BF_ASSERT(foundBreakpoint != NULL);
  2105. DbgSubprogram* subprogram = mDebugTarget->FindSubProgram(pcAddress);
  2106. if (CheckConditionalBreakpoint(foundBreakpoint, subprogram, pcAddress))
  2107. {
  2108. if (foundBreakpoint != NULL)
  2109. {
  2110. mDebugManager->mOutMessages.push_back(StrFormat("memoryBreak %s", EncodeDataPtr(foundBreakpoint->mMemoryBreakpointInfo->mMemoryAddress, false).c_str()));
  2111. mRunState = RunState_Paused;
  2112. }
  2113. mActiveBreakpoint = foundBreakpoint;
  2114. mBreakStackFrameIdx = -1;
  2115. RemoveTempBreakpoints();
  2116. BfLogDbg("Memory breakpoint hit: %p\n", foundBreakpoint);
  2117. }
  2118. else
  2119. ClearCallStack();
  2120. break;
  2121. }
  2122. if ((mRunState == RunState_DebugEval) && (mDebugEvalThreadInfo.mThreadId == mDebuggerWaitingThread->mThreadId))
  2123. {
  2124. if ((addr_target)(intptr)exceptionRecord->ExceptionAddress == mDebugEvalSetRegisters.GetPC())
  2125. {
  2126. // This indicates we are returning from kernel mode and our registers are clobbered
  2127. SetRegisters(&mDebugEvalSetRegisters);
  2128. }
  2129. break;
  2130. }
  2131. bool hadBreakpointContinue = true;
  2132. if (threadInfo->mBreakpointAddressContinuing != 0)
  2133. {
  2134. bool wantsBreakpoint = WantsBreakpointAt(threadInfo->mBreakpointAddressContinuing);
  2135. BfLogDbg("Continuing breakpoint at %p WantsReset:%d\n", threadInfo->mBreakpointAddressContinuing, wantsBreakpoint);
  2136. if (wantsBreakpoint)
  2137. {
  2138. PhysSetBreakpoint(threadInfo->mBreakpointAddressContinuing);
  2139. }
  2140. threadInfo->mBreakpointAddressContinuing = NULL;
  2141. hadBreakpointContinue = true;
  2142. ThreadRestoreUnpause();
  2143. }
  2144. if ((mSteppingThread != NULL) && (mSteppingThread != mActiveThread))
  2145. {
  2146. // This SINGLE_STEP happened in the wrong thread - we need the stepping thread to do the stepping!
  2147. // Try again.
  2148. mActiveThread = mSteppingThread;
  2149. SingleStepX86();
  2150. break;
  2151. }
  2152. bool isDeeper = mStepSP > BF_CONTEXT_SP(lcContext);
  2153. if ((mStepSwitchedThreads) && (mStepType == StepType_StepOver) && (isDeeper))
  2154. {
  2155. if (HasSteppedIntoCall())
  2156. {
  2157. // Since we switched threads, we needed to do a hardware step which has placed us inside a
  2158. // call, so we need to step out of that now...
  2159. SetupStep(StepType_StepOut_NoFrame);
  2160. break;
  2161. }
  2162. }
  2163. // If we don't have a mStepBreakpointAddrs set, that means we're stepping through individual instructions --
  2164. // so process the new location here
  2165. if (((mStepType == StepType_StepInto) || (mStepType == StepType_StepInto_Unfiltered) || (mStepType == StepType_StepOver)) && (mStepBreakpointAddrs.size() == 0))
  2166. {
  2167. DbgSubprogram* dwSubprogram = NULL;
  2168. DbgLineData* dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  2169. if ((dwSubprogram != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC) && (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced))
  2170. {
  2171. BfLogDbg("Stepping through hot thunk\n");
  2172. mRunState = RunState_Running;
  2173. SingleStepX86();
  2174. break;
  2175. }
  2176. if ((mStepType == StepType_StepOver) && (!mStepInAssembly))
  2177. {
  2178. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  2179. {
  2180. BfLogDbg("Attempting StepOver of inlined method - SingleStep\n");
  2181. SetupStep(StepType_StepOut);
  2182. mRunState = RunState_Running;
  2183. break;
  2184. }
  2185. }
  2186. // Column of -1 means "Illegal", keep stepping!
  2187. if ((mStepInAssembly) ||
  2188. ((dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dwLineData->mColumn >= 0) &&
  2189. ((dwSubprogram->GetLineAddr(*dwLineData) == pcAddress) || (mStepStopOnNextInstruction))))
  2190. {
  2191. // Hit a line while stepping, we're done!
  2192. mRunState = RunState_Paused;
  2193. StepLineTryPause(pcAddress, false);
  2194. if (mRunState == RunState_Paused)
  2195. {
  2196. if ((mStepType == StepType_StepInto) && (!wasUnfilteredStep) && (!mStepInAssembly) && (dwSubprogram != NULL))
  2197. {
  2198. // Don't filter out the current subprogram (would break cases where we explicitly stepped into or hit breakpoint in a filtered subprogram)
  2199. bool isInStartSubprogram = (mStepStartPC >= dwSubprogram->mBlock.mLowPC) && (mStepStartPC < dwSubprogram->mBlock.mHighPC);
  2200. if ((!isInStartSubprogram) && (IsStepFiltered(dwSubprogram, dwLineData)))
  2201. {
  2202. BfLogDbg("Hit step filter (2)\n");
  2203. mRunState = RunState_Running;
  2204. SetupStep(StepType_StepOut_ThenInto);
  2205. break;
  2206. }
  2207. }
  2208. ClearStep();
  2209. mCurNoInfoStepTries = 0; // Reset
  2210. }
  2211. else
  2212. SetupStep(mStepType);
  2213. }
  2214. else if (dwSubprogram != NULL)
  2215. {
  2216. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && ((mStepType == StepType_StepInto) || (mStepType == StepType_StepInto_Unfiltered)))
  2217. {
  2218. SingleStepX86();
  2219. }
  2220. else
  2221. {
  2222. // Inside a line's instruction, keep going
  2223. SetupStep(mStepType);
  2224. mCurNoInfoStepTries = 0; // Reset
  2225. }
  2226. }
  2227. else if (mStepType == StepType_StepInto_Unfiltered)
  2228. {
  2229. CPUInst inst;
  2230. if (mDebugTarget->DecodeInstruction(pcAddress, &inst))
  2231. {
  2232. if (inst.IsBranch())
  2233. {
  2234. auto target = inst.GetTarget();
  2235. if (target != 0)
  2236. {
  2237. DbgSubprogram* destSubprogram = mDebugTarget->FindSubProgram(target);
  2238. if ((destSubprogram != NULL) && (target == destSubprogram->mBlock.mLowPC))
  2239. {
  2240. // We're jumping to an actual subprogram, so continue stepping here
  2241. mStepType = StepType_StepInto_UnfilteredSingle;
  2242. SingleStepX86();
  2243. break;
  2244. }
  2245. }
  2246. }
  2247. }
  2248. // We requested to step into this method so stop here even if we don't have source
  2249. mRunState = RunState_Paused;
  2250. }
  2251. else
  2252. {
  2253. // No debug info!
  2254. bool doStepOut = false;
  2255. if (mCurNoInfoStepTries < 16)
  2256. {
  2257. mCurNoInfoStepTries++;
  2258. BfLogDbg("NoInfoStepTries: %d\n", mCurNoInfoStepTries);
  2259. if (!SetupStep(mStepType))
  2260. doStepOut = true;
  2261. }
  2262. else
  2263. doStepOut = true;
  2264. if (doStepOut)
  2265. {
  2266. // Step out of current call.
  2267. mStepSP = 0;
  2268. SetupStep(StepType_StepOut_NoFrame);
  2269. // Aggressive stepout - don't monitor BP
  2270. mStepSP = 0;
  2271. }
  2272. }
  2273. }
  2274. else if (!hadBreakpointContinue)
  2275. {
  2276. BF_DBG_FATAL("EXCEPTION_SINGLE_STEP bad debugger state");
  2277. }
  2278. if (mRunState == RunState_Paused)
  2279. threadInfo->mStoppedAtAddress = pcAddress;
  2280. }
  2281. break;
  2282. default:
  2283. {
  2284. bool isSystemException =
  2285. (exceptionRecord->ExceptionCode >= STATUS_ACCESS_VIOLATION) &&
  2286. (exceptionRecord->ExceptionCode <= STATUS_ASSERTION_FAILURE);
  2287. bool isFirstChance = mDebugEvent.u.Exception.dwFirstChance != 0;
  2288. bool handled = false;
  2289. //TODO: Use a user-defined filter here to determine whether to stop or continue
  2290. if ((!isSystemException) && (isFirstChance))
  2291. {
  2292. if (exceptionRecord->ExceptionCode == 0x406D1388) // Visual C
  2293. {
  2294. if ((int32)exceptionRecord->ExceptionInformation[0] == 0x1000)
  2295. {
  2296. struct THREADNAME_INFO
  2297. {
  2298. DWORD dwType; // Must be 0x1000.
  2299. LPCSTR szName; // Pointer to name (in user addr space).
  2300. DWORD dwThreadID; // Thread ID (-1=caller thread).
  2301. DWORD dwFlags; // Reserved for future use, must be zero.
  2302. };
  2303. THREADNAME_INFO* threadNameInfo = (THREADNAME_INFO*)exceptionRecord->ExceptionInformation;
  2304. DwFormatInfo formatInfo;
  2305. formatInfo.mRawString = true;
  2306. String nameStr = ReadString(DbgType_SChar, (intptr)threadNameInfo->szName, false, 1024, formatInfo);
  2307. WdThreadInfo* namingThreadInfo = threadInfo;
  2308. if (threadNameInfo->dwThreadID != (DWORD)-1)
  2309. {
  2310. namingThreadInfo = NULL;
  2311. mThreadMap.TryGetValue(threadNameInfo->dwThreadID, &namingThreadInfo);
  2312. }
  2313. if (namingThreadInfo != NULL)
  2314. {
  2315. namingThreadInfo->mName = nameStr;
  2316. FilterThreadName(namingThreadInfo->mName);
  2317. }
  2318. }
  2319. else if (((int32)exceptionRecord->ExceptionInformation[0] == 0x1001) && ((int32)exceptionRecord->ExceptionInformation[1] == 0x1002))
  2320. {
  2321. struct FailMessage
  2322. {
  2323. addr_target mPtr0; // Unknown
  2324. addr_target mPtr1; // 0
  2325. addr_target mPtr2; // 0
  2326. addr_target mPtr3; // Unknown
  2327. addr_target mErrorStr;
  2328. };
  2329. FailMessage failMessage = ReadMemory<FailMessage>(exceptionRecord->ExceptionInformation[2]);
  2330. DwFormatInfo formatInfo;
  2331. String failStr = ReadString(DbgType_SChar16, failMessage.mErrorStr, false, 8192, formatInfo);
  2332. mDebugManager->mOutMessages.push_back(StrFormat("error Run-Time Check Failure %d - %s", exceptionRecord->ExceptionInformation[6], failStr.c_str()));
  2333. mRunState = RunState_Paused;
  2334. mRequestedStackFrameIdx = -2; // -2 = "auto"
  2335. handled = true;
  2336. }
  2337. }
  2338. if (!handled)
  2339. {
  2340. OutputMessage(StrFormat("Skipping first chance exception %08Xd at address %@ in thread %d\n", exceptionRecord->ExceptionCode, exceptionRecord->ExceptionAddress, threadInfo->mThreadId));
  2341. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_EXCEPTION_NOT_HANDLED);
  2342. mIsDebuggerWaiting = false;
  2343. }
  2344. }
  2345. else
  2346. {
  2347. BfLogDbg("EXCEPTION in thread %d at %p\n", threadInfo->mThreadId, exceptionRecord->ExceptionAddress);
  2348. OutputDebugStrF("EXCEPTION\n");
  2349. mActiveThread = threadInfo;
  2350. memcpy(&mCurException, exceptionRecord, sizeof(EXCEPTION_RECORD));
  2351. if (mRunState == RunState_DebugEval)
  2352. {
  2353. if ((intptr)mCurException.ExceptionAddress == 42)
  2354. {
  2355. BfLogDbg("RunState_DebugEval_Done\n");
  2356. OutputDebugStrF(" RunState_DebugEval_Done\n");
  2357. }
  2358. else
  2359. {
  2360. BfLogDbg("Exception at 0x%@ in thread %d, exception code 0x%08X",
  2361. mCurException.ExceptionAddress, mActiveThread->mThreadId, mCurException.ExceptionCode);
  2362. mDebugPendingExpr->mException = StrFormat("Exception at 0x%@ in thread %d, exception code 0x%08X",
  2363. mCurException.ExceptionAddress, mActiveThread->mThreadId, mCurException.ExceptionCode);
  2364. }
  2365. mRunState = RunState_DebugEval_Done;
  2366. mExplicitStopThread = mActiveThread;
  2367. mRequestedStackFrameIdx = mDebugPendingExpr->mCallStackIdx;
  2368. }
  2369. else
  2370. {
  2371. mRunState = RunState_Exception;
  2372. }
  2373. }
  2374. }
  2375. break;
  2376. }
  2377. }
  2378. break;
  2379. }
  2380. if ((mDebugEvalThreadInfo.mThreadId != 0) && (mRunState != RunState_DebugEval) && (mRunState != RunState_DebugEval_Done))
  2381. {
  2382. CleanupDebugEval();
  2383. }
  2384. // Stepping done?
  2385. if (mStepType == StepType_None)
  2386. {
  2387. mLastValidStepIntoPC = 0;
  2388. }
  2389. BF_ASSERT(mDebuggerWaitingThread != NULL);
  2390. return true;
  2391. }
  2392. void WinDebugger::Update()
  2393. {
  2394. AutoCrit autoCrit(mDebugManager->mCritSect);
  2395. // if (mRunState == RunState_DebugEval)
  2396. // ContinueDebugEvent();
  2397. if (mRunState == RunState_DebugEval_Done)
  2398. {
  2399. if (mDebugPendingExpr != NULL)
  2400. {
  2401. mDebugPendingExpr->mIdleTicks++;
  2402. if (mDebugPendingExpr->mIdleTicks >= 2)
  2403. {
  2404. BfLogDbg("Finishing pending expr in thread %d\n", mDebugEvalThreadInfo.mThreadId);
  2405. mRunState = RunState_Paused;
  2406. CleanupDebugEval();
  2407. }
  2408. }
  2409. }
  2410. else if (mDebugPendingExpr != NULL)
  2411. {
  2412. mDebugPendingExpr->mIdleTicks = 0;
  2413. }
  2414. }
  2415. void WinDebugger::ContinueDebugEvent()
  2416. {
  2417. AutoCrit autoCrit(mDebugManager->mCritSect);
  2418. BF_ASSERT(mRunState != RunState_DebugEval_Done);
  2419. if (!mWantsDebugContinue)
  2420. return;
  2421. if (!TryRunContinue())
  2422. return;
  2423. // if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId != mDebugEvalThreadInfo.mThreadId))
  2424. // {
  2425. // // Don't process the 'mIsAtBreakpointAddress' stuff
  2426. // mWantsDebugContinue = false;
  2427. // mContinueEvent.Set();
  2428. // return;
  2429. // }
  2430. if ((mDebuggerWaitingThread->mIsAtBreakpointAddress == 0) && (mDebuggerWaitingThread->mStoppedAtAddress != 0))
  2431. {
  2432. auto breakpoint = FindBreakpointAt(mDebuggerWaitingThread->mStoppedAtAddress);
  2433. if (breakpoint != NULL)
  2434. {
  2435. mDebuggerWaitingThread->mIsAtBreakpointAddress = mDebuggerWaitingThread->mStoppedAtAddress;
  2436. }
  2437. }
  2438. if (mDebuggerWaitingThread->mIsAtBreakpointAddress != 0)
  2439. {
  2440. if (!ContinueFromBreakpoint())
  2441. {
  2442. BfLogDbg("ContinueFromBreakpoint failed\n");
  2443. ClearCallStack();
  2444. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  2445. mDebuggerWaitingThread->mIsAtBreakpointAddress = 0;
  2446. mWantsDebugContinue = false;
  2447. mContinueFromBreakpointFailed = true;
  2448. mContinueEvent.Set();
  2449. return;
  2450. }
  2451. }
  2452. if ((mRunState == RunState_Breakpoint) || (mRunState == RunState_Paused))
  2453. {
  2454. ClearCallStack();
  2455. mRunState = RunState_Running;
  2456. }
  2457. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  2458. mWantsDebugContinue = false;
  2459. BF_ASSERT_REL(mDebuggerWaitingThread->mIsAtBreakpointAddress == 0);
  2460. mContinueEvent.Set();
  2461. }
  2462. static BOOL CALLBACK WdEnumWindowsProc(HWND hwnd, LPARAM lParam)
  2463. {
  2464. HWND owner = GetWindow(hwnd, GW_OWNER);
  2465. if (!IsWindowVisible(hwnd))
  2466. return TRUE;
  2467. DWORD processId = 0;
  2468. DWORD threadId = GetWindowThreadProcessId(hwnd, &processId);
  2469. if (processId != ((WinDebugger*)gDebugger)->mProcessInfo.dwProcessId)
  2470. return TRUE;
  2471. SetForegroundWindow(hwnd);
  2472. return TRUE;
  2473. }
  2474. void WinDebugger::ForegroundTarget()
  2475. {
  2476. EnumWindows(WdEnumWindowsProc, 0);
  2477. }
  2478. static int gFindLineDataAt = 0;
  2479. DbgLineData* WinDebugger::FindLineDataAtAddress(addr_target address, DbgSubprogram** outSubProgram, DbgSrcFile** outSrcFile, int* outLineIdx, DbgOnDemandKind onDemandKind)
  2480. {
  2481. gFindLineDataAt++;
  2482. BP_ZONE("WinDebugger::FindLineDataAtAddress");
  2483. auto dwSubprogram = mDebugTarget->FindSubProgram((addr_target)address, onDemandKind);
  2484. if (dwSubprogram == NULL)
  2485. return NULL;
  2486. FixupLineDataForSubprogram(dwSubprogram);
  2487. auto lineData = dwSubprogram->FindClosestLine(address, outSubProgram, outSrcFile, outLineIdx);
  2488. return lineData;
  2489. }
  2490. DbgLineData* WinDebugger::FindLineDataInSubprogram(addr_target address, DbgSubprogram* dwSubprogram)
  2491. {
  2492. auto dwCompileUnit = dwSubprogram->mCompileUnit;
  2493. FixupLineDataForSubprogram(dwSubprogram);
  2494. auto lineData = dwSubprogram->FindClosestLine(address);
  2495. return lineData;
  2496. }
  2497. bool WinDebugger::IsStepFiltered(DbgSubprogram* dbgSubprogram, DbgLineData* dbgLineData)
  2498. {
  2499. if (mIsStepIntoSpecific)
  2500. return false;
  2501. if (dbgSubprogram->mStepFilterVersion != mDebugManager->mStepFilterVersion)
  2502. {
  2503. String filterName;
  2504. CreateFilterName(filterName, dbgSubprogram);
  2505. dbgSubprogram->PopulateSubprogram();
  2506. bool doDefault = false;
  2507. StepFilter* stepFilterPtr;
  2508. if (mDebugManager->mStepFilters.TryGetValue(filterName, &stepFilterPtr))
  2509. {
  2510. switch (stepFilterPtr->mFilterKind)
  2511. {
  2512. case BfStepFilterKind_Default:
  2513. doDefault = true;
  2514. break;
  2515. case BfStepFilterKind_Filtered:
  2516. dbgSubprogram->mIsStepFiltered = true;
  2517. break;
  2518. case BfStepFilterKind_NotFiltered:
  2519. dbgSubprogram->mIsStepFiltered = false;
  2520. break;
  2521. }
  2522. }
  2523. else
  2524. {
  2525. doDefault = true;
  2526. }
  2527. if (doDefault)
  2528. {
  2529. dbgSubprogram->mIsStepFiltered = dbgSubprogram->mIsStepFilteredDefault;
  2530. }
  2531. dbgSubprogram->mStepFilterVersion = mDebugManager->mStepFilterVersion;
  2532. }
  2533. if (!dbgSubprogram->mIsStepFiltered)
  2534. {
  2535. if (dbgLineData != NULL)
  2536. {
  2537. auto dbgSrcFile = dbgSubprogram->GetLineSrcFile(*dbgLineData);
  2538. if (dbgSrcFile->mStepFilterVersion != mDebugManager->mStepFilterVersion)
  2539. {
  2540. dbgSrcFile->mFileExistKind = dbgSubprogram->mCompileUnit->mDbgModule->CheckSourceFileExist(dbgSrcFile->GetLocalPath());
  2541. dbgSrcFile->mStepFilterVersion = mDebugManager->mStepFilterVersion;
  2542. }
  2543. switch (dbgSrcFile->mFileExistKind)
  2544. {
  2545. case DbgFileExistKind_NotFound:
  2546. return true;
  2547. case DbgFileExistKind_HasOldSourceCommand:
  2548. if (mDebugManager->mStepOverExternalFiles)
  2549. return true;
  2550. }
  2551. }
  2552. }
  2553. return dbgSubprogram->mIsStepFiltered;
  2554. }
  2555. void WinDebugger::RemoveTempBreakpoints()
  2556. {
  2557. BfLogDbg("RemoveTempBreakpoints\n");
  2558. for (auto address : mTempBreakpoint)
  2559. {
  2560. RemoveBreakpoint(address);
  2561. // if (FindBreakpointAt(address) == NULL)
  2562. // {
  2563. // RemoveBreakpoint(address);
  2564. // }
  2565. // else
  2566. // {
  2567. // BfLogDbg("Ignoring remove on temp breakpoint %p\n", address);
  2568. // }
  2569. }
  2570. mTempBreakpoint.Clear();
  2571. mStepBreakpointAddrs.Clear();
  2572. }
  2573. void WinDebugger::RehupBreakpoints(bool doFlush)
  2574. {
  2575. BfLogDbg("RehupBreakpoints\n");
  2576. // First pass- detach breakpoints that need to be rebound
  2577. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  2578. {
  2579. auto breakpoint = mBreakpoints[i];
  2580. while (breakpoint != NULL)
  2581. {
  2582. if (((breakpoint->mSrcFile != NULL) && (breakpoint->mSrcFile->mDeferredRefs.size() > 0)) ||
  2583. (!breakpoint->mSymbolName.IsEmpty()))
  2584. {
  2585. // This breakpoint was already bound, but we loaded a debug module that also had this file so rebind it
  2586. DetachBreakpoint(breakpoint);
  2587. }
  2588. breakpoint = (WdBreakpoint*)breakpoint->mLinkedSibling;
  2589. }
  2590. }
  2591. // Second pass- actually set breakpoints
  2592. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  2593. {
  2594. auto breakpoint = mBreakpoints[i];
  2595. while (breakpoint != NULL)
  2596. {
  2597. CheckBreakpoint(breakpoint);
  2598. if (breakpoint->mAddr != 0)
  2599. SetBreakpoint(breakpoint->mAddr, true);
  2600. breakpoint = (WdBreakpoint*)breakpoint->mLinkedSibling;
  2601. }
  2602. }
  2603. mNeedsRehupBreakpoints = false;
  2604. }
  2605. bool WinDebugger::WantsBreakpointAt(addr_target address)
  2606. {
  2607. if (mTempBreakpoint.Contains(address))
  2608. return true;
  2609. for (auto breakpoint : mBreakpoints)
  2610. {
  2611. WdBreakpoint* checkBreakpoint = breakpoint;
  2612. while (checkBreakpoint != NULL)
  2613. {
  2614. if (address == checkBreakpoint->mAddr)
  2615. return true;
  2616. checkBreakpoint = (WdBreakpoint*)checkBreakpoint->mLinkedSibling;
  2617. }
  2618. }
  2619. return false;
  2620. }
  2621. void WinDebugger::CheckBreakpoint(WdBreakpoint* wdBreakpoint, DbgSrcFile* srcFile, int lineNum, int hotIdx)
  2622. {
  2623. BP_ZONE("WinDebugger::CheckBreakpoint:atLoc");
  2624. if (hotIdx == -1)
  2625. {
  2626. BF_ASSERT(wdBreakpoint->mPendingHotBindIdx == -1);
  2627. }
  2628. WdBreakpoint* headBreakpoint = wdBreakpoint;
  2629. headBreakpoint->mPendingHotBindIdx = -1;
  2630. bool foundInSequence = false;
  2631. DbgSubprogram* lastFoundSubprogram = NULL;
  2632. int highestHotIdx = -1;
  2633. bool foundLine = false;
  2634. int bestLineNum = -1;
  2635. int bestLineOffset = 0x7FFFFFFF;
  2636. auto _CheckLineInfo = [&](DbgSubprogram* dbgSubprogram, DbgLineInfo* dbgLineInfo)
  2637. {
  2638. // Scan first so we can determine if we want to do fix up line data or not.
  2639. bool hasNear = false;
  2640. int maxLineDist = 6;
  2641. for (int lineIdx = 0; lineIdx < dbgLineInfo->mLines.mSize; lineIdx++)
  2642. {
  2643. auto lineData = &dbgLineInfo->mLines[lineIdx];
  2644. auto& ctx = dbgLineInfo->mContexts[lineData->mCtxIdx];
  2645. if (ctx.mSrcFile != srcFile)
  2646. continue;
  2647. int lineOffset = lineData->mLine - lineNum;
  2648. if ((lineOffset >= 0) && (lineOffset <= maxLineDist))
  2649. hasNear = true;
  2650. }
  2651. if (!hasNear)
  2652. return;
  2653. FixupLineDataForSubprogram(dbgSubprogram);
  2654. for (int lineIdx = 0; lineIdx < dbgLineInfo->mLines.mSize; lineIdx++)
  2655. {
  2656. //TODO: Do fixup lineData... ?
  2657. auto lineData = &dbgLineInfo->mLines[lineIdx];
  2658. auto& ctx = dbgLineInfo->mContexts[lineData->mCtxIdx];
  2659. if (ctx.mSrcFile != srcFile)
  2660. continue;
  2661. // if (ctx.mInlinee != NULL)
  2662. // {
  2663. // if (lineIdx + 1 < dbgLineInfo->mLines.mSize)
  2664. // {
  2665. // auto nextLineData = &dbgLineInfo->mLines[lineIdx + 1];
  2666. // if (nextLineData->mRelAddress == lineData->mRelAddress)
  2667. // {
  2668. // // Use the later entry (same logic from DisassembleAt)
  2669. // continue;
  2670. // }
  2671. // }
  2672. // }
  2673. if ((lineData->mColumn == -1) && (wdBreakpoint->mInstrOffset == -1))
  2674. continue;
  2675. int lineOffset = lineData->mLine - lineNum;
  2676. if (lineOffset == 0)
  2677. {
  2678. foundLine = true;
  2679. auto address = dbgSubprogram->GetLineAddr(*lineData);
  2680. auto subProgram = mDebugTarget->FindSubProgram(address);
  2681. if (subProgram->mNeedLineDataFixup)
  2682. FixupLineDataForSubprogram(subProgram);
  2683. if (subProgram != NULL)
  2684. highestHotIdx = BF_MAX(highestHotIdx, subProgram->mCompileUnit->mDbgModule->mHotIdx);
  2685. if ((foundInSequence) && (subProgram != lastFoundSubprogram))
  2686. foundInSequence = false;
  2687. if ((subProgram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && (address < subProgram->mBlock.mLowPC + sizeof(HotJumpOp)))
  2688. {
  2689. // If this breakpoint ends up on the hot jmp instruction
  2690. continue;
  2691. }
  2692. if (!foundInSequence)
  2693. {
  2694. lastFoundSubprogram = subProgram;
  2695. if ((subProgram != NULL) && (subProgram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && (address == subProgram->mBlock.mLowPC))
  2696. {
  2697. // This instruction is actually the hot jump, we don't need a breakpoint here
  2698. foundInSequence = true;
  2699. continue;
  2700. }
  2701. if (wdBreakpoint->mSrcFile != NULL)
  2702. {
  2703. wdBreakpoint = new WdBreakpoint();
  2704. // Insert at head
  2705. wdBreakpoint->mLinkedSibling = headBreakpoint->mLinkedSibling;
  2706. headBreakpoint->mLinkedSibling = wdBreakpoint;
  2707. wdBreakpoint->mRequestedLineNum = headBreakpoint->mRequestedLineNum;
  2708. wdBreakpoint->mLineNum = headBreakpoint->mLineNum;
  2709. wdBreakpoint->mColumn = headBreakpoint->mColumn;
  2710. wdBreakpoint->mInstrOffset = headBreakpoint->mInstrOffset;
  2711. wdBreakpoint->mIsLinkedSibling = true;
  2712. wdBreakpoint->mHead = headBreakpoint;
  2713. }
  2714. if (wdBreakpoint->mInstrOffset > 0)
  2715. {
  2716. for (int instIdx = 0; instIdx < wdBreakpoint->mInstrOffset; instIdx++)
  2717. {
  2718. CPUInst inst;
  2719. if (!mDebugTarget->DecodeInstruction(address, &inst))
  2720. break;
  2721. address += inst.mSize;
  2722. }
  2723. }
  2724. wdBreakpoint->mSrcFile = ctx.mSrcFile;
  2725. wdBreakpoint->mLineData = DbgLineDataEx(lineData, subProgram);
  2726. wdBreakpoint->mBreakpointType = BreakpointType_User;
  2727. wdBreakpoint->mAddr = address;
  2728. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mStoppedAtAddress == address))
  2729. {
  2730. BfLogDbg("CheckBreakpoint setting mIsAtBreakpointAddress = %p\n", address);
  2731. mDebuggerWaitingThread->mIsAtBreakpointAddress = address;
  2732. }
  2733. BfLogDbg("Breakpoint %p found at %s in %s\n", wdBreakpoint, subProgram->mName, GetFileName(subProgram->mCompileUnit->mDbgModule->mFilePath).c_str());
  2734. mBreakpointAddrMap.ForceAdd(address, wdBreakpoint);
  2735. SetBreakpoint(address);
  2736. foundInSequence = true;
  2737. }
  2738. }
  2739. else
  2740. {
  2741. //TODO: We didn't have this here, but if we don't have this then there are some cases where the method-closing brace generates code in
  2742. // multiple places so we need to ensure this will break on them all
  2743. foundInSequence = false;
  2744. }
  2745. if ((lineOffset >= 0) && (lineOffset <= maxLineDist) && (lineOffset <= bestLineOffset))
  2746. {
  2747. if (lineOffset < bestLineOffset)
  2748. {
  2749. bestLineNum = lineData->mLine;
  2750. bestLineOffset = lineOffset;
  2751. }
  2752. }
  2753. }
  2754. };
  2755. for (int pass = 0; pass < 2; pass++)
  2756. {
  2757. if (lineNum == -1)
  2758. break;
  2759. bestLineNum = -1;
  2760. bestLineOffset = 0x7FFFFFFF;
  2761. if (hotIdx >= 0)
  2762. {
  2763. if (hotIdx >= srcFile->mHotReplacedDbgLineInfo.size())
  2764. return;
  2765. auto hotReplacedLineInfo = srcFile->mHotReplacedDbgLineInfo[hotIdx];
  2766. for (auto& hotReplacedEntry : hotReplacedLineInfo->mEntries)
  2767. {
  2768. _CheckLineInfo(hotReplacedEntry.mSubprogram, hotReplacedEntry.mLineInfo);
  2769. }
  2770. }
  2771. else
  2772. {
  2773. for (auto subprogram : srcFile->mLineDataRefs)
  2774. _CheckLineInfo(subprogram, subprogram->mLineInfo);
  2775. }
  2776. if (foundLine)
  2777. break;
  2778. // Don't allow the breakpoint to be inexactly bound -- only match on pass 0
  2779. if (hotIdx != -1)
  2780. break;
  2781. if (bestLineNum == -1)
  2782. break;
  2783. lineNum = bestLineNum;
  2784. wdBreakpoint->mLineNum = bestLineNum;
  2785. }
  2786. int highestCheckHotIdx = highestHotIdx - 1;
  2787. if (hotIdx != -1)
  2788. highestCheckHotIdx = hotIdx - 1;
  2789. for (int hotFileIdx = highestCheckHotIdx; hotFileIdx >= 0; hotFileIdx--)
  2790. {
  2791. auto& hotReplacedDbgLineData = wdBreakpoint->mSrcFile->mHotReplacedDbgLineInfo;
  2792. // Only try to bind to an old hot version if we haven't unloaded the hot module
  2793. if ((hotFileIdx < (int)hotReplacedDbgLineData.size()) && (hotReplacedDbgLineData[hotFileIdx]->mEntries.size() > 0))
  2794. {
  2795. headBreakpoint->mPendingHotBindIdx = hotFileIdx;
  2796. break;
  2797. }
  2798. }
  2799. }
  2800. void WinDebugger::HotBindBreakpoint(Breakpoint* breakpoint, int lineNum, int hotIdx)
  2801. {
  2802. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  2803. CheckBreakpoint(wdBreakpoint, wdBreakpoint->mSrcFile, lineNum, hotIdx);
  2804. }
  2805. void WinDebugger::CheckBreakpoint(WdBreakpoint* wdBreakpoint)
  2806. {
  2807. if (!mGotStartupEvent)
  2808. return;
  2809. if (wdBreakpoint->mThreadId == 0) // Not bound to threadId yet...
  2810. {
  2811. return;
  2812. }
  2813. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  2814. {
  2815. if (wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap != 0)
  2816. return;
  2817. if (mFreeMemoryBreakIndices.size() == 0)
  2818. return;
  2819. if ((IsInRunState()) || (mActiveThread == NULL))
  2820. return;
  2821. int wantBytes[4];
  2822. int wantBindCount = 0;
  2823. int bytesLeft = wdBreakpoint->mMemoryBreakpointInfo->mByteCount;
  2824. addr_target curAddr = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress;
  2825. while (bytesLeft > 0)
  2826. {
  2827. if (wantBindCount >= mFreeMemoryBreakIndices.size())
  2828. return;
  2829. int curByteCount = 1;
  2830. #ifdef BF_DBG_64
  2831. if ((bytesLeft >= 8) && ((curAddr & 7) == 0))
  2832. curByteCount = 8;
  2833. else
  2834. #endif
  2835. if ((bytesLeft >= 4) && ((curAddr & 3) == 0))
  2836. curByteCount = 4;
  2837. else if ((bytesLeft >= 2) && ((curAddr & 1) == 0))
  2838. curByteCount = 2;
  2839. wantBytes[wantBindCount++] = curByteCount;
  2840. bytesLeft -= curByteCount;
  2841. curAddr += curByteCount;
  2842. }
  2843. addr_target curOfs = 0;
  2844. for (int i = 0; i < wantBindCount; i++)
  2845. {
  2846. int memoryBreakIdx = mFreeMemoryBreakIndices.back();
  2847. mFreeMemoryBreakIndices.pop_back();
  2848. mMemoryBreakpoints[memoryBreakIdx].mBreakpoint = wdBreakpoint;
  2849. mMemoryBreakpoints[memoryBreakIdx].mAddress = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress + curOfs;
  2850. mMemoryBreakpoints[memoryBreakIdx].mByteCount = wantBytes[i];
  2851. mMemoryBreakpoints[memoryBreakIdx].mOfs = curOfs;
  2852. curOfs += wantBytes[i];
  2853. mMemoryBreakpointVersion++;
  2854. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap |= 1<<memoryBreakIdx;
  2855. }
  2856. UpdateThreadDebugRegisters();
  2857. }
  2858. if (wdBreakpoint->mAddr != 0)
  2859. return;
  2860. if (!wdBreakpoint->mSymbolName.IsEmpty())
  2861. {
  2862. auto headBreakpoint = wdBreakpoint->GetHeadBreakpoint();
  2863. String symbolName = wdBreakpoint->mSymbolName;
  2864. bool onlyBindFirst = false;
  2865. if (symbolName.StartsWith("-"))
  2866. {
  2867. symbolName.Remove(0);
  2868. onlyBindFirst = true;
  2869. }
  2870. for (auto dbgModule : mDebugTarget->mDbgModules)
  2871. {
  2872. dbgModule->ParseSymbolData();
  2873. addr_target targetAddr = -1;
  2874. auto entry = dbgModule->mSymbolNameMap.Find(symbolName.c_str());
  2875. if (entry != NULL)
  2876. {
  2877. DbgSymbol* dwSymbol = entry->mValue;
  2878. targetAddr = dwSymbol->mAddress;
  2879. }
  2880. if (targetAddr == -1)
  2881. {
  2882. if (symbolName == ".")
  2883. {
  2884. targetAddr = mDebugTarget->mLaunchBinary->mImageBase + mDebugTarget->mLaunchBinary->mEntryPoint;
  2885. onlyBindFirst = true;
  2886. }
  2887. }
  2888. if (targetAddr != -1)
  2889. {
  2890. if (wdBreakpoint->mAddr == 0)
  2891. {
  2892. wdBreakpoint->mAddr = targetAddr;
  2893. wdBreakpoint->mBreakpointType = BreakpointType_User;
  2894. mBreakpointAddrMap.ForceAdd(wdBreakpoint->mAddr, wdBreakpoint);
  2895. SetBreakpoint(wdBreakpoint->mAddr);
  2896. }
  2897. else
  2898. {
  2899. wdBreakpoint = new WdBreakpoint();
  2900. // Insert at head
  2901. wdBreakpoint->mLinkedSibling = headBreakpoint->mLinkedSibling;
  2902. headBreakpoint->mLinkedSibling = wdBreakpoint;
  2903. wdBreakpoint->mSymbolName = headBreakpoint->mSymbolName;
  2904. wdBreakpoint->mIsLinkedSibling = true;
  2905. wdBreakpoint->mHead = headBreakpoint;
  2906. }
  2907. if (onlyBindFirst)
  2908. break;
  2909. }
  2910. }
  2911. return;
  2912. }
  2913. BP_ZONE("WinDebugger::CheckBreakpoint");
  2914. // Rehup if we load a DLL that also uses this file we bound to (thus the mDeferredRefs check)
  2915. if (wdBreakpoint->mSrcFile == NULL)
  2916. {
  2917. DbgSrcFile* srcFile = mDebugTarget->GetSrcFile(wdBreakpoint->mFilePath);
  2918. if (srcFile == NULL)
  2919. return;
  2920. for (auto& deferredSrcFileRef : srcFile->mDeferredRefs)
  2921. {
  2922. deferredSrcFileRef.mDbgModule->ParseCompileUnit(deferredSrcFileRef.mCompileUnitId);
  2923. }
  2924. srcFile->mDeferredRefs.Clear();
  2925. CheckBreakpoint(wdBreakpoint, srcFile, wdBreakpoint->mRequestedLineNum, -1);
  2926. }
  2927. }
  2928. bool WinDebugger::IsMemoryBreakpointSizeValid(addr_target addr, int size)
  2929. {
  2930. int wantBindCount = 0;
  2931. int bytesLeft = size;
  2932. addr_target curAddr = addr;
  2933. for (int i = 0; i < 4; i++)
  2934. {
  2935. int curByteCount = 1;
  2936. #ifdef BF_DBG_64
  2937. if ((bytesLeft >= 8) && ((curAddr & 7) == 0))
  2938. curByteCount = 8;
  2939. else
  2940. #endif
  2941. if ((bytesLeft >= 4) && ((curAddr & 3) == 0))
  2942. curByteCount = 4;
  2943. else if ((bytesLeft >= 2) && ((curAddr & 1) == 0))
  2944. curByteCount = 2;
  2945. bytesLeft -= curByteCount;
  2946. curAddr += curByteCount;
  2947. if (bytesLeft == 0)
  2948. return true;
  2949. }
  2950. return false;
  2951. }
  2952. bool WinDebugger::HasMemoryBreakpoint(addr_target addr, int size)
  2953. {
  2954. for (int i = 0; i < 4; i++)
  2955. {
  2956. if ((mMemoryBreakpoints[i].mAddress == addr) &&
  2957. (mMemoryBreakpoints[i].mOfs == 0) &&
  2958. (mMemoryBreakpoints[i].mBreakpoint->mMemoryBreakpointInfo->mByteCount == size))
  2959. return true;
  2960. }
  2961. return false;
  2962. }
  2963. Breakpoint* WinDebugger::CreateBreakpoint(const StringImpl& fileName, int lineNum, int wantColumn, int instrOffset)
  2964. {
  2965. AutoCrit autoCrit(mDebugManager->mCritSect);
  2966. BfLogDbg("CreateBreakpoint %s %d %d\n", fileName.c_str(), lineNum, wantColumn);
  2967. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  2968. wdBreakpoint->mFilePath = FixPathAndCase(fileName);
  2969. wdBreakpoint->mRequestedLineNum = lineNum;
  2970. wdBreakpoint->mLineNum = lineNum;
  2971. wdBreakpoint->mColumn = wantColumn;
  2972. wdBreakpoint->mInstrOffset = instrOffset;
  2973. mBreakpoints.push_back(wdBreakpoint);
  2974. BfLogDbg("CreateBreakpoint Created %p\n", wdBreakpoint);
  2975. return wdBreakpoint;
  2976. }
  2977. void WinDebugger::CheckBreakpoint(Breakpoint* checkBreakpoint)
  2978. {
  2979. AutoCrit autoCrit(mDebugManager->mCritSect);
  2980. CheckBreakpoint((WdBreakpoint*)checkBreakpoint);
  2981. }
  2982. Breakpoint* WinDebugger::CreateMemoryBreakpoint(intptr addr, int byteCount)
  2983. {
  2984. AutoCrit autoCrit(mDebugManager->mCritSect);
  2985. BfLogDbg("CreateMemoryBreakpoint %p %d\n", addr, byteCount);
  2986. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  2987. WdMemoryBreakpointInfo* memoryBreakInfo = new WdMemoryBreakpointInfo();
  2988. memoryBreakInfo->mMemoryAddress = addr;
  2989. memoryBreakInfo->mByteCount = byteCount;
  2990. wdBreakpoint->mMemoryBreakpointInfo = memoryBreakInfo;
  2991. mBreakpoints.push_back(wdBreakpoint);
  2992. CheckBreakpoint(wdBreakpoint);
  2993. return wdBreakpoint;
  2994. }
  2995. Breakpoint* WinDebugger::CreateSymbolBreakpoint(const StringImpl& symbolName)
  2996. {
  2997. AutoCrit autoCrit(mDebugManager->mCritSect);
  2998. BfLogDbg("CreateSymbolBreakpoint %s\n", symbolName.c_str());
  2999. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  3000. wdBreakpoint->mSymbolName = symbolName;
  3001. mBreakpoints.push_back(wdBreakpoint);
  3002. CheckBreakpoint(wdBreakpoint);
  3003. return wdBreakpoint;
  3004. }
  3005. Breakpoint* WinDebugger::CreateAddressBreakpoint(intptr inAddress)
  3006. {
  3007. AutoCrit autoCrit(mDebugManager->mCritSect);
  3008. BfLogDbg("CreateAddressBreakpoint %p\n", inAddress);
  3009. addr_target address = (addr_target)inAddress;
  3010. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  3011. wdBreakpoint->mAddr = address;
  3012. mBreakpointAddrMap.ForceAdd(wdBreakpoint->mAddr, wdBreakpoint);
  3013. SetBreakpoint(address);
  3014. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mStoppedAtAddress == address))
  3015. {
  3016. BfLogDbg("CreateAddressBreakpoint setting mIsAtBreakpointAddress = %p\n", address);
  3017. mDebuggerWaitingThread->mIsAtBreakpointAddress = address;
  3018. }
  3019. mBreakpoints.push_back(wdBreakpoint);
  3020. return wdBreakpoint;
  3021. }
  3022. void WinDebugger::DeleteBreakpoint(Breakpoint* breakpoint)
  3023. {
  3024. AutoCrit autoCrit(mDebugManager->mCritSect);
  3025. if (breakpoint == mActiveBreakpoint)
  3026. mActiveBreakpoint = NULL;
  3027. BfLogDbg("WinDebugger::DeleteBreakpoint %p Count:%d\n", breakpoint, mBreakpoints.size());
  3028. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3029. if (wdBreakpoint->mCondition != NULL)
  3030. {
  3031. if (!wdBreakpoint->mIsLinkedSibling)
  3032. delete wdBreakpoint->mCondition;
  3033. }
  3034. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  3035. {
  3036. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  3037. {
  3038. if (mMemoryBreakpoints[memoryWatchSlot].mBreakpoint == wdBreakpoint)
  3039. {
  3040. mFreeMemoryBreakIndices.push_back(memoryWatchSlot);
  3041. mMemoryBreakpoints[memoryWatchSlot] = WdMemoryBreakpointBind();
  3042. mMemoryBreakpointVersion++;
  3043. UpdateThreadDebugRegisters();
  3044. }
  3045. }
  3046. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap = 0;
  3047. }
  3048. if (wdBreakpoint->mAddr != 0)
  3049. {
  3050. mBreakpointAddrMap.Remove(wdBreakpoint->mAddr, wdBreakpoint);
  3051. RemoveBreakpoint(wdBreakpoint->mAddr);
  3052. for (auto thread : mThreadList)
  3053. {
  3054. if (thread->mIsAtBreakpointAddress == wdBreakpoint->mAddr)
  3055. thread->mIsAtBreakpointAddress = NULL;
  3056. if (thread->mBreakpointAddressContinuing == wdBreakpoint->mAddr)
  3057. thread->mBreakpointAddressContinuing = NULL;
  3058. }
  3059. }
  3060. if (!wdBreakpoint->mIsLinkedSibling)
  3061. {
  3062. mBreakpoints.Remove(wdBreakpoint);
  3063. }
  3064. if (wdBreakpoint->mLinkedSibling != NULL)
  3065. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  3066. delete wdBreakpoint;
  3067. }
  3068. void WinDebugger::DetachBreakpoint(Breakpoint* breakpoint)
  3069. {
  3070. AutoCrit autoCrit(mDebugManager->mCritSect);
  3071. BfLogDbg("WinDebugger::DetachBreakpoint %p\n", breakpoint);
  3072. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3073. if (wdBreakpoint->mAddr != 0)
  3074. {
  3075. mBreakpointAddrMap.Remove(wdBreakpoint->mAddr, wdBreakpoint);
  3076. RemoveBreakpoint(wdBreakpoint->mAddr);
  3077. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mIsAtBreakpointAddress == wdBreakpoint->mAddr))
  3078. mDebuggerWaitingThread->mIsAtBreakpointAddress = NULL;
  3079. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mBreakpointAddressContinuing == wdBreakpoint->mAddr))
  3080. mDebuggerWaitingThread->mBreakpointAddressContinuing = NULL;
  3081. wdBreakpoint->mLineData = DbgLineDataEx();
  3082. wdBreakpoint->mAddr = 0;
  3083. }
  3084. if (wdBreakpoint->mCondition != NULL)
  3085. {
  3086. delete wdBreakpoint->mCondition->mDbgEvaluationContext;
  3087. wdBreakpoint->mCondition->mDbgEvaluationContext = NULL;
  3088. }
  3089. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  3090. {
  3091. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  3092. {
  3093. if (mMemoryBreakpoints[memoryWatchSlot].mBreakpoint == wdBreakpoint)
  3094. {
  3095. mFreeMemoryBreakIndices.push_back(memoryWatchSlot);
  3096. mMemoryBreakpoints[memoryWatchSlot] = WdMemoryBreakpointBind();
  3097. mMemoryBreakpointVersion++;
  3098. UpdateThreadDebugRegisters();
  3099. }
  3100. }
  3101. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap = 0;
  3102. }
  3103. if (wdBreakpoint->mLinkedSibling != NULL)
  3104. {
  3105. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  3106. wdBreakpoint->mLinkedSibling = NULL;
  3107. }
  3108. wdBreakpoint->mSrcFile = NULL;
  3109. wdBreakpoint->mPendingHotBindIdx = -1;
  3110. }
  3111. void WinDebugger::MoveBreakpoint(Breakpoint* breakpoint, int lineNum, int wantColumn, bool rebindNow)
  3112. {
  3113. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3114. AutoCrit autoCrit(mDebugManager->mCritSect);
  3115. DetachBreakpoint(wdBreakpoint);
  3116. //TODO: This doesn't actually rebind correctly while the app is running
  3117. if ((lineNum != -1) && (wantColumn != -1))
  3118. {
  3119. wdBreakpoint->mRequestedLineNum = lineNum;
  3120. wdBreakpoint->mLineNum = lineNum;
  3121. wdBreakpoint->mColumn = wantColumn;
  3122. }
  3123. if (rebindNow)
  3124. CheckBreakpoint(wdBreakpoint);
  3125. }
  3126. void WinDebugger::MoveMemoryBreakpoint(Breakpoint* breakpoint, intptr addr, int byteCount)
  3127. {
  3128. AutoCrit autoCrit(mDebugManager->mCritSect);
  3129. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3130. DetachBreakpoint(wdBreakpoint);
  3131. wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress = addr;
  3132. wdBreakpoint->mMemoryBreakpointInfo->mByteCount = byteCount;
  3133. CheckBreakpoint(wdBreakpoint);
  3134. }
  3135. void WinDebugger::DisableBreakpoint(Breakpoint* breakpoint)
  3136. {
  3137. AutoCrit autoCrit(mDebugManager->mCritSect);
  3138. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3139. DetachBreakpoint(wdBreakpoint);
  3140. delete wdBreakpoint->mMemoryBreakpointInfo;
  3141. wdBreakpoint->mMemoryBreakpointInfo = NULL;
  3142. }
  3143. void WinDebugger::SetBreakpointCondition(Breakpoint* breakpoint, const StringImpl& conditionExpr)
  3144. {
  3145. AutoCrit autoCrit(mDebugManager->mCritSect);
  3146. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3147. BF_ASSERT(!wdBreakpoint->mIsLinkedSibling);
  3148. if (conditionExpr.empty())
  3149. {
  3150. delete wdBreakpoint->mCondition;
  3151. WdBreakpoint* curBreakpoint = wdBreakpoint;
  3152. wdBreakpoint->mCondition = NULL;
  3153. }
  3154. else
  3155. {
  3156. delete wdBreakpoint->mCondition;
  3157. auto condition = new WdBreakpointCondition();
  3158. condition->mExpr = conditionExpr;
  3159. wdBreakpoint->mCondition = condition;
  3160. }
  3161. }
  3162. void WinDebugger::SetBreakpointLogging(Breakpoint* breakpoint, const StringImpl& logging, bool breakAfterLogging)
  3163. {
  3164. AutoCrit autoCrit(mDebugManager->mCritSect);
  3165. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3166. BF_ASSERT(!wdBreakpoint->mIsLinkedSibling);
  3167. wdBreakpoint->mLogging = logging;
  3168. wdBreakpoint->mBreakAfterLogging = breakAfterLogging;
  3169. }
  3170. bool WinDebugger::CheckConditionalBreakpoint(WdBreakpoint* breakpoint, DbgSubprogram* dbgSubprogram, addr_target pcAddress)
  3171. {
  3172. // What was this assertion for?
  3173. //BF_ASSERT(mCallStack.size() == 0);
  3174. auto headBreakpoint = breakpoint->GetHeadBreakpoint();
  3175. if (headBreakpoint->mThreadId != -1)
  3176. {
  3177. if ((mActiveThread != NULL) && (mActiveThread->mThreadId != headBreakpoint->mThreadId))
  3178. return false;
  3179. }
  3180. auto _SplitExpr = [&](const StringImpl& expr, StringImpl& outExpr, StringImpl& outSubject)
  3181. {
  3182. int crPos = expr.IndexOf('\n');
  3183. if (crPos != -1)
  3184. {
  3185. outExpr += expr.Substring(0, crPos);
  3186. outSubject += expr.Substring(crPos + 1);
  3187. }
  3188. else
  3189. {
  3190. outExpr += expr;
  3191. }
  3192. };
  3193. if (headBreakpoint->mCondition != NULL)
  3194. {
  3195. ClearCallStack();
  3196. auto conditional = headBreakpoint->mCondition;
  3197. if (conditional->mDbgEvaluationContext == NULL)
  3198. {
  3199. CPURegisters registers;
  3200. PopulateRegisters(&registers);
  3201. auto pcAddress = registers.GetPC();
  3202. DbgSubprogram* subprogram = mDebugTarget->FindSubProgram(pcAddress);
  3203. if (subprogram == NULL)
  3204. {
  3205. return false;
  3206. }
  3207. StringT<256> expr;
  3208. StringT<256> subjectExpr;
  3209. if (breakpoint->mMemoryBreakpointInfo != NULL)
  3210. {
  3211. subjectExpr += "*";
  3212. }
  3213. _SplitExpr(conditional->mExpr, expr, subjectExpr);
  3214. DbgLanguage language = DbgLanguage_Unknown;
  3215. if (expr.StartsWith("@Beef:"))
  3216. {
  3217. expr.Remove(0, 6);
  3218. language = DbgLanguage_Beef;
  3219. }
  3220. else if (expr.StartsWith("@C:"))
  3221. {
  3222. expr.Remove(0, 3);
  3223. language = DbgLanguage_C;
  3224. }
  3225. conditional->mDbgEvaluationContext = new DbgEvaluationContext(this, subprogram->mCompileUnit->mDbgModule, expr);
  3226. if (language != DbgLanguage_Unknown)
  3227. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mLanguage = language;
  3228. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mSubjectExpr = subjectExpr;
  3229. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mDbgCompileUnit = subprogram->mCompileUnit;
  3230. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mCallStackIdx = 0;
  3231. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mExpressionFlags = (DwEvalExpressionFlags)(DwEvalExpressionFlag_AllowSideEffects);
  3232. }
  3233. WdStackFrame* wdStackFrame = new WdStackFrame();
  3234. PopulateRegisters(&wdStackFrame->mRegisters);
  3235. mCallStack.Add(wdStackFrame);
  3236. DbgTypedValue result = conditional->mDbgEvaluationContext->EvaluateInContext(DbgTypedValue());
  3237. ClearCallStack();
  3238. if ((result.mType != NULL) && (result.mType->mTypeCode == DbgType_Bitfield))
  3239. result.mType = result.mType->mTypeParam;
  3240. if (conditional->mDbgEvaluationContext->mPassInstance->HasFailed())
  3241. {
  3242. String errorStr = "FAILED";
  3243. for (auto error : conditional->mDbgEvaluationContext->mPassInstance->mErrors)
  3244. {
  3245. if (!error->mIsWarning)
  3246. errorStr = error->mError;
  3247. }
  3248. String condError = StrFormat("error Conditional breakpoint expression '%s' failed: %s", conditional->mExpr.c_str(), errorStr.c_str());
  3249. mDebugManager->mOutMessages.push_back(condError);
  3250. return true;
  3251. }
  3252. else if (conditional->mDbgEvaluationContext->mDbgExprEvaluator->mBlockedSideEffects)
  3253. {
  3254. mDebugManager->mOutMessages.push_back(StrFormat("error Conditional breakpoint expression '%s' contained function calls, which is not allowed", conditional->mExpr.c_str()));
  3255. return true;
  3256. }
  3257. else if ((!result) || (!result.mType->IsBoolean()))
  3258. {
  3259. mDebugManager->mOutMessages.push_back(StrFormat("error Conditional breakpoint expression '%s' must result in a boolean value", conditional->mExpr.c_str()));
  3260. return true;
  3261. }
  3262. else if (!result.mBool)
  3263. return false;
  3264. }
  3265. headBreakpoint->mHitCount++;
  3266. switch (headBreakpoint->mHitCountBreakKind)
  3267. {
  3268. case DbgHitCountBreakKind_Equals:
  3269. if (headBreakpoint->mHitCount != headBreakpoint->mTargetHitCount)
  3270. return false;
  3271. break;
  3272. case DbgHitCountBreakKind_GreaterEquals:
  3273. if (headBreakpoint->mHitCount < headBreakpoint->mTargetHitCount)
  3274. return false;
  3275. break;
  3276. case DbgHitCountBreakKind_Multiple:
  3277. if ((headBreakpoint->mHitCount % headBreakpoint->mTargetHitCount) != 0)
  3278. return false;
  3279. break;
  3280. }
  3281. mActiveBreakpoint = breakpoint;
  3282. mBreakStackFrameIdx = -1;
  3283. if (!headBreakpoint->mLogging.IsEmpty())
  3284. {
  3285. ClearCallStack();
  3286. DwFormatInfo formatInfo;
  3287. formatInfo.mCallStackIdx = 0;
  3288. DbgCompileUnit* dbgCompileUnit = NULL;
  3289. if (dbgSubprogram == NULL)
  3290. dbgSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3291. if (dbgSubprogram != NULL)
  3292. {
  3293. dbgCompileUnit = dbgSubprogram->mCompileUnit;
  3294. formatInfo.mLanguage = dbgSubprogram->GetLanguage();
  3295. }
  3296. auto prevRunState = mRunState;
  3297. mRunState = RunState_Paused; // We need to be paused to avoid certain errors in the eval
  3298. String displayString;
  3299. String expr;
  3300. _SplitExpr(headBreakpoint->mLogging, expr, formatInfo.mSubjectExpr);
  3301. if (expr.StartsWith("@Beef:"))
  3302. {
  3303. expr.Remove(0, 6);
  3304. formatInfo.mLanguage = DbgLanguage_Beef;
  3305. }
  3306. else if (expr.StartsWith("@C:"))
  3307. {
  3308. expr.Remove(0, 3);
  3309. formatInfo.mLanguage = DbgLanguage_C;
  3310. }
  3311. ProcessEvalString(dbgCompileUnit, DbgTypedValue(), expr, displayString, formatInfo, NULL, false);
  3312. mRunState = prevRunState;
  3313. displayString.Insert(0, "log ");
  3314. displayString.Append("\n");
  3315. mDebugManager->mOutMessages.push_back(displayString);
  3316. if (!headBreakpoint->mBreakAfterLogging)
  3317. return false;
  3318. }
  3319. return true;
  3320. }
  3321. void WinDebugger::CleanupDebugEval(bool restoreRegisters)
  3322. {
  3323. BfLogDbg("CleanupDebugEval ThreadId=%d\n", mDebugEvalThreadInfo.mThreadId);
  3324. WdThreadInfo* evalThreadInfo = NULL;
  3325. if (mThreadMap.TryGetValue(mDebugEvalThreadInfo.mThreadId, &evalThreadInfo))
  3326. {
  3327. if ((restoreRegisters) && (!mDbgBreak))
  3328. {
  3329. SetAndRestoreValue<WdThreadInfo*> activeThread(mActiveThread, evalThreadInfo);
  3330. RestoreAllRegisters();
  3331. // if (mRunState == RunState_Running_ToTempBreakpoint)
  3332. // mRunState = RunState_Paused;
  3333. }
  3334. evalThreadInfo->mStartSP = mDebugEvalThreadInfo.mStartSP;
  3335. evalThreadInfo->mStoppedAtAddress = mDebugEvalThreadInfo.mStoppedAtAddress;
  3336. evalThreadInfo->mIsAtBreakpointAddress = mDebugEvalThreadInfo.mIsAtBreakpointAddress;
  3337. evalThreadInfo->mBreakpointAddressContinuing = mDebugEvalThreadInfo.mBreakpointAddressContinuing;
  3338. }
  3339. delete mDebugPendingExpr;
  3340. mDebugPendingExpr = NULL;
  3341. mDebugEvalThreadInfo = WdThreadInfo();
  3342. OutputRawMessage("rehupLoc");
  3343. }
  3344. bool WinDebugger::FixCallStackIdx(int& callStackIdx)
  3345. {
  3346. callStackIdx = BF_MAX(callStackIdx, 0);
  3347. if (mCallStack.IsEmpty())
  3348. UpdateCallStack();
  3349. int stackSize = (int)mCallStack.size();
  3350. while (callStackIdx >= mCallStack.size())
  3351. {
  3352. UpdateCallStack();
  3353. if (stackSize == (int)mCallStack.size())
  3354. break; // Didn't change
  3355. stackSize = (int)mCallStack.size();
  3356. }
  3357. if (callStackIdx >= stackSize)
  3358. {
  3359. callStackIdx = 0;
  3360. return false;
  3361. }
  3362. return true;
  3363. }
  3364. bool WinDebugger::HasLineInfoAt(addr_target address)
  3365. {
  3366. BP_ZONE("WinDebugger::HasLineInfoAt");
  3367. DbgSubprogram* dbgSubprogram = NULL;
  3368. auto dwLineData = FindLineDataAtAddress(address, &dbgSubprogram);
  3369. return (dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dbgSubprogram->GetLineAddr(*dwLineData) == address);
  3370. }
  3371. void WinDebugger::StepLineTryPause(addr_target address, bool requireExactMatch)
  3372. {
  3373. if (mStepInAssembly)
  3374. return;
  3375. if (mStepLineData.mLineData != NULL)
  3376. {
  3377. DbgSubprogram* dbgSubprogram = NULL;
  3378. DbgSrcFile* dbgSrcFile = NULL;
  3379. auto dwLineData = FindLineDataAtAddress(address, &dbgSubprogram, &dbgSrcFile);
  3380. if ((dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && ((!requireExactMatch) || (dbgSubprogram->GetLineAddr(*dwLineData) == address)))
  3381. {
  3382. // "Invalid" line
  3383. if (dwLineData->mColumn == -1)
  3384. {
  3385. SetupStep(mStepType);
  3386. mRunState = RunState_Running;
  3387. return;
  3388. }
  3389. // If we're on the same line but a different column or a <= address then keep it keep looking
  3390. if ((dbgSrcFile == mStepLineData.GetSrcFile()) &&
  3391. ((!requireExactMatch) || (dwLineData != mStepLineData.mLineData) || (address <= mStepStartPC)) &&
  3392. (dwLineData->mLine == mStepLineData.mLineData->mLine))
  3393. {
  3394. SetupStep(mStepType);
  3395. mRunState = RunState_Running;
  3396. return;
  3397. }
  3398. }
  3399. }
  3400. mRunState = RunState_Paused;
  3401. }
  3402. void WinDebugger::BreakAll()
  3403. {
  3404. AutoCrit autoCrit(mDebugManager->mCritSect);
  3405. ::DebugBreakProcess(mProcessInfo.hProcess);
  3406. }
  3407. void WinDebugger::StepInto(bool inAssembly)
  3408. {
  3409. AutoCrit autoCrit(mDebugManager->mCritSect);
  3410. if (!TryRunContinue())
  3411. return;
  3412. BfLogDbg("StepInto\n");
  3413. mCurNoInfoStepTries = 0; // Reset
  3414. mStepInAssembly = inAssembly;
  3415. SetupStep(StepType_StepInto);
  3416. ContinueDebugEvent();
  3417. }
  3418. void WinDebugger::StepIntoSpecific(intptr inAddr)
  3419. {
  3420. addr_target addr = (addr_target)inAddr;
  3421. AutoCrit autoCrit(mDebugManager->mCritSect);
  3422. if (!TryRunContinue())
  3423. return;
  3424. BfLogDbg("StepIntoSpecific %p\n", addr);
  3425. mCurNoInfoStepTries = 0; // Reset
  3426. mStepInAssembly = false;
  3427. SetupStep(StepType_StepInto);
  3428. mIsStepIntoSpecific = true;
  3429. mStepType = StepType_StepInto_Unfiltered;
  3430. if (mStepStartPC != addr)
  3431. {
  3432. RemoveTempBreakpoints();
  3433. SetTempBreakpoint(addr);
  3434. mStepBreakpointAddrs.push_back(addr);
  3435. }
  3436. ContinueDebugEvent();
  3437. }
  3438. void WinDebugger::PushValue(CPURegisters* registers, int64 val)
  3439. {
  3440. addr_target* regSP = registers->GetSPRegisterRef();
  3441. *regSP -= sizeof(addr_target);
  3442. WriteMemory<addr_target>(*regSP, (addr_target)val);
  3443. }
  3444. void WinDebugger::PushValue(CPURegisters* registers, const DbgTypedValue& typedValue)
  3445. {
  3446. addr_target* regSP = registers->GetSPRegisterRef();
  3447. int byteCount = typedValue.mType->GetByteCount();
  3448. if ((byteCount == 8) || (sizeof(addr_target) == 8))
  3449. {
  3450. *regSP -= sizeof(int64);
  3451. addr_target val = typedValue.mInt64;
  3452. if (typedValue.mType->IsCompositeType())
  3453. val = typedValue.mSrcAddress;
  3454. WriteMemory<int64>(*regSP, val);
  3455. }
  3456. else
  3457. {
  3458. *regSP -= sizeof(int32);
  3459. addr_target val = typedValue.mInt32;
  3460. if (typedValue.mType->IsCompositeType())
  3461. val = typedValue.mSrcAddress;
  3462. WriteMemory<int32>(*regSP, val);
  3463. }
  3464. }
  3465. void WinDebugger::SetThisRegister(CPURegisters* registers, addr_target val)
  3466. {
  3467. #if BF_DBG_32
  3468. registers->mIntRegs.ecx = val;
  3469. #else
  3470. registers->mIntRegs.rcx = val;
  3471. #endif
  3472. }
  3473. void WinDebugger::AddParamValue(int paramIdx, bool hadThis, CPURegisters* registers, const DbgTypedValue& typedValue)
  3474. {
  3475. #if BF_DBG_32
  3476. PushValue(registers, typedValue);
  3477. #else
  3478. int regIdx = paramIdx + (hadThis ? 1 : 0);
  3479. if (typedValue.mType->IsFloat())
  3480. {
  3481. PushValue(registers, typedValue);
  3482. if (regIdx < 4)
  3483. {
  3484. if (typedValue.mType->mTypeCode == DbgType_Single)
  3485. {
  3486. registers->mXmmRegsArray[regIdx].f[0] = typedValue.mSingle;
  3487. }
  3488. else
  3489. {
  3490. registers->mXmmDRegsArray[regIdx].d[0] = typedValue.mDouble;
  3491. }
  3492. }
  3493. }
  3494. else
  3495. {
  3496. PushValue(registers, typedValue);
  3497. if (regIdx < 4)
  3498. {
  3499. int64 val;
  3500. if (typedValue.mType->IsCompositeType())
  3501. val = typedValue.mSrcAddress;
  3502. else
  3503. val = typedValue.mPtr;
  3504. if (regIdx == 0)
  3505. registers->mIntRegs.rcx = val;
  3506. else if (regIdx == 1)
  3507. registers->mIntRegs.rdx = val;
  3508. else if (regIdx == 2)
  3509. registers->mIntRegs.r8 = val;
  3510. else if (regIdx == 3)
  3511. registers->mIntRegs.r9 = val;
  3512. }
  3513. }
  3514. #endif
  3515. }
  3516. bool WinDebugger::CheckNeedsSRetArgument(DbgType* retType)
  3517. {
  3518. if (!retType->IsCompositeType())
  3519. return false;
  3520. if (retType->GetByteCount() == 0)
  3521. return false;
  3522. //TODO: Change when we change the calling convention
  3523. if (retType->GetLanguage() == DbgLanguage_Beef)
  3524. return true;
  3525. int retSize = retType->GetByteCount();
  3526. //TODO: Check for 'POD' type?
  3527. if ((retSize == 1) || (retSize == 2) || (retSize == 4) || (retSize == sizeof(addr_target)))
  3528. return false;
  3529. return true;
  3530. }
  3531. DbgTypedValue WinDebugger::ReadReturnValue(CPURegisters* registers, DbgType* type)
  3532. {
  3533. DbgTypedValue retValue;
  3534. if (type->IsFloat())
  3535. {
  3536. retValue.mType = type;
  3537. #if BF_DBG_32
  3538. retValue.mDouble = ConvertFloat80ToDouble(registers->mFpMmRegsArray[0].fp.fp80);
  3539. if (type->mSize == 4)
  3540. retValue.mSingle = (float)retValue.mDouble;
  3541. #else
  3542. if (retValue.mType->mTypeCode == DbgType_Single)
  3543. retValue.mSingle = registers->mXmmRegsArray[0].f[0];
  3544. else
  3545. retValue.mDouble = registers->mXmmDRegsArray[0].d[0];
  3546. #endif
  3547. }
  3548. else if (type->IsCompositeType())
  3549. {
  3550. retValue.mType = type;
  3551. if (CheckNeedsSRetArgument(type))
  3552. {
  3553. #ifdef BF_DBG_32
  3554. retValue.mSrcAddress = mSavedContext.Esp - BF_ALIGN(type->GetByteCount(), 16);
  3555. #else
  3556. retValue.mSrcAddress = mSavedContext.Rsp - BF_ALIGN(type->GetByteCount(), 16);
  3557. #endif
  3558. }
  3559. else
  3560. {
  3561. #ifdef BF_DBG_32
  3562. retValue.mInt32 = mSavedContext.Eax;
  3563. #else
  3564. retValue.mInt64 = mSavedContext.Rax;
  3565. #endif
  3566. }
  3567. }
  3568. else
  3569. {
  3570. #ifdef BF_DBG_32
  3571. retValue.mType = type;
  3572. retValue.mInt32 = registers->mIntRegs.eax;
  3573. if (type->mSize == 8)
  3574. (&retValue.mInt32)[1] = registers->mIntRegs.edx;
  3575. #else
  3576. retValue.mType = type;
  3577. retValue.mInt64 = registers->mIntRegs.rax;
  3578. #endif
  3579. return retValue;
  3580. }
  3581. return retValue;
  3582. }
  3583. bool WinDebugger::SetRegisters(CPURegisters* registers)
  3584. {
  3585. BF_CONTEXT lcContext;
  3586. lcContext.ContextFlags = BF_CONTEXT_CONTROL | BF_CONTEXT_INTEGER | BF_CONTEXT_FLOATING_POINT | BF_CONTEXT_EXTENDED_REGISTERS | BF_CONTEXT_SEGMENTS;
  3587. lcContext.ContextFlags |= BF_CONTEXT_EXCEPTION_REQUEST;
  3588. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  3589. #ifdef BF_DBG_32
  3590. lcContext.Eax = registers->mIntRegs.eax;
  3591. lcContext.Ecx = registers->mIntRegs.ecx;
  3592. lcContext.Edx = registers->mIntRegs.edx;
  3593. lcContext.Ebx = registers->mIntRegs.ebx;
  3594. lcContext.Esp = registers->mIntRegs.esp;
  3595. lcContext.Ebp = registers->mIntRegs.ebp;
  3596. lcContext.Esi = registers->mIntRegs.esi;
  3597. lcContext.Edi = registers->mIntRegs.edi;
  3598. lcContext.Eip = registers->mIntRegs.eip;
  3599. lcContext.EFlags = registers->mIntRegs.efl;
  3600. BF_ASSERT(sizeof(lcContext.FloatSave.RegisterArea) == sizeof(registers->mFpMmRegsArray));
  3601. memcpy(lcContext.FloatSave.RegisterArea, registers->mFpMmRegsArray, sizeof(lcContext.FloatSave.RegisterArea));
  3602. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 32*sizeof(float));
  3603. memcpy(&lcContext.ExtendedRegisters[160], registers->mXmmRegsArray, sizeof(registers->mXmmRegsArray));
  3604. #else
  3605. lcContext.Rax = registers->mIntRegs.rax;
  3606. lcContext.Rcx = registers->mIntRegs.rcx;
  3607. lcContext.Rdx = registers->mIntRegs.rdx;
  3608. lcContext.Rbx = registers->mIntRegs.rbx;
  3609. lcContext.Rsp = registers->mIntRegs.rsp;
  3610. lcContext.Rbp = registers->mIntRegs.rbp;
  3611. lcContext.Rsi = registers->mIntRegs.rsi;
  3612. lcContext.Rdi = registers->mIntRegs.rdi;
  3613. lcContext.Rip = registers->mIntRegs.rip;
  3614. lcContext.EFlags = (DWORD)registers->mIntRegs.efl;
  3615. lcContext.R8 = registers->mIntRegs.r8;
  3616. lcContext.R9 = registers->mIntRegs.r9;
  3617. lcContext.R10 = registers->mIntRegs.r10;
  3618. lcContext.R11 = registers->mIntRegs.r11;
  3619. lcContext.R12 = registers->mIntRegs.r12;
  3620. lcContext.R13 = registers->mIntRegs.r13;
  3621. lcContext.R14 = registers->mIntRegs.r14;
  3622. lcContext.R15 = registers->mIntRegs.r15;
  3623. for (int i = 0; i < 8; i++)
  3624. {
  3625. memcpy(&lcContext.FltSave.FloatRegisters[i], &registers->mFpMmRegsArray[i], 10);
  3626. }
  3627. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 64 * sizeof(float));
  3628. memcpy(BF_CONTEXT_XMMDATA(lcContext), registers->mXmmRegsArray, sizeof(registers->mXmmRegsArray));
  3629. #endif
  3630. //lcContext.ContextFlags |= BF_CONTEXT_EXCEPTION_REQUEST;
  3631. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  3632. return (lcContext.ContextFlags & (BF_CONTEXT_EXCEPTION_ACTIVE | BF_CONTEXT_SERVICE_ACTIVE)) == 0;
  3633. }
  3634. void WinDebugger::SaveAllRegisters()
  3635. {
  3636. BfLogDbg("SaveAllRegisters setting mSavedAtBreakpointAddress = %p\n", mActiveThread->mIsAtBreakpointAddress);
  3637. mSavedAtBreakpointAddress = mActiveThread->mIsAtBreakpointAddress;
  3638. mSavedBreakpointAddressContinuing = mActiveThread->mBreakpointAddressContinuing;
  3639. mSavedContext.ContextFlags = BF_CONTEXT_ALL;
  3640. BF_GetThreadContext(mActiveThread->mHThread, &mSavedContext);
  3641. }
  3642. void WinDebugger::RestoreAllRegisters()
  3643. {
  3644. BfLogDbg("RestoreAllRegisters setting mIsAtBreakpointAddress = %p\n", mSavedAtBreakpointAddress);
  3645. mActiveThread->mIsAtBreakpointAddress = mSavedAtBreakpointAddress;
  3646. mActiveThread->mBreakpointAddressContinuing = mSavedBreakpointAddressContinuing;
  3647. BF_SetThreadContext(mActiveThread->mHThread, &mSavedContext);
  3648. #ifdef BF_DBG_32
  3649. //TODO: Find the test that this was required for...
  3650. // if (mActiveThread->mIsAtBreakpointAddress == mSavedContext.Eip)
  3651. // {
  3652. // if (mRunState == RunState_Running_ToTempBreakpoint)
  3653. // mRunState = RunState_Paused;
  3654. // }
  3655. // else
  3656. // {
  3657. // SetTempBreakpoint(mSavedContext.Eip);
  3658. // mRunState = RunState_Running_ToTempBreakpoint;
  3659. // mStepType = StepType_ToTempBreakpoint;
  3660. // mSteppingThread = mActiveThread;
  3661. // }
  3662. #endif
  3663. }
  3664. void WinDebugger::OutputMessage(const StringImpl& msg)
  3665. {
  3666. if (this == NULL)
  3667. return;
  3668. AutoCrit autoCrit(mDebugManager->mCritSect);
  3669. mDebugManager->mOutMessages.push_back("msg " + msg);
  3670. }
  3671. void WinDebugger::OutputRawMessage(const StringImpl& msg)
  3672. {
  3673. if (this == NULL)
  3674. return;
  3675. AutoCrit autoCrit(mDebugManager->mCritSect);
  3676. mDebugManager->mOutMessages.push_back(msg);
  3677. }
  3678. void WinDebugger::SetRunState(RunState runState)
  3679. {
  3680. mRunState = runState;
  3681. }
  3682. bool WinDebugger::TryRunContinue()
  3683. {
  3684. if (mRunState == RunState_Exception)
  3685. {
  3686. mIsContinuingFromException = true;
  3687. mRunState = RunState_Paused;
  3688. }
  3689. if (((mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint)) && (mNeedsRehupBreakpoints))
  3690. RehupBreakpoints(true);
  3691. return true;
  3692. }
  3693. void WinDebugger::ClearStep()
  3694. {
  3695. BfLogDbg("ClearStep\n");
  3696. RemoveTempBreakpoints();
  3697. mOrigStepType = StepType_None;
  3698. mStepType = StepType_None;
  3699. mStepStartPC = 0;
  3700. mStepSP = 0;
  3701. mStepPC = 0;
  3702. mIsStepIntoSpecific = false;
  3703. mStepIsRecursing = false;
  3704. mStepStopOnNextInstruction = false;
  3705. mStepLineData = DbgLineDataEx();
  3706. }
  3707. bool WinDebugger::SetupStep(StepType stepType)
  3708. {
  3709. BP_ZONE("SetupStep");
  3710. RemoveTempBreakpoints();
  3711. if (mNeedsRehupBreakpoints)
  3712. RehupBreakpoints(true);
  3713. if (mOrigStepType == StepType_None)
  3714. mOrigStepType = stepType;
  3715. mStepType = stepType;
  3716. mSteppingThread = mActiveThread;
  3717. mStepSwitchedThreads = false;
  3718. mContinueFromBreakpointFailed = false;
  3719. CPURegisters registers;
  3720. PopulateRegisters(&registers);
  3721. addr_target pcAddress = registers.GetPC();
  3722. if (mStepLineData.IsNull())
  3723. {
  3724. DbgSubprogram* dbgSubprogram = NULL;
  3725. auto dbgLineData = FindLineDataAtAddress(pcAddress, &dbgSubprogram);
  3726. mStepLineData = DbgLineDataEx(dbgLineData, dbgSubprogram);
  3727. mStepStartPC = registers.GetPC();
  3728. }
  3729. bool isDeeper = mStepSP > registers.GetSP();
  3730. BfLogDbg("SetupStep %d PC:%p SP:%p StepStartSP:%p Thread:%d\n", stepType, (addr_target)registers.GetPC(), (addr_target)registers.GetSP(), (addr_target)mStepSP, mSteppingThread->mThreadId);
  3731. mStepSP = registers.GetSP();
  3732. mStepPC = registers.GetPC();
  3733. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_NoFrame) || (mStepType == StepType_StepOut_ThenInto))
  3734. {
  3735. if (mStepType != StepType_StepOut_NoFrame)
  3736. {
  3737. // Test for stepping out of an inline method
  3738. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3739. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL))
  3740. {
  3741. DbgSubprogram* topSubprogram = dwSubprogram->GetRootInlineParent();
  3742. if ((mOrigStepType == StepType_StepInto) || (mOrigStepType == StepType_StepInto_Unfiltered))
  3743. {
  3744. mStepType = mOrigStepType;
  3745. }
  3746. else
  3747. {
  3748. mStepType = StepType_StepOut_Inline;
  3749. // Set up pcAddress to detect recursion
  3750. //TODO: We can't set a physical breakpoint here because we will immediately hit it when attempting to step over an inlined method.
  3751. // An inlined method can't recurse anyway, but store the pcAddress in mTempBreakpoints because we still check that for recursion
  3752. // SetTempBreakpoint(pcAddress);
  3753. //mTempBreakpoint.push_back(pcAddress);
  3754. mStepBreakpointAddrs.push_back(pcAddress);
  3755. }
  3756. addr_target endAddress = dwSubprogram->mBlock.mHighPC;
  3757. if (dwSubprogram->mHasLineAddrGaps)
  3758. {
  3759. // Keep bumping out the address as long as we can find lines that contain the nextPC
  3760. addr_target nextAddr = pcAddress;
  3761. for (auto& lineInfo : topSubprogram->mLineInfo->mLines)
  3762. {
  3763. auto lineAddr = topSubprogram->GetLineAddr(lineInfo);
  3764. if ((nextAddr >= lineAddr) && (nextAddr < lineAddr + lineInfo.mContribSize))
  3765. {
  3766. auto ctx = topSubprogram->mLineInfo->mContexts[lineInfo.mCtxIdx];
  3767. if (ctx.mInlinee == dwSubprogram)
  3768. {
  3769. nextAddr = lineAddr + lineInfo.mContribSize;
  3770. }
  3771. }
  3772. }
  3773. if (nextAddr != pcAddress)
  3774. endAddress = nextAddr;
  3775. }
  3776. BfLogDbg("Stepping out of inlined method, end address: %p\n", endAddress);
  3777. SetTempBreakpoint(endAddress);
  3778. mStepBreakpointAddrs.push_back(endAddress);
  3779. addr_target decodeAddress = dwSubprogram->mBlock.mLowPC;
  3780. while (decodeAddress < endAddress)
  3781. {
  3782. CPUInst inst;
  3783. if (!mDebugTarget->DecodeInstruction(decodeAddress, &inst))
  3784. break;
  3785. addr_target targetAddress = inst.GetTarget();
  3786. // We need to find a targetAddress
  3787. if ((targetAddress != 0) &&
  3788. !((targetAddress >= dwSubprogram->mBlock.mLowPC) && (targetAddress < dwSubprogram->mBlock.mHighPC)) &&
  3789. ((targetAddress >= topSubprogram->mBlock.mLowPC) && (targetAddress < topSubprogram->mBlock.mHighPC)))
  3790. {
  3791. BfLogDbg("Stepping out of inlined method, branch address: %p\n", targetAddress);
  3792. SetTempBreakpoint(targetAddress);
  3793. mStepBreakpointAddrs.push_back(targetAddress);
  3794. }
  3795. decodeAddress += inst.GetLength();
  3796. }
  3797. return true;
  3798. }
  3799. }
  3800. if ((mStepType != StepType_StepOut_NoFrame) && (RollBackStackFrame(&registers, true)))
  3801. {
  3802. bool isStackAdjust = false;
  3803. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3804. if (dwSubprogram != NULL)
  3805. {
  3806. if ((strcmp(dwSubprogram->mName, "_chkstk") == 0) ||
  3807. (strcmp(dwSubprogram->mName, "__chkstk") == 0) ||
  3808. (strcmp(dwSubprogram->mName, "_alloca_probe") == 0))
  3809. isStackAdjust = true;
  3810. }
  3811. pcAddress = registers.GetPC();
  3812. if (isStackAdjust)
  3813. {
  3814. // We set it to zero so we never detect an "isDeeper" condition which would skip over the return-location breakpoint
  3815. mStepSP = 0;
  3816. }
  3817. else
  3818. {
  3819. addr_target oldAddress = pcAddress;
  3820. CPUInst inst;
  3821. while (true)
  3822. {
  3823. if (mStepInAssembly)
  3824. break;
  3825. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  3826. break;
  3827. if ((inst.IsBranch()) || (inst.IsCall()) || (inst.IsReturn()))
  3828. break;
  3829. #ifdef BF_DBG_32
  3830. if (!inst.StackAdjust(mStepSP))
  3831. break;
  3832. #endif
  3833. DbgSubprogram* checkSubprogram = NULL;
  3834. auto checkLineData = FindLineDataAtAddress(pcAddress, &checkSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  3835. if (checkLineData == NULL)
  3836. break;
  3837. if (checkSubprogram->GetLineAddr(*checkLineData) == pcAddress)
  3838. break;
  3839. pcAddress += inst.GetLength();
  3840. }
  3841. if (pcAddress != oldAddress)
  3842. {
  3843. BfLogDbg("Adjusting stepout address from %p to %p\n", oldAddress, pcAddress);
  3844. }
  3845. }
  3846. BfLogDbg("SetupStep Stepout SetTempBreakpoint %p\n", pcAddress);
  3847. SetTempBreakpoint(pcAddress);
  3848. mStepBreakpointAddrs.push_back(pcAddress);
  3849. if (mStepType != StepType_StepOut_ThenInto)
  3850. mStepType = StepType_StepOut;
  3851. }
  3852. else
  3853. {
  3854. // Try to handle the case where we just entered this call so the return address is the first entry on the stack
  3855. addr_target* regSP = registers.GetSPRegisterRef();
  3856. pcAddress = ReadMemory<addr_target>(*regSP);
  3857. *regSP += sizeof(addr_target);
  3858. if (mDebugTarget->FindSubProgram(pcAddress) != NULL)
  3859. {
  3860. BfLogDbg("SetupStep Stepout SetTempBreakpoint (2) %p\n", pcAddress);
  3861. SetTempBreakpoint(pcAddress);
  3862. mStepBreakpointAddrs.push_back(pcAddress);
  3863. if (mOrigStepType == StepType_StepInto)
  3864. mStepType = StepType_StepInto;
  3865. else
  3866. mStepType = StepType_StepOver;
  3867. return true;
  3868. }
  3869. else
  3870. {
  3871. // Just do stepovers until we eventually step out
  3872. //BF_DBG_FATAL("StepOut Failed");
  3873. BfLogDbg("StepOut Failed\n");
  3874. if (mLastValidStepIntoPC != 0)
  3875. {
  3876. BfLogDbg("Using mLastValidStepIntoPC: %p\n", mLastValidStepIntoPC);
  3877. if (mOrigStepType == StepType_StepInto)
  3878. mStepType = StepType_StepInto;
  3879. else
  3880. mStepType = StepType_StepOver;
  3881. SetTempBreakpoint(mLastValidStepIntoPC);
  3882. mStepBreakpointAddrs.push_back(0);
  3883. mStepBreakpointAddrs.push_back(mLastValidStepIntoPC);
  3884. mLastValidStepIntoPC = 0;
  3885. return true;
  3886. }
  3887. else
  3888. {
  3889. BfLogDbg("Stopping");
  3890. mStepType = StepType_None;
  3891. mRunState = RunState_Paused;
  3892. return true;
  3893. }
  3894. }
  3895. }
  3896. }
  3897. if ((mStepType != StepType_StepOut) && (mStepType != StepType_StepOut_ThenInto))
  3898. {
  3899. if (mDebuggerWaitingThread != mSteppingThread)
  3900. {
  3901. // We've switched threads, so there's a possible race condition:
  3902. // This new thread may already have an EXCEPTION_BREAKPOINT queued up so the PC is actually
  3903. // located one byte past the BREAK instruction, which is one byte into whatever instruction
  3904. // was previously there. We can't insert normal BREAK instructions because we don't know
  3905. // if the current PC is actually at an instruction start, so we do a single step with a
  3906. // slower stack call check to see if we need to step out after a "step over"
  3907. BfLogDbg("Step - switched threads mIsAtBreakpointAddress:%p\n", mSteppingThread->mIsAtBreakpointAddress);
  3908. mStepSwitchedThreads = true;
  3909. SingleStepX86();
  3910. return true;
  3911. }
  3912. bool breakOnNext = false;
  3913. int instIdx = 0;
  3914. for (instIdx = 0; true; instIdx++)
  3915. {
  3916. bool isAtLine = false;
  3917. DbgSubprogram* dwSubprogram = NULL;
  3918. auto dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  3919. isAtLine = (instIdx > 0) && (dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dwSubprogram->GetLineAddr(*dwLineData) == pcAddress);
  3920. // "Never step into" line
  3921. if ((dwLineData != NULL) && (dwLineData->mColumn == -2) && (stepType == StepType_StepInto))
  3922. stepType = StepType_StepOver;
  3923. CPUInst inst;
  3924. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  3925. {
  3926. BfLogDbg("Decode failed, set up SingleStepX86 %p\n", pcAddress);
  3927. SingleStepX86();
  3928. mStepStopOnNextInstruction = true;
  3929. return true;
  3930. }
  3931. if (instIdx > 256)
  3932. {
  3933. BfLogDbg("Too many SetupStep iterations");
  3934. breakOnNext = true;
  3935. }
  3936. if ((inst.IsReturn()) && (instIdx == 0) && (!mStepInAssembly))
  3937. {
  3938. // Do actual STEP OUT so we set up proper "stepping over unimportant post-return instructions"
  3939. if (stepType == StepType_StepInto)
  3940. return SetupStep(StepType_StepOut_ThenInto);
  3941. else
  3942. return SetupStep(StepType_StepOut);
  3943. }
  3944. if ((breakOnNext) || (mStepInAssembly) || (isAtLine) || (inst.IsBranch()) || (inst.IsCall()) || (inst.IsReturn()))
  3945. {
  3946. if (((instIdx == 0) || (mStepInAssembly)) && (!breakOnNext))
  3947. {
  3948. if ((stepType == StepType_StepOver) && (inst.IsCall()))
  3949. {
  3950. // Continue - sets a breakpoint on the call line to detect recursion.
  3951. // The next loop through will set a breakpoint on the line after the return
  3952. BfLogDbg("StepHadCall\n");
  3953. breakOnNext = true;
  3954. BfLogDbg("StepHadCall setting mIsAtBreakpointAddress = %p\n", pcAddress);
  3955. mSteppingThread->mIsAtBreakpointAddress = pcAddress;
  3956. SetTempBreakpoint(pcAddress);
  3957. mStepBreakpointAddrs.push_back(pcAddress);
  3958. }
  3959. else
  3960. {
  3961. if (inst.IsCall())
  3962. {
  3963. if ((mLastValidStepIntoPC == 0) || (dwSubprogram != NULL))
  3964. mLastValidStepIntoPC = pcAddress + inst.mSize;
  3965. }
  3966. if ((dwLineData != NULL) && (inst.IsBranch()))
  3967. {
  3968. addr_target targetAddr = inst.GetTarget();
  3969. if (targetAddr < dwSubprogram->GetLineAddr(*dwLineData))
  3970. {
  3971. // Jumping backwards, stop at next instruction
  3972. mStepStopOnNextInstruction = true;
  3973. }
  3974. }
  3975. bool isPrefixOnly = false;
  3976. if ((mStepInAssembly) && (stepType == StepType_StepOver) && (inst.IsRep(isPrefixOnly)))
  3977. {
  3978. if (isPrefixOnly)
  3979. {
  3980. CPUInst nextInst;
  3981. if (mDebugTarget->DecodeInstruction(pcAddress + inst.GetLength(), &nextInst))
  3982. {
  3983. if (nextInst.IsBranch())
  3984. {
  3985. // repne jmp - this appears in __chkstk (for example)
  3986. // We don't have a good way to "step over" this one, so just do a single step
  3987. }
  3988. else
  3989. {
  3990. // Step over the rep + target instruction
  3991. auto doneAddr = pcAddress + inst.GetLength() + nextInst.GetLength();
  3992. BfLogDbg("SetupStep SetTempBreakpoint %p\n", doneAddr);
  3993. SetTempBreakpoint(doneAddr);
  3994. mStepBreakpointAddrs.push_back(doneAddr);
  3995. break;
  3996. }
  3997. }
  3998. }
  3999. else
  4000. {
  4001. // Step over the instruction
  4002. auto doneAddr = pcAddress + inst.GetLength();
  4003. BfLogDbg("SetupStep SetTempBreakpoint %p\n", doneAddr);
  4004. SetTempBreakpoint(doneAddr);
  4005. mStepBreakpointAddrs.push_back(doneAddr);
  4006. break;
  4007. }
  4008. }
  4009. // Just step a single instruction
  4010. BfLogDbg("SetupStep SingleStepX86 %p\n", pcAddress);
  4011. SingleStepX86();
  4012. if (inst.IsReturn())
  4013. mStepStopOnNextInstruction = true;
  4014. break;
  4015. }
  4016. }
  4017. else
  4018. {
  4019. // Move us to this instruction so we can hardware single-step into it
  4020. BfLogDbg("SetupStep SetTempBreakpoint %p\n", pcAddress);
  4021. SetTempBreakpoint(pcAddress);
  4022. mStepBreakpointAddrs.push_back(pcAddress);
  4023. break;
  4024. }
  4025. }
  4026. // Not an interesting instruction - move to next
  4027. pcAddress += inst.mSize;
  4028. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress >= dwSubprogram->mBlock.mHighPC))
  4029. {
  4030. auto endAddress = dwSubprogram->mBlock.mHighPC;
  4031. BfLogDbg("Stepping past end of inlined method, end address: %p\n", endAddress);
  4032. mStepType = StepType_StepOut_Inline;
  4033. SetTempBreakpoint(endAddress);
  4034. mStepBreakpointAddrs.push_back(endAddress);
  4035. return true;
  4036. }
  4037. }
  4038. if (instIdx > 1)
  4039. BfLogDbg("SetupStep instIdx: %d\n", instIdx);
  4040. }
  4041. return true;
  4042. }
  4043. void WinDebugger::CheckNonDebuggerBreak()
  4044. {
  4045. enum MessageType
  4046. {
  4047. MessageType_None = 0,
  4048. MessageType_Error = 1,
  4049. MessageType_ProfilerCmd = 2
  4050. };
  4051. CPURegisters registers;
  4052. PopulateRegisters(&registers);
  4053. addr_target pcAddress = registers.GetPC();
  4054. addr_target debugMessageDataAddr = (addr_target)-1;
  4055. if (mDebugTarget->mTargetBinary != NULL)
  4056. {
  4057. mDebugTarget->mTargetBinary->ParseSymbolData();
  4058. debugMessageDataAddr = mDebugTarget->FindSymbolAddr("gBfDebugMessageData");
  4059. }
  4060. if (debugMessageDataAddr != (addr_target)-1)
  4061. {
  4062. struct BfDebugMessageData
  4063. {
  4064. int mMessageType; // 0 = none, 1 = error
  4065. int mStackWindbackCount;
  4066. int mBufParamLen;
  4067. addr_target mBufParam;
  4068. addr_target mPCOverride;
  4069. };
  4070. BfDebugMessageData messageData = ReadMemory<BfDebugMessageData>(debugMessageDataAddr);
  4071. WriteMemory<int>(debugMessageDataAddr, 0); // Zero out type so we won't trigger again
  4072. if (messageData.mMessageType != 0)
  4073. {
  4074. llvm::SmallVector<char, 4096> strBuf;
  4075. int strLen = messageData.mBufParamLen;
  4076. strBuf.resize(strLen + 1);
  4077. char* str = &strBuf[0];
  4078. str[strLen] = 0;
  4079. if (ReadMemory(messageData.mBufParam, strLen, str))
  4080. {
  4081. if (messageData.mMessageType == MessageType_Error)
  4082. {
  4083. mRequestedStackFrameIdx = messageData.mStackWindbackCount;
  4084. if (messageData.mPCOverride != 0)
  4085. {
  4086. mShowPCOverride = messageData.mPCOverride;
  4087. mRequestedStackFrameIdx = -2;
  4088. }
  4089. mDebugManager->mOutMessages.push_back(StrFormat("error %s", str));
  4090. }
  4091. else if (messageData.mMessageType == MessageType_ProfilerCmd)
  4092. {
  4093. // It's important to set this here, because we unlock the critSect during StopSampling and we can't have the
  4094. // IDE thinking that we're actually paused when it checks the mRunState
  4095. mRunState = RunState_Running;
  4096. char* cmd = strtok(str, "\t");
  4097. if (strcmp(cmd, "StartSampling") == 0)
  4098. {
  4099. char* sessionIdStr = strtok(NULL, "\t");
  4100. char* threadIdStr = strtok(NULL, "\t");
  4101. char* sampleRateStr = strtok(NULL, "\t");
  4102. char* descStr = strtok(NULL, "\t");
  4103. if (threadIdStr != NULL)
  4104. {
  4105. int threadId = atoi(threadIdStr);
  4106. int sampleRate = atoi(sampleRateStr);
  4107. int sessionId = atoi(sessionIdStr);
  4108. Profiler** profilerPtr;
  4109. if (mPendingProfilerMap.TryAdd(sessionId, NULL, &profilerPtr))
  4110. {
  4111. DbgProfiler* profiler = new DbgProfiler(this);
  4112. if (descStr != NULL)
  4113. profiler->mDescription = descStr;
  4114. if (sampleRate > 0)
  4115. profiler->mSamplesPerSecond = sampleRate;
  4116. profiler->Start();
  4117. *profilerPtr = profiler;
  4118. mDebugManager->mOutMessages.push_back("newProfiler");
  4119. mNewProfilerList.push_back(profiler);
  4120. }
  4121. }
  4122. }
  4123. else if (strcmp(cmd, "StopSampling") == 0)
  4124. {
  4125. char* sessionIdStr = strtok(NULL, "\t");
  4126. if (sessionIdStr != NULL)
  4127. {
  4128. int sessionId = atoi(sessionIdStr);
  4129. Profiler* profiler;
  4130. if (mPendingProfilerMap.Remove(sessionId, &profiler))
  4131. {
  4132. if (profiler->IsSampling())
  4133. {
  4134. // Need to unlock so we don't deadlock
  4135. mDebugManager->mCritSect.Unlock();
  4136. profiler->Stop();
  4137. mDebugManager->mCritSect.Lock();
  4138. }
  4139. }
  4140. }
  4141. }
  4142. else if (strcmp(cmd, "ClearSampling") == 0)
  4143. {
  4144. for (auto& kv : mPendingProfilerMap)
  4145. {
  4146. auto profiler = kv.mValue;
  4147. profiler->Clear();
  4148. }
  4149. }
  4150. else if (strcmp(cmd, "ClearOutput") == 0)
  4151. {
  4152. mDebugManager->mOutMessages.push_back("clearOutput");
  4153. }
  4154. }
  4155. return;
  4156. }
  4157. }
  4158. }
  4159. intptr_target objAddr;
  4160. if (mDebugTarget->IsObjectAccessBreak(pcAddress, &registers, &objAddr))
  4161. {
  4162. String errorStr = "error Attempted to access deleted object";
  4163. String objectAddr = EncodeDataPtr((addr_target)objAddr, true);
  4164. errorStr += StrFormat("\x1LEAK\t(System.Object)%s\n (%s)%s\n", objectAddr.c_str(), "System.Object", objectAddr.c_str());
  4165. mDebugManager->mOutMessages.push_back(errorStr);
  4166. return;
  4167. }
  4168. bool showMainThread = false;
  4169. String symbol;
  4170. addr_target offset;
  4171. DbgModule* dbgModule;
  4172. if (mDebugTarget->FindSymbolAt(pcAddress, &symbol, &offset, &dbgModule))
  4173. {
  4174. if ((symbol == "DbgBreakPoint") || (symbol == "RtlUserThreadStart") || (symbol == "RtlUserThreadStart@8"))
  4175. {
  4176. showMainThread = true;
  4177. }
  4178. }
  4179. #ifdef BF_DBG_32
  4180. else if ((dbgModule != NULL) && (dbgModule->mDisplayName.Equals("kernel32.dll", StringImpl::CompareKind_OrdinalIgnoreCase)))
  4181. {
  4182. showMainThread = true;
  4183. }
  4184. #endif
  4185. if (showMainThread)
  4186. {
  4187. // This is a manual break, show the main thread
  4188. mActiveThread = mThreadList.front();
  4189. if (mDebugPendingExpr != NULL)
  4190. {
  4191. for (auto thread : mThreadList)
  4192. {
  4193. if (thread->mThreadId == mDebugEvalThreadInfo.mThreadId)
  4194. {
  4195. mActiveThread = thread;
  4196. break;
  4197. }
  4198. }
  4199. }
  4200. }
  4201. }
  4202. bool WinDebugger::HasSteppedIntoCall()
  4203. {
  4204. // Some calls (like __chkstk) actually push results to the stack, so we need to check
  4205. // if we're REALLY deeper or not, by rolling back the callstack once
  4206. CPURegisters registers;
  4207. PopulateRegisters(&registers);
  4208. if (RollBackStackFrame(&registers, true))
  4209. {
  4210. // If the previous frames SP is equal or deeper than our step start then we are indeed inside a call!
  4211. if (mStepSP >= registers.GetSP())
  4212. return true;
  4213. }
  4214. return false;
  4215. }
  4216. void WinDebugger::StepOver(bool inAssembly)
  4217. {
  4218. AutoCrit autoCrit(mDebugManager->mCritSect);
  4219. BfLogDbg("StepOver\n");
  4220. if (!TryRunContinue())
  4221. return;
  4222. mCurNoInfoStepTries = 0; // Reset
  4223. mStepInAssembly = inAssembly;
  4224. SetupStep(StepType_StepOver);
  4225. ContinueDebugEvent();
  4226. }
  4227. void WinDebugger::StepOut(bool inAssembly)
  4228. {
  4229. AutoCrit autoCrit(mDebugManager->mCritSect);
  4230. BfLogDbg("StepOut\n");
  4231. if (!TryRunContinue())
  4232. return;
  4233. mCurNoInfoStepTries = 0; // Reset
  4234. mStepInAssembly = inAssembly;
  4235. SetupStep(StepType_StepOut);
  4236. ContinueDebugEvent();
  4237. }
  4238. void WinDebugger::SetNextStatement(bool inAssembly, const StringImpl& fileName, int64 lineNumOrAsmAddr, int wantColumn)
  4239. {
  4240. AutoCrit autoCrit(mDebugManager->mCritSect);
  4241. DbgSubprogram* subProgram = NULL;
  4242. if (!inAssembly)
  4243. {
  4244. if (mCallStack.size() == 0)
  4245. UpdateCallStack();
  4246. if (mCallStack.size() > 0)
  4247. {
  4248. UpdateCallStackMethod(0);
  4249. subProgram = mCallStack[0]->mSubProgram;
  4250. }
  4251. if (subProgram == NULL)
  4252. return;
  4253. }
  4254. DbgSubprogram* rootInlineParent = NULL;
  4255. if (subProgram != NULL)
  4256. rootInlineParent = subProgram->GetRootInlineParent();
  4257. String result;
  4258. if (mDebugTarget == NULL)
  4259. return;
  4260. DbgSrcFile* srcFile = NULL;
  4261. if (!fileName.IsEmpty())
  4262. {
  4263. srcFile = mDebugTarget->GetSrcFile(fileName);
  4264. if (srcFile == NULL)
  4265. return;
  4266. }
  4267. addr_target pcAddress = 0;
  4268. if (inAssembly)
  4269. {
  4270. pcAddress = lineNumOrAsmAddr;
  4271. }
  4272. else
  4273. {
  4274. int lineNum = (int)lineNumOrAsmAddr;
  4275. addr_target bestAddr[2] = { 0, 0 };
  4276. int checkLineNum[2] = { lineNum - 1, lineNum };
  4277. auto _CheckLineInfo = [&](DbgSubprogram* dbgSubprogram, DbgLineInfo* dbgLineInfo)
  4278. {
  4279. for (int iPass = 0; iPass < 2; ++iPass)
  4280. {
  4281. int bestLineOffset = 0x7FFFFFFF;
  4282. for (auto& lineData : dbgLineInfo->mLines)
  4283. {
  4284. auto addr = dbgSubprogram->GetLineAddr(lineData);
  4285. if ((addr < subProgram->mBlock.mLowPC) || (addr >= subProgram->mBlock.mHighPC))
  4286. continue;
  4287. int lineOffset = lineData.mLine - checkLineNum[iPass];
  4288. if ((lineOffset >= 0) && (lineOffset <= 6) && (lineOffset <= bestLineOffset))
  4289. {
  4290. if (lineOffset < bestLineOffset)
  4291. {
  4292. bestLineOffset = lineOffset;
  4293. bestAddr[iPass] = addr;
  4294. }
  4295. }
  4296. }
  4297. }
  4298. };
  4299. for (int checkHotIdx = -1; checkHotIdx < (int)srcFile->mHotReplacedDbgLineInfo.size(); checkHotIdx++)
  4300. {
  4301. if (checkHotIdx >= 0)
  4302. {
  4303. auto hotReplacedLineInfo = srcFile->mHotReplacedDbgLineInfo[checkHotIdx];
  4304. for (auto& hotReplacedEntry : hotReplacedLineInfo->mEntries)
  4305. {
  4306. _CheckLineInfo(hotReplacedEntry.mSubprogram, hotReplacedEntry.mLineInfo);
  4307. }
  4308. }
  4309. else
  4310. {
  4311. for (auto subprogram : srcFile->mLineDataRefs)
  4312. _CheckLineInfo(subprogram, subprogram->mLineInfo);
  4313. }
  4314. if (bestAddr[1] != 0)
  4315. break;
  4316. }
  4317. if (bestAddr[1] != 0)
  4318. {
  4319. const int kMaxAddrDist = 64; // within reasonable range
  4320. if ((bestAddr[0] != 0) && (bestAddr[1] - bestAddr[0] <= kMaxAddrDist))
  4321. {
  4322. addr_target addrStart = bestAddr[0];
  4323. addr_target addrEnd = bestAddr[1];
  4324. addr_target addr = addrStart;
  4325. BF_ASSERT(addrEnd - addr <= kMaxAddrDist);
  4326. addr_target lastOp = 0;
  4327. while (addr < addrEnd)
  4328. {
  4329. CPUInst inst;
  4330. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  4331. break;
  4332. lastOp = addr;
  4333. addr += inst.GetLength();
  4334. }
  4335. }
  4336. pcAddress = (uint64)bestAddr[1];
  4337. }
  4338. }
  4339. if (pcAddress)
  4340. {
  4341. BF_ASSERT(mActiveThread->mBreakpointAddressContinuing == 0);
  4342. mActiveThread->mIsAtBreakpointAddress = 0;
  4343. mActiveThread->mStoppedAtAddress = pcAddress;
  4344. if (mCallStack.size() == 0)
  4345. UpdateCallStack();
  4346. CPURegisters* regs = &mCallStack.front()->mRegisters;
  4347. *regs->GetPCRegisterRef() = pcAddress;
  4348. SetRegisters(regs);
  4349. WdBreakpoint* breakpoint = (WdBreakpoint*)FindBreakpointAt(pcAddress);
  4350. if (breakpoint != NULL)
  4351. {
  4352. BfLogDbg("SetNextStatement setting mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  4353. mActiveThread->mIsAtBreakpointAddress = breakpoint->mAddr;
  4354. }
  4355. }
  4356. }
  4357. bool WinDebugger::PopulateRegisters(CPURegisters* registers, BF_CONTEXT& lcContext)
  4358. {
  4359. #ifdef BF_DBG_32
  4360. registers->mIntRegs.eax = lcContext.Eax;
  4361. registers->mIntRegs.ecx = lcContext.Ecx;
  4362. registers->mIntRegs.edx = lcContext.Edx;
  4363. registers->mIntRegs.ebx = lcContext.Ebx;
  4364. registers->mIntRegs.esp = lcContext.Esp;
  4365. registers->mIntRegs.ebp = lcContext.Ebp;
  4366. registers->mIntRegs.esi = lcContext.Esi;
  4367. registers->mIntRegs.edi = lcContext.Edi;
  4368. registers->mIntRegs.eip = lcContext.Eip;
  4369. registers->mIntRegs.efl = lcContext.EFlags;
  4370. BF_ASSERT(sizeof(lcContext.FloatSave.RegisterArea) == sizeof(registers->mFpMmRegsArray));
  4371. memcpy(registers->mFpMmRegsArray, lcContext.FloatSave.RegisterArea, sizeof(lcContext.FloatSave.RegisterArea));
  4372. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 32 * sizeof(float));
  4373. memcpy(registers->mXmmRegsArray, &lcContext.ExtendedRegisters[160], sizeof(registers->mXmmRegsArray));
  4374. #else
  4375. registers->mIntRegs.rax = lcContext.Rax;
  4376. registers->mIntRegs.rcx = lcContext.Rcx;
  4377. registers->mIntRegs.rdx = lcContext.Rdx;
  4378. registers->mIntRegs.rbx = lcContext.Rbx;
  4379. registers->mIntRegs.rsp = lcContext.Rsp;
  4380. registers->mIntRegs.rbp = lcContext.Rbp;
  4381. registers->mIntRegs.rsi = lcContext.Rsi;
  4382. registers->mIntRegs.rdi = lcContext.Rdi;
  4383. registers->mIntRegs.rip = lcContext.Rip;
  4384. registers->mIntRegs.efl = lcContext.EFlags;
  4385. registers->mIntRegs.r8 = lcContext.R8;
  4386. registers->mIntRegs.r9 = lcContext.R9;
  4387. registers->mIntRegs.r10 = lcContext.R10;
  4388. registers->mIntRegs.r11 = lcContext.R11;
  4389. registers->mIntRegs.r12 = lcContext.R12;
  4390. registers->mIntRegs.r13 = lcContext.R13;
  4391. registers->mIntRegs.r14 = lcContext.R14;
  4392. registers->mIntRegs.r15 = lcContext.R15;
  4393. registers->mIntRegs.gs = lcContext.SegGs;
  4394. for (int i = 0; i < 8; i++)
  4395. {
  4396. memcpy(&registers->mFpMmRegsArray[i], &lcContext.FltSave.FloatRegisters[i], 10);
  4397. }
  4398. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 64 * sizeof(float));
  4399. memcpy(registers->mXmmRegsArray, BF_CONTEXT_XMMDATA(lcContext), sizeof(registers->mXmmRegsArray));
  4400. #endif
  4401. return (lcContext.ContextFlags & (BF_CONTEXT_EXCEPTION_ACTIVE | BF_CONTEXT_SERVICE_ACTIVE)) == 0;
  4402. }
  4403. bool WinDebugger::PopulateRegisters(CPURegisters* registers)
  4404. {
  4405. /*static bool sCheckedProcessorFeatures = false;
  4406. static bool sMmxAvailable = false;
  4407. static bool sXmmAvailable = false;
  4408. if (!sCheckedProcessorFeatures)
  4409. {
  4410. //CDH we don't do anything with these yet since we grab BF_CONTEXT_ALL anyway, but could be useful
  4411. sMmxAvailable = ::IsProcessorFeaturePresent(PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  4412. sXmmAvailable = ::IsProcessorFeaturePresent(PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  4413. sCheckedProcessorFeatures = true;
  4414. }*/
  4415. BF_ASSERT(registers != nullptr);
  4416. BF_CONTEXT lcContext;
  4417. lcContext.ContextFlags = BF_CONTEXT_ALL | BF_CONTEXT_EXCEPTION_REQUEST;
  4418. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4419. return PopulateRegisters(registers, lcContext);
  4420. }
  4421. bool WinDebugger::RollBackStackFrame(CPURegisters* registers, bool isStackStart)
  4422. {
  4423. BF_ASSERT(registers != nullptr);
  4424. return mDebugTarget->RollBackStackFrame(registers, NULL, isStackStart);
  4425. }
  4426. bool WinDebugger::SetHotJump(DbgSubprogram* oldSubprogram, addr_target newTarget, int newTargetSize)
  4427. {
  4428. BfLogDbg("SetHotJump %s %p->%p\n", oldSubprogram->mName, oldSubprogram->mBlock.mLowPC, newTarget);
  4429. //AutoCrit autoCrit(mDebugManager->mCritSect);
  4430. BF_ASSERT(mDebugManager->mCritSect.mLockCount == 1);
  4431. addr_target jmpInstStart = oldSubprogram->mBlock.mLowPC;
  4432. addr_target jmpInstEnd = jmpInstStart + sizeof(HotJumpOp);
  4433. if (jmpInstEnd > oldSubprogram->mBlock.mHighPC)
  4434. {
  4435. if ((oldSubprogram->mBlock.mHighPC - oldSubprogram->mBlock.mLowPC == 1) &&
  4436. (newTargetSize == 1))
  4437. return true; // Special case for just stub 'ret' methods
  4438. String err = StrFormat("Failed to hot replace method, method '%s' too small to insert hot thunk", oldSubprogram->ToString().c_str());
  4439. Fail(err);
  4440. return false;
  4441. }
  4442. if (oldSubprogram->mHotReplaceKind != DbgSubprogram::HotReplaceKind_Replaced)
  4443. {
  4444. for (int hotThreadIdx = 0; hotThreadIdx < (int)mHotThreadStates.size(); hotThreadIdx++)
  4445. {
  4446. auto& hotThreadState = mHotThreadStates[hotThreadIdx];
  4447. WdThreadInfo* threadInfo = NULL;
  4448. if (!mThreadMap.TryGetValue((uint32)hotThreadState.mThreadId, &threadInfo))
  4449. continue;
  4450. int tryStart = GetTickCount();
  4451. while ((hotThreadState.mRegisters.GetPC() >= jmpInstStart) && (hotThreadState.mRegisters.GetPC() < jmpInstEnd))
  4452. {
  4453. if (GetTickCount() - tryStart >= 8000)
  4454. {
  4455. Fail("Failed to hot replace method, can't move past prelude");
  4456. return false;
  4457. }
  4458. BfLogDbg("SetHotJump skipping through %p\n", hotThreadState.mRegisters.GetPC());
  4459. bool removedBreakpoint = false;
  4460. mActiveThread = threadInfo;
  4461. if ((mActiveThread->mStoppedAtAddress >= jmpInstStart) && (mActiveThread->mStoppedAtAddress < jmpInstEnd))
  4462. {
  4463. for (addr_target addr = jmpInstStart; addr < jmpInstEnd; addr++)
  4464. {
  4465. if (mPhysBreakpointAddrMap.ContainsKey(addr))
  4466. {
  4467. removedBreakpoint = true;
  4468. RemoveBreakpoint(addr);
  4469. }
  4470. }
  4471. }
  4472. RunState oldRunState = mRunState;
  4473. mRunState = RunState_HotStep;
  4474. if (mWantsDebugContinue)
  4475. {
  4476. mWantsDebugContinue = false;
  4477. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4478. mContinueEvent.Set();
  4479. }
  4480. BF_CONTEXT lcContext;
  4481. lcContext.ContextFlags = BF_CONTEXT_ALL;
  4482. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4483. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  4484. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  4485. ::ResumeThread(mActiveThread->mHThread);
  4486. BfLogDbg("ResumeThread %d\n", mActiveThread->mThreadId);
  4487. while (mRunState != RunState_Terminated)
  4488. {
  4489. mDebugManager->mCritSect.Unlock();
  4490. Sleep(0);
  4491. mDebugManager->mCritSect.Lock();
  4492. if (IsPaused())
  4493. break;
  4494. if (mWantsDebugContinue)
  4495. {
  4496. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4497. mWantsDebugContinue = false;
  4498. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4499. mContinueEvent.Set();
  4500. }
  4501. }
  4502. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4503. ::SuspendThread(mActiveThread->mHThread);
  4504. BfLogDbg("SuspendThread %d\n", mActiveThread->mThreadId);
  4505. mRunState = oldRunState;
  4506. if ((mRunState != RunState_Terminated) && (mRunState != RunState_Terminating))
  4507. {
  4508. if (!IsPaused())
  4509. {
  4510. BF_ASSERT(mWantsDebugContinue);
  4511. mWantsDebugContinue = false;
  4512. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4513. mContinueEvent.Set();
  4514. }
  4515. }
  4516. PopulateRegisters(&hotThreadState.mRegisters);
  4517. }
  4518. }
  4519. }
  4520. HotJumpOp jumpOp;
  4521. jumpOp.mOpCode = 0xE9;
  4522. jumpOp.mRelTarget = newTarget - oldSubprogram->mBlock.mLowPC - sizeof(HotJumpOp);
  4523. WriteMemory(oldSubprogram->mBlock.mLowPC, jumpOp);
  4524. ::FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)oldSubprogram->mBlock.mLowPC, sizeof(HotJumpOp));
  4525. return true;
  4526. }
  4527. DbgSubprogram* WinDebugger::TryFollowHotJump(DbgSubprogram* subprogram, addr_target addr)
  4528. {
  4529. if (subprogram->mHotReplaceKind != DbgSubprogram::HotReplaceKind_Replaced)
  4530. return subprogram;
  4531. if (addr != subprogram->mBlock.mLowPC)
  4532. return subprogram;
  4533. auto dbgModule = subprogram->mCompileUnit->mDbgModule;
  4534. HotJumpOp jumpOp = ReadMemory<HotJumpOp>(addr);
  4535. if (jumpOp.mOpCode != 0xE9)
  4536. return subprogram;
  4537. addr_target jumpAddr = addr + jumpOp.mRelTarget + sizeof(HotJumpOp);
  4538. auto jumpSubprogram = mDebugTarget->FindSubProgram(jumpAddr);
  4539. if (jumpSubprogram == NULL)
  4540. return subprogram;
  4541. return jumpSubprogram;
  4542. }
  4543. bool WinDebugger::ShouldShowStaticMember(DbgType* dbgType, DbgVariable* member)
  4544. {
  4545. // If locationData is non-null, that means it was added in addition to the static declaration in the CV type info,
  4546. // so only add the names from the type definition
  4547. auto flavor = dbgType->mCompileUnit->mDbgModule->mDbgFlavor;
  4548. return ((((dbgType->IsNamespace()) || (flavor != DbgFlavor_MS)) && ((member->mLocationData != NULL) || member->mIsConst)) ||
  4549. ((flavor == DbgFlavor_MS) && (member->mLocationData == NULL)));
  4550. }
  4551. String WinDebugger::GetMemberList(DbgType* dbgType, const StringImpl& expr, bool isPtr, bool isStatic, bool forceCast, bool isSplat, bool isReadOnly)
  4552. {
  4553. auto dbgModule = dbgType->GetDbgModule();
  4554. dbgType->PopulateType();
  4555. auto language = dbgType->GetLanguage();
  4556. if (!isStatic)
  4557. {
  4558. String retVal;
  4559. bool needsNewline = false;
  4560. bool isBfObject = false;
  4561. if (dbgType->IsBfObjectPtr())
  4562. {
  4563. isBfObject = true;
  4564. dbgType = dbgType->mTypeParam;
  4565. }
  4566. int baseIdx = 0;
  4567. for (auto baseTypeEntry : dbgType->mBaseTypes)
  4568. {
  4569. auto baseType = baseTypeEntry->mBaseType;
  4570. if ((baseType->mSize > 0) || (baseType->mTypeCode != DbgType_Struct) || (strcmp(baseType->mTypeName, "ValueType") != 0))
  4571. {
  4572. String baseTypeStr = baseType->ToStringRaw(language);
  4573. if (baseIdx > 0)
  4574. retVal += "\n";
  4575. if (isSplat)
  4576. retVal += "[base]\t((" + baseTypeStr + ")" + expr + "), nv";
  4577. else if (dbgType->WantsRefThis())
  4578. retVal += "[base]\t((" + baseTypeStr + ")this), nd, na, nv, this=" + expr;
  4579. else
  4580. retVal += "[base]\t((" + baseTypeStr + "*)this), nd, na, nv, this=" + expr;
  4581. if (isReadOnly)
  4582. retVal += ", ne";
  4583. }
  4584. needsNewline = true;
  4585. baseIdx++;
  4586. }
  4587. String thisExpr = expr;
  4588. String castString;
  4589. if (dbgType->IsBfObject())
  4590. {
  4591. auto ptrType = dbgType->GetDbgModule()->GetPointerType(dbgType);
  4592. castString = ptrType->ToStringRaw(language);
  4593. }
  4594. else
  4595. castString = dbgType->ToStringRaw(language);
  4596. bool hadStatics = false;
  4597. for (auto member : dbgType->mMemberList)
  4598. {
  4599. if (member->mMemberOffset < 0)
  4600. continue;
  4601. if (member->mIsStatic)
  4602. {
  4603. if (ShouldShowStaticMember(dbgType, member))
  4604. hadStatics = true;
  4605. }
  4606. else
  4607. {
  4608. bool ignoreMember = false;
  4609. if (member->mName != NULL)
  4610. {
  4611. if ((member->mName[0] == '?') ||
  4612. (member->mName[0] == '$') ||
  4613. (strncmp(member->mName, "_vptr$", 6) == 0))
  4614. ignoreMember = true;
  4615. }
  4616. if (!ignoreMember)
  4617. {
  4618. if (needsNewline)
  4619. retVal += "\n";
  4620. if (member->mName == NULL)
  4621. {
  4622. retVal += GetMemberList(member->mType, expr, isPtr, isStatic, forceCast, isSplat, isReadOnly);
  4623. }
  4624. else
  4625. {
  4626. retVal += String(member->mName);
  4627. if (isSplat)
  4628. {
  4629. retVal += "\t(" + thisExpr + ")." + String(member->mName);
  4630. // We don't want to rely on this being enforced here. For one, ref types shouldn't get ", ne" added,
  4631. // and this doesn't solve the issue of attempting to assign via the Immediate window
  4632. /*if (isReadOnly)
  4633. retVal += ", ne";*/
  4634. }
  4635. else
  4636. {
  4637. if (forceCast)
  4638. retVal += "\t((" + castString + ")this)." + String(member->mName);
  4639. else if ((member->mName[0] >= '0') && (member->mName[0] <= '9')) // Numbered tuple member?
  4640. retVal += "\tthis." + String(member->mName);
  4641. else
  4642. retVal += "\t" + String(member->mName);
  4643. retVal += ", this=" + thisExpr;
  4644. // if (isReadOnly)
  4645. // retVal += ", ne";
  4646. }
  4647. }
  4648. needsNewline = true;
  4649. }
  4650. }
  4651. }
  4652. if (hadStatics)
  4653. {
  4654. if (needsNewline)
  4655. retVal += "\n";
  4656. retVal += "Static values\t" + castString;
  4657. }
  4658. return retVal;
  4659. }
  4660. else
  4661. {
  4662. if (dbgType->IsBfObjectPtr())
  4663. dbgType = dbgType->mTypeParam;
  4664. String retVal;
  4665. String memberPrefix = expr;
  4666. bool needsNewline = false;
  4667. bool hadStatics = false;
  4668. for (auto member : dbgType->mMemberList)
  4669. {
  4670. if (member->mIsStatic)
  4671. {
  4672. if (ShouldShowStaticMember(dbgType, member))
  4673. {
  4674. if (needsNewline)
  4675. retVal += "\n";
  4676. retVal += String(member->mName) + "\t" + memberPrefix + "." + String(member->mName);
  4677. needsNewline = true;
  4678. }
  4679. }
  4680. }
  4681. return retVal;
  4682. }
  4683. return "";
  4684. }
  4685. bool WinDebugger::ParseFormatInfo(DbgModule* dbgModule, const StringImpl& formatInfoStr, DwFormatInfo* formatInfo, BfPassInstance* bfPassInstance, int* assignExprOffset, String* assignExprString, String* errorString, DbgTypedValue contextTypedValue)
  4686. {
  4687. String formatFlags = formatInfoStr;
  4688. if (assignExprOffset != NULL)
  4689. *assignExprOffset = -1;
  4690. while (formatFlags.length() > 0)
  4691. {
  4692. formatFlags = Trim(formatFlags);
  4693. if (formatFlags.IsEmpty())
  4694. break;
  4695. if (formatFlags[0] != ',')
  4696. {
  4697. return false;
  4698. }
  4699. else
  4700. {
  4701. int nextComma = formatFlags.IndexOf(',', 1);
  4702. int quotePos = formatFlags.IndexOf('"', 1);
  4703. if ((quotePos != -1) && (quotePos < nextComma))
  4704. {
  4705. int nextQuotePos = formatFlags.IndexOf('"', quotePos + 1);
  4706. if (nextQuotePos != -1)
  4707. nextComma = formatFlags.IndexOf(',', nextQuotePos + 1);
  4708. }
  4709. if (nextComma == -1)
  4710. nextComma = formatFlags.length();
  4711. String formatCmd = formatFlags.Substring(1, nextComma - 1);
  4712. formatCmd = Trim(formatCmd);
  4713. bool hadError = false;
  4714. if (strncmp(formatCmd.c_str(), "this=", 5) == 0)
  4715. {
  4716. formatCmd = formatFlags.Substring(1);
  4717. formatCmd = Trim(formatCmd);
  4718. String thisExpr = formatCmd.Substring(5);
  4719. if (thisExpr.empty())
  4720. break;
  4721. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, thisExpr, formatInfo);
  4722. formatInfo->mExplicitThis = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4723. if (dbgEvaluationContext.HadError())
  4724. {
  4725. if (errorString != NULL)
  4726. *errorString = dbgEvaluationContext.GetErrorStr();
  4727. return false;
  4728. }
  4729. formatFlags = thisExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4730. continue;
  4731. }
  4732. else if (strncmp(formatCmd.c_str(), "count=", 6) == 0)
  4733. {
  4734. formatCmd = formatFlags.Substring(1);
  4735. formatCmd = Trim(formatCmd);
  4736. String countExpr = formatCmd.Substring(6);
  4737. if (countExpr.empty())
  4738. break;
  4739. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4740. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4741. if ((countValue) && (countValue.mType->IsInteger()))
  4742. formatInfo->mOverrideCount = (intptr)countValue.GetInt64();
  4743. if (dbgEvaluationContext.HadError())
  4744. {
  4745. if (errorString != NULL)
  4746. *errorString = dbgEvaluationContext.GetErrorStr();
  4747. return false;
  4748. }
  4749. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4750. continue;
  4751. }
  4752. else if (strncmp(formatCmd.c_str(), "maxcount=", 9) == 0)
  4753. {
  4754. formatCmd = formatFlags.Substring(1);
  4755. formatCmd = Trim(formatCmd);
  4756. String countExpr = formatCmd.Substring(9);
  4757. if (countExpr.empty())
  4758. break;
  4759. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4760. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4761. if ((countValue) && (countValue.mType->IsInteger()))
  4762. formatInfo->mMaxCount = (intptr)countValue.GetInt64();
  4763. if (dbgEvaluationContext.HadError())
  4764. {
  4765. if (errorString != NULL)
  4766. *errorString = dbgEvaluationContext.GetErrorStr();
  4767. return false;
  4768. }
  4769. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4770. continue;
  4771. }
  4772. else if (strncmp(formatCmd.c_str(), "arraysize=", 10) == 0)
  4773. {
  4774. formatCmd = formatFlags.Substring(1);
  4775. formatCmd = Trim(formatCmd);
  4776. String countExpr = formatCmd.Substring(10);
  4777. if (countExpr.empty())
  4778. break;
  4779. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4780. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4781. if ((countValue) && (countValue.mType->IsInteger()))
  4782. formatInfo->mArrayLength = (intptr)countValue.GetInt64();
  4783. if (dbgEvaluationContext.HadError())
  4784. {
  4785. if (errorString != NULL)
  4786. *errorString = dbgEvaluationContext.GetErrorStr();
  4787. return false;
  4788. }
  4789. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4790. continue;
  4791. }
  4792. else if (strncmp(formatCmd.c_str(), "assign=", 7) == 0)
  4793. {
  4794. formatCmd = formatFlags.Substring(1);
  4795. formatCmd = Trim(formatCmd);
  4796. String assignExpr = formatCmd.Substring(7);
  4797. if (assignExpr.empty())
  4798. break;
  4799. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, assignExpr, formatInfo);
  4800. if (dbgEvaluationContext.HadError())
  4801. {
  4802. if (errorString != NULL)
  4803. *errorString = dbgEvaluationContext.GetErrorStr();
  4804. return false;
  4805. }
  4806. if (assignExprOffset != NULL)
  4807. {
  4808. //TODO: Keep track of the offset directly, this is a hack
  4809. *assignExprOffset = (int)formatInfoStr.IndexOf("assign=") + 7;
  4810. }
  4811. if (assignExprString != NULL)
  4812. *assignExprString = dbgEvaluationContext.mExprNode->ToString();
  4813. formatFlags = assignExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4814. continue;
  4815. }
  4816. else if (strncmp(formatCmd.c_str(), "refid=", 6) == 0)
  4817. {
  4818. formatInfo->mReferenceId = formatCmd.Substring(6);
  4819. if (formatInfo->mReferenceId[0] == '\"')
  4820. formatInfo->mReferenceId = formatInfo->mReferenceId.Substring(1, formatInfo->mReferenceId.length() - 2);
  4821. }
  4822. else if (strncmp(formatCmd.c_str(), "_=", 2) == 0)
  4823. {
  4824. formatInfo->mSubjectExpr = formatCmd.Substring(2);
  4825. if (formatInfo->mSubjectExpr[0] == '\"')
  4826. formatInfo->mSubjectExpr = formatInfo->mSubjectExpr.Substring(1, formatInfo->mSubjectExpr.length() - 2);
  4827. }
  4828. else if (strncmp(formatCmd.c_str(), "expectedType=", 13) == 0)
  4829. {
  4830. formatInfo->mExpectedType = formatCmd.Substring(13);
  4831. if (formatInfo->mExpectedType[0] == '\"')
  4832. formatInfo->mExpectedType = formatInfo->mExpectedType.Substring(1, formatInfo->mExpectedType.length() - 2);
  4833. }
  4834. else if (strncmp(formatCmd.c_str(), "namespaceSearch=", 16) == 0)
  4835. {
  4836. formatInfo->mNamespaceSearch = formatCmd.Substring(16);
  4837. if (formatInfo->mNamespaceSearch[0] == '\"')
  4838. formatInfo->mNamespaceSearch = formatInfo->mNamespaceSearch.Substring(1, formatInfo->mNamespaceSearch.length() - 2);
  4839. }
  4840. else if (formatCmd == "d")
  4841. {
  4842. formatInfo->mDisplayType = DwDisplayType_Decimal;
  4843. }
  4844. else if (formatCmd == "x")
  4845. {
  4846. formatInfo->mDisplayType = DwDisplayType_HexLower;
  4847. }
  4848. else if (formatCmd == "X")
  4849. {
  4850. formatInfo->mDisplayType = DwDisplayType_HexUpper;
  4851. }
  4852. else if (formatCmd == "s")
  4853. {
  4854. formatInfo->mHidePointers = true;
  4855. formatInfo->mDisplayType = DwDisplayType_Ascii;
  4856. }
  4857. else if (formatCmd == "s8")
  4858. {
  4859. formatInfo->mHidePointers = true;
  4860. formatInfo->mDisplayType = DwDisplayType_Utf8;
  4861. }
  4862. else if (formatCmd == "s16")
  4863. {
  4864. formatInfo->mHidePointers = true;
  4865. formatInfo->mDisplayType = DwDisplayType_Utf16;
  4866. }
  4867. else if (formatCmd == "s32")
  4868. {
  4869. formatInfo->mHidePointers = true;
  4870. formatInfo->mDisplayType = DwDisplayType_Utf32;
  4871. }
  4872. else if (formatCmd == "nd")
  4873. {
  4874. formatInfo->mIgnoreDerivedClassInfo = true;
  4875. }
  4876. else if (formatCmd == "na")
  4877. {
  4878. formatInfo->mHidePointers = true;
  4879. }
  4880. else if (formatCmd == "nm")
  4881. {
  4882. formatInfo->mNoMembers = true;
  4883. }
  4884. else if (formatCmd == "ne")
  4885. {
  4886. formatInfo->mNoEdit = true;
  4887. }
  4888. else if (formatCmd == "nv")
  4889. {
  4890. formatInfo->mNoVisualizers = true;
  4891. }
  4892. else if (formatCmd == "rawStr")
  4893. {
  4894. formatInfo->mRawString = true;
  4895. }
  4896. else if (((!formatCmd.IsEmpty()) && ((formatCmd[0] >= '0') && (formatCmd[0] <= '9'))) ||
  4897. (formatCmd.StartsWith("(")))
  4898. {
  4899. String countExpr = formatCmd;
  4900. if (countExpr.empty())
  4901. break;
  4902. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4903. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4904. if ((countValue) && (countValue.mType->IsInteger()))
  4905. formatInfo->mArrayLength = (intptr)countValue.GetInt64();
  4906. if (dbgEvaluationContext.HadError())
  4907. {
  4908. if (errorString != NULL)
  4909. *errorString = dbgEvaluationContext.GetErrorStr();
  4910. return false;
  4911. }
  4912. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4913. continue;
  4914. }
  4915. else
  4916. hadError = true;
  4917. if (hadError)
  4918. {
  4919. if (errorString != NULL)
  4920. *errorString = "Invalid format flags";
  4921. return false;
  4922. }
  4923. formatFlags = formatFlags.Substring(nextComma);
  4924. }
  4925. }
  4926. return true;
  4927. }
  4928. String WinDebugger::MaybeQuoteFormatInfoParam(const StringImpl& str)
  4929. {
  4930. bool needsQuote = false;
  4931. for (int i = 0; i < (int)str.length(); i++)
  4932. {
  4933. char c = str[i];
  4934. if (c == ',')
  4935. needsQuote = true;
  4936. }
  4937. if (!needsQuote)
  4938. return str;
  4939. String qStr = "\"";
  4940. qStr += str;
  4941. qStr += "\"";
  4942. return qStr;
  4943. }
  4944. DbgTypedValue WinDebugger::EvaluateInContext(DbgCompileUnit* dbgCompileUnit, const DbgTypedValue& contextTypedValue, const StringImpl& subExpr, DwFormatInfo* formatInfo, String* outReferenceId, String* outErrors)
  4945. {
  4946. DbgEvaluationContext dbgEvaluationContext(this, dbgCompileUnit->mDbgModule, subExpr, formatInfo, contextTypedValue);
  4947. dbgEvaluationContext.mDbgExprEvaluator->mDbgCompileUnit = dbgCompileUnit;
  4948. if (formatInfo != NULL)
  4949. {
  4950. dbgEvaluationContext.mDbgExprEvaluator->mLanguage = formatInfo->mLanguage;
  4951. dbgEvaluationContext.mDbgExprEvaluator->mSubjectExpr = formatInfo->mSubjectExpr;
  4952. }
  4953. dbgEvaluationContext.mDbgExprEvaluator->mReferenceId = outReferenceId;
  4954. auto result = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4955. if ((formatInfo != NULL) && (dbgEvaluationContext.mDbgExprEvaluator->mCountResultOverride != -1))
  4956. formatInfo->mOverrideCount = dbgEvaluationContext.mDbgExprEvaluator->mCountResultOverride;
  4957. if (dbgEvaluationContext.mPassInstance->HasFailed())
  4958. {
  4959. if (outErrors != NULL)
  4960. {
  4961. int errIdx = 0;
  4962. for (auto err : dbgEvaluationContext.mPassInstance->mErrors)
  4963. {
  4964. if (errIdx > 0)
  4965. (*outErrors) += "\n";
  4966. (*outErrors) += err->mError;
  4967. errIdx++;
  4968. }
  4969. }
  4970. return DbgTypedValue();
  4971. }
  4972. return result;
  4973. }
  4974. void WinDebugger::DbgVisFailed(DebugVisualizerEntry* debugVis, const StringImpl& evalString, const StringImpl& errors)
  4975. {
  4976. bool onlyMemError = errors.StartsWith("Failed to read") && !errors.Contains('\n');
  4977. if ((!debugVis->mShowedError) && (!onlyMemError))
  4978. {
  4979. debugVis->mShowedError = true;
  4980. String errStr = StrFormat("DbgVis '%s' failed while evaluating condition '%s'\n", debugVis->mName.c_str(), evalString.c_str());
  4981. String spacedErrors = errors;
  4982. spacedErrors.Insert(0, " ");
  4983. spacedErrors.Replace("\n", "\n ");
  4984. errStr += spacedErrors;
  4985. OutputMessage(errStr);
  4986. }
  4987. }
  4988. bool WinDebugger::EvalCondition(DebugVisualizerEntry* debugVis, DbgCompileUnit* dbgCompileUnit, DbgTypedValue typedVal, DwFormatInfo& formatInfo, const StringImpl& condition, const Array<String>& dbgVisWildcardCaptures, String& errorStr)
  4989. {
  4990. DwFormatInfo displayStrFormatInfo = formatInfo;
  4991. displayStrFormatInfo.mHidePointers = false;
  4992. displayStrFormatInfo.mRawString = false;
  4993. String errors;
  4994. const String conditionStr = mDebugManager->mDebugVisualizers->DoStringReplace(condition, dbgVisWildcardCaptures);
  4995. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, typedVal, conditionStr, &displayStrFormatInfo, NULL, &errors);
  4996. if ((!evalResult) || (!evalResult.mType->IsBoolean()))
  4997. {
  4998. if (formatInfo.mRawString)
  4999. return false;
  5000. errorStr += "<DbgVis Failed>";
  5001. DbgVisFailed(debugVis, conditionStr, errors);
  5002. return false;
  5003. }
  5004. return evalResult.mBool;
  5005. }
  5006. String WinDebugger::GetArrayItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgType* valueType, DbgTypedValue& curNode, int& count, String* outContinuationData)
  5007. {
  5008. DbgEvaluationContext conditionEvaluationContext(this, dbgCompileUnit, debugVis->mCondition);
  5009. String addrs;
  5010. bool checkLeft = true;
  5011. int usedCount = 0;
  5012. while (usedCount < count)
  5013. {
  5014. DbgTypedValue condVal = conditionEvaluationContext.EvaluateInContext(curNode);
  5015. if (!condVal)
  5016. break;
  5017. if (condVal.mBool)
  5018. {
  5019. auto val = curNode;
  5020. if (valueType == NULL)
  5021. {
  5022. String typeAddr = val.mType->ToStringRaw();
  5023. // RPad
  5024. typeAddr.Append(' ', sizeof(addr_target) * 2 - typeAddr.length());
  5025. addrs += typeAddr;
  5026. }
  5027. String addr = EncodeDataPtr(val.mPtr, false);
  5028. addrs += addr;
  5029. usedCount++;
  5030. }
  5031. curNode.mPtr += curNode.mType->mTypeParam->GetStride();
  5032. }
  5033. count = usedCount;
  5034. if (outContinuationData != NULL)
  5035. {
  5036. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(valueType, false) +
  5037. EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  5038. }
  5039. return addrs;
  5040. }
  5041. String WinDebugger::GetLinkedListItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, addr_target endNodePtr, DbgType* valueType, DbgTypedValue& curNode, int& count, String* outContinuationData)
  5042. {
  5043. DbgEvaluationContext nextEvaluationContext(this, dbgCompileUnit, debugVis->mNextPointer);
  5044. DbgEvaluationContext valueEvaluationContext(this, dbgCompileUnit, debugVis->mValuePointer);
  5045. String addrs;
  5046. bool checkLeft = true;
  5047. int mapIdx;
  5048. for (mapIdx = 0; mapIdx < count; mapIdx++)
  5049. {
  5050. if (curNode.mPtr == endNodePtr)
  5051. break;
  5052. DbgTypedValue val = valueEvaluationContext.EvaluateInContext(curNode);
  5053. if (!val)
  5054. break;
  5055. if (val.mPtr == 0)
  5056. break;
  5057. if (valueType == NULL)
  5058. {
  5059. String typeAddr = val.mType->ToStringRaw();
  5060. // RPad
  5061. typeAddr.Append(' ', sizeof(addr_target)*2 - typeAddr.length());
  5062. addrs += typeAddr;
  5063. }
  5064. String addr = EncodeDataPtr(val.mPtr, false);
  5065. addrs += addr;
  5066. curNode = nextEvaluationContext.EvaluateInContext(curNode);
  5067. }
  5068. count = mapIdx;
  5069. if (outContinuationData != NULL)
  5070. {
  5071. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(endNodePtr, false) + EncodeDataPtr(valueType, false) +
  5072. EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  5073. }
  5074. return addrs;
  5075. }
  5076. String WinDebugger::GetDictionaryItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgTypedValue dictValue, int bucketIdx, int nodeIdx, int& count, String* outContinuationData)
  5077. {
  5078. //DbgEvaluationContext bucketsEvaluationContext(this, dbgModule, debugVis->mBuckets);
  5079. DbgEvaluationContext nextEvaluationContext(this, dbgCompileUnit->mDbgModule, debugVis->mNextPointer);
  5080. DbgTypedValue bucketsPtr = EvaluateInContext(dbgCompileUnit, dictValue, debugVis->mBuckets);
  5081. DbgTypedValue entriesPtr = EvaluateInContext(dbgCompileUnit, dictValue, debugVis->mEntries);
  5082. if ((!bucketsPtr) || (!entriesPtr))
  5083. {
  5084. count = -1;
  5085. return "";
  5086. }
  5087. int entrySize = entriesPtr.mType->mTypeParam->GetStride();
  5088. int bucketIdxSize = bucketsPtr.mType->mTypeParam->GetStride();
  5089. String addrs;
  5090. bool checkLeft = true;
  5091. int encodeCount = 0;
  5092. while (encodeCount < count)
  5093. {
  5094. if (nodeIdx != -1)
  5095. {
  5096. DbgTypedValue entryValue;
  5097. entryValue.mSrcAddress = entriesPtr.mPtr + (nodeIdx * entrySize);
  5098. entryValue.mType = entriesPtr.mType->mTypeParam;
  5099. addrs += EncodeDataPtr(entryValue.mSrcAddress, false);
  5100. DbgTypedValue nextValue = nextEvaluationContext.EvaluateInContext(entryValue);
  5101. if ((!nextValue) || (!nextValue.mType->IsInteger()))
  5102. {
  5103. break;
  5104. }
  5105. nodeIdx = (int)nextValue.GetInt64();
  5106. encodeCount++;
  5107. }
  5108. else
  5109. {
  5110. if (bucketIdxSize == 4)
  5111. nodeIdx = ReadMemory<int>(bucketsPtr.mPtr + bucketIdx * sizeof(int32));
  5112. else
  5113. nodeIdx = (int)ReadMemory<int64>(bucketsPtr.mPtr + bucketIdx * sizeof(int64));
  5114. bucketIdx++;
  5115. }
  5116. }
  5117. count = encodeCount;
  5118. //count = mapIdx;
  5119. if (outContinuationData != NULL)
  5120. {
  5121. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(dictValue.mType, false) + EncodeDataPtr(dictValue.mSrcAddress, false) +
  5122. EncodeDataPtr((addr_target)bucketIdx, false) + EncodeDataPtr((addr_target)nodeIdx, false);
  5123. }
  5124. return addrs;
  5125. }
  5126. String WinDebugger::GetTreeItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, Array<addr_target>& parentList, DbgType*& valueType, DbgTypedValue& curNode, int count, String* outContinuationData)
  5127. {
  5128. DbgEvaluationContext leftEvaluationContext(this, dbgCompileUnit, debugVis->mLeftPointer);
  5129. DbgEvaluationContext rightEvaluationContext(this, dbgCompileUnit, debugVis->mRightPointer);
  5130. DbgEvaluationContext valueEvaluationContext(this, dbgCompileUnit, debugVis->mValuePointer);
  5131. DbgEvaluationContext conditionEvaluationContext(this, dbgCompileUnit, debugVis->mCondition);
  5132. String addrs;
  5133. bool checkLeft = true;
  5134. if ((curNode.mPtr & 2) != 0) // Flag from continuation
  5135. {
  5136. checkLeft = false;
  5137. curNode.mPtr &= (addr_target)~2;
  5138. }
  5139. HashSet<intptr> seenAddrs;
  5140. for (int mapIdx = 0; mapIdx < count; mapIdx++)
  5141. {
  5142. DbgTypedValue readNode;
  5143. while (true)
  5144. {
  5145. bool checkNode = (curNode.mPtr & 1) == 0;
  5146. readNode = curNode;
  5147. readNode.mPtr &= (addr_target)~1;
  5148. if (checkLeft)
  5149. {
  5150. DbgTypedValue leftValue = leftEvaluationContext.EvaluateInContext(readNode);
  5151. bool isEmpty = leftValue.mPtr == NULL;
  5152. if ((leftValue) && (conditionEvaluationContext.HasExpression()))
  5153. {
  5154. auto condValue = conditionEvaluationContext.EvaluateInContext(leftValue);
  5155. if (condValue)
  5156. isEmpty = !condValue.mBool;
  5157. }
  5158. if (isEmpty)
  5159. {
  5160. checkLeft = false;
  5161. break; // Handle node
  5162. }
  5163. parentList.push_back(curNode.mPtr);
  5164. curNode = leftValue;
  5165. }
  5166. else if (checkNode)
  5167. {
  5168. break; // Handle node
  5169. }
  5170. else
  5171. {
  5172. DbgTypedValue rightValue = rightEvaluationContext.EvaluateInContext(readNode);
  5173. bool isEmpty = rightValue.mPtr == NULL;
  5174. if ((rightValue) && (conditionEvaluationContext.HasExpression()))
  5175. {
  5176. auto condValue = conditionEvaluationContext.EvaluateInContext(rightValue);
  5177. if (condValue)
  5178. isEmpty = !condValue.mBool;
  5179. }
  5180. if (!isEmpty)
  5181. {
  5182. curNode = rightValue;
  5183. checkLeft = true;
  5184. }
  5185. else
  5186. {
  5187. if (parentList.size() == 0)
  5188. {
  5189. // Failed
  5190. break;
  5191. }
  5192. curNode.mPtr = parentList.back();
  5193. parentList.pop_back();
  5194. continue; // Don't check against seenAddrs
  5195. }
  5196. }
  5197. if (!seenAddrs.Add(curNode.mPtr))
  5198. {
  5199. // Failed!
  5200. return "";
  5201. }
  5202. }
  5203. DbgTypedValue val = valueEvaluationContext.EvaluateInContext(readNode);
  5204. if (valueType == NULL)
  5205. valueType = val.mType;
  5206. String addr = EncodeDataPtr(val.mPtr, false);
  5207. addrs += addr;
  5208. curNode.mPtr |= 1; // Node handled
  5209. }
  5210. if (!checkLeft)
  5211. curNode.mPtr |= 2;
  5212. if (outContinuationData != NULL)
  5213. {
  5214. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(valueType, false) + EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  5215. for (auto parent : parentList)
  5216. *outContinuationData += EncodeDataPtr(parent, false);
  5217. }
  5218. return addrs;
  5219. }
  5220. String WinDebugger::GetCollectionContinuation(const StringImpl& continuationData, int callStackIdx, int count)
  5221. {
  5222. DbgCompileUnit* dbgCompileUnit = GetCallStackCompileUnit(callStackIdx);;
  5223. if (!IsPaused())
  5224. return "";
  5225. const char* dataPtr = continuationData.c_str();
  5226. DebugVisualizerEntry* debugVis = (DebugVisualizerEntry*)DecodeLocalDataPtr(dataPtr);
  5227. if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_TreeItems)
  5228. {
  5229. DbgType* valueType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5230. DbgTypedValue curNode;
  5231. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5232. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5233. Array<addr_target> parentList;
  5234. String newContinuationData;
  5235. while (*dataPtr != 0)
  5236. parentList.push_back(DecodeTargetDataPtr(dataPtr));
  5237. String retVal = GetTreeItems(dbgCompileUnit, debugVis, parentList, valueType, curNode, count, &newContinuationData);
  5238. retVal += "\n" + newContinuationData;
  5239. return retVal;
  5240. }
  5241. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_LinkedList)
  5242. {
  5243. addr_target endNodePtr = DecodeTargetDataPtr(dataPtr);
  5244. DbgType* valueType = (DbgType*) DecodeLocalDataPtr(dataPtr);
  5245. DbgTypedValue curNode;
  5246. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5247. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5248. String newContinuationData;
  5249. if (count < 0)
  5250. count = 3;
  5251. String retVal = GetLinkedListItems(dbgCompileUnit, debugVis, endNodePtr, valueType, curNode, count, &newContinuationData);
  5252. retVal += "\n" + newContinuationData;
  5253. return retVal;
  5254. }
  5255. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Array)
  5256. {
  5257. DbgType* valueType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5258. DbgTypedValue curNode;
  5259. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5260. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5261. String newContinuationData;
  5262. if (count < 0)
  5263. count = 3;
  5264. String retVal = GetArrayItems(dbgCompileUnit, debugVis, valueType, curNode, count, &newContinuationData);
  5265. retVal += "\n" + newContinuationData;
  5266. return retVal;
  5267. }
  5268. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Dictionary)
  5269. {
  5270. DbgTypedValue dictValue;
  5271. dictValue.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5272. dictValue.mSrcAddress = DecodeTargetDataPtr(dataPtr);
  5273. int bucketIdx = (int)DecodeTargetDataPtr(dataPtr);
  5274. int nodeIdx = (int)DecodeTargetDataPtr(dataPtr);
  5275. String newContinuationData;
  5276. String retVal = GetDictionaryItems(dbgCompileUnit, debugVis, dictValue, bucketIdx, nodeIdx, count, &newContinuationData);
  5277. retVal += "\n" + newContinuationData;
  5278. return retVal;
  5279. }
  5280. return "";
  5281. }
  5282. template <typename T>
  5283. static String IntTypeToString(T val, const StringImpl& name, DwDisplayInfo* displayInfo, DwFormatInfo& formatInfo)
  5284. {
  5285. auto intDisplayType = displayInfo->mIntDisplayType;
  5286. if (formatInfo.mDisplayType == DwDisplayType_Decimal)
  5287. intDisplayType = DwIntDisplayType_Decimal;
  5288. else if (formatInfo.mDisplayType == DwDisplayType_HexUpper)
  5289. intDisplayType = DwIntDisplayType_HexadecimalUpper;
  5290. else if (formatInfo.mDisplayType == DwDisplayType_HexLower)
  5291. intDisplayType = DwIntDisplayType_HexadecimalLower;
  5292. if (intDisplayType == DwIntDisplayType_Binary)
  5293. {
  5294. String binary;
  5295. for (int i = 0; i < sizeof(T) * 8; i++)
  5296. {
  5297. if ((i != 0) && (i % 4 == 0))
  5298. binary = "'" + binary;
  5299. if ((i != 0) && (i % 16 == 0))
  5300. binary = "'" + binary;
  5301. binary = ((val & ((T)1 << i)) ? "1" : "0") + binary;
  5302. }
  5303. return StrFormat("0b'%s\n%s", binary.c_str(), name.c_str());
  5304. }
  5305. if (intDisplayType == DwIntDisplayType_Octal)
  5306. {
  5307. String format;
  5308. if (sizeof(T) == 8)
  5309. {
  5310. format = StrFormat("0o%%lo\n%s", name.c_str());
  5311. }
  5312. else
  5313. format = StrFormat("0o%%0%do\n%s", sizeof(val) * 2, name.c_str());
  5314. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5315. }
  5316. if (intDisplayType == DwIntDisplayType_HexadecimalUpper)
  5317. {
  5318. String format;
  5319. if (sizeof(T) == 8)
  5320. {
  5321. format = StrFormat("0x%%l@\n%s", name.c_str());
  5322. }
  5323. else
  5324. format = StrFormat("0x%%0%dX\n%s", sizeof(val) * 2, name.c_str());
  5325. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5326. }
  5327. //TODO: Implement HexadecimalLower
  5328. if (intDisplayType == DwIntDisplayType_HexadecimalLower)
  5329. {
  5330. String format;
  5331. if (sizeof(T) == 8)
  5332. {
  5333. format = StrFormat("0x%%l@\n%s", name.c_str());
  5334. }
  5335. else
  5336. format = StrFormat("0x%%0%dX\n%s", sizeof(val) * 2, name.c_str());
  5337. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5338. }
  5339. if (std::is_unsigned<T>::value)
  5340. {
  5341. if (sizeof(T) == 8)
  5342. {
  5343. if (val > 0x7FFFFFFFF)
  5344. return StrFormat("%llu\n%s\n:editVal\t%lluUL", val, name.c_str(), val);
  5345. else
  5346. return StrFormat("%llu\n%s", val, name.c_str());
  5347. }
  5348. else
  5349. return StrFormat("%u\n%s", val, name.c_str());
  5350. }
  5351. else
  5352. {
  5353. if (sizeof(T) == 8)
  5354. {
  5355. if ((val > 0x7FFFFFFFF) || (val < -0x80000000LL))
  5356. return StrFormat("%lld\n%s\n:editVal\t%lldL", val, name.c_str(), val);
  5357. else
  5358. return StrFormat("%lld\n%s", val, name.c_str(), val);
  5359. }
  5360. else
  5361. return StrFormat("%d\n%s", val, name.c_str());
  5362. }
  5363. }
  5364. DwDisplayInfo* WinDebugger::GetDisplayInfo(const StringImpl& referenceId)
  5365. {
  5366. DwDisplayInfo* displayInfo = &mDebugManager->mDefaultDisplayInfo;
  5367. if (!referenceId.empty())
  5368. {
  5369. mDebugManager->mDisplayInfos.TryGetValue(referenceId, &displayInfo);
  5370. }
  5371. return displayInfo;
  5372. }
  5373. static String WrapWithModifiers(const StringImpl& origName, DbgType* dbgType, DbgLanguage language)
  5374. {
  5375. if (language == DbgLanguage_Unknown)
  5376. language = dbgType->GetLanguage();
  5377. String name = origName;
  5378. while (true)
  5379. {
  5380. if (dbgType->mTypeCode == DbgType_Const)
  5381. {
  5382. if (language == DbgLanguage_Beef)
  5383. name = "readonly " + name;
  5384. else
  5385. name = "const " + name;
  5386. dbgType = dbgType->mTypeParam;
  5387. }
  5388. else if (dbgType->mTypeCode == DbgType_Volatile)
  5389. {
  5390. name = "volatile " + name;
  5391. dbgType = dbgType->mTypeParam;
  5392. }
  5393. else if (dbgType->mTypeCode == DbgType_TypeDef)
  5394. {
  5395. dbgType = dbgType->mTypeParam;
  5396. }
  5397. else if (dbgType->mTypeCode == DbgType_Ref)
  5398. {
  5399. if (language == DbgLanguage_Beef)
  5400. name = "ref " + name;
  5401. else
  5402. name = name + "&";
  5403. dbgType = dbgType->mTypeParam;
  5404. }
  5405. else if (dbgType->mTypeCode == DbgType_Bitfield)
  5406. {
  5407. return dbgType->ToString(language);
  5408. }
  5409. else
  5410. return name;
  5411. }
  5412. }
  5413. DebugVisualizerEntry* WinDebugger::FindVisualizerForType(DbgType* dbgType, Array<String>* wildcardCaptures)
  5414. {
  5415. auto entry = mDebugManager->mDebugVisualizers->FindEntryForType(dbgType->ToString(DbgLanguage_Unknown, true), dbgType->mCompileUnit->mDbgModule->mDbgFlavor, wildcardCaptures);
  5416. if (entry == NULL)
  5417. {
  5418. dbgType = dbgType->GetPrimaryType();
  5419. dbgType->PopulateType();
  5420. for (auto baseTypeEntry : dbgType->mBaseTypes)
  5421. {
  5422. entry = FindVisualizerForType(baseTypeEntry->mBaseType, wildcardCaptures);
  5423. if (entry != NULL)
  5424. break;
  5425. }
  5426. }
  5427. return entry;
  5428. }
  5429. #define GET_FROM(ptr, T) *((T*)(ptr += sizeof(T)) - 1)
  5430. String WinDebugger::ReadString(DbgTypeCode charType, intptr addr, bool isLocalAddr, intptr maxLength, DwFormatInfo& formatInfo)
  5431. {
  5432. int origMaxLength = maxLength;
  5433. if (addr == 0)
  5434. return "";
  5435. BP_ZONE("WinDebugger::ReadString");
  5436. String retVal = "\"";
  5437. bool wasTerminated = false;
  5438. String valString;
  5439. intptr maxShowSize = 255;
  5440. if (maxLength == -1)
  5441. maxLength = formatInfo.mOverrideCount;
  5442. else if (formatInfo.mOverrideCount != -1)
  5443. maxLength = BF_MIN(formatInfo.mOverrideCount, maxLength);
  5444. if (formatInfo.mMaxCount != -1)
  5445. maxLength = BF_MIN(formatInfo.mMaxCount, maxLength);
  5446. if (maxLength == -1)
  5447. maxLength = 8 * 1024 * 1024; // Is 8MB crazy?
  5448. if (!formatInfo.mRawString)
  5449. maxLength = BF_MIN(maxLength, maxShowSize);
  5450. //EnableMemCache();
  5451. bool readFailed = false;
  5452. intptr strPtr = addr;
  5453. int charLen = 1;
  5454. if ((charType == DbgType_SChar16) || (charType == DbgType_UChar16))
  5455. charLen = 2;
  5456. else if ((charType == DbgType_SChar32) || (charType == DbgType_UChar32))
  5457. charLen = 4;
  5458. bool isUTF8 = formatInfo.mDisplayType == DwDisplayType_Utf8;
  5459. int readSize = BF_MIN(1024, maxLength * charLen);
  5460. uint8 buf[1024];
  5461. uint8* bufPtr = NULL;
  5462. uint8* bufEnd = NULL;
  5463. bool hasHighAscii = false;
  5464. int i;
  5465. for (i = 0; i < maxLength; i++)
  5466. {
  5467. if (bufPtr >= bufEnd)
  5468. {
  5469. while (true)
  5470. {
  5471. if (readSize < charLen)
  5472. {
  5473. readFailed = true;
  5474. break;
  5475. }
  5476. if (ReadMemory(strPtr, readSize, buf, isLocalAddr))
  5477. break;
  5478. readSize /= 2;
  5479. }
  5480. if (readFailed)
  5481. break;
  5482. bufPtr = buf;
  5483. bufEnd = buf + readSize;
  5484. }
  5485. switch (charLen)
  5486. {
  5487. case 1:
  5488. {
  5489. char c = GET_FROM(bufPtr, char);
  5490. if ((c != 0) || (formatInfo.mOverrideCount != -1))
  5491. {
  5492. if ((uint8)c >= 0x80)
  5493. hasHighAscii = true;
  5494. valString.Append(c);
  5495. }
  5496. else
  5497. wasTerminated = true;
  5498. }
  5499. break;
  5500. case 2:
  5501. {
  5502. uint16 c16 = GET_FROM(bufPtr, uint16);
  5503. if ((c16 != 0) || (formatInfo.mOverrideCount != -1))
  5504. {
  5505. char str[8];
  5506. u8_toutf8(str, 8, c16);
  5507. valString += str;
  5508. }
  5509. else
  5510. wasTerminated = true;
  5511. }
  5512. break;
  5513. case 4:
  5514. {
  5515. uint32 c32 = GET_FROM(bufPtr, uint32);
  5516. if ((c32 != 0) || (formatInfo.mOverrideCount != -1))
  5517. {
  5518. char str[8];
  5519. u8_toutf8(str, 8, c32);
  5520. valString += str;
  5521. }
  5522. else
  5523. wasTerminated = true;
  5524. }
  5525. break;
  5526. }
  5527. if ((wasTerminated) && (formatInfo.mOverrideCount != -1))
  5528. {
  5529. valString += '\x00';
  5530. wasTerminated = false;
  5531. }
  5532. if ((wasTerminated) || (readFailed))
  5533. {
  5534. break;
  5535. }
  5536. strPtr += charLen;
  5537. }
  5538. //DisableMemCache();
  5539. if (formatInfo.mOverrideCount != -1)
  5540. {
  5541. if (i == formatInfo.mOverrideCount)
  5542. wasTerminated = true;
  5543. }
  5544. if (strPtr == addr + origMaxLength)
  5545. wasTerminated = true;
  5546. if (valString.length() == formatInfo.mOverrideCount)
  5547. wasTerminated = true;
  5548. // if (formatInfo.mDisplayType == DwDisplayType_Ascii)
  5549. // {
  5550. // // Our encoding for retVal is already assumed to be UTF8, so the special case here actually Ascii
  5551. // valString = UTF8Encode(ToWString(valString));
  5552. // }
  5553. if (formatInfo.mRawString)
  5554. {
  5555. if ((formatInfo.mDisplayType == DwDisplayType_Utf8) || (!hasHighAscii))
  5556. return valString;
  5557. String utf8Str;
  5558. for (int i = 0; i < (int)valString.length(); i++)
  5559. {
  5560. char c = valString[i];
  5561. if ((uint8)c >= 0x80)
  5562. {
  5563. utf8Str += (char)(0xC0 | (((uint8)c & 0xFF) >> 6));
  5564. utf8Str += (char)(0x80 | ((uint8)c & 0x3F));
  5565. }
  5566. else
  5567. utf8Str += c;
  5568. }
  5569. return utf8Str;
  5570. }
  5571. if ((readFailed) && (valString.IsEmpty()))
  5572. return "< Failed to read string >";
  5573. retVal += SlashString(valString, true, true, formatInfo.mLanguage == DbgLanguage_Beef);
  5574. // We could go over 'maxShowSize' if we have a lot of slashed chars. An uninitialized string can be filled with '\xcc' chars
  5575. if ((!formatInfo.mRawString) && ((int)retVal.length() > maxShowSize))
  5576. {
  5577. retVal = retVal.Substring(0, maxShowSize);
  5578. wasTerminated = false;
  5579. }
  5580. if (wasTerminated)
  5581. retVal += "\"";
  5582. else
  5583. retVal += "...";
  5584. return retVal;
  5585. }
  5586. void WinDebugger::ProcessEvalString(DbgCompileUnit* dbgCompileUnit, DbgTypedValue useTypedValue, String& evalStr, String& displayString, DwFormatInfo& formatInfo, DebugVisualizerEntry* debugVis, bool limitLength)
  5587. {
  5588. for (int i = 0; i < (int)evalStr.length(); i++)
  5589. {
  5590. char c = evalStr[i];
  5591. char nextC = 0;
  5592. if (i < (int)evalStr.length() - 1)
  5593. nextC = evalStr[i + 1];
  5594. if ((c == '{') && (nextC != '{'))
  5595. {
  5596. // Evaluate
  5597. int endIdx = i;
  5598. for (; endIdx < (int)evalStr.length(); endIdx++)
  5599. {
  5600. //TODO: Do better parsing - this paren could be inside a string, for example
  5601. if (evalStr[endIdx] == '}')
  5602. break;
  5603. }
  5604. DwFormatInfo displayStrFormatInfo = formatInfo;
  5605. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + (int)displayString.length();
  5606. displayStrFormatInfo.mHidePointers = false;
  5607. if ((limitLength) && (displayStrFormatInfo.mTotalSummaryLength > 255))
  5608. {
  5609. displayString += "...";
  5610. }
  5611. else
  5612. {
  5613. String evalString = evalStr.Substring(i + 1, endIdx - i - 1);
  5614. String errors;
  5615. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, useTypedValue, evalString, &displayStrFormatInfo, NULL, &errors);
  5616. if (evalResult)
  5617. {
  5618. if (displayStrFormatInfo.mNoEdit)
  5619. formatInfo.mNoEdit = true;
  5620. String result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  5621. if ((formatInfo.mRawString) && (limitLength))
  5622. {
  5623. displayString = result;
  5624. return;
  5625. }
  5626. int crPos = result.IndexOf('\n');
  5627. if (crPos != -1)
  5628. displayString += result.Substring(0, crPos);
  5629. else
  5630. displayString += result;
  5631. }
  5632. else if (debugVis != NULL)
  5633. {
  5634. displayString += "<DbgVis Failed>";
  5635. DbgVisFailed(debugVis, evalString, errors);
  5636. }
  5637. else
  5638. {
  5639. displayString += "<Eval Failed>";
  5640. }
  5641. }
  5642. i = endIdx;
  5643. continue;
  5644. }
  5645. else if ((c == '{') && (nextC == '{'))
  5646. {
  5647. // Skip next paren
  5648. i++;
  5649. }
  5650. else if ((c == '}') && (nextC == '}'))
  5651. {
  5652. // Skip next paren
  5653. i++;
  5654. }
  5655. displayString += c;
  5656. }
  5657. }
  5658. static bool IsNormalChar(uint32 c)
  5659. {
  5660. return (c < 0x80);
  5661. }
  5662. String WinDebugger::DbgTypedValueToString(const DbgTypedValue& origTypedValue, const StringImpl& expr, DwFormatInfo& formatInfo, DbgExprEvaluator* optEvaluator, bool fullPrecision)
  5663. {
  5664. BP_ZONE("WinDebugger::DbgTypedValueToString");
  5665. DbgTypedValue typedValue = origTypedValue;
  5666. auto dbgCompileUnit = typedValue.mType->mCompileUnit;
  5667. auto dbgModule = typedValue.mType->GetDbgModule();
  5668. auto language = origTypedValue.mType->GetLanguage();
  5669. if (language == DbgLanguage_Unknown)
  5670. language = formatInfo.mLanguage;
  5671. formatInfo.mLanguage = language;
  5672. bool isBeef = language == DbgLanguage_Beef;
  5673. char str[32];
  5674. bool readFailed = false;
  5675. bool isCompositeType = false;
  5676. bool isSizedArray = false;
  5677. bool isEnum = false;
  5678. int64 enumVal = 0;
  5679. String result;
  5680. DwDisplayInfo* displayInfo = GetDisplayInfo(formatInfo.mReferenceId);
  5681. DbgType* origValueType = typedValue.mType;
  5682. bool origHadRef = false;
  5683. DbgType* dwValueType = typedValue.mType->RemoveModifiers(&origHadRef);
  5684. if (dwValueType == NULL)
  5685. dwValueType = dbgModule->GetPrimitiveType(DbgType_Void, language);
  5686. else
  5687. dwValueType = dwValueType->GetPrimaryType();
  5688. if (dwValueType->mTypeCode == DbgType_TypeDef)
  5689. {
  5690. DbgTypedValue realTypedVal = typedValue;
  5691. realTypedVal.mType = dwValueType->mTypeParam;
  5692. return DbgTypedValueToString(realTypedVal, expr, formatInfo, optEvaluator);
  5693. }
  5694. if (formatInfo.mRawString)
  5695. {
  5696. if ((dwValueType->mTypeCode != DbgType_Struct) && (dwValueType->mTypeCode != DbgType_Class) && (dwValueType->mTypeCode != DbgType_Ptr) && (dwValueType->mTypeCode != DbgType_SizedArray))
  5697. return "";
  5698. }
  5699. auto _ShowArraySummary = [&](String& retVal, addr_target ptrVal, int64 arraySize, DbgType* innerType)
  5700. {
  5701. String displayString;
  5702. displayString += "{";
  5703. for (int idx = 0; idx < arraySize; idx++)
  5704. {
  5705. if (formatInfo.mTotalSummaryLength + retVal.length() + displayString.length() > 255)
  5706. {
  5707. displayString += "...";
  5708. break;
  5709. }
  5710. if ((idx != 0) && (!displayString.EndsWith('{')))
  5711. displayString += ", ";
  5712. DwFormatInfo displayStrFormatInfo = formatInfo;
  5713. displayStrFormatInfo.mExpandItemDepth = 1;
  5714. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + retVal.length() + displayString.length();
  5715. displayStrFormatInfo.mHidePointers = false;
  5716. displayStrFormatInfo.mArrayLength = -1;
  5717. // Why did we have this "na" on here? It made "void*[3]" type things show up as "{,,}"
  5718. //String evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + StrFormat(")[%d], na", idx);
  5719. String evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + StrFormat(")[%lld]", idx);
  5720. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, typedValue, evalStr, &displayStrFormatInfo);
  5721. String result;
  5722. if (evalResult)
  5723. {
  5724. result = DbgTypedValueToString(evalResult, evalStr, displayStrFormatInfo, NULL);
  5725. int crPos = result.IndexOf('\n');
  5726. if (crPos != -1)
  5727. result.RemoveToEnd(crPos);
  5728. }
  5729. else
  5730. result = "???";
  5731. displayString += result;
  5732. }
  5733. displayString += "}";
  5734. retVal += displayString;
  5735. };
  5736. if (formatInfo.mArrayLength != -1)
  5737. {
  5738. if (formatInfo.mRawString)
  5739. return "";
  5740. if (dwValueType->IsPointer())
  5741. {
  5742. String retVal;
  5743. addr_target ptrVal = (addr_target)typedValue.mPtr;
  5744. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  5745. {
  5746. retVal = EncodeDataPtr(ptrVal, true) + " ";
  5747. retVal += dwValueType->mTypeParam->ToString(language);
  5748. retVal += StrFormat("[%lld] ", (int64)formatInfo.mArrayLength);
  5749. }
  5750. _ShowArraySummary(retVal, ptrVal, formatInfo.mArrayLength, dwValueType->mTypeParam);
  5751. String idxStr = "[{0}]";
  5752. DbgType* innerType = dwValueType->mTypeParam;
  5753. retVal += "\n" + dwValueType->ToString(language);
  5754. String evalStr = "*((" + typedValue.mType->ToStringRaw(language) + ")" + EncodeDataPtr(ptrVal, true) + " + {0})";
  5755. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, (int)BF_MAX(formatInfo.mArrayLength, 0), 10000) +
  5756. "\t" + idxStr + "\t" + evalStr;
  5757. return retVal;
  5758. }
  5759. else
  5760. {
  5761. DwFormatInfo newFormatInfo = formatInfo;
  5762. newFormatInfo.mArrayLength = -1;
  5763. String retVal = DbgTypedValueToString(typedValue, expr, newFormatInfo, optEvaluator);
  5764. int crPos = (int)retVal.IndexOf('\n');
  5765. if (crPos != -1)
  5766. retVal = "!Array length flag not valid with this type" + retVal.Substring(crPos);
  5767. return retVal;
  5768. }
  5769. }
  5770. switch (dwValueType->mTypeCode)
  5771. {
  5772. case DbgType_Void:
  5773. return "\nvoid";
  5774. case DbgType_Bool:
  5775. {
  5776. if (typedValue.mUInt8 == 0)
  5777. return "false\n" + WrapWithModifiers("bool", origValueType, language);
  5778. else if (typedValue.mUInt8 == 1)
  5779. return "true\n" + WrapWithModifiers("bool", origValueType, language);
  5780. else
  5781. return StrFormat("true (%d)\n", typedValue.mUInt8) + WrapWithModifiers("bool", origValueType, language);
  5782. }
  5783. break;
  5784. case DbgType_UChar:
  5785. if (language != DbgLanguage_Beef)
  5786. return IntTypeToString<uint8>(typedValue.mUInt8, WrapWithModifiers("uint8_t", origValueType, language), displayInfo, formatInfo);
  5787. case DbgType_SChar:
  5788. {
  5789. if (typedValue.mInt8 != 0)
  5790. {
  5791. char str[2] = {(char)typedValue.mInt8};
  5792. result = SlashString(str, formatInfo.mDisplayType == DwDisplayType_Utf8, true);
  5793. if (!IsNormalChar(typedValue.mUInt8))
  5794. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt8);
  5795. else
  5796. result = StrFormat("'%s'\n", result.c_str());
  5797. }
  5798. else
  5799. result = "'\\0'\n";
  5800. return result + WrapWithModifiers("char", origValueType, language);
  5801. }
  5802. break;
  5803. case DbgType_UChar16:
  5804. if (language != DbgLanguage_Beef)
  5805. return IntTypeToString<int16>(typedValue.mUInt8, WrapWithModifiers("uint16_t", origValueType, language), displayInfo, formatInfo);
  5806. case DbgType_SChar16:
  5807. {
  5808. if (typedValue.mInt16 != 0)
  5809. {
  5810. u8_toutf8(str, 8, typedValue.mUInt32);
  5811. result = SlashString(str, true, true);
  5812. if (!IsNormalChar(typedValue.mUInt32))
  5813. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt16);
  5814. else
  5815. result = StrFormat("'%s'\n", result.c_str());
  5816. }
  5817. else
  5818. result = "'\\0'\n";
  5819. return result + WrapWithModifiers(isBeef ? "char16" : "int16_t", origValueType, language);
  5820. }
  5821. break;
  5822. case DbgType_UChar32:
  5823. case DbgType_SChar32:
  5824. {
  5825. if (typedValue.mInt32 != 0)
  5826. {
  5827. u8_toutf8(str, 8, typedValue.mUInt32);
  5828. result = SlashString(str, true, true);
  5829. if (!IsNormalChar(typedValue.mUInt32))
  5830. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt32);
  5831. else
  5832. result = StrFormat("'%s'\n", result.c_str());
  5833. }
  5834. else
  5835. result = "'\\0'\n";
  5836. return result + WrapWithModifiers(isBeef ? "char32" : "int32_t", origValueType, language);
  5837. }
  5838. break;
  5839. case DbgType_i8:
  5840. return IntTypeToString<int8>(typedValue.mInt8, WrapWithModifiers(isBeef ? "int8" : "int8_t", origValueType, language), displayInfo, formatInfo);
  5841. case DbgType_u8:
  5842. return IntTypeToString<uint8>(typedValue.mUInt8, WrapWithModifiers(isBeef ? "uint8" : "uint8_t", origValueType, language), displayInfo, formatInfo);
  5843. case DbgType_i16:
  5844. return IntTypeToString<int16>(typedValue.mInt16, WrapWithModifiers(isBeef ? "int16" : "int16_t", origValueType, language), displayInfo, formatInfo);
  5845. case DbgType_u16:
  5846. return IntTypeToString<uint16>(typedValue.mUInt16, WrapWithModifiers(isBeef ? "uint16" : "uint16_t", origValueType, language), displayInfo, formatInfo);
  5847. case DbgType_i32:
  5848. return IntTypeToString<int32>(typedValue.mInt32, WrapWithModifiers(isBeef ? "int32" : "int32_t", origValueType, language), displayInfo, formatInfo);
  5849. case DbgType_u32:
  5850. return IntTypeToString<uint32>(typedValue.mUInt32, WrapWithModifiers(isBeef ? "uint32" : "uint32_t", origValueType, language), displayInfo, formatInfo);
  5851. case DbgType_i64:
  5852. return IntTypeToString<int64>(typedValue.mInt64, WrapWithModifiers(isBeef ? "int64" : "int64_t", origValueType, language), displayInfo, formatInfo);
  5853. case DbgType_u64:
  5854. return IntTypeToString<uint64>(typedValue.mUInt64, WrapWithModifiers(isBeef ? "uint64" : "uint64_t", origValueType, language), displayInfo, formatInfo);
  5855. case DbgType_RegGroup:
  5856. {
  5857. if ((typedValue.mRegNum >= CPUReg_M128_XMMREG_FIRST) && (typedValue.mRegNum <= CPUReg_M128_XMMREG_LAST))
  5858. {
  5859. int callStackIdx = formatInfo.mCallStackIdx;
  5860. FixCallStackIdx(callStackIdx);
  5861. UpdateRegisterUsage(callStackIdx);
  5862. WdStackFrame* wdStackFrame = mCallStack[callStackIdx];
  5863. RegForm regForm = RegForm_Unknown;
  5864. if (typedValue.mRegNum < (int)wdStackFrame->mRegForms.size())
  5865. regForm = wdStackFrame->mRegForms[typedValue.mRegNum];
  5866. int xmmMajor = typedValue.mRegNum - CPUReg_M128_XMMREG_FIRST;
  5867. String headerStr;
  5868. String xmmType = "__m128";
  5869. int xmmCount = 4;
  5870. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2) ||
  5871. (regForm == RegForm_Long) || (regForm == RegForm_Long2) ||
  5872. (regForm == RegForm_ULong) || (regForm == RegForm_ULong2))
  5873. xmmCount = 2;
  5874. //TODO: add byte, short, int, etc...
  5875. if (optEvaluator)
  5876. {
  5877. DwMmDisplayType mmDwMmDisplayType = displayInfo->mMmDisplayType;
  5878. if (mmDwMmDisplayType == DwMmDisplayType_Default)
  5879. {
  5880. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2))
  5881. mmDwMmDisplayType = DwMmDisplayType_Double;
  5882. else if (regForm == RegForm_Int4)
  5883. mmDwMmDisplayType = DwMmDisplayType_Int;
  5884. }
  5885. //TODO: Add support for int types
  5886. if (mmDwMmDisplayType == DwMmDisplayType_Double)
  5887. {
  5888. xmmType = "__m128d";
  5889. xmmCount = 2;
  5890. double xmmRegVals[2];
  5891. CPURegisters* regs = optEvaluator->GetRegisters();
  5892. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5893. {
  5894. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5895. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_Double);
  5896. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5897. xmmRegVals[xmmMinor] = xmmReg.mDouble;
  5898. }
  5899. headerStr = StrFormat("(%f, %f)", xmmRegVals[0], xmmRegVals[1]);
  5900. }
  5901. else if (mmDwMmDisplayType == DwMmDisplayType_Byte)
  5902. {
  5903. int xmmRegVals[4];
  5904. xmmCount = 4;
  5905. CPURegisters* regs = optEvaluator->GetRegisters();
  5906. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5907. {
  5908. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5909. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i32);
  5910. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5911. xmmRegVals[xmmMinor] = xmmReg.mInt8;
  5912. }
  5913. headerStr = StrFormat("(%d, %d, %d, %d)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  5914. }
  5915. else if (mmDwMmDisplayType == DwMmDisplayType_Short)
  5916. {
  5917. int xmmRegVals[4];
  5918. xmmCount = 4;
  5919. CPURegisters* regs = optEvaluator->GetRegisters();
  5920. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5921. {
  5922. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5923. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i32);
  5924. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5925. xmmRegVals[xmmMinor] = xmmReg.mInt16;
  5926. }
  5927. headerStr = StrFormat("(%d, %d, %d, %d)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  5928. }
  5929. else if (mmDwMmDisplayType == DwMmDisplayType_Int)
  5930. {
  5931. int xmmRegVals[4];
  5932. xmmCount = 4;
  5933. CPURegisters* regs = optEvaluator->GetRegisters();
  5934. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5935. {
  5936. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5937. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i32);
  5938. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5939. xmmRegVals[xmmMinor] = xmmReg.mInt32;
  5940. }
  5941. headerStr = StrFormat("(%d, %d, %d, %d)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  5942. }
  5943. else // Float
  5944. {
  5945. float xmmRegVals[4];
  5946. xmmCount = 4;
  5947. CPURegisters* regs = optEvaluator->GetRegisters();
  5948. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5949. {
  5950. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5951. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_Single);
  5952. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5953. xmmRegVals[xmmMinor] = xmmReg.mSingle;
  5954. }
  5955. headerStr = StrFormat("(%f, %f, %f, %f)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  5956. }
  5957. }
  5958. else
  5959. {
  5960. headerStr = StrFormat("XMM%d", xmmMajor);
  5961. }
  5962. result = headerStr + "\n" + xmmType;
  5963. for (int i = 0; i < xmmCount; i++)
  5964. result += WrapWithModifiers(StrFormat("\n[%d]\t$xmm%d_%d", i, xmmMajor, i, language), origValueType, language);
  5965. return result;
  5966. }
  5967. else
  5968. {
  5969. switch (typedValue.mRegNum)
  5970. {
  5971. case CPUReg_CAT_ALLREGS:
  5972. {
  5973. return "ALLREGS\n__allregs\niregs\t$iregs\nflags\t$flags\nfpregs\t$fpregs\nmmregs\t$mmregs\nxmmregs\t$xmmregs";
  5974. }
  5975. break;
  5976. case CPUReg_CAT_IREGS:
  5977. {
  5978. #ifdef BF_DBG_32
  5979. String headerStr;
  5980. if (optEvaluator)
  5981. {
  5982. CPURegisters* regs = optEvaluator->GetRegisters();
  5983. headerStr = StrFormat("(eax=0x%08x, ebx=0x%08x, ecx=0x%08x, edx=0x%08x, esi=0x%08x, edi=0x%08x, esp=0x%08x, ebp=0x%08x, eip=0x%08x, efl=0x%08x)",
  5984. (uint32)regs->mIntRegs.eax, (uint32)regs->mIntRegs.ebx, (uint32)regs->mIntRegs.ecx, (uint32)regs->mIntRegs.edx,
  5985. (uint32)regs->mIntRegs.esi, (uint32)regs->mIntRegs.edi, (uint32)regs->mIntRegs.esp, (uint32)regs->mIntRegs.ebp,
  5986. (uint32)regs->mIntRegs.eip, (uint32)regs->mIntRegs.efl);
  5987. }
  5988. else
  5989. {
  5990. headerStr = "IREGS";
  5991. }
  5992. return StrFormat("%s\n__iregs\neax\t$eax\nebx\t$ebx\necx\t$ecx\nedx\t$edx\nesi\t$esi\nedi\t$edi\nesp\t$esp\nebp\t$ebp\neip\t$eip", headerStr.c_str());
  5993. #else
  5994. String headerStr;
  5995. if (optEvaluator)
  5996. {
  5997. CPURegisters* regs = optEvaluator->GetRegisters();
  5998. headerStr = StrFormat("(rax=0x%@, rbx=0x%@, rcx=0x%@, rdx=0x%@, rsi=0x%@, rdi=0x%@, rsp=0x%@, rbp=0x%@, eip=0x%@, r8=0x%@, r9=0x%@, r10=0x%@, r11=0x%@, r12=0x%@, r13=0x%@, r14=0x%@, r15=0x%@, efl=0x%08x)",
  5999. (uint64)regs->mIntRegs.rax, (uint64)regs->mIntRegs.rbx, (uint64)regs->mIntRegs.rcx, (uint64)regs->mIntRegs.rdx,
  6000. (uint64)regs->mIntRegs.rsi, (uint64)regs->mIntRegs.rdi, (uint64)regs->mIntRegs.rsp, (uint64)regs->mIntRegs.rbp,
  6001. (uint64)regs->mIntRegs.rip,
  6002. (uint64)regs->mIntRegs.r8, (uint64)regs->mIntRegs.r9, (uint64)regs->mIntRegs.r10, (uint64)regs->mIntRegs.r11,
  6003. (uint64)regs->mIntRegs.r12, (uint64)regs->mIntRegs.r13, (uint64)regs->mIntRegs.r14, (uint64)regs->mIntRegs.r15,
  6004. (uint32)regs->mIntRegs.efl);
  6005. }
  6006. else
  6007. {
  6008. headerStr = "IREGS";
  6009. }
  6010. return StrFormat("%s\n__iregs\neax\t$eax\nebx\t$ebx\necx\t$ecx\nedx\t$edx\nesi\t$esi\nedi\t$edi\nesp\t$esp\nebp\t$ebp\neip\t$eip\nr8\t$r8\nr9\t$r9\nr10\t$r10\nr11\t$r11\nr12\t$r12\nr13\t$r13\nr14\t$r14\nr15\t$r15", headerStr.c_str());
  6011. #endif
  6012. }
  6013. break;
  6014. case CPUReg_CAT_FPREGS:
  6015. {
  6016. String headerStr;
  6017. if (optEvaluator)
  6018. {
  6019. CPURegisters* regs = optEvaluator->GetRegisters();
  6020. headerStr = "(";
  6021. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6022. {
  6023. if (i)
  6024. headerStr += ", ";
  6025. double val = ConvertFloat80ToDouble(regs->mFpMmRegsArray[i].fp.fp80);
  6026. headerStr += StrFormat("%f", val);
  6027. }
  6028. headerStr += ")";
  6029. }
  6030. else
  6031. {
  6032. headerStr = "FPREGS";
  6033. }
  6034. result = StrFormat("%s\n__fpregs", headerStr.c_str());
  6035. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6036. result += StrFormat("\n[%d]\t$st%d", i, i);
  6037. return result;
  6038. }
  6039. break;
  6040. case CPUReg_CAT_MMREGS:
  6041. {
  6042. String headerStr;
  6043. if (optEvaluator)
  6044. {
  6045. CPURegisters* regs = optEvaluator->GetRegisters();
  6046. headerStr = "(";
  6047. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6048. {
  6049. if (i)
  6050. headerStr += ", ";
  6051. uint64 val = regs->mFpMmRegsArray[i].mm;
  6052. headerStr += StrFormat("0x%016llx", val);
  6053. }
  6054. headerStr += ")";
  6055. }
  6056. else
  6057. {
  6058. headerStr = "MMREGS";
  6059. }
  6060. result = StrFormat("%s\n__mmregs", headerStr.c_str());
  6061. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6062. result += StrFormat("\n[%d]\t$mm%d", i, i);
  6063. return result;
  6064. }
  6065. break;
  6066. case CPUReg_CAT_XMMREGS:
  6067. {
  6068. String headerStr = StrFormat("XMMREGS[%d]", CPURegisters::kNumXmmRegs); // these are too big to put a useful header for the entire category
  6069. result = StrFormat("%s\n__xmmregs", headerStr.c_str());
  6070. for (int i = 0; i < CPURegisters::kNumXmmRegs; ++i)
  6071. result += StrFormat("\n[%d]\t$xmm%d", i, i);
  6072. return result;
  6073. }
  6074. break;
  6075. case CPUReg_CAT_FLAGS:
  6076. {
  6077. String headerStr;
  6078. if (optEvaluator)
  6079. {
  6080. CPURegisters* regs = optEvaluator->GetRegisters();
  6081. #ifdef BF_DBG_32
  6082. #define FLAGVAR(abbr, name) int flag##abbr = ((regs->mIntRegs.efl & ((uint64)1 << CPURegisters::GetFlagBitForRegister(X86Reg_FLAG_##abbr##_##name))) != 0) ? 1 : 0
  6083. FLAGVAR(CF, CARRY);
  6084. FLAGVAR(PF, PARITY);
  6085. FLAGVAR(AF, ADJUST);
  6086. FLAGVAR(ZF, ZERO);
  6087. FLAGVAR(SF, SIGN);
  6088. FLAGVAR(IF, INTERRUPT);
  6089. FLAGVAR(DF, DIRECTION);
  6090. FLAGVAR(OF, OVERFLOW);
  6091. #undef FLAGVAR
  6092. #else
  6093. #define FLAGVAR(abbr, name) int flag##abbr = ((regs->mIntRegs.efl & ((uint64)1 << CPURegisters::GetFlagBitForRegister(X64Reg_FLAG_##abbr##_##name))) != 0) ? 1 : 0
  6094. FLAGVAR(CF, CARRY);
  6095. FLAGVAR(PF, PARITY);
  6096. FLAGVAR(AF, ADJUST);
  6097. FLAGVAR(ZF, ZERO);
  6098. FLAGVAR(SF, SIGN);
  6099. FLAGVAR(IF, INTERRUPT);
  6100. FLAGVAR(DF, DIRECTION);
  6101. FLAGVAR(OF, OVERFLOW);
  6102. #undef FLAGVAR
  6103. #endif
  6104. headerStr = StrFormat("(CF=%d, PF=%d, AF=%d, ZF=%d, SF=%d, IF=%d, DF=%d, OF=%d)",
  6105. flagCF, flagPF, flagAF, flagZF, flagSF, flagIF, flagDF, flagOF);
  6106. }
  6107. else
  6108. {
  6109. headerStr = "FLAGS";
  6110. }
  6111. return StrFormat("%s\n__flags\nCarry (CF)\t$flagcf\nParity (PF)\t$flagpf\nAdjust (AF)\t$flagaf\nZero (ZF)\t$flagzf\nSign (SF)\t$flagsf\nInterrupt (IF)\t$flagif\nDirection (DF)\t$flagdf\nOverflow (OF)\t$flagof",
  6112. headerStr.c_str());
  6113. }
  6114. break;
  6115. default:
  6116. BF_ASSERT(false && "unknown category register");
  6117. return "UNKNOWNCATEGORY\n__unknown\n";
  6118. }
  6119. }
  6120. }
  6121. break;
  6122. case DbgType_Single:
  6123. {
  6124. DwFloatDisplayType floatDisplayType = displayInfo->mFloatDisplayType;
  6125. if (floatDisplayType == DwFloatDisplayType_Default)
  6126. floatDisplayType = DwFloatDisplayType_Minimal;
  6127. if (floatDisplayType == DwFloatDisplayType_Minimal)
  6128. ExactMinimalFloatToStr(typedValue.mSingle, str);
  6129. else if (floatDisplayType == DwFloatDisplayType_Full)
  6130. sprintf(str, "%1.9g", typedValue.mSingle);
  6131. else if (floatDisplayType == DwFloatDisplayType_HexUpper)
  6132. sprintf(str, "0x%04X", typedValue.mUInt32);
  6133. else //if (floatDisplayType == DwFloatDisplayType_HexLower)
  6134. sprintf(str, "0x%04x", typedValue.mUInt32);
  6135. return StrFormat("%s\n%s", str, WrapWithModifiers("float", origValueType, language).c_str());
  6136. }
  6137. case DbgType_Double:
  6138. {
  6139. DwFloatDisplayType floatDisplayType = displayInfo->mFloatDisplayType;
  6140. if (floatDisplayType == DwFloatDisplayType_Default)
  6141. floatDisplayType = DwFloatDisplayType_Minimal;
  6142. if (floatDisplayType == DwFloatDisplayType_Minimal)
  6143. ExactMinimalDoubleToStr(typedValue.mDouble, str);
  6144. else if (floatDisplayType == DwFloatDisplayType_Full)
  6145. sprintf(str, "%1.17g", typedValue.mDouble);
  6146. else if (floatDisplayType == DwFloatDisplayType_HexUpper)
  6147. sprintf(str, "0x%08llX", typedValue.mUInt64);
  6148. else //if (floatDisplayType == DwFloatDisplayType_HexLower)
  6149. sprintf(str, "0x%08llx", typedValue.mUInt64);
  6150. return StrFormat("%s\n%s", str, WrapWithModifiers("double", origValueType, language).c_str());
  6151. }
  6152. case DbgType_Subroutine:
  6153. if (typedValue.mCharPtr != NULL)
  6154. return StrFormat("%s\nfunc", typedValue.mCharPtr);
  6155. else
  6156. return "\nfunc";
  6157. case DbgType_RawText:
  6158. return StrFormat("%s\nrawtext", typedValue.mCharPtr);
  6159. case DbgType_Ptr:
  6160. {
  6161. addr_target ptrVal = (addr_target)typedValue.mPtr;
  6162. String retVal;
  6163. DbgType* innerType = dwValueType->mTypeParam;
  6164. if (innerType == NULL)
  6165. return EncodeDataPtr(ptrVal, true) + "\nvoid*";
  6166. bool isChar = false;
  6167. DbgType* unmodInnerType = innerType->RemoveModifiers();
  6168. if (unmodInnerType != NULL)
  6169. {
  6170. if (language == DbgLanguage_Beef)
  6171. {
  6172. if ((unmodInnerType->mTypeCode == DbgType_UChar) ||
  6173. (unmodInnerType->mTypeCode == DbgType_UChar16) ||
  6174. (unmodInnerType->mTypeCode == DbgType_UChar32))
  6175. isChar = true;
  6176. }
  6177. else
  6178. {
  6179. if ((unmodInnerType->mTypeCode == DbgType_SChar) ||
  6180. (unmodInnerType->mTypeCode == DbgType_SChar16) ||
  6181. (unmodInnerType->mTypeCode == DbgType_SChar32))
  6182. isChar = true;
  6183. }
  6184. }
  6185. if ((isChar) && (formatInfo.mArrayLength == -1))
  6186. {
  6187. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6188. retVal = EncodeDataPtr(ptrVal, true);
  6189. int strLen = formatInfo.mOverrideCount;
  6190. if (typedValue.mIsLiteral)
  6191. {
  6192. if (strLen == -1)
  6193. strLen = 0x7FFFFFFF;
  6194. if (typedValue.mDataLen > 0)
  6195. strLen = BF_MIN(strLen, typedValue.mDataLen);
  6196. else
  6197. strLen = BF_MIN(strLen, strlen(typedValue.mCharPtr));
  6198. }
  6199. SetAndRestoreValue<intptr> prevOverrideLen(formatInfo.mOverrideCount, strLen);
  6200. String strResult = ReadString(unmodInnerType->mTypeCode, typedValue.mLocalIntPtr, typedValue.mIsLiteral, strLen, formatInfo);
  6201. if (formatInfo.mRawString)
  6202. return strResult;
  6203. if (!strResult.IsEmpty())
  6204. {
  6205. if (!retVal.IsEmpty())
  6206. retVal += " ";
  6207. retVal += strResult;
  6208. }
  6209. retVal += "\n" + origValueType->ToString(language);
  6210. return retVal;
  6211. }
  6212. else if ((unmodInnerType != NULL) &&
  6213. ((unmodInnerType->mTypeCode == DbgType_Class) || (unmodInnerType->mTypeCode == DbgType_Struct) || (unmodInnerType->mTypeCode == DbgType_Union)))
  6214. {
  6215. isCompositeType = true;
  6216. }
  6217. else if ((unmodInnerType != NULL) && (unmodInnerType->mTypeCode == DbgType_SizedArray))
  6218. {
  6219. isSizedArray = true;
  6220. }
  6221. else if (unmodInnerType->mTypeCode == DbgType_Subroutine)
  6222. {
  6223. if (formatInfo.mRawString)
  6224. return "";
  6225. addr_target funcPtr = (addr_target)typedValue.mPtr;
  6226. String retVal;
  6227. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6228. retVal = EncodeDataPtr(funcPtr, true);
  6229. String symbolName;
  6230. addr_target offset;
  6231. DbgModule* dwarf;
  6232. static String demangledName;
  6233. auto subProgram = mDebugTarget->FindSubProgram(funcPtr);
  6234. if (subProgram != NULL)
  6235. {
  6236. demangledName = subProgram->ToString();
  6237. }
  6238. else if (mDebugTarget->FindSymbolAt(funcPtr, &symbolName, &offset, &dwarf))
  6239. {
  6240. demangledName = BfDemangler::Demangle(symbolName, language);
  6241. if (offset != 0)
  6242. demangledName += StrFormat("+%d", offset);
  6243. }
  6244. else
  6245. {
  6246. auto dbgModule = mDebugTarget->FindDbgModuleForAddress(funcPtr);
  6247. if (dbgModule != NULL)
  6248. demangledName += dbgModule->GetLinkedModule()->mDisplayName + "!";
  6249. demangledName += StrFormat("0x%@", funcPtr);
  6250. }
  6251. retVal += " {";
  6252. retVal += demangledName;
  6253. retVal += "}";
  6254. retVal += "\n" + origValueType->ToString(language);
  6255. return retVal;
  6256. }
  6257. else if (unmodInnerType->mTypeCode == DbgType_Void)
  6258. {
  6259. if (formatInfo.mRawString)
  6260. return "";
  6261. addr_target ptr = (addr_target)typedValue.mPtr;
  6262. String symbolName;
  6263. addr_target offset;
  6264. DbgModule* dwarf;
  6265. String demangledName;
  6266. retVal += demangledName = StrFormat("0x%@", ptr);
  6267. if (mDebugTarget->FindSymbolAt(ptr, &symbolName, &offset, &dwarf))
  6268. {
  6269. if (offset == 0)
  6270. {
  6271. retVal += " {";
  6272. retVal += BfDemangler::Demangle(symbolName, language);
  6273. retVal += "}";
  6274. }
  6275. }
  6276. retVal += "\n" + origValueType->ToString(language);
  6277. return retVal;
  6278. }
  6279. else
  6280. {
  6281. if (formatInfo.mRawString)
  6282. return "";
  6283. addr_target ptrVal = (addr_target)typedValue.mPtr;
  6284. String retVal;
  6285. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6286. retVal = EncodeDataPtr(ptrVal, true);
  6287. if (ptrVal != 0)
  6288. {
  6289. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, NULL, -1, -1);
  6290. DbgTypedValue innerTypedVal = dbgExprEvaluator.ReadTypedValue(NULL, innerType, typedValue.mPtr, DbgAddrType_Target);
  6291. if (innerTypedVal)
  6292. {
  6293. DwFormatInfo defaultFormatInfo;
  6294. defaultFormatInfo.mLanguage = formatInfo.mLanguage;
  6295. defaultFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + 2; // Take into accout the necessary {}'s
  6296. defaultFormatInfo.mExpandItemDepth++;
  6297. String innerStr = DbgTypedValueToString(innerTypedVal, "", defaultFormatInfo, &dbgExprEvaluator);
  6298. int crIdx = innerStr.IndexOf('\n');
  6299. if (crIdx != -1)
  6300. {
  6301. String innerDataStr = innerStr.Substring(0, crIdx);
  6302. if (!innerDataStr.empty())
  6303. {
  6304. if (!retVal.empty())
  6305. retVal += " ";
  6306. retVal += "{" + innerDataStr + "}";
  6307. }
  6308. }
  6309. else
  6310. {
  6311. retVal += "{ ??? }";
  6312. }
  6313. }
  6314. }
  6315. retVal += "\n" + origValueType->ToString(language);
  6316. innerType->PopulateType();
  6317. if ((ptrVal != 0) &&
  6318. ((!innerType->mMemberList.IsEmpty()) || (innerType->mSize > 0) || (innerType->mTypeParam != NULL)))
  6319. {
  6320. String ptrDataStr = StrFormat("(%s)", dwValueType->ToStringRaw(language).c_str()) + EncodeDataPtr(typedValue.mPtr, true);
  6321. retVal += "\n*\t";
  6322. // Why did we have this? It messed up a pointer to sized array
  6323. /*if (language == DbgLanguage_Beef)
  6324. retVal += "this";
  6325. else*/
  6326. retVal += "*this";
  6327. if (!formatInfo.mReferenceId.empty())
  6328. retVal += ", refid=" + MaybeQuoteFormatInfoParam(formatInfo.mReferenceId);
  6329. retVal += ", this=" + ptrDataStr;
  6330. }
  6331. return retVal;
  6332. }
  6333. break;
  6334. }
  6335. case DbgType_Union:
  6336. case DbgType_Class:
  6337. case DbgType_Struct:
  6338. isCompositeType = true;
  6339. break;
  6340. case DbgType_Enum:
  6341. enumVal = typedValue.GetInt64();
  6342. isEnum = true;
  6343. break;
  6344. case DbgType_SizedArray:
  6345. {
  6346. isSizedArray = true;
  6347. }
  6348. break;
  6349. default:
  6350. break;
  6351. }
  6352. if (isSizedArray)
  6353. {
  6354. String retVal;
  6355. addr_target ptrVal = 0;
  6356. DbgType* arrayType = dwValueType;
  6357. DbgType* innerType = dwValueType->mTypeParam;
  6358. if (dwValueType->mTypeCode == DbgType_SizedArray)
  6359. {
  6360. ptrVal = (addr_target)typedValue.mSrcAddress;
  6361. }
  6362. else
  6363. {
  6364. BF_ASSERT(dwValueType->mTypeCode == DbgType_Ptr);
  6365. arrayType = innerType;
  6366. innerType = arrayType->mTypeParam;
  6367. ptrVal = typedValue.mPtr;
  6368. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6369. retVal = EncodeDataPtr(ptrVal, true) + " ";
  6370. }
  6371. if (ptrVal == 0)
  6372. ptrVal = typedValue.mPtr;
  6373. intptr arraySize = 0;
  6374. intptr innerSize = innerType->GetStride();
  6375. if (innerSize > 0)
  6376. arraySize = arrayType->GetStride() / innerSize;
  6377. else
  6378. {
  6379. // Failure!
  6380. }
  6381. String idxStr = "[{0}]";
  6382. if (innerType->IsChar(language))
  6383. {
  6384. String strVal = ReadString(innerType->mTypeCode, typedValue.mSrcAddress, false, arraySize, formatInfo);
  6385. if (formatInfo.mRawString)
  6386. return strVal;
  6387. retVal += strVal;
  6388. }
  6389. else
  6390. {
  6391. if (formatInfo.mRawString)
  6392. return "";
  6393. _ShowArraySummary(retVal, ptrVal, arraySize, innerType);
  6394. }
  6395. retVal += "\n" + origValueType->ToString(language);
  6396. String referenceId = dwValueType->ToString(language);
  6397. String evalStr;
  6398. // Why did we have the "na"? Do we not want to show addresses for all members?
  6399. evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + ")[{0}], refid=" + MaybeQuoteFormatInfoParam(referenceId + ".[]");
  6400. if (typedValue.mIsReadOnly)
  6401. evalStr += ", ne";
  6402. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, (int)BF_MAX(arraySize, 0), 10000) +
  6403. "\t" + idxStr + "\t" + evalStr;
  6404. return retVal;
  6405. }
  6406. dwValueType->PopulateType();
  6407. if (isEnum)
  6408. {
  6409. String retVal;
  6410. int64 bitsLeft = enumVal;
  6411. int valueCount = 0;
  6412. String editVal;
  6413. dwValueType = dwValueType->GetPrimaryType();
  6414. dwValueType->PopulateType();
  6415. while ((bitsLeft != 0) || (valueCount == 0))
  6416. {
  6417. DbgVariable* bestMatch = NULL;
  6418. for (auto member : dwValueType->mMemberList)
  6419. {
  6420. if (member->mConstValue == bitsLeft)
  6421. {
  6422. bestMatch = member;
  6423. break;
  6424. }
  6425. }
  6426. if (bestMatch == NULL)
  6427. {
  6428. for (auto member : dwValueType->mMemberList)
  6429. {
  6430. if ((member->mConstValue != 0) &&
  6431. ((member->mConstValue & bitsLeft) == member->mConstValue))
  6432. {
  6433. bestMatch = member;
  6434. break;
  6435. }
  6436. }
  6437. }
  6438. if (bestMatch == NULL)
  6439. break;
  6440. if (valueCount > 0)
  6441. {
  6442. retVal += " | ";
  6443. if (language == DbgLanguage_C)
  6444. editVal += " | ";
  6445. }
  6446. if (language == DbgLanguage_Beef)
  6447. retVal += ".";
  6448. retVal += bestMatch->mName;
  6449. if (language == DbgLanguage_C)
  6450. {
  6451. if (dwValueType->mParent != NULL)
  6452. {
  6453. editVal += dwValueType->mParent->ToString(language);
  6454. editVal += "::";
  6455. }
  6456. editVal += bestMatch->mName;
  6457. }
  6458. valueCount++;
  6459. bitsLeft &= ~bestMatch->mConstValue;
  6460. }
  6461. if ((valueCount == 0) || (bitsLeft != 0))
  6462. {
  6463. if (valueCount > 0)
  6464. retVal += " | ";
  6465. retVal += StrFormat("%d", bitsLeft);
  6466. if (language == DbgLanguage_C)
  6467. {
  6468. if (valueCount > 0)
  6469. editVal += " | ";
  6470. editVal += StrFormat("%d", bitsLeft);
  6471. }
  6472. }
  6473. retVal += "\n" + origValueType->ToString();
  6474. if (language == DbgLanguage_C)
  6475. {
  6476. retVal += "\n:editVal\t";
  6477. retVal += editVal;
  6478. }
  6479. retVal += "\n:canEdit";
  6480. return retVal;
  6481. }
  6482. else if (isCompositeType)
  6483. {
  6484. addr_target ptrVal;
  6485. if (dwValueType->IsPointer())
  6486. ptrVal = (addr_target)typedValue.mPtr;
  6487. else
  6488. ptrVal = (addr_target)typedValue.mSrcAddress;
  6489. String retVal;
  6490. if ((!typedValue.mIsLiteral) && (dwValueType->IsPointer()) &&
  6491. ((!formatInfo.mHidePointers) || (ptrVal == 0)))
  6492. retVal = EncodeDataPtr(ptrVal, true);
  6493. DbgType* innerType = dwValueType;
  6494. bool wasPtr = false;
  6495. if (innerType->mTypeCode == DbgType_Ptr)
  6496. {
  6497. wasPtr = true;
  6498. innerType = dwValueType->mTypeParam;
  6499. innerType = innerType->RemoveModifiers();
  6500. }
  6501. innerType = innerType->GetPrimaryType();
  6502. addr_target dataPtr = wasPtr ? typedValue.mPtr : typedValue.mSrcAddress;
  6503. DbgType* actualType = NULL;
  6504. bool useActualRawType = false;
  6505. bool isBfObject = innerType->IsBfObject();
  6506. bool hasCPPVTable = false;
  6507. if (!isBfObject)
  6508. hasCPPVTable = innerType->HasCPPVTable();
  6509. int bfObjectFlags = 0;
  6510. addr_target classVDataPtr = 0;
  6511. bool isAppendBfObject = false;
  6512. bool isStackBfObject = false;
  6513. bool isDeletedBfObject = false;
  6514. bool isCompositeWithoutAddress = false;
  6515. if (innerType->IsBfPayloadEnum())
  6516. {
  6517. if (formatInfo.mRawString)
  6518. return "";
  6519. auto tagMember = innerType->mMemberList.mTail;
  6520. int tagIdx = 0;
  6521. if (dataPtr == -1)
  6522. {
  6523. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, "(int)" + expr, &formatInfo);
  6524. auto dscValue = dbgEvaluationContext.EvaluateInContext(DbgTypedValue());
  6525. tagIdx = dscValue.mInt32;
  6526. }
  6527. else if (!ReadMemory((intptr)ptrVal + tagMember->mMemberOffset, tagMember->mType->mSize, (void*)&tagIdx))
  6528. {
  6529. return StrFormat("!Failed to read from 0x%@", ptrVal);
  6530. }
  6531. char findStr[16];
  6532. findStr[0] = '_';
  6533. itoa(tagIdx, findStr + 1, 10);
  6534. int len = strlen(findStr);
  6535. findStr[len] = '_';
  6536. len++;
  6537. if (!retVal.empty())
  6538. retVal += " ";
  6539. int startIdx = 0;
  6540. for (auto member : innerType->mMemberList)
  6541. {
  6542. if (strncmp(member->mName, findStr, len) == 0)
  6543. {
  6544. retVal += ".";
  6545. retVal += member->mName + len;
  6546. String tupleExpr;
  6547. DbgTypedValue tupleVal;
  6548. if (dataPtr == -1)
  6549. {
  6550. tupleVal.mSrcAddress = -1;
  6551. tupleVal.mType = member->mType;
  6552. //tupleExpr = "$" + expr + "$u";
  6553. tupleVal.mVariable = typedValue.mVariable;
  6554. tupleExpr = "(" + member->mType->ToStringRaw() + ")(" + expr + ")";
  6555. }
  6556. else
  6557. {
  6558. tupleVal.mType = member->mType;
  6559. tupleVal.mSrcAddress = ptrVal;
  6560. }
  6561. DwFormatInfo displayStrFormatInfo = formatInfo;
  6562. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + (int)retVal.length();
  6563. displayStrFormatInfo.mExpandItemDepth++;
  6564. displayStrFormatInfo.mHidePointers = false;
  6565. retVal += DbgTypedValueToString(tupleVal, tupleExpr, displayStrFormatInfo, NULL);
  6566. int idx = (int)retVal.IndexOf('\n');
  6567. if (idx != -1)
  6568. {
  6569. if ((idx > 2) && (strncmp(retVal.c_str() + idx - 2, "()", 2) == 0))
  6570. {
  6571. // Take off a terminating "()" on the value, if there is one
  6572. retVal.Remove(idx - 2, 2);
  6573. }
  6574. String typeName = innerType->ToString(DbgLanguage_Unknown, true);
  6575. typeName += " ";
  6576. retVal.Insert(idx + 1, typeName);
  6577. }
  6578. return retVal;
  6579. }
  6580. }
  6581. }
  6582. if (isBfObject)
  6583. {
  6584. classVDataPtr = ReadMemory<addr_target>(ptrVal);
  6585. mDebugTarget->GetCompilerSettings();
  6586. if (mDebugTarget->mBfObjectHasFlags)
  6587. {
  6588. bfObjectFlags = ((int)classVDataPtr) & 0xFF;
  6589. if ((bfObjectFlags & BfObjectFlag_Deleted) != 0)
  6590. isDeletedBfObject = true;
  6591. if ((bfObjectFlags & BfObjectFlag_AppendAlloc) != 0)
  6592. isAppendBfObject = true;
  6593. if ((bfObjectFlags & (BfObjectFlag_StackAlloc | BfObjectFlag_Allocated)) == BfObjectFlag_StackAlloc)
  6594. isStackBfObject = true;
  6595. classVDataPtr &= ~0xFF;
  6596. }
  6597. }
  6598. if (!formatInfo.mIgnoreDerivedClassInfo)
  6599. {
  6600. if (isBfObject)
  6601. {
  6602. dbgModule->ParseSymbolData();
  6603. String symbolName;
  6604. addr_target symOffset;
  6605. if ((mDebugTarget->FindSymbolAt(classVDataPtr, &symbolName, &symOffset)) && (symOffset < 0x100))
  6606. {
  6607. String mangledClassName;
  6608. const char* symEnd = "sBfClassVData";
  6609. int symEndLen = strlen(symEnd);
  6610. if (((int)symbolName.length() > symEndLen) && (strstr(symbolName.c_str(), symEnd) != NULL))
  6611. mangledClassName = symbolName;
  6612. // If we have flags then we may be pointing past the _typeData, actually. We could fix this by masking out
  6613. // the flags area, but we need to be sure we are running a build that supports flags
  6614. symEnd = "sBfTypeData";
  6615. symEndLen = strlen(symEnd);
  6616. if (((int) symbolName.length() > symEndLen) && (strstr(symbolName.c_str(), symEnd) != NULL))
  6617. mangledClassName = symbolName;
  6618. if (mangledClassName.length() > 0)
  6619. {
  6620. String className = BfDemangler::Demangle(mangledClassName, innerType->GetLanguage(), BfDemangler::Flag_RawDemangle);
  6621. for (int i = 0; i < className.length() - 3; i++)
  6622. {
  6623. if ((className[i] == 'b') &&
  6624. (className[i + 1] == 'f') &&
  6625. (className[i + 2] == '.'))
  6626. {
  6627. bool matches;
  6628. if (i == 0)
  6629. matches = true;
  6630. else
  6631. {
  6632. char prevC = className[i - 1];
  6633. if ((prevC == ' ') ||
  6634. (prevC == ',') ||
  6635. (prevC == '<'))
  6636. {
  6637. matches = true;
  6638. }
  6639. }
  6640. if (matches)
  6641. className.Remove(i, 3);
  6642. }
  6643. }
  6644. int lastDot = (int)className.LastIndexOf('.');
  6645. if (lastDot > 0)
  6646. className = className.Substring(0, lastDot);
  6647. const char* arrPrefix = "System.Array1<";
  6648. if (strncmp(className.c_str(), arrPrefix, strlen(arrPrefix)) == 0)
  6649. {
  6650. className = className.Substring(strlen(arrPrefix), className.length() - strlen(arrPrefix) - 1);
  6651. className += "[]";
  6652. }
  6653. auto typeEntry = dbgModule->GetLinkedModule()->mTypeMap.Find(className.c_str(), DbgLanguage_BeefUnfixed);
  6654. if (typeEntry != NULL)
  6655. {
  6656. actualType = typeEntry->mValue;
  6657. if (!actualType->IsBfObject())
  6658. {
  6659. if (actualType->mTypeCode == DbgType_Ptr)
  6660. {
  6661. actualType = actualType->mTypeParam;
  6662. }
  6663. }
  6664. }
  6665. }
  6666. }
  6667. }
  6668. else if (hasCPPVTable)
  6669. {
  6670. dbgModule->ParseSymbolData();
  6671. addr_target classVDataPtr = ReadMemory<addr_target>(ptrVal);
  6672. String symbolName;
  6673. addr_target offset = 0;
  6674. if (mDebugTarget->FindSymbolAt(classVDataPtr, &symbolName, &offset, NULL))
  6675. {
  6676. // On GNU, vtable indices can "go negative" for things like RTTI and virtual inheritance, so
  6677. // we can't rely on an exact vtable address lookup
  6678. if (offset < 0x200)
  6679. {
  6680. DbgLanguage lang = innerType->GetLanguage();
  6681. const char* symStart = (innerType->mCompileUnit->mDbgModule->mDbgFlavor == DbgFlavor_GNU) ? "_ZTV" : "??_7";
  6682. if (strncmp(symbolName.c_str(), symStart, strlen(symStart)) == 0)
  6683. {
  6684. //String mangledClassName = symbolName.Substring(1);
  6685. String className = BfDemangler::Demangle(symbolName, lang);
  6686. int vtableNameIdx = (int)className.IndexOf("::`vftable'");
  6687. if (vtableNameIdx != -1)
  6688. className = className.Substring(0, vtableNameIdx);
  6689. auto typeEntry = dbgModule->mTypeMap.Find(className.c_str(), DbgLanguage_C);
  6690. if (typeEntry != NULL)
  6691. {
  6692. actualType = typeEntry->mValue;
  6693. if ((int)className.IndexOf('<') != -1)
  6694. useActualRawType = true;
  6695. int thisOffset = 0;
  6696. if (!DbgExprEvaluator::TypeIsSubTypeOf(actualType, innerType, &thisOffset))
  6697. {
  6698. // This catches virtual inheritance cases where we can't downcast
  6699. actualType = NULL;
  6700. }
  6701. }
  6702. }
  6703. }
  6704. }
  6705. }
  6706. }
  6707. DbgType* displayType = origValueType;
  6708. String displayString;
  6709. bool wantsCustomExpandedItems = false;
  6710. DebugVisualizerEntry* debugVis = NULL;
  6711. Array<String> dbgVisWildcardCaptures;
  6712. DbgType* dwUseType = (actualType != NULL) ? actualType : innerType;
  6713. //auto ptrDataType = dwValueType;
  6714. //TODO: Changed this from the above to account for COFF types where 'this' is always a fwd reference, does this cause any issues?
  6715. auto ptrDataType = innerType;
  6716. String ptrDataStr;
  6717. if (/*(!innerType->IsBfObject()) &&*/ (!ptrDataType->IsPointer()))
  6718. {
  6719. if ((dataPtr != 0) || (ptrDataType->GetByteCount() > sizeof(addr_target)))
  6720. {
  6721. bool wantsRefThis = ptrDataType->WantsRefThis();
  6722. ptrDataType = ptrDataType->GetDbgModule()->GetPointerType(ptrDataType);
  6723. if (wantsRefThis)
  6724. ptrDataStr += "*";
  6725. }
  6726. else
  6727. {
  6728. // Data is inline - must be int-sized or less
  6729. isCompositeWithoutAddress = true;
  6730. dataPtr = typedValue.mPtr;
  6731. }
  6732. }
  6733. String ptrDataTypeStr = ptrDataType->ToStringRaw();
  6734. ptrDataStr += StrFormat("(%s)", ptrDataTypeStr.c_str()) + EncodeDataPtr(dataPtr, true);
  6735. DbgType* dwUsePtrType = dwUseType;
  6736. String ptrUseDataStr;
  6737. if (!dwUsePtrType->IsPointer())
  6738. {
  6739. bool wantsRefThis = dwUsePtrType->WantsRefThis();
  6740. dwUsePtrType = dwUsePtrType->GetDbgModule()->GetPointerType(dwUsePtrType);
  6741. if (wantsRefThis)
  6742. ptrUseDataStr += "*";
  6743. }
  6744. String ptrUseDataTypeStr = dwUsePtrType->ToStringRaw();
  6745. ptrUseDataStr += StrFormat("(%s)", ptrUseDataTypeStr.c_str()) + EncodeDataPtr(dataPtr, true);
  6746. if ((origTypedValue.mSrcAddress == -1) && (origTypedValue.mVariable != NULL))
  6747. {
  6748. ptrDataStr = origTypedValue.mVariable->mName;
  6749. if (!origTypedValue.mType->RemoveModifiers()->Equals(origTypedValue.mVariable->mType->RemoveModifiers()))
  6750. {
  6751. //ptrDataStr = StrFormat("(%s)%s", origTypedValue.mType->ToString().c_str(), origTypedValue.mVariable->mName);
  6752. ptrDataStr = expr;
  6753. }
  6754. ptrUseDataStr = ptrDataStr;
  6755. }
  6756. bool isNull = wasPtr && (dataPtr == 0);
  6757. bool isBadSrc = !wasPtr && (dataPtr == 0) && (!dwValueType->IsValuelessType());
  6758. if ((ptrVal == 0) && (dwValueType->IsTypedPrimitive()))
  6759. {
  6760. DbgTypedValue rawVal;
  6761. rawVal.mInt64 = origTypedValue.mInt64;
  6762. rawVal.mType = dwValueType->GetRootBaseType();
  6763. ptrDataStr = "(" + dwUseType->ToStringRaw() + ")";
  6764. ptrDataStr += DbgTypedValueToString(rawVal, expr, formatInfo, optEvaluator, fullPrecision);
  6765. int editValIdx = ptrDataStr.IndexOf(":editVal");
  6766. if (editValIdx != -1)
  6767. ptrDataStr.Remove(0, editValIdx + 9);
  6768. int crPos = (int)ptrDataStr.IndexOf('\n');
  6769. if (crPos != -1)
  6770. ptrDataStr.RemoveToEnd(crPos);
  6771. ptrUseDataStr = ptrDataStr;
  6772. if ((origTypedValue.mRegNum != -1) && (!expr.IsEmpty()) && (!formatInfo.mExplicitThis))
  6773. {
  6774. // There's no address, use direct local identifier
  6775. ptrDataStr = expr;
  6776. ptrUseDataStr = expr;
  6777. }
  6778. // This keeps 'function' types from showing null as "<null parent>"
  6779. isBadSrc = false;
  6780. }
  6781. else if ((ptrVal == 0) && (dwValueType->IsCompositeType()))
  6782. {
  6783. }
  6784. DbgTypedValue useTypedValue = typedValue;
  6785. if ((origHadRef) || ((typedValue.mType->HasPointer()) && (!dwUseType->HasPointer())))
  6786. {
  6787. useTypedValue.mSrcAddress = useTypedValue.mPtr;
  6788. useTypedValue.mPtr = 0;
  6789. if (dwUseType->IsTypedPrimitive())
  6790. {
  6791. int byteCount = dwUseType->GetByteCount();
  6792. if (byteCount <= sizeof(intptr))
  6793. {
  6794. ReadMemory(useTypedValue.mSrcAddress, byteCount, &useTypedValue.mPtr);
  6795. }
  6796. }
  6797. }
  6798. useTypedValue.mType = dwUseType;
  6799. if ((!formatInfo.mNoVisualizers) && (!isNull) && (!isBadSrc))
  6800. {
  6801. if (language == DbgLanguage_Beef)
  6802. dwUseType->FixName();
  6803. debugVis = FindVisualizerForType(dwUseType, &dbgVisWildcardCaptures);
  6804. }
  6805. bool hadCustomDisplayString = false;
  6806. if (debugVis != NULL)
  6807. {
  6808. auto& displayStringList = formatInfo.mRawString ? debugVis->mStringViews : debugVis->mDisplayStrings;
  6809. for (auto displayEntry : displayStringList)
  6810. {
  6811. if (!displayEntry->mCondition.empty())
  6812. {
  6813. if (!EvalCondition(debugVis, dbgCompileUnit, useTypedValue, formatInfo, displayEntry->mCondition, dbgVisWildcardCaptures, displayString))
  6814. continue;
  6815. }
  6816. hadCustomDisplayString = true;
  6817. String displayStr = mDebugManager->mDebugVisualizers->DoStringReplace(displayEntry->mString, dbgVisWildcardCaptures);
  6818. if (displayString.length() > 0)
  6819. displayString += " ";
  6820. ProcessEvalString(dbgCompileUnit, useTypedValue, displayStr, displayString, formatInfo, debugVis, true);
  6821. if (formatInfo.mRawString)
  6822. return displayString;
  6823. break;
  6824. }
  6825. if ((!debugVis->mExpandItems.empty()) || (debugVis->mCollectionType != DebugVisualizerEntry::CollectionType_None))
  6826. {
  6827. wantsCustomExpandedItems = true;
  6828. }
  6829. }
  6830. if (formatInfo.mRawString)
  6831. return "";
  6832. bool isTuple = (dwUseType->mName != NULL) && (dwUseType->mName[0] == '(') && (language == DbgLanguage_Beef);
  6833. if (isBadSrc)
  6834. {
  6835. displayString += "<null parent>";
  6836. }
  6837. else if ((!isNull) && (!formatInfo.mNoVisualizers) && (!hadCustomDisplayString))
  6838. {
  6839. // Create our own custom display
  6840. String firstRet;
  6841. String bigRet = isTuple ? "(" : "{ ";
  6842. int memberIdx = 0;
  6843. DbgType* summaryType = dwUseType;
  6844. bool summaryDone = false;
  6845. bool truncatedMemberList = false;
  6846. DbgTypedValue summaryTypedValue = useTypedValue;
  6847. String summaryDataStr = ptrDataStr;
  6848. String splatStr;
  6849. if (dataPtr == -1)
  6850. splatStr = expr;
  6851. while (summaryType != NULL)
  6852. {
  6853. summaryType->PopulateType();
  6854. if ((summaryType->IsTypedPrimitive()) &&
  6855. ((summaryType->mBaseTypes.IsEmpty()) || (!summaryType->mBaseTypes.front()->mBaseType->IsTypedPrimitive())))
  6856. {
  6857. if (formatInfo.mTotalSummaryLength + (int)displayString.length() > 255)
  6858. {
  6859. truncatedMemberList = true;
  6860. summaryDone = true;
  6861. bigRet += "...";
  6862. }
  6863. else
  6864. {
  6865. DwFormatInfo displayStrFormatInfo = formatInfo;
  6866. displayStrFormatInfo.mExpandItemDepth = 1;
  6867. displayStrFormatInfo.mTotalSummaryLength += (int)displayString.length();
  6868. displayStrFormatInfo.mHidePointers = false;
  6869. DbgType* primType = summaryType->mTypeParam;
  6870. String result;
  6871. if (primType->IsInteger())
  6872. formatInfo.mTypeKindFlags = (DbgTypeKindFlags)(formatInfo.mTypeKindFlags | DbgTypeKindFlag_Int);
  6873. if ((dataPtr != 0) && (dataPtr != -1))
  6874. {
  6875. String evalString = "(" + primType->ToString() + ")" + ptrDataStr;
  6876. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, origTypedValue, evalString, &displayStrFormatInfo);
  6877. if (evalResult)
  6878. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  6879. }
  6880. else
  6881. {
  6882. DbgTypedValue evalResult = origTypedValue;
  6883. evalResult.mType = primType;
  6884. String evalString = "(" + primType->ToString() + ")" + expr;
  6885. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  6886. }
  6887. if (formatInfo.mRawString)
  6888. return result;
  6889. int crPos = result.IndexOf('\n');
  6890. if (crPos != -1)
  6891. result.RemoveToEnd(crPos);
  6892. if (memberIdx == 0)
  6893. firstRet = result;
  6894. bigRet += result;
  6895. memberIdx++;
  6896. }
  6897. }
  6898. for (auto member : summaryType->mMemberList)
  6899. {
  6900. if (!member->mIsStatic)
  6901. {
  6902. if (formatInfo.mTotalSummaryLength + retVal.length() + bigRet.length() > 255)
  6903. {
  6904. truncatedMemberList = true;
  6905. summaryDone = true;
  6906. bigRet += "...";
  6907. break;
  6908. }
  6909. if (member->mName != NULL)
  6910. {
  6911. if (member->mName[0] == '$')
  6912. continue;
  6913. if (!isdigit(*member->mName))
  6914. {
  6915. if (memberIdx != 0)
  6916. bigRet += isTuple ? ", " : " ";
  6917. if ((!isTuple) || (member->mName[0] != '_'))
  6918. {
  6919. bigRet += String(member->mName);
  6920. bigRet += isTuple ? ":" : "=";
  6921. }
  6922. }
  6923. else
  6924. {
  6925. if (memberIdx != 0)
  6926. bigRet += ", ";
  6927. }
  6928. DwFormatInfo displayStrFormatInfo = formatInfo;
  6929. displayStrFormatInfo.mExpandItemDepth = 1;
  6930. displayStrFormatInfo.mHidePointers = false;
  6931. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + retVal.length() + bigRet.length();
  6932. String evalString;
  6933. if (dataPtr != -1)
  6934. {
  6935. if ((member->mName[0] >= '0') && (member->mName[0] <= '9'))
  6936. evalString += "this.";
  6937. evalString += String(member->mName); // +", this=" + summaryDataStr;
  6938. }
  6939. else
  6940. {
  6941. evalString = "(";
  6942. evalString += splatStr;
  6943. evalString += ").";
  6944. evalString += member->mName;
  6945. }
  6946. String referenceId;
  6947. String result;
  6948. if (!member->mType->IsValuelessType())
  6949. {
  6950. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, summaryTypedValue, evalString, &displayStrFormatInfo, &referenceId);
  6951. if (evalResult)
  6952. {
  6953. displayStrFormatInfo.mReferenceId = referenceId;
  6954. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  6955. int crPos = result.IndexOf('\n');
  6956. if (crPos != -1)
  6957. result.RemoveToEnd(crPos);
  6958. }
  6959. else
  6960. result = "???";
  6961. }
  6962. if (member->mType->IsInteger())
  6963. formatInfo.mTypeKindFlags = (DbgTypeKindFlags)(formatInfo.mTypeKindFlags | DbgTypeKindFlag_Int);
  6964. if (formatInfo.mRawString)
  6965. return result;
  6966. if (memberIdx == 0)
  6967. firstRet = result;
  6968. bigRet += result;
  6969. //formatInfo.mEmbeddedDisplayCount = displayStrFormatInfo.mEmbeddedDisplayCount;
  6970. memberIdx++;
  6971. }
  6972. else
  6973. {
  6974. //TODO: Handle C++ unions?
  6975. }
  6976. }
  6977. }
  6978. if (truncatedMemberList)
  6979. break;
  6980. // Find first base class with members
  6981. DbgType* nextSummaryType = NULL;
  6982. for (auto checkBase : summaryType->mBaseTypes)
  6983. {
  6984. auto checkBaseType = checkBase->mBaseType;
  6985. checkBaseType = checkBaseType->GetPrimaryType();
  6986. checkBaseType->PopulateType();
  6987. if ((checkBaseType->GetByteCount() > 0) || (checkBaseType->IsPrimitiveType()))
  6988. {
  6989. if (!splatStr.empty())
  6990. {
  6991. splatStr = "(" + checkBaseType->ToString() + ")" + splatStr;
  6992. }
  6993. else
  6994. {
  6995. summaryTypedValue.mType = checkBaseType;
  6996. }
  6997. nextSummaryType = checkBaseType;
  6998. break;
  6999. }
  7000. }
  7001. summaryType = nextSummaryType;
  7002. if (summaryType == NULL)
  7003. break;
  7004. // Don't add the Object members
  7005. if ((summaryType->GetBaseType() == NULL) && (summaryType->IsBfObject()))
  7006. break;
  7007. // If we don't have many members then find a base class with some members to show
  7008. if ((memberIdx != 0) && (displayString.length() >= 255))
  7009. {
  7010. truncatedMemberList = true;
  7011. bigRet += "...";
  7012. break;
  7013. }
  7014. }
  7015. bigRet += isTuple ? ")" : " }";
  7016. if (displayString.length() > 0)
  7017. displayString += " ";
  7018. if ((memberIdx == 1) && (!truncatedMemberList) && (firstRet.IndexOf('{') == -1) && (!isTuple))
  7019. displayString += "{ " + firstRet + " }";
  7020. else
  7021. displayString += bigRet;
  7022. }
  7023. DbgType* memberListType = actualType;
  7024. bool memberListForceCast = false;
  7025. if (actualType != NULL)
  7026. {
  7027. String valTypeName = displayType->ToString();
  7028. String actualTypeName = actualType->ToString(DbgLanguage_Unknown, true);
  7029. String actualUseTypeName = actualTypeName;
  7030. if ((int)actualTypeName.IndexOf('^') != -1)
  7031. useActualRawType = true;
  7032. if (useActualRawType)
  7033. actualUseTypeName = actualType->ToStringRaw();
  7034. if (displayString.empty())
  7035. {
  7036. // Nothing to display
  7037. }
  7038. else
  7039. {
  7040. if (!retVal.empty())
  7041. retVal += " ";
  7042. retVal += displayString;
  7043. }
  7044. retVal += "\n" + valTypeName;
  7045. if ((innerType->IsBaseBfObject()) || (innerType->IsInterface()))
  7046. {
  7047. if (actualType != innerType)
  7048. {
  7049. retVal += " {" + actualTypeName + "}";
  7050. memberListForceCast = true;
  7051. }
  7052. }
  7053. else
  7054. {
  7055. if (actualType != innerType)
  7056. {
  7057. retVal += " {" + actualTypeName + "}";
  7058. retVal += "\n";
  7059. if (!wantsCustomExpandedItems)
  7060. {
  7061. retVal += "[" + actualTypeName + "]\t((" + actualUseTypeName;
  7062. if (!actualType->IsBfObject())
  7063. retVal += "*";
  7064. retVal += ")this), nd, na, nv, this=" + ptrDataStr;
  7065. memberListType = innerType;
  7066. }
  7067. }
  7068. }
  7069. }
  7070. else
  7071. {
  7072. if ((formatInfo.mHidePointers) && (formatInfo.mIgnoreDerivedClassInfo))
  7073. {
  7074. displayType = innerType;
  7075. if (displayString.empty())
  7076. retVal += displayType->ToString(DbgLanguage_Unknown, true);
  7077. }
  7078. if (!displayString.empty())
  7079. {
  7080. if (!retVal.empty())
  7081. retVal += " ";
  7082. retVal += displayString;
  7083. }
  7084. else
  7085. {
  7086. if (formatInfo.mRawString)
  7087. return "";
  7088. }
  7089. retVal += "\n" + displayType->ToString(DbgLanguage_Unknown, true);
  7090. memberListType = innerType;
  7091. }
  7092. if ((isBfObject) && (mDebugTarget->mBfObjectHasFlags) && (!formatInfo.mNoVisualizers) && (!formatInfo.mRawString))
  7093. {
  7094. int stackTraceLen = 1;
  7095. addr_target stackTraceAddr = ptrVal + sizeof(addr_target);
  7096. if ((bfObjectFlags & BfObjectFlag_AllocInfo) != 0)
  7097. {
  7098. addr_target objectSize = ReadMemory<addr_target>(ptrVal + sizeof(addr_target));
  7099. addr_target largeAllocInfo = ReadMemory<addr_target>(ptrVal + objectSize);
  7100. stackTraceLen = largeAllocInfo & 0xFFFF;
  7101. stackTraceAddr = ptrVal + objectSize + sizeof(addr_target);
  7102. }
  7103. else if ((bfObjectFlags & BfObjectFlag_AllocInfo_Short) != 0)
  7104. {
  7105. addr_target dbgAllocInfo = ReadMemory<addr_target>(ptrVal + sizeof(addr_target));
  7106. stackTraceLen = dbgAllocInfo & 0xFF;
  7107. stackTraceAddr = ptrVal + (dbgAllocInfo >> 16);
  7108. }
  7109. if (stackTraceLen == 1)
  7110. {
  7111. retVal += StrFormat("\n[AllocStackTrace]\t*(System.CallStackAddr*)%s, nm", EncodeDataPtr(stackTraceAddr, true).c_str());
  7112. }
  7113. else if (stackTraceLen > 0)
  7114. {
  7115. retVal += StrFormat("\n[AllocStackTrace]\t(System.CallStackAddr*)%s, %d, na", EncodeDataPtr(stackTraceAddr, true).c_str(), stackTraceLen);
  7116. }
  7117. }
  7118. retVal += StrFormat("\n:language\t%d", language);
  7119. if (formatInfo.mNoMembers)
  7120. {
  7121. //
  7122. }
  7123. else if (wantsCustomExpandedItems)
  7124. {
  7125. HandleCustomExpandedItems(retVal, dbgCompileUnit, debugVis, dwUseType, dwValueType, ptrUseDataStr, ptrDataStr, useTypedValue, dbgVisWildcardCaptures, formatInfo);
  7126. }
  7127. else if ((!isNull) && (!isBadSrc))
  7128. {
  7129. if (dataPtr == -1)
  7130. {
  7131. //String splatName = ((origTypedValue.mSrcAddress == -1) && (origTypedValue.mVariable != NULL)) ? origTypedValue.mVariable->mName : expr;
  7132. String splatName = expr;
  7133. retVal += "\n" + GetMemberList(memberListType, splatName, wasPtr, false, false, true, origTypedValue.mIsReadOnly);
  7134. }
  7135. else
  7136. {
  7137. retVal += "\n" + GetMemberList(memberListType, ptrDataStr, wasPtr, false, memberListForceCast, isCompositeWithoutAddress, origTypedValue.mIsReadOnly);
  7138. }
  7139. }
  7140. if (formatInfo.mExpandItemDepth > 0)
  7141. return retVal;
  7142. if (isAppendBfObject)
  7143. retVal += "\n:appendAlloc";
  7144. if (isStackBfObject)
  7145. retVal += "\n:stack";
  7146. if (isDeletedBfObject)
  7147. retVal += "\n:deleted";
  7148. if ((debugVis != NULL) && (!debugVis->mAction.empty()))
  7149. {
  7150. String rawActionStr = mDebugManager->mDebugVisualizers->DoStringReplace(debugVis->mAction, dbgVisWildcardCaptures);
  7151. String actionStr;
  7152. ProcessEvalString(dbgCompileUnit, useTypedValue, rawActionStr, actionStr, formatInfo, debugVis, true);
  7153. retVal += "\n:action\t" + actionStr;
  7154. }
  7155. if ((!typedValue.mIsLiteral) && (dwValueType->IsPointer()))
  7156. {
  7157. retVal += "\n:editVal\t" + EncodeDataPtr(ptrVal, true);
  7158. }
  7159. return retVal;
  7160. }
  7161. return "Unknown Type\n" + origValueType->ToString();
  7162. }
  7163. void WinDebugger::HandleCustomExpandedItems(String& retVal, DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgType* dwUseType, DbgType* dwValueType, String& ptrUseDataStr, String& ptrDataStr, DbgTypedValue useTypedValue, Array<String>& dbgVisWildcardCaptures, DwFormatInfo& formatInfo)
  7164. {
  7165. auto debugVisualizers = mDebugManager->mDebugVisualizers;
  7166. auto dbgModule = dbgCompileUnit->mDbgModule;
  7167. if (formatInfo.mExpandItemDepth > 10) // Avoid crashing on circular ExpandItems
  7168. return;
  7169. auto language = formatInfo.mLanguage;
  7170. bool isReadOnly = false;
  7171. if (useTypedValue.mIsReadOnly)
  7172. isReadOnly = true;
  7173. for (auto entry : debugVis->mExpandItems)
  7174. {
  7175. if (!entry->mCondition.empty())
  7176. {
  7177. String error;
  7178. if (!EvalCondition(debugVis, dbgCompileUnit, useTypedValue, formatInfo, entry->mCondition, dbgVisWildcardCaptures, error))
  7179. {
  7180. if (!error.empty())
  7181. retVal += "\n" + entry->mName + "\t@!<DbgVis Failed>@!";
  7182. continue;
  7183. }
  7184. }
  7185. String replacedStr = debugVisualizers->DoStringReplace(entry->mValue, dbgVisWildcardCaptures);
  7186. retVal += "\n" + entry->mName + "\t" + replacedStr + ", this=(" + ptrUseDataStr + ")";
  7187. }
  7188. String referenceId = dwUseType->ToString();
  7189. if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_ExpandedItem)
  7190. {
  7191. DbgTypedValue itemValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7192. if (itemValue)
  7193. {
  7194. DwFormatInfo itemFormatInfo = formatInfo;
  7195. itemFormatInfo.mExpandItemDepth++;
  7196. String itemRetVal = DbgTypedValueToString(itemValue, "", itemFormatInfo, NULL);
  7197. int crIdx = (int)itemRetVal.IndexOf('\n');
  7198. if (crIdx != -1)
  7199. {
  7200. crIdx = (int)itemRetVal.IndexOf('\n', crIdx + 1);
  7201. if (crIdx != -1)
  7202. retVal += itemRetVal.Substring(crIdx);
  7203. }
  7204. }
  7205. }
  7206. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Array)
  7207. {
  7208. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7209. Array<int> lowerDimSizes;
  7210. for (auto lowerDim : debugVis->mLowerDimSizes)
  7211. {
  7212. DbgTypedValue lowerDimValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(lowerDim, dbgVisWildcardCaptures), &formatInfo);
  7213. int dimSize = 0;
  7214. if ((lowerDimValue) && (lowerDimValue.mType->IsInteger()))
  7215. dimSize = (int)lowerDimValue.GetInt64();
  7216. dimSize = BF_MAX(dimSize, 1);
  7217. lowerDimSizes.push_back(dimSize);
  7218. }
  7219. if ((sizeValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7220. {
  7221. if (!debugVis->mCondition.IsEmpty())
  7222. {
  7223. int size = (int)sizeValue.GetInt64();
  7224. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7225. DbgTypedValue curNode = headPointer;
  7226. Array<addr_target> parentList;
  7227. String continuationData;
  7228. int totalSize = 2;
  7229. auto valueType = headPointer.mType;
  7230. String addrs = GetArrayItems(dbgCompileUnit, debugVis, valueType, headPointer, totalSize, &continuationData);
  7231. String firstAddr;
  7232. String secondAddr;
  7233. bool hasSecondAddr = valueType == NULL;
  7234. if (addrs.length() > 0)
  7235. {
  7236. const char* addrsPtr = addrs.c_str();
  7237. firstAddr = addrs.Substring(0, sizeof(addr_target) * 2);
  7238. if (hasSecondAddr)
  7239. secondAddr = addrs.Substring(sizeof(addr_target) * 2, sizeof(addr_target) * 2);
  7240. }
  7241. String evalStr;
  7242. if (valueType != NULL)
  7243. {
  7244. evalStr = "(" + valueType->ToStringRaw();
  7245. if (!valueType->IsPointer())
  7246. evalStr += "*";
  7247. evalStr += ")0x{1}";
  7248. }
  7249. else
  7250. {
  7251. evalStr += "({1})0x{2}";
  7252. }
  7253. if (!debugVis->mShowElementAddrs)
  7254. evalStr.Insert(0, "*");
  7255. if (addrs.length() > 0)
  7256. {
  7257. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7258. if (isReadOnly)
  7259. evalStr += ", ne";
  7260. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, BF_MAX(size, 0), 10000) +
  7261. "\t[{0}]\t" + evalStr + "\t" + firstAddr;
  7262. if (hasSecondAddr)
  7263. retVal += "\t" + secondAddr;
  7264. if (size != 0)
  7265. {
  7266. retVal += "\n:addrs\t" + addrs;
  7267. if (valueType == NULL)
  7268. retVal += "\n:addrsEntrySize\t2";
  7269. if (continuationData.length() > 0)
  7270. retVal += "\n:continuation\t" + continuationData;
  7271. }
  7272. }
  7273. }
  7274. else if (lowerDimSizes.size() == 1)
  7275. {
  7276. int dimSize1 = lowerDimSizes[0];
  7277. String evalStr = "(" + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7278. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7279. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7280. if (isReadOnly)
  7281. evalStr += ", ne";
  7282. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64() / dimSize1, 50000) +
  7283. "\t[{0}]\t" + evalStr;
  7284. }
  7285. else if (lowerDimSizes.size() == 2)
  7286. {
  7287. int dimSize1 = lowerDimSizes[0];
  7288. int dimSize2 = lowerDimSizes[1];
  7289. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7290. if ((headPointer.mType != NULL) && (headPointer.mType->IsPointer()))
  7291. {
  7292. String evalStr = StrFormat("((%s[%d]*)", headPointer.mType->mTypeParam->ToStringRaw(language).c_str(), dimSize2) + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7293. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7294. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7295. if (isReadOnly)
  7296. evalStr += ", ne";
  7297. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64() / dimSize1 / dimSize2, 50000) +
  7298. "\t[{0}]\t" + evalStr;
  7299. }
  7300. }
  7301. else if (lowerDimSizes.size() == 3)
  7302. {
  7303. int dimSize1 = lowerDimSizes[0];
  7304. int dimSize2 = lowerDimSizes[1];
  7305. int dimSize3 = lowerDimSizes[2];
  7306. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7307. if ((headPointer.mType != NULL) && (headPointer.mType->IsPointer()))
  7308. {
  7309. String evalStr = StrFormat("((%s[%d][%d]*)", headPointer.mType->mTypeParam->ToStringRaw(language).c_str(), dimSize2, dimSize3) + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7310. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7311. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7312. if (isReadOnly)
  7313. evalStr += ", ne";
  7314. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64() / dimSize1 / dimSize2 / dimSize3, 50000) +
  7315. "\t[{0}]\t" + evalStr;
  7316. }
  7317. }
  7318. else
  7319. {
  7320. String evalStr = "*(" + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) + " + {0}), this=" + ptrUseDataStr;
  7321. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7322. if (isReadOnly)
  7323. evalStr += ", ne";
  7324. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64(), 50000) +
  7325. "\t[{0}]\t" + evalStr;
  7326. }
  7327. }
  7328. }
  7329. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_IndexItems)
  7330. {
  7331. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7332. if ((sizeValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7333. {
  7334. String evalStr = debugVis->mValuePointer + ", this=" + ptrUseDataStr;
  7335. evalStr.Replace("$i", "{0}");
  7336. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7337. if (isReadOnly)
  7338. evalStr += ", ne";
  7339. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64(), 50000) +
  7340. "\t[{0}]\t" + evalStr;
  7341. }
  7342. }
  7343. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_LinkedList)
  7344. {
  7345. DbgType* valueType = NULL;
  7346. if (!debugVis->mValueType.empty())
  7347. {
  7348. valueType = dbgModule->FindType(debugVisualizers->DoStringReplace(debugVis->mValueType, dbgVisWildcardCaptures), dwValueType);
  7349. if (valueType != NULL)
  7350. valueType = valueType->ResolveTypeDef();
  7351. }
  7352. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mHeadPointer, dbgVisWildcardCaptures), &formatInfo);
  7353. if (headPointer)
  7354. {
  7355. DbgTypedValue endPointer;
  7356. if (!debugVis->mEndPointer.empty())
  7357. endPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mEndPointer, dbgVisWildcardCaptures), &formatInfo);
  7358. DbgTypedValue nextPointer = EvaluateInContext(dbgCompileUnit, headPointer, debugVisualizers->DoStringReplace(debugVis->mNextPointer, dbgVisWildcardCaptures), &formatInfo);
  7359. int size = -1;
  7360. if (!debugVis->mSize.empty())
  7361. {
  7362. auto sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7363. if (sizeValue)
  7364. size = (int)sizeValue.GetInt64();
  7365. }
  7366. DbgTypedValue curNode = headPointer;
  7367. Array<addr_target> parentList;
  7368. String continuationData;
  7369. int totalSize = 2;
  7370. String addrs = GetLinkedListItems(dbgCompileUnit, debugVis, endPointer.mPtr, valueType, curNode, totalSize, &continuationData);
  7371. String firstAddr;
  7372. String secondAddr;
  7373. bool hasSecondAddr = valueType == NULL;
  7374. if (addrs.length() > 0)
  7375. {
  7376. const char* addrsPtr = addrs.c_str();
  7377. firstAddr = addrs.Substring(0, sizeof(addr_target)*2);
  7378. if (hasSecondAddr)
  7379. secondAddr = addrs.Substring(sizeof(addr_target)*2, sizeof(addr_target)*2);
  7380. }
  7381. String evalStr;
  7382. if (valueType != NULL)
  7383. {
  7384. evalStr = "(" + valueType->ToStringRaw();
  7385. if (!valueType->IsPointer())
  7386. evalStr += "*";
  7387. evalStr += ")0x{1}";
  7388. }
  7389. else
  7390. {
  7391. evalStr += "({1})0x{2}";
  7392. }
  7393. if (!debugVis->mShowElementAddrs)
  7394. evalStr.Insert(0, "*");
  7395. if (addrs.length() > 0)
  7396. {
  7397. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7398. if (isReadOnly)
  7399. evalStr += ", ne";
  7400. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, size, 10000) +
  7401. "\t[{0}]\t" + evalStr + "\t" + firstAddr;
  7402. if (hasSecondAddr)
  7403. retVal += "\t" + secondAddr;
  7404. if (size != 0)
  7405. {
  7406. retVal += "\n:addrs\t" + addrs;
  7407. if (valueType == NULL)
  7408. retVal += "\n:addrsEntrySize\t2";
  7409. if (continuationData.length() > 0)
  7410. retVal += "\n:continuation\t" + continuationData;
  7411. }
  7412. }
  7413. }
  7414. }
  7415. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_TreeItems)
  7416. {
  7417. DbgType* valueType = NULL;
  7418. if (!debugVis->mValueType.empty())
  7419. {
  7420. valueType = dbgModule->FindType(debugVisualizers->DoStringReplace(debugVis->mValueType, dbgVisWildcardCaptures), dwValueType);
  7421. if (valueType != NULL)
  7422. valueType = valueType->ResolveTypeDef();
  7423. }
  7424. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7425. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mHeadPointer, dbgVisWildcardCaptures), &formatInfo);
  7426. if (sizeValue)
  7427. sizeValue.mType = sizeValue.mType->RemoveModifiers();
  7428. if ((sizeValue) && (headPointer) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7429. {
  7430. DbgTypedValue curNode = headPointer;
  7431. Array<addr_target> parentList;
  7432. String continuationData;
  7433. int getItemCount = (int)BF_MIN(sizeValue.GetInt64(), 32LL);
  7434. String addrs = GetTreeItems(dbgCompileUnit, debugVis, parentList, valueType, curNode, getItemCount, &continuationData);
  7435. addr_target firstAddr = 0;
  7436. addr_target secondAddr = 0;
  7437. bool hasSecondAddr = valueType == NULL;
  7438. if (addrs.length() > 0)
  7439. {
  7440. const char* addrsPtr = addrs.c_str();
  7441. firstAddr = DecodeTargetDataPtr(addrsPtr);
  7442. if (hasSecondAddr)
  7443. secondAddr = DecodeTargetDataPtr(addrsPtr);
  7444. }
  7445. String evalStr;
  7446. if (valueType != NULL)
  7447. {
  7448. evalStr = "*(" + valueType->ToStringRaw();
  7449. if (!valueType->IsPointer())
  7450. evalStr += "*";
  7451. evalStr += ")0x{1}";
  7452. }
  7453. else
  7454. {
  7455. evalStr += "*(_T_{1}*)0x{2}";
  7456. }
  7457. int size = (int)sizeValue.GetInt64();
  7458. if (addrs.length() == 0)
  7459. {
  7460. evalStr = ""; // Failed
  7461. }
  7462. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7463. if (isReadOnly)
  7464. evalStr += ", ne";
  7465. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, size, 10000) +
  7466. "\t[{0}]\t" + evalStr + "\t" + EncodeDataPtr(firstAddr, false);
  7467. if (hasSecondAddr)
  7468. retVal += "\t" + EncodeDataPtr(secondAddr, false);
  7469. if (addrs.length() > 0)
  7470. {
  7471. retVal += "\n:addrs\t" + addrs;
  7472. if (continuationData.length() > 0)
  7473. retVal += "\n:continuation\t" + continuationData;
  7474. }
  7475. }
  7476. }
  7477. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Dictionary)
  7478. {
  7479. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7480. DbgTypedValue entriesPtrValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mEntries, dbgVisWildcardCaptures), &formatInfo);
  7481. if (sizeValue)
  7482. sizeValue.mType = sizeValue.mType->RemoveModifiers();
  7483. if ((sizeValue) && (entriesPtrValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7484. {
  7485. String continuationData;
  7486. DbgType* valueType = entriesPtrValue.mType;
  7487. int getItemCount = (int)std::min(sizeValue.GetInt64(), 2LL);
  7488. DbgType* useTypedValType = useTypedValue.mType;
  7489. addr_target useTypedValPtr = useTypedValue.mPtr;
  7490. addr_target useTypedValAddr = useTypedValue.mSrcAddress;
  7491. String addrs = GetDictionaryItems(dbgCompileUnit, debugVis, useTypedValue, 0, -1, getItemCount, &continuationData);
  7492. addr_target firstAddr = 0;
  7493. if (addrs.length() > 0)
  7494. {
  7495. const char* addrsPtr = addrs.c_str();
  7496. firstAddr = DecodeTargetDataPtr(addrsPtr);
  7497. }
  7498. String evalStr = "((" + valueType->ToStringRaw() + ")0x{1}), na";
  7499. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7500. if (isReadOnly)
  7501. evalStr += ", ne";
  7502. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64(), 10000) +
  7503. "\t[{0}]\t" + evalStr + "\t" + EncodeDataPtr(firstAddr, false);
  7504. if (addrs.length() > 0)
  7505. {
  7506. retVal += "\n:addrs\t" + addrs;
  7507. if (continuationData.length() > 0)
  7508. retVal += "\n:continuation\t" + continuationData;
  7509. }
  7510. }
  7511. }
  7512. if (formatInfo.mExpandItemDepth == 0)
  7513. {
  7514. //retVal += "\n[Raw View]\tthis, this=" + ptrDataStr + ", nv";
  7515. retVal += "\n[Raw View]\t" + ptrDataStr + ", nv";
  7516. }
  7517. }
  7518. bool WinDebugger::IsPaused()
  7519. {
  7520. return (mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint) || (mRunState == RunState_Exception) || (mRunState == RunState_DebugEval_Done);
  7521. }
  7522. DbgTypedValue WinDebugger::GetRegister(const StringImpl& regName, DbgLanguage language, CPURegisters* registers, Array<RegForm>* regForms)
  7523. {
  7524. int regNum = -1;
  7525. String lwrRegName(regName);
  7526. _strlwr((char*)lwrRegName.c_str());
  7527. // int regs
  7528. #ifdef BF_DBG_32
  7529. DbgTypeCode regType = DbgType_i32;
  7530. if (lwrRegName == "eax")
  7531. regNum = X86Reg_EAX;
  7532. else if (lwrRegName == "ecx")
  7533. regNum = X86Reg_ECX;
  7534. else if (lwrRegName == "edx")
  7535. regNum = X86Reg_EDX;
  7536. else if (lwrRegName == "ebx")
  7537. regNum = X86Reg_EBX;
  7538. else if (lwrRegName == "esp")
  7539. regNum = X86Reg_ESP;
  7540. else if (lwrRegName == "ebp")
  7541. regNum = X86Reg_EBP;
  7542. else if (lwrRegName == "esi")
  7543. regNum = X86Reg_ESI;
  7544. else if (lwrRegName == "edi")
  7545. regNum = X86Reg_EDI;
  7546. else if (lwrRegName == "eip")
  7547. regNum = X86Reg_EIP;
  7548. else if (lwrRegName == "efl")
  7549. regNum = X86Reg_EFL;
  7550. #else
  7551. DbgTypeCode regType = DbgType_i64;
  7552. if (lwrRegName == "rax")
  7553. regNum = X64Reg_RAX;
  7554. else if (lwrRegName == "rcx")
  7555. regNum = X64Reg_RCX;
  7556. else if (lwrRegName == "rdx")
  7557. regNum = X64Reg_RDX;
  7558. else if (lwrRegName == "rbx")
  7559. regNum = X64Reg_RBX;
  7560. else if (lwrRegName == "rsp")
  7561. regNum = X64Reg_RSP;
  7562. else if (lwrRegName == "rbp")
  7563. regNum = X64Reg_RBP;
  7564. else if (lwrRegName == "rsi")
  7565. regNum = X64Reg_RSI;
  7566. else if (lwrRegName == "rdi")
  7567. regNum = X64Reg_RDI;
  7568. else if (lwrRegName == "rip")
  7569. regNum = X64Reg_RIP;
  7570. else if (lwrRegName == "r8")
  7571. regNum = X64Reg_R8;
  7572. else if (lwrRegName == "r9")
  7573. regNum = X64Reg_R9;
  7574. else if (lwrRegName == "r10")
  7575. regNum = X64Reg_R10;
  7576. else if (lwrRegName == "r11")
  7577. regNum = X64Reg_R11;
  7578. else if (lwrRegName == "r12")
  7579. regNum = X64Reg_R12;
  7580. else if (lwrRegName == "r13")
  7581. regNum = X64Reg_R13;
  7582. else if (lwrRegName == "r14")
  7583. regNum = X64Reg_R14;
  7584. else if (lwrRegName == "r15")
  7585. regNum = X64Reg_R15;
  7586. else
  7587. {
  7588. regType = DbgType_i32;
  7589. if (lwrRegName == "eax")
  7590. regNum = X64Reg_RAX;
  7591. else if (lwrRegName == "ecx")
  7592. regNum = X64Reg_RCX;
  7593. else if (lwrRegName == "edx")
  7594. regNum = X64Reg_RDX;
  7595. else if (lwrRegName == "ebx")
  7596. regNum = X64Reg_RBX;
  7597. else if (lwrRegName == "efl")
  7598. regNum = X64Reg_EFL;
  7599. else if (lwrRegName == "esi")
  7600. regNum = X64Reg_RSI;
  7601. else if (lwrRegName == "edi")
  7602. regNum = X64Reg_RDI;
  7603. else if (lwrRegName == "r8d")
  7604. regNum = X64Reg_R8;
  7605. else if (lwrRegName == "r9d")
  7606. regNum = X64Reg_R9;
  7607. else if (lwrRegName == "r10d")
  7608. regNum = X64Reg_R10;
  7609. else if (lwrRegName == "r11d")
  7610. regNum = X64Reg_R11;
  7611. else if (lwrRegName == "r12d")
  7612. regNum = X64Reg_R12;
  7613. else if (lwrRegName == "r13d")
  7614. regNum = X64Reg_R13;
  7615. else if (lwrRegName == "r14d")
  7616. regNum = X64Reg_R14;
  7617. else if (lwrRegName == "r15d")
  7618. regNum = X64Reg_R15;
  7619. else
  7620. {
  7621. regType = DbgType_i16;
  7622. if (lwrRegName == "ax")
  7623. regNum = X64Reg_RAX;
  7624. else if (lwrRegName == "cx")
  7625. regNum = X64Reg_RCX;
  7626. else if (lwrRegName == "dx")
  7627. regNum = X64Reg_RDX;
  7628. else if (lwrRegName == "bx")
  7629. regNum = X64Reg_RBX;
  7630. else if (lwrRegName == "si")
  7631. regNum = X64Reg_RSI;
  7632. else if (lwrRegName == "di")
  7633. regNum = X64Reg_RDI;
  7634. else if (lwrRegName == "r8w")
  7635. regNum = X64Reg_R8;
  7636. else if (lwrRegName == "r9w")
  7637. regNum = X64Reg_R9;
  7638. else if (lwrRegName == "r10w")
  7639. regNum = X64Reg_R10;
  7640. else if (lwrRegName == "r11w")
  7641. regNum = X64Reg_R11;
  7642. else if (lwrRegName == "r12w")
  7643. regNum = X64Reg_R12;
  7644. else if (lwrRegName == "r13w")
  7645. regNum = X64Reg_R13;
  7646. else if (lwrRegName == "r14w")
  7647. regNum = X64Reg_R14;
  7648. else if (lwrRegName == "r15w")
  7649. regNum = X64Reg_R15;
  7650. else
  7651. {
  7652. regType = DbgType_i8;
  7653. if (lwrRegName == "al")
  7654. regNum = X64Reg_RAX;
  7655. else if (lwrRegName == "cl")
  7656. regNum = X64Reg_RCX;
  7657. else if (lwrRegName == "dl")
  7658. regNum = X64Reg_RDX;
  7659. else if (lwrRegName == "bl")
  7660. regNum = X64Reg_RBX;
  7661. else if (lwrRegName == "sil")
  7662. regNum = X64Reg_RSI;
  7663. else if (lwrRegName == "dil")
  7664. regNum = X64Reg_RDI;
  7665. else if (lwrRegName == "r8b")
  7666. regNum = X64Reg_R8;
  7667. else if (lwrRegName == "r9b")
  7668. regNum = X64Reg_R9;
  7669. else if (lwrRegName == "r10b")
  7670. regNum = X64Reg_R10;
  7671. else if (lwrRegName == "r11b")
  7672. regNum = X64Reg_R11;
  7673. else if (lwrRegName == "r12b")
  7674. regNum = X64Reg_R12;
  7675. else if (lwrRegName == "r13b")
  7676. regNum = X64Reg_R13;
  7677. else if (lwrRegName == "r14b")
  7678. regNum = X64Reg_R14;
  7679. else if (lwrRegName == "r15b")
  7680. regNum = X64Reg_R15;
  7681. }
  7682. }
  7683. }
  7684. #endif
  7685. auto dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  7686. if (regNum != -1)
  7687. {
  7688. DbgTypedValue typedVal;
  7689. typedVal.mType = dbgModule->GetPrimitiveType(regType, language);
  7690. typedVal.mInt64 = registers->mIntRegsArray[regNum];
  7691. typedVal.mRegNum = regNum;
  7692. return typedVal;
  7693. }
  7694. // st regs
  7695. if ((lwrRegName.length() == 3) && (lwrRegName[0] == 's') && (lwrRegName[1] == 't') && (lwrRegName[2] >= '0') && (lwrRegName[2] <= '7'))
  7696. {
  7697. regNum = CPUReg_FPSTREG_FIRST + (lwrRegName[2] - '0');
  7698. }
  7699. if (regNum != -1)
  7700. {
  7701. DbgTypedValue typedVal;
  7702. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Double, language);
  7703. typedVal.mDouble = ConvertFloat80ToDouble(registers->mFpMmRegsArray[regNum - CPUReg_FPSTREG_FIRST].fp.fp80);
  7704. typedVal.mRegNum = regNum;
  7705. return typedVal;
  7706. }
  7707. // mm regs
  7708. if ((lwrRegName.length() == 3) && (lwrRegName[0] == 'm') && (lwrRegName[1] == 'm') && (lwrRegName[2] >= '0') && (lwrRegName[2] <= '7'))
  7709. {
  7710. regNum = CPUReg_MMREG_FIRST + (lwrRegName[2] - '0');
  7711. }
  7712. if (regNum != -1)
  7713. {
  7714. DbgTypedValue typedVal;
  7715. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_i64, language);
  7716. typedVal.mInt64 = registers->mFpMmRegsArray[regNum - CPUReg_MMREG_FIRST].mm;
  7717. typedVal.mRegNum = regNum;
  7718. return typedVal;
  7719. }
  7720. // xmm regs
  7721. #ifdef BF_DBG_32
  7722. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '7') &&
  7723. (lwrRegName[4] == '_') && (lwrRegName[5] >= '0') && (lwrRegName[5] <= '3'))
  7724. {
  7725. regNum = CPUReg_XMMREG_FIRST + ((lwrRegName[3] - '0') * 4) + (lwrRegName[5] - '0');
  7726. }
  7727. #else
  7728. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '9') &&
  7729. (lwrRegName[4] == '_') && (lwrRegName[5] >= '0') && (lwrRegName[5] <= '3'))
  7730. {
  7731. regNum = CPUReg_XMMREG_FIRST + ((lwrRegName[3] - '0') * 4) + (lwrRegName[5] - '0');
  7732. }
  7733. if ((lwrRegName.length() == 7) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] == '1') && (lwrRegName[4] >= '0') && (lwrRegName[4] <= '9') &&
  7734. (lwrRegName[5] == '_') && (lwrRegName[6] >= '0') && (lwrRegName[6] <= '3'))
  7735. {
  7736. regNum = CPUReg_XMMREG_FIRST + ((10 + (lwrRegName[4] - '0')) * 4) + (lwrRegName[6] - '0');
  7737. }
  7738. #endif
  7739. if (regNum != -1)
  7740. {
  7741. int xmmMajor = (regNum - CPUReg_XMMREG_FIRST) >> 2;
  7742. int xmmMinor = (regNum - CPUReg_XMMREG_FIRST) & 3;
  7743. DwMmDisplayType mmDisplayType = GetDisplayInfo(StrFormat("$XMM%d", xmmMajor))->mMmDisplayType;
  7744. RegForm regForm = RegForm_Unknown;
  7745. if (regForms != NULL)
  7746. {
  7747. int regFormIdx = CPUReg_M128_XMMREG_FIRST + xmmMajor;
  7748. if (regFormIdx < (int)regForms->size())
  7749. regForm = (*regForms)[regFormIdx];
  7750. }
  7751. if (mmDisplayType == DwMmDisplayType_Default)
  7752. {
  7753. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2))
  7754. mmDisplayType = DwMmDisplayType_Double;
  7755. else if (regForm == RegForm_Int4)
  7756. mmDisplayType = DwMmDisplayType_Int;
  7757. }
  7758. //TODO: Add int types
  7759. if (mmDisplayType == DwMmDisplayType_Double)
  7760. {
  7761. DbgTypedValue typedVal;
  7762. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Double, language);
  7763. typedVal.mDouble = registers->mXmmDRegsArray[xmmMajor].d[xmmMinor];
  7764. typedVal.mRegNum = regNum;
  7765. return typedVal;
  7766. }
  7767. if ((mmDisplayType == DwMmDisplayType_Byte) || (mmDisplayType == DwMmDisplayType_Short) || (mmDisplayType == DwMmDisplayType_Int))
  7768. {
  7769. DbgTypedValue typedVal;
  7770. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_i32, language);
  7771. typedVal.mInt32 = registers->mXmmIRegsARray[xmmMajor].i[xmmMinor];
  7772. typedVal.mRegNum = regNum;
  7773. return typedVal;
  7774. }
  7775. DbgTypedValue typedVal;
  7776. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Single, language);
  7777. typedVal.mSingle = registers->mXmmRegsArray[xmmMajor].f[xmmMinor];
  7778. typedVal.mRegNum = regNum;
  7779. return typedVal;
  7780. }
  7781. #ifdef BF_DBG_32
  7782. if ((lwrRegName.length() == 4) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '7'))
  7783. {
  7784. regNum = CPUReg_M128_XMMREG_FIRST + (lwrRegName[3] - '0');
  7785. }
  7786. #else
  7787. if ((lwrRegName.length() == 4) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '9'))
  7788. {
  7789. regNum = CPUReg_M128_XMMREG_FIRST + (lwrRegName[3] - '0');
  7790. }
  7791. if ((lwrRegName.length() == 5) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] == '1') && (lwrRegName[4] >= '0') && (lwrRegName[4] <= '5'))
  7792. {
  7793. regNum = CPUReg_M128_XMMREG_FIRST + 10 + (lwrRegName[4] - '0');
  7794. }
  7795. #endif
  7796. if (regNum != -1)
  7797. {
  7798. DbgTypedValue typedVal;
  7799. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_RegGroup, language);
  7800. typedVal.mSingle = 0.0f; // ignored at a higher level (but if it's used as an rvalue in the meantime, it'll resolve to zero)
  7801. typedVal.mRegNum = regNum;
  7802. return typedVal;
  7803. }
  7804. // flags
  7805. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'f') && (lwrRegName[1] == 'l') && (lwrRegName[2] == 'a') && (lwrRegName[3] == 'g') && (lwrRegName[5] == 'f'))
  7806. {
  7807. switch(lwrRegName[4])
  7808. {
  7809. case 'c': regNum = CPUReg_FLAG_CF_CARRY; break;
  7810. case 'p': regNum = CPUReg_FLAG_PF_PARITY; break;
  7811. case 'a': regNum = CPUReg_FLAG_AF_ADJUST; break;
  7812. case 'z': regNum = CPUReg_FLAG_ZF_ZERO; break;
  7813. case 's': regNum = CPUReg_FLAG_SF_SIGN; break;
  7814. case 'i': regNum = CPUReg_FLAG_IF_INTERRUPT; break;
  7815. case 'd': regNum = CPUReg_FLAG_DF_DIRECTION; break;
  7816. case 'o': regNum = CPUReg_FLAG_OF_OVERFLOW; break;
  7817. default: break;
  7818. }
  7819. }
  7820. if (regNum != -1)
  7821. {
  7822. int flagBit = CPURegisters::GetFlagBitForRegister(regNum);
  7823. BF_ASSERT(flagBit >= 0);
  7824. DbgTypedValue typedVal;
  7825. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Bool, language);
  7826. typedVal.mBool = (registers->mIntRegs.efl & ((uint64)1 << flagBit)) != 0;
  7827. typedVal.mRegNum = regNum;
  7828. return typedVal;
  7829. }
  7830. // categories
  7831. if (lwrRegName == "allregs")
  7832. regNum = CPUReg_CAT_ALLREGS;
  7833. else if (lwrRegName == "iregs")
  7834. regNum = CPUReg_CAT_IREGS;
  7835. else if (lwrRegName == "fpregs")
  7836. regNum = CPUReg_CAT_FPREGS;
  7837. else if (lwrRegName == "mmregs")
  7838. regNum = CPUReg_CAT_MMREGS;
  7839. else if (lwrRegName == "xmmregs")
  7840. regNum = CPUReg_CAT_XMMREGS;
  7841. else if (lwrRegName == "flags")
  7842. regNum = CPUReg_CAT_FLAGS;
  7843. if (regNum != -1)
  7844. {
  7845. DbgTypedValue typedVal;
  7846. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_RegGroup, language);
  7847. typedVal.mSingle = 0.0f; // ignored at a higher level (but if it's used as an rvalue in the meantime, it'll resolve to zero)
  7848. typedVal.mRegNum = regNum;
  7849. return typedVal;
  7850. }
  7851. return DbgTypedValue();
  7852. }
  7853. DbgModule* WinDebugger::GetCallStackDbgModule(int callStackIdx)
  7854. {
  7855. if ((mRunState == RunState_NotStarted) || (!IsPaused()))
  7856. return mEmptyDebugTarget->GetMainDbgModule();
  7857. if (callStackIdx == -1)
  7858. return mDebugTarget->GetMainDbgModule();
  7859. FixCallStackIdx(callStackIdx);
  7860. if (callStackIdx >= mCallStack.size())
  7861. return mDebugTarget->GetMainDbgModule();
  7862. UpdateCallStackMethod(callStackIdx);
  7863. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  7864. if (subProgram != NULL)
  7865. return subProgram->mCompileUnit->mDbgModule;
  7866. auto dbgModule = mDebugTarget->FindDbgModuleForAddress(mCallStack[callStackIdx]->mRegisters.GetPC());
  7867. if (dbgModule != NULL)
  7868. return dbgModule;
  7869. return mDebugTarget->GetMainDbgModule();
  7870. }
  7871. DbgSubprogram* WinDebugger::GetCallStackSubprogram(int callStackIdx)
  7872. {
  7873. if ((IsInRunState()) || (mRunState == RunState_NotStarted) || (callStackIdx == -1))
  7874. return NULL;
  7875. if (callStackIdx >= (int)mCallStack.size())
  7876. UpdateCallStack();
  7877. if (mCallStack.IsEmpty())
  7878. return NULL;
  7879. if (callStackIdx >= (int)mCallStack.size())
  7880. callStackIdx = 0;
  7881. UpdateCallStackMethod(callStackIdx);
  7882. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  7883. return subProgram;
  7884. }
  7885. DbgCompileUnit* WinDebugger::GetCallStackCompileUnit(int callStackIdx)
  7886. {
  7887. if ((IsInRunState()) || (mRunState == RunState_NotStarted) || (callStackIdx == -1))
  7888. return NULL;
  7889. if (callStackIdx >= (int)mCallStack.size())
  7890. UpdateCallStack();
  7891. if (mCallStack.IsEmpty())
  7892. return NULL;
  7893. if (callStackIdx >= (int)mCallStack.size())
  7894. callStackIdx = 0;
  7895. UpdateCallStackMethod(callStackIdx);
  7896. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  7897. if (subProgram == NULL)
  7898. return NULL;
  7899. return subProgram->mCompileUnit;
  7900. }
  7901. String WinDebugger::EvaluateContinue(DbgPendingExpr* pendingExpr, BfPassInstance& bfPassInstance)
  7902. {
  7903. DbgModule* dbgModule = NULL;
  7904. DbgCompileUnit* dbgCompileUnit = NULL;
  7905. if (pendingExpr->mThreadId == -1)
  7906. {
  7907. if ((pendingExpr->mFormatInfo.mLanguage == DbgLanguage_Beef) && (mDebugTarget != NULL) && (mDebugTarget->mTargetBinary != NULL))
  7908. dbgModule = mDebugTarget->mTargetBinary;
  7909. else
  7910. dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  7911. }
  7912. else
  7913. {
  7914. dbgModule = GetCallStackDbgModule(pendingExpr->mCallStackIdx);
  7915. if ((dbgModule != NULL) &&(!dbgModule->mDebugTarget->mIsEmpty))
  7916. dbgCompileUnit = GetCallStackCompileUnit(pendingExpr->mCallStackIdx);
  7917. }
  7918. if (dbgModule == NULL)
  7919. dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  7920. if (!pendingExpr->mException.empty())
  7921. {
  7922. RestoreAllRegisters();
  7923. return "!" + pendingExpr->mException;
  7924. }
  7925. DwAutoComplete autoComplete;
  7926. if (bfPassInstance.HasFailed())
  7927. {
  7928. // Don't allow pending calls if we've already failed in the calling Evaluate()
  7929. pendingExpr->mExpressionFlags = (DwEvalExpressionFlags)(pendingExpr->mExpressionFlags & ~DwEvalExpressionFlag_AllowCalls);
  7930. }
  7931. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, pendingExpr->mCallStackIdx, pendingExpr->mCursorPos);
  7932. dbgExprEvaluator.mLanguage = pendingExpr->mFormatInfo.mLanguage;
  7933. dbgExprEvaluator.mReferenceId = &pendingExpr->mReferenceId;
  7934. dbgExprEvaluator.mExpressionFlags = pendingExpr->mExpressionFlags;
  7935. dbgExprEvaluator.mExplicitThis = pendingExpr->mFormatInfo.mExplicitThis;
  7936. dbgExprEvaluator.mSubjectExpr = pendingExpr->mFormatInfo.mSubjectExpr;
  7937. dbgExprEvaluator.mNamespaceSearchStr = pendingExpr->mFormatInfo.mNamespaceSearch;
  7938. dbgExprEvaluator.mExpectingTypeName = pendingExpr->mFormatInfo.mExpectedType;
  7939. dbgExprEvaluator.mCallResults = &pendingExpr->mCallResults;
  7940. if ((pendingExpr->mExpressionFlags & DwEvalExpressionFlag_ValidateOnly) != 0)
  7941. {
  7942. dbgExprEvaluator.mValidateOnly = true;
  7943. }
  7944. if (pendingExpr->mCursorPos != -1)
  7945. {
  7946. dbgExprEvaluator.mAutoComplete = &autoComplete;
  7947. }
  7948. dbgExprEvaluator.mDbgCompileUnit = dbgCompileUnit;
  7949. DbgTypedValue exprResult;
  7950. if (pendingExpr->mExplitType != NULL)
  7951. {
  7952. exprResult.mHasNoValue = true;
  7953. exprResult.mType = pendingExpr->mExplitType;
  7954. }
  7955. else if (pendingExpr->mExprNode != NULL)
  7956. {
  7957. exprResult = dbgExprEvaluator.Resolve(pendingExpr->mExprNode);
  7958. }
  7959. if (dbgExprEvaluator.mCreatedPendingCall)
  7960. {
  7961. BF_ASSERT(mRunState == RunState_DebugEval);
  7962. //ContinueDebugEvent();
  7963. return "!pending";
  7964. }
  7965. if (dbgExprEvaluator.mCountResultOverride != -1)
  7966. pendingExpr->mFormatInfo.mOverrideCount = dbgExprEvaluator.mCountResultOverride;
  7967. String val;
  7968. if (bfPassInstance.HasFailed())
  7969. {
  7970. BfLogDbgExpr("Evaluate Failed: %s\n", bfPassInstance.mErrors[0]->mError.c_str());
  7971. val = StrFormat("!%d\t%d\t%s", bfPassInstance.mErrors[0]->GetSrcStart(), bfPassInstance.mErrors[0]->GetSrcLength(), bfPassInstance.mErrors[0]->mError.c_str());
  7972. }
  7973. else if (dbgExprEvaluator.mBlockedSideEffects)
  7974. {
  7975. BfLogDbgExpr("Evaluate blocked side effects\n");
  7976. val = "!sideeffects";
  7977. }
  7978. else if (!exprResult)
  7979. {
  7980. if (exprResult.mType != NULL)
  7981. {
  7982. BfLogDbgExpr("Evaluate success\n");
  7983. String typeName = exprResult.mType->ToString();
  7984. DbgType* rawType = exprResult.mType;
  7985. if (rawType->IsBfObjectPtr())
  7986. rawType = rawType->mTypeParam;
  7987. String typeNameRaw = rawType->ToStringRaw();
  7988. val = typeName + "\n" + typeName;
  7989. val += "\n" + GetMemberList(exprResult.mType, typeNameRaw, false, true, false, false, exprResult.mIsReadOnly);
  7990. if (exprResult.mType->mTypeCode == DbgType_Namespace)
  7991. {
  7992. val += "\n:type\tnamespace";
  7993. }
  7994. else
  7995. {
  7996. auto type = exprResult.mType;
  7997. if (type->IsPointer())
  7998. type = type->mTypeParam;
  7999. if (type->IsBfObject())
  8000. val += "\n:type\tclass";
  8001. else
  8002. val += "\n:type\tvaluetype";
  8003. }
  8004. if (!pendingExpr->mReferenceId.empty())
  8005. val += "\n:referenceId\t" + pendingExpr->mReferenceId;
  8006. }
  8007. else
  8008. val = "!";
  8009. }
  8010. else if ((pendingExpr->mExpressionFlags & (DwEvalExpressionFlag_MemoryAddress)) != 0)
  8011. {
  8012. DbgType* resultType = exprResult.mType->RemoveModifiers();
  8013. if ((resultType->IsInteger()) || (resultType->IsPointerOrRef()))
  8014. {
  8015. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", 0);
  8016. }
  8017. else
  8018. {
  8019. if (exprResult.mSrcAddress != 0)
  8020. val = StrFormat("!Type '%s' is invalid. A pointer or address value is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  8021. else
  8022. val = StrFormat("!Type '%s' is invalid. A pointer or address value is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  8023. }
  8024. }
  8025. else if ((pendingExpr->mExpressionFlags & (DwEvalExpressionFlag_MemoryWatch)) != 0)
  8026. {
  8027. DbgType* resultType = exprResult.mType->RemoveModifiers();
  8028. bool isMemoryWatch = (pendingExpr->mExpressionFlags & DwEvalExpressionFlag_MemoryWatch) != 0;
  8029. if (!resultType->IsPointerOrRef())
  8030. {
  8031. if (exprResult.mSrcAddress != 0)
  8032. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  8033. else
  8034. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  8035. }
  8036. else
  8037. {
  8038. auto innerType = resultType->mTypeParam;
  8039. int byteCount = innerType->GetByteCount();
  8040. if (pendingExpr->mFormatInfo.mArrayLength != -1)
  8041. byteCount *= pendingExpr->mFormatInfo.mArrayLength;
  8042. if (byteCount == 0)
  8043. {
  8044. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected, try casting to a non-void pointer type.", exprResult.mType->ToString().c_str());
  8045. }
  8046. #ifdef BF_DBG_32
  8047. else if ((isMemoryWatch) && (!IsMemoryBreakpointSizeValid(exprResult.mPtr, byteCount)))
  8048. {
  8049. if (innerType->mSize > 16)
  8050. val = StrFormat("!Element size is %d bytes. A maximum of 16 bytes can be watched. Try casting to an appropriately-sized pointer or watching an individual member.", byteCount);
  8051. else if (!IsMemoryBreakpointSizeValid(0, byteCount))
  8052. val = StrFormat("!Element size is %d bytes, which is not a supported size for a memory watch. Try casting to an appropriately-sized pointer.", byteCount);
  8053. else
  8054. val = StrFormat("!Element size is %d bytes, which is not a supported size for a memory watch at non-aligned address %@. Try casting to an appropriately-sized pointer.", byteCount, exprResult.mPtr);
  8055. }
  8056. #else
  8057. else if ((isMemoryWatch) && (!IsMemoryBreakpointSizeValid(exprResult.mPtr, byteCount)))
  8058. {
  8059. if (innerType->mSize > 32)
  8060. val = StrFormat("!Element size is %d bytes. A maximum of 32 bytes can be watched. Try casting to an appropriately-sized pointer or watching an individual member.", byteCount);
  8061. else if (!IsMemoryBreakpointSizeValid(0, byteCount))
  8062. val = StrFormat("!Element size is %d bytes, which is not a supported size for a memory watch. Try casting to an appropriately-sized pointer.", byteCount);
  8063. else
  8064. val = StrFormat("!Element size is %d bytes, which is not a supported size for a memory watch at non-aligned address %@. Try casting to an appropriately-sized pointer.", byteCount, exprResult.mPtr);
  8065. }
  8066. #endif
  8067. else
  8068. {
  8069. auto language = dbgExprEvaluator.GetLanguage();
  8070. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", byteCount) + "\n" + StrFormat("%d\t", language) + innerType->ToStringRaw(language);
  8071. }
  8072. }
  8073. }
  8074. else
  8075. {
  8076. if (pendingExpr->mFormatInfo.mNoEdit)
  8077. exprResult.mIsReadOnly = true;
  8078. if (!pendingExpr->mReferenceId.empty())
  8079. pendingExpr->mFormatInfo.mReferenceId = pendingExpr->mReferenceId;
  8080. val = DbgTypedValueToString(exprResult, pendingExpr->mExprNode->ToString(), pendingExpr->mFormatInfo, &dbgExprEvaluator, (pendingExpr->mExpressionFlags & DwEvalExpressionFlag_FullPrecision) != 0);
  8081. if ((!val.empty()) && (val[0] == '!'))
  8082. return val;
  8083. if (pendingExpr->mFormatInfo.mRawString)
  8084. return val;
  8085. if (exprResult.mIsLiteral)
  8086. val += "\n:literal";
  8087. if (bfPassInstance.HasMessages())
  8088. {
  8089. for (auto error : bfPassInstance.mErrors)
  8090. {
  8091. if (error->mIsWarning)
  8092. {
  8093. val += "\n:warn\t";
  8094. val += error->mError;
  8095. }
  8096. }
  8097. }
  8098. if (!pendingExpr->mFormatInfo.mReferenceId.empty())
  8099. val += "\n:referenceId\t" + pendingExpr->mFormatInfo.mReferenceId;
  8100. if ((exprResult.mSrcAddress != 0) && (HasMemoryBreakpoint(exprResult.mSrcAddress, exprResult.mType->GetByteCount())))
  8101. val += StrFormat("\n:break\t%@", exprResult.mSrcAddress);
  8102. auto checkType = exprResult.mType->RemoveModifiers();
  8103. if (checkType->IsBfObjectPtr())
  8104. val += "\n:type\tobject";
  8105. else if ((checkType->IsPointer()) || (checkType->mTypeCode == DbgType_Subroutine))
  8106. val += "\n:type\tpointer";
  8107. else if (checkType->IsInteger())
  8108. val += "\n:type\tint";
  8109. else if (checkType->IsFloat())
  8110. val += "\n:type\tfloat";
  8111. else if ((exprResult.mRegNum >= X64Reg_M128_XMM0) && (exprResult.mRegNum <= X64Reg_M128_XMM15))
  8112. val += "\n:type\tmm128";
  8113. else
  8114. val += "\n:type\tvaluetype";
  8115. if ((pendingExpr->mFormatInfo.mTypeKindFlags & DbgTypeKindFlag_Int) != 0)
  8116. val += "\n:type\tint";
  8117. if (dbgExprEvaluator.mHadSideEffects)
  8118. val += "\n:sideeffects";
  8119. auto underlyingType = exprResult.mType->RemoveModifiers();
  8120. bool canEdit = true;
  8121. if (pendingExpr->mFormatInfo.mLanguage == DbgLanguage_Beef)
  8122. {
  8123. if (exprResult.mType->IsConst())
  8124. canEdit = false;
  8125. }
  8126. if (pendingExpr->mFormatInfo.mNoEdit)
  8127. canEdit = false;
  8128. if (exprResult.mIsReadOnly)
  8129. canEdit = false;
  8130. if (val[0] == '!')
  8131. {
  8132. // Already has an error embedded, can't edit
  8133. }
  8134. else if ((exprResult.mSrcAddress != 0) && (underlyingType->mTypeCode >= DbgType_i8) && (underlyingType->mTypeCode <= DbgType_Ptr) &&
  8135. (underlyingType->mTypeCode != DbgType_Class) && (underlyingType->mTypeCode != DbgType_Struct))
  8136. {
  8137. if (canEdit)
  8138. val += "\n:canEdit";
  8139. if (exprResult.mType->mTypeCode == DbgType_Ptr)
  8140. {
  8141. val += "\n:editVal\t" + EncodeDataPtr(exprResult.mPtr, true);
  8142. }
  8143. }
  8144. else if ((underlyingType->IsStruct()) && (exprResult.mSrcAddress != 0) && (underlyingType->IsTypedPrimitive()))
  8145. {
  8146. auto primType = underlyingType->GetRootBaseType();
  8147. DbgTypedValue primVal = dbgExprEvaluator.ReadTypedValue(NULL, primType, exprResult.mSrcAddress, DbgAddrType_Target);
  8148. String primResult = DbgTypedValueToString(primVal, "", pendingExpr->mFormatInfo, NULL);
  8149. int crPos = (int)primResult.IndexOf('\n');
  8150. if (crPos != -1)
  8151. primResult.RemoveToEnd(crPos);
  8152. if (canEdit)
  8153. val += "\n:canEdit";
  8154. val += "\n:editVal\t" + primResult;
  8155. }
  8156. else if (exprResult.mRegNum >= 0)
  8157. {
  8158. bool isPseudoReg = ( ((exprResult.mRegNum >= X86Reg_M128_XMMREG_FIRST) && (exprResult.mRegNum <= X86Reg_M128_XMMREG_LAST))
  8159. || ((exprResult.mRegNum >= X86Reg_CAT_FIRST) && (exprResult.mRegNum <= X86Reg_CAT_LAST)) );
  8160. if (!isPseudoReg)
  8161. {
  8162. if (canEdit)
  8163. val += "\n:canEdit";
  8164. }
  8165. }
  8166. }
  8167. if (pendingExpr->mFormatInfo.mRawString)
  8168. return "";
  8169. if (pendingExpr->mCursorPos != -1)
  8170. val += GetAutocompleteOutput(autoComplete);
  8171. return val;
  8172. }
  8173. String WinDebugger::EvaluateContinue()
  8174. {
  8175. BP_ZONE("WinDebugger::EvaluateContinue");
  8176. AutoCrit autoCrit(mDebugManager->mCritSect);
  8177. if (mDebugPendingExpr == NULL)
  8178. return "!Evaluation canceled";
  8179. if (!IsPaused())
  8180. return "!Not paused";
  8181. if (mRunState == RunState_DebugEval_Done)
  8182. mRunState = RunState_Paused;
  8183. BfPassInstance bfPassInstance(mBfSystem);
  8184. String result = EvaluateContinue(mDebugPendingExpr, bfPassInstance);
  8185. if (result != "!pending")
  8186. {
  8187. BfLogDbg("EvaluateContinue finishing pending expr in thread %d\n", mDebugEvalThreadInfo.mThreadId);
  8188. CleanupDebugEval();
  8189. }
  8190. return result;
  8191. }
  8192. void WinDebugger::EvaluateContinueKeep()
  8193. {
  8194. if (mDebugPendingExpr != NULL)
  8195. mDebugPendingExpr->mIdleTicks = 0;
  8196. }
  8197. static void PdbTestFile(WinDebugger* debugger, const StringImpl& path)
  8198. {
  8199. if (!path.EndsWith(".PDB", StringImpl::CompareKind_OrdinalIgnoreCase))
  8200. return;
  8201. OutputDebugStrF("Testing %s\n", path.c_str());
  8202. COFF coffFile(debugger->mDebugTarget);
  8203. uint8 wantGuid[16] = { 0 };
  8204. if (!coffFile.TryLoadPDB(path, wantGuid, -1))
  8205. return;
  8206. if (!coffFile.mIs64Bit)
  8207. return;
  8208. coffFile.ParseTypeData();
  8209. coffFile.ParseSymbolData();
  8210. coffFile.ParseGlobalsData();
  8211. }
  8212. static void PdbTest(WinDebugger* debugger, const StringImpl& path)
  8213. {
  8214. for (auto& fileEntry : FileEnumerator(path, FileEnumerator::Flags_Files))
  8215. {
  8216. String filePath = fileEntry.GetFilePath();
  8217. PdbTestFile(debugger, filePath);
  8218. }
  8219. for (auto& fileEntry : FileEnumerator(path, FileEnumerator::Flags_Directories))
  8220. {
  8221. String childPath = fileEntry.GetFilePath();
  8222. String dirName;
  8223. dirName = GetFileName(childPath);
  8224. PdbTest(debugger, childPath);
  8225. }
  8226. }
  8227. String WinDebugger::Evaluate(const StringImpl& expr, DwFormatInfo formatInfo, int callStackIdx, int cursorPos, int language, DwEvalExpressionFlags expressionFlags)
  8228. {
  8229. BP_ZONE_F("WinDebugger::Evaluate %s", BP_DYN_STR(expr.c_str()));
  8230. AutoCrit autoCrit(mDebugManager->mCritSect);
  8231. if ((expressionFlags & DwEvalExpressionFlag_Symbol) != 0)
  8232. {
  8233. DwAutoComplete autoComplete;
  8234. String retVal;
  8235. retVal += GetAutocompleteOutput(autoComplete);
  8236. return retVal;
  8237. }
  8238. UpdateCallStackMethod(callStackIdx);
  8239. BfLogDbgExpr("Evaluate %s in thread %d\n", expr.c_str(), (mActiveThread != NULL) ? mActiveThread->mThreadId : 0);
  8240. if (language != -1)
  8241. formatInfo.mLanguage = (DbgLanguage)language;
  8242. auto activeThread = mActiveThread;
  8243. if ((!IsPaused()) && (mRunState != RunState_NotStarted) && (mRunState != RunState_DebugEval))
  8244. {
  8245. activeThread = NULL;
  8246. callStackIdx = -1;
  8247. }
  8248. if (mDebugPendingExpr != NULL)
  8249. {
  8250. // We already have a pending call
  8251. expressionFlags = (DwEvalExpressionFlags)(expressionFlags & ~DwEvalExpressionFlag_AllowCalls);
  8252. }
  8253. auto dbgModule = GetCallStackDbgModule(callStackIdx);
  8254. auto dbgSubprogram = GetCallStackSubprogram(callStackIdx);
  8255. DbgCompileUnit* dbgCompileUnit = NULL;
  8256. if (dbgSubprogram != NULL)
  8257. dbgCompileUnit = dbgSubprogram->mCompileUnit;
  8258. auto terminatedExpr = expr + ";";
  8259. if ((expr.length() > 0) && (expr[0] == '!'))
  8260. {
  8261. if (expr.StartsWith("!step "))
  8262. {
  8263. expressionFlags = (DwEvalExpressionFlags)(expressionFlags | DwEvalExpressionFlag_StepIntoCalls);
  8264. for (int i = 0; i < 5; i++)
  8265. terminatedExpr[i] = ' ';
  8266. }
  8267. else
  8268. {
  8269. String cmd = expr;
  8270. int commaPos = (int)cmd.IndexOf(',');
  8271. if (commaPos != -1)
  8272. cmd.RemoveToEnd(commaPos);
  8273. if (cmd == "!info")
  8274. {
  8275. OutputMessage(StrFormat("Module: %s\n", dbgModule->mDisplayName.c_str()));
  8276. if (dbgSubprogram == NULL)
  8277. {
  8278. //
  8279. }
  8280. else if (dbgSubprogram->mLinkName != NULL)
  8281. {
  8282. OutputMessage(StrFormat("Link Name: %s\n", dbgSubprogram->mLinkName));
  8283. }
  8284. else
  8285. {
  8286. String outSymbol;
  8287. if (mDebugTarget->FindSymbolAt(dbgSubprogram->mBlock.mLowPC, &outSymbol))
  8288. {
  8289. OutputMessage(StrFormat("Link Name: %s\n", outSymbol.c_str()));
  8290. }
  8291. }
  8292. return "";
  8293. }
  8294. else if (cmd == "!dbg")
  8295. {
  8296. mDbgBreak = true;
  8297. return "";
  8298. }
  8299. else if (cmd == "!pdbtest")
  8300. {
  8301. PdbTest(this, "c:\\");
  8302. }
  8303. }
  8304. }
  8305. bool valIsAddr = false;
  8306. BfParser* parser = new BfParser(mBfSystem);
  8307. parser->mCompatMode = true;
  8308. BfPassInstance bfPassInstance(mBfSystem);
  8309. if ((terminatedExpr.length() > 2) && (terminatedExpr[0] == '@'))
  8310. {
  8311. if (terminatedExpr[1] == '!') // Return string as error
  8312. {
  8313. int errorEnd = (int)terminatedExpr.IndexOf("@!", 2);
  8314. if (errorEnd != -1)
  8315. return terminatedExpr.Substring(1, errorEnd - 1);
  8316. else
  8317. return terminatedExpr.Substring(1);
  8318. }
  8319. else if (terminatedExpr[1] == '>') // Return string as text
  8320. {
  8321. int errorEnd = (int)terminatedExpr.IndexOf("@>", 2);
  8322. if (errorEnd != -1)
  8323. return terminatedExpr.Substring(2, errorEnd - 1);
  8324. else
  8325. return terminatedExpr.Substring(2);
  8326. }
  8327. else // Look for "@:" or "@Beef:" style
  8328. {
  8329. int colonIdx = terminatedExpr.IndexOf(':');
  8330. if (colonIdx > 0)
  8331. {
  8332. bool isValid = true;
  8333. DbgLanguage language = DbgLanguage_Unknown;
  8334. String lang = terminatedExpr.Substring(1, colonIdx - 1);
  8335. lang = ToUpper(lang);
  8336. if ((lang == "") || (lang == "BEEF"))
  8337. {
  8338. language = DbgLanguage_Beef;
  8339. }
  8340. else if (lang == "C")
  8341. {
  8342. language = DbgLanguage_C;
  8343. }
  8344. if (language != DbgLanguage_Unknown)
  8345. {
  8346. for (int i = 0; i < colonIdx + 1; i++)
  8347. terminatedExpr[i] = ' ';
  8348. DbgLanguage curLanguage = DbgLanguage_Unknown;
  8349. if (dbgSubprogram != NULL)
  8350. curLanguage = dbgSubprogram->GetLanguage();
  8351. if (language != curLanguage)
  8352. {
  8353. dbgModule = mDebugTarget->mTargetBinary;
  8354. dbgSubprogram = NULL;
  8355. formatInfo.mLanguage = language;
  8356. callStackIdx = -1;
  8357. }
  8358. }
  8359. }
  8360. }
  8361. }
  8362. parser->SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  8363. parser->Parse(&bfPassInstance);
  8364. BfReducer bfReducer;
  8365. bfReducer.mAlloc = parser->mAlloc;
  8366. bfReducer.mSystem = mBfSystem;
  8367. bfReducer.mPassInstance = &bfPassInstance;
  8368. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser->mRootNode);
  8369. bfReducer.mVisitorPos.MoveNext();
  8370. bfReducer.mCompatMode = parser->mCompatMode;
  8371. bfReducer.mSource = parser;
  8372. auto exprNode = bfReducer.CreateExpression(parser->mRootNode->mChildArr.GetAs<BfAstNode*>(0));
  8373. parser->Close();
  8374. formatInfo.mCallStackIdx = callStackIdx;
  8375. if ((formatInfo.mLanguage == DbgLanguage_Unknown) && (dbgSubprogram != NULL))
  8376. formatInfo.mLanguage = dbgSubprogram->GetLanguage();
  8377. DbgPendingExpr* pendingExpr = new DbgPendingExpr();
  8378. if (activeThread != NULL)
  8379. pendingExpr->mThreadId = activeThread->mThreadId;
  8380. pendingExpr->mParser = parser;
  8381. pendingExpr->mCallStackIdx = callStackIdx;
  8382. pendingExpr->mCursorPos = cursorPos;
  8383. pendingExpr->mExpressionFlags = expressionFlags;
  8384. pendingExpr->mExprNode = exprNode;
  8385. DbgType* explicitType = NULL;
  8386. String formatFlags;
  8387. String assignExpr;
  8388. int assignExprOffset = -1;
  8389. if ((exprNode != NULL) && (exprNode->GetSrcEnd() < (int)expr.length()))
  8390. {
  8391. int formatOffset = exprNode->GetSrcEnd();
  8392. while (formatOffset < (int)expr.length())
  8393. {
  8394. char c = expr[formatOffset];
  8395. if (c == ' ')
  8396. formatOffset++;
  8397. else
  8398. break;
  8399. }
  8400. formatFlags = Trim(expr.Substring(formatOffset));
  8401. bool isComplexType = false;
  8402. for (char c : formatFlags)
  8403. if (c == '>')
  8404. isComplexType = true;
  8405. if (isComplexType)
  8406. {
  8407. explicitType = dbgModule->FindType(expr);
  8408. }
  8409. if ((explicitType == NULL) && (formatFlags.length() > 0))
  8410. {
  8411. String errorString = "Invalid expression";
  8412. if (!ParseFormatInfo(dbgModule, formatFlags, &formatInfo, &bfPassInstance, &assignExprOffset, &assignExpr, &errorString))
  8413. {
  8414. if (formatInfo.mRawString)
  8415. return "";
  8416. bfPassInstance.FailAt(errorString, parser->mSourceData, exprNode->GetSrcEnd(), (int) expr.length() - exprNode->GetSrcEnd());
  8417. formatFlags = "";
  8418. }
  8419. if (assignExprOffset != -1)
  8420. assignExprOffset += formatOffset;
  8421. }
  8422. }
  8423. if (assignExpr.length() > 0)
  8424. {
  8425. String newEvalStr = exprNode->ToString() + " = ";
  8426. int errorOffset = (int)newEvalStr.length();
  8427. newEvalStr += assignExpr;
  8428. String result = Evaluate(newEvalStr, formatInfo, callStackIdx, cursorPos, language, expressionFlags);
  8429. if (result[0] == '!')
  8430. {
  8431. int tabPos = (int)result.IndexOf('\t');
  8432. if (tabPos > 0)
  8433. {
  8434. int errorStart = atoi(result.Substring(1, tabPos - 1).c_str());
  8435. if (errorStart >= errorOffset)
  8436. {
  8437. result = StrFormat("!%d", errorStart - errorOffset + assignExprOffset) + result.Substring(tabPos);
  8438. }
  8439. }
  8440. }
  8441. return result;
  8442. }
  8443. pendingExpr->mExplitType = explicitType;
  8444. pendingExpr->mFormatInfo = formatInfo;
  8445. String result = EvaluateContinue(pendingExpr, bfPassInstance);
  8446. if (result == "!pending")
  8447. {
  8448. BF_ASSERT(mDebugPendingExpr == NULL);
  8449. if (mDebugPendingExpr != NULL)
  8450. {
  8451. return "!retry"; // We already have a pending
  8452. }
  8453. mDebugPendingExpr = pendingExpr;
  8454. mDebugEvalThreadInfo = *mActiveThread;
  8455. mActiveThread->mIsAtBreakpointAddress = 0;
  8456. mActiveThread->mStoppedAtAddress = 0;
  8457. mActiveThread->mBreakpointAddressContinuing = 0;
  8458. }
  8459. else
  8460. delete pendingExpr;
  8461. return result;
  8462. }
  8463. String WinDebugger::Evaluate(const StringImpl& expr, int callStackIdx, int cursorPos, int language, DwEvalExpressionFlags expressionFlags)
  8464. {
  8465. DwFormatInfo formatInfo;
  8466. return Evaluate(expr, formatInfo, callStackIdx, cursorPos, language, expressionFlags);
  8467. }
  8468. static void ConvertDoubleToFloat80(double d, byte fp80[10])
  8469. {
  8470. uint64 di = *reinterpret_cast<uint64*>(&d);
  8471. uint64 m = di & (((uint64)1 << 52) - 1);
  8472. uint64 e = (di >> 52) & 0x7ff;
  8473. memset(fp80, 0, 10);
  8474. // sign bit is directly transferred
  8475. if (di & ((uint64)1 << 63))
  8476. fp80[9] |= 0x80;
  8477. if (!e && !m)
  8478. return; // zero
  8479. fp80[7] |= 0x80; // leading integer bit in mantissa (always 1 in normalized numbers)
  8480. if (e == 0x7ff)
  8481. {
  8482. fp80[9] |= 0x7f;
  8483. fp80[8] = 0xff;
  8484. if (m == 0)
  8485. return; // inf
  8486. fp80[7] |= 0x3f; // any nonzero value will be a NaN (SNaN or QNaN)
  8487. if (m & ((uint64)1 << 51))
  8488. fp80[7] |= 0x40; // QNaN
  8489. return;
  8490. }
  8491. int useExponent = (int)e - 1023;
  8492. if (!e)
  8493. {
  8494. // denormal; can renormalize though since fp80 supports lower exponents
  8495. BF_ASSERT(m != 0); // we should have trapped zero above
  8496. while (!(m & ((uint64)1 << 51)))
  8497. {
  8498. m <<= 1;
  8499. --useExponent;
  8500. }
  8501. // finally we have our leading 1 bit; strip that off and we have a normalized number again
  8502. m <<= 1;
  8503. --useExponent;
  8504. m &= (((uint64)1 << 52) - 1);
  8505. }
  8506. useExponent += 16383;
  8507. BF_ASSERT((useExponent > 0) && (useExponent < 0x7fff));
  8508. *reinterpret_cast<uint16*>(&fp80[8]) |= (uint16)useExponent;
  8509. *reinterpret_cast<uint64*>(&fp80[0]) |= (m << 11);
  8510. }
  8511. bool WinDebugger::AssignToReg(int callStackIdx, DbgTypedValue regVal, DbgTypedValue value, String& outError)
  8512. {
  8513. BF_ASSERT(regVal.mRegNum >= 0);
  8514. if (mCallStack.size() == 0)
  8515. {
  8516. outError = "No call stack";
  8517. return false;
  8518. }
  8519. if (callStackIdx >= (int)mCallStack.size())
  8520. {
  8521. outError = "Invalid call stack index";
  8522. return false;
  8523. }
  8524. auto registers = &mCallStack[callStackIdx]->mRegisters;
  8525. void* regPtr = NULL;
  8526. #ifdef BF_DBG_32
  8527. if ((regVal.mRegNum >= X86Reg_INTREG_FIRST) && (regVal.mRegNum <= X86Reg_INTREG_LAST))
  8528. {
  8529. BF_ASSERT(regVal.mType->mSize == sizeof(int32));
  8530. registers->mIntRegsArray[regVal.mRegNum - X86Reg_INTREG_FIRST] = (uint64)value.mUInt32; // don't sign-extend
  8531. }
  8532. else if ((regVal.mRegNum >= X86Reg_FPSTREG_FIRST) && (regVal.mRegNum <= X86Reg_FPSTREG_LAST))
  8533. {
  8534. BF_ASSERT(regVal.mType->mSize == sizeof(float) || regVal.mType->mSize == sizeof(double));
  8535. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X86Reg_FPSTREG_FIRST];
  8536. double d;
  8537. if (regVal.mType->mSize == sizeof(float))
  8538. d = (double)value.mSingle;
  8539. else
  8540. d = value.mDouble;
  8541. ConvertDoubleToFloat80(d, reg->fp.fp80);
  8542. }
  8543. else if ((regVal.mRegNum >= X86Reg_MMREG_FIRST) && (regVal.mRegNum <= X86Reg_MMREG_LAST))
  8544. {
  8545. BF_ASSERT(regVal.mType->mSize == sizeof(int32) || regVal.mType->mSize == sizeof(int64));
  8546. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X86Reg_MMREG_FIRST];
  8547. if (regVal.mType->mSize == sizeof(int32))
  8548. reg->mm = (uint64)value.mUInt32; // don't sign-extend
  8549. else if (regVal.mType->mSize == sizeof(int64))
  8550. reg->mm = value.mInt64;
  8551. // whenever we use the low 64 bits of the reg as mm, the upper 16 bits of the 80-bit float must be set to all-1s to indicate NaN
  8552. reg->fp.fp80[8] = reg->fp.fp80[9] = 0xFF;
  8553. }
  8554. else if ((regVal.mRegNum >= X86Reg_XMMREG_FIRST) && (regVal.mRegNum <= X86Reg_XMMREG_LAST))
  8555. {
  8556. int xmmMajor = (regVal.mRegNum - X86Reg_XMMREG_FIRST) >> 2;
  8557. int xmmMinor = (regVal.mRegNum - X86Reg_XMMREG_FIRST) & 3;
  8558. registers->mXmmRegsArray[xmmMajor].f[xmmMinor] = value.mSingle;
  8559. }
  8560. else if ((regVal.mRegNum >= X86Reg_M128_XMMREG_FIRST) && (regVal.mRegNum <= X86Reg_M128_XMMREG_LAST))
  8561. {
  8562. outError = "Cannot write directly to 128-bit XMM register, please use inner float components";
  8563. return false;
  8564. }
  8565. else if ((regVal.mRegNum >= X86Reg_FLAG_FIRST) && (regVal.mRegNum <= X86Reg_FLAG_LAST))
  8566. {
  8567. int flagBit = CPURegisters::GetFlagBitForRegister(regVal.mRegNum);
  8568. if (flagBit >= 0)
  8569. {
  8570. if (value.mBool)
  8571. registers->mIntRegs.efl |= ((uint64)1 << flagBit);
  8572. else
  8573. registers->mIntRegs.efl &= ~((uint64)1 << flagBit);
  8574. }
  8575. else
  8576. {
  8577. outError = "Unrecognized flag";
  8578. return false;
  8579. }
  8580. }
  8581. else if ((regVal.mRegNum >= X86Reg_CAT_FIRST) && (regVal.mRegNum <= X86Reg_CAT_LAST))
  8582. {
  8583. outError = "Cannot write directly to register categories, please use inner float components";
  8584. return false;
  8585. }
  8586. #else
  8587. if ((regVal.mRegNum >= X64Reg_INTREG_FIRST) && (regVal.mRegNum <= X64Reg_INTREG_LAST))
  8588. {
  8589. //BF_ASSERT(regVal.mType->mSize == sizeof(addr_target));
  8590. registers->mIntRegsArray[regVal.mRegNum - X64Reg_INTREG_FIRST] = value.GetInt64(); // don't sign-extend
  8591. regPtr = &registers->mIntRegsArray[regVal.mRegNum - X64Reg_INTREG_FIRST];
  8592. }
  8593. else if ((regVal.mRegNum >= X64Reg_FPSTREG_FIRST) && (regVal.mRegNum <= X64Reg_FPSTREG_LAST))
  8594. {
  8595. BF_ASSERT(regVal.mType->mSize == sizeof(float) || regVal.mType->mSize == sizeof(double));
  8596. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X64Reg_FPSTREG_FIRST];
  8597. double d;
  8598. if (regVal.mType->mSize == sizeof(float))
  8599. d = (double)value.mSingle;
  8600. else
  8601. d = value.mDouble;
  8602. ConvertDoubleToFloat80(d, reg->fp.fp80);
  8603. regPtr = reg;
  8604. }
  8605. else if ((regVal.mRegNum >= X64Reg_MMREG_FIRST) && (regVal.mRegNum <= X64Reg_MMREG_LAST))
  8606. {
  8607. BF_ASSERT(regVal.mType->mSize == sizeof(int32) || regVal.mType->mSize == sizeof(int64));
  8608. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X64Reg_MMREG_FIRST];
  8609. if (regVal.mType->mSize == sizeof(int32))
  8610. reg->mm = (uint64)value.mUInt32; // don't sign-extend
  8611. else if (regVal.mType->mSize == sizeof(int64))
  8612. reg->mm = value.mInt64;
  8613. // whenever we use the low 64 bits of the reg as mm, the upper 16 bits of the 80-bit float must be set to all-1s to indicate NaN
  8614. reg->fp.fp80[8] = reg->fp.fp80[9] = 0xFF;
  8615. regPtr = reg;
  8616. }
  8617. else if ((regVal.mRegNum >= X64Reg_XMMREG_FIRST) && (regVal.mRegNum <= X64Reg_XMMREG_LAST))
  8618. {
  8619. int xmmMajor = (regVal.mRegNum - X64Reg_XMMREG_FIRST) >> 2;
  8620. int xmmMinor = (regVal.mRegNum - X64Reg_XMMREG_FIRST) & 3;
  8621. if (value.mType->GetByteCount() == 4)
  8622. registers->mXmmRegsArray[xmmMajor].f[xmmMinor] = value.mSingle;
  8623. else if (value.mType->GetByteCount() == 8)
  8624. registers->mXmmDRegsArray[xmmMajor].d[xmmMinor] = value.mDouble;
  8625. else
  8626. BF_FATAL("Invalid XMM set value type");
  8627. regPtr = &registers->mXmmRegsArray[xmmMajor];
  8628. }
  8629. else if ((regVal.mRegNum >= X64Reg_M128_XMMREG_FIRST) && (regVal.mRegNum <= X64Reg_M128_XMMREG_LAST))
  8630. {
  8631. outError = "Cannot write directly to 128-bit XMM register, please use inner float components";
  8632. return false;
  8633. }
  8634. else if ((regVal.mRegNum >= X64Reg_FLAG_FIRST) && (regVal.mRegNum <= X64Reg_FLAG_LAST))
  8635. {
  8636. int flagBit = CPURegisters::GetFlagBitForRegister(regVal.mRegNum);
  8637. if (flagBit >= 0)
  8638. {
  8639. if (value.mBool)
  8640. registers->mIntRegs.efl |= ((uint64)1 << flagBit);
  8641. else
  8642. registers->mIntRegs.efl &= ~((uint64)1 << flagBit);
  8643. regPtr = &registers->mIntRegs.efl;
  8644. }
  8645. else
  8646. {
  8647. outError = "Unrecognized flag";
  8648. return false;
  8649. }
  8650. }
  8651. else if ((regVal.mRegNum >= X64Reg_CAT_FIRST) && (regVal.mRegNum <= X64Reg_CAT_LAST))
  8652. {
  8653. outError = "Cannot write directly to register categories, please use inner float components";
  8654. return false;
  8655. }
  8656. else
  8657. BF_FATAL("Not implemented");
  8658. #endif
  8659. if (callStackIdx == 0)
  8660. {
  8661. SetRegisters(&mCallStack[0]->mRegisters);
  8662. return true;
  8663. }
  8664. else
  8665. {
  8666. bool wasSaved = false;
  8667. for (int calleeStackIdx = callStackIdx - 1; calleeStackIdx >= 0; calleeStackIdx--)
  8668. {
  8669. auto calleeRegisters = &mCallStack[calleeStackIdx]->mRegisters;
  8670. if (!mDebugTarget->PropogateRegisterUpCallStack(registers, calleeRegisters, regPtr, wasSaved))
  8671. {
  8672. outError = "Failed to set register";
  8673. return false;
  8674. }
  8675. if (wasSaved)
  8676. return true;
  8677. }
  8678. // This register wasn't saved, so commit it to the callstack top
  8679. return AssignToReg(0, regVal, value, outError);
  8680. }
  8681. }
  8682. String WinDebugger::GetAutocompleteOutput(DwAutoComplete& autoComplete)
  8683. {
  8684. String val = "\n:autocomplete\n";
  8685. if (autoComplete.mInsertStartIdx != -1)
  8686. {
  8687. val += StrFormat("insertRange\t%d %d\n", autoComplete.mInsertStartIdx, autoComplete.mInsertEndIdx);
  8688. }
  8689. Array<AutoCompleteEntry*> entries;
  8690. for (auto& entry : autoComplete.mEntriesSet)
  8691. {
  8692. entries.Add(&entry);
  8693. }
  8694. std::sort(entries.begin(), entries.end(), [](AutoCompleteEntry* lhs, AutoCompleteEntry* rhs)
  8695. {
  8696. return stricmp(lhs->mDisplay, rhs->mDisplay) < 0;
  8697. });
  8698. for (auto entry : entries)
  8699. {
  8700. val += String(entry->mEntryType);
  8701. val += "\t";
  8702. val += String(entry->mDisplay);
  8703. val += "\n";
  8704. }
  8705. /*if (autoComplete.mEntries.size() != 0)
  8706. {
  8707. for (auto& entry : autoComplete.mEntries)
  8708. {
  8709. val += String(entry.mEntryType) + "\t" + String(entry.mDisplay) + "\n";
  8710. }
  8711. }*/
  8712. return val;
  8713. }
  8714. String WinDebugger::EvaluateToAddress(const StringImpl& expr, int callStackIdx, int cursorPos)
  8715. {
  8716. AutoCrit autoCrit(mDebugManager->mCritSect);
  8717. if (IsInRunState())
  8718. return "!Target not paused";
  8719. auto dbgModule = GetCallStackDbgModule(callStackIdx);
  8720. auto dbgCompileUnit = GetCallStackCompileUnit(callStackIdx);
  8721. BfParser parser(mBfSystem);
  8722. parser.mCompatMode = true;
  8723. BfPassInstance bfPassInstance(mBfSystem);
  8724. auto terminatedExpr = expr + ";";
  8725. parser.SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  8726. parser.Parse(&bfPassInstance);
  8727. BfReducer bfReducer;
  8728. bfReducer.mAlloc = parser.mAlloc;
  8729. bfReducer.mSystem = mBfSystem;
  8730. bfReducer.mPassInstance = &bfPassInstance;
  8731. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser.mRootNode);
  8732. bfReducer.mVisitorPos.MoveNext();
  8733. bfReducer.mSource = &parser;
  8734. auto exprNode = bfReducer.CreateExpression(parser.mRootNode->GetFirst());
  8735. parser.Close();
  8736. DwAutoComplete autoComplete;
  8737. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, callStackIdx, cursorPos);
  8738. if (cursorPos != -1)
  8739. dbgExprEvaluator.mAutoComplete = &autoComplete;
  8740. dbgExprEvaluator.mDbgCompileUnit = dbgCompileUnit;
  8741. DwFormatInfo formatInfo;
  8742. formatInfo.mCallStackIdx = callStackIdx;
  8743. DbgTypedValue exprResult;
  8744. if (exprNode != NULL)
  8745. exprResult = dbgExprEvaluator.Resolve(exprNode);
  8746. DbgType* resultType = exprResult.mType->RemoveModifiers();
  8747. String val;
  8748. if (bfPassInstance.HasFailed())
  8749. {
  8750. val = StrFormat("!%d\t%d\t%s", bfPassInstance.mErrors[0]->mSrcStart, bfPassInstance.mErrors[0]->GetSrcLength(), bfPassInstance.mErrors[0]->mError.c_str());
  8751. }
  8752. else if (exprResult.mType == NULL)
  8753. {
  8754. val = "!Invalid expression";
  8755. }
  8756. else if (!resultType->IsPointerOrRef())
  8757. {
  8758. if (exprResult.mSrcAddress != 0)
  8759. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  8760. else
  8761. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  8762. }
  8763. else
  8764. {
  8765. auto innerType = resultType->mTypeParam;
  8766. int byteCount = innerType->GetByteCount();
  8767. if (byteCount == 0)
  8768. {
  8769. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected, try casting to a non-void pointer type.", exprResult.mType->ToString().c_str());
  8770. }
  8771. #ifdef BF_DBG_32
  8772. else if ((byteCount != 1) && (byteCount != 2) && (byteCount != 4))
  8773. {
  8774. val = StrFormat("!Element size is %d bytes. Only 1, 2, or 4 byte elements can be tracked. Try casting to an appropriately-sized pointer.", innerType->mSize);
  8775. }
  8776. #else
  8777. else if ((byteCount != 1) && (byteCount != 2) && (byteCount != 4) && (byteCount != 8))
  8778. {
  8779. val = StrFormat("!Element size is %d bytes. Only 1, 2, 4, or 8 byte elements can be tracked. Try casting to an appropriately-sized pointer.", innerType->mSize);
  8780. }
  8781. #endif
  8782. else
  8783. {
  8784. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", byteCount);
  8785. }
  8786. }
  8787. if (cursorPos != -1)
  8788. val += GetAutocompleteOutput(autoComplete);
  8789. return val;
  8790. }
  8791. // This is currently only used for autocomplete during conditional breakpoint expression entry.
  8792. // If we want to use it for more than that then remove DwEvalExpressionFlags_ValidateOnly
  8793. String WinDebugger::EvaluateAtAddress(const StringImpl& expr, intptr atAddr, int cursorPos)
  8794. {
  8795. AutoCrit autoCrit(mDebugManager->mCritSect);
  8796. if (IsInRunState())
  8797. return "!Target not paused";
  8798. if (!IsPaused())
  8799. return "!Target not running";
  8800. WdStackFrame stackFrame;
  8801. memset(&stackFrame.mRegisters, 0, sizeof(stackFrame.mRegisters));
  8802. stackFrame.mHasGottenSubProgram = true;
  8803. *stackFrame.mRegisters.GetPCRegisterRef() = (intptr_target)atAddr;
  8804. stackFrame.mSubProgram = mDebugTarget->FindSubProgram((addr_target)atAddr);
  8805. if (stackFrame.mSubProgram == NULL)
  8806. return "!Invalid address";
  8807. mCallStack.push_back(&stackFrame);
  8808. int callStackIdx = (int)mCallStack.size() - 1;
  8809. String val = Evaluate(expr, callStackIdx, cursorPos, -1, DwEvalExpressionFlag_ValidateOnly);
  8810. mCallStack.pop_back();
  8811. return val;
  8812. }
  8813. String WinDebugger::GetAutoExpressions(int callStackIdx, uint64 memoryRangeStart, uint64 memoryRangeLen)
  8814. {
  8815. BP_ZONE("WinDebugger::GetAutoExpressions");
  8816. AutoCrit autoCrit(mDebugManager->mCritSect);
  8817. if (IsInRunState())
  8818. return "!Not paused";
  8819. if (!IsPaused())
  8820. return "!Not running";
  8821. if (!FixCallStackIdx(callStackIdx))
  8822. return "";
  8823. CPUStackFrame* stackFrame = (callStackIdx >= 0) ? mCallStack[callStackIdx] : mCallStack.front();
  8824. String result;
  8825. DbgAutoValueMapType dwarfAutos;
  8826. mDebugTarget->GetAutoValueNames(dwarfAutos, stackFrame, memoryRangeStart, memoryRangeLen);
  8827. for (auto const &a : dwarfAutos)
  8828. {
  8829. std::pair<uint64, uint64> varRange = a.mValue;
  8830. if (varRange.first != 0)
  8831. result += StrFormat("&%s\t%llu\t%llu\n", a.mKey.c_str(), varRange.second, varRange.first);
  8832. else
  8833. result += StrFormat("?%s\t%llu\n", a.mKey.c_str(), varRange.second);
  8834. }
  8835. #ifdef BF_DBG_64
  8836. // add int regs
  8837. const char* regStrs[] = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "rip", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", 0 };
  8838. #else
  8839. // add int regs
  8840. const char* regStrs[] = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "eip", 0 };
  8841. #endif
  8842. for (const char** p = regStrs; *p; ++p)
  8843. result += StrFormat("$%s\t%d\n", *p, sizeof(addr_target));
  8844. if (callStackIdx < (int)mCallStack.size() - 2)
  8845. {
  8846. WdStackFrame* prevStackFrame = mCallStack[callStackIdx + 1];
  8847. // Inlined methods have no stack frame
  8848. int stackSize = prevStackFrame->mRegisters.GetSP() - stackFrame->mRegisters.GetSP();
  8849. result += StrFormat("&$StackFrame\t%llu\t%llu\n", stackSize, stackFrame->mRegisters.GetSP());
  8850. }
  8851. return result;
  8852. }
  8853. String WinDebugger::GetAutoLocals(int stackFrameIdx, bool showRegs)
  8854. {
  8855. BP_ZONE("WinDebugger::GetAutoExpressions");
  8856. AutoCrit autoCrit(mDebugManager->mCritSect);
  8857. if (IsInRunState())
  8858. return "";
  8859. if (!IsPaused())
  8860. return "";
  8861. if (mCallStack.size() == 0)
  8862. UpdateCallStack();
  8863. String result;
  8864. Array<String> localList;
  8865. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  8866. UpdateCallStackMethod(actualStackFrameIdx);
  8867. if (actualStackFrameIdx >= mCallStack.size())
  8868. return "";
  8869. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  8870. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  8871. if (dwSubprogram == NULL)
  8872. return "";
  8873. auto langage = dwSubprogram->GetLanguage();
  8874. DbgLineData* dwLineData = FindLineDataInSubprogram(wdStackFrame->GetSourcePC(), dwSubprogram);
  8875. if (dwLineData == NULL)
  8876. return "";
  8877. dwSubprogram->PopulateSubprogram();
  8878. mDebugTarget->GetAutoLocalsInBlock(localList, dwSubprogram, &dwSubprogram->mBlock, wdStackFrame, dwLineData);
  8879. String lastLocal;
  8880. for (auto local : localList)
  8881. {
  8882. if (langage == DbgLanguage_C)
  8883. {
  8884. if ((local == "this") && (strncmp(dwSubprogram->mName, "<lambda_", 8) == 0))
  8885. {
  8886. // Use explicit "$this" so we can see the actual capture
  8887. result += "$this\n";
  8888. continue;
  8889. }
  8890. }
  8891. bool wasAlias = false;
  8892. for (int i = 0; i < (int)local.length() - 1; i++)
  8893. {
  8894. if ((local[i] == '$') && (local[i + 1] == 'a'))
  8895. {
  8896. // Alias
  8897. wasAlias = true;
  8898. String localName = local.Substring(0, i) + "\n";
  8899. if (localName != lastLocal)
  8900. {
  8901. result += localName;
  8902. lastLocal = localName;
  8903. }
  8904. break;
  8905. }
  8906. }
  8907. if (!wasAlias)
  8908. result += local + "\n";
  8909. }
  8910. if (showRegs)
  8911. {
  8912. result += "$FLAGS\n";
  8913. UpdateRegisterUsage(stackFrameIdx);
  8914. for (int regIdx = 0; regIdx < (int)wdStackFrame->mRegForms.size(); regIdx++)
  8915. {
  8916. if (wdStackFrame->mRegForms[regIdx] != RegForm_Invalid)
  8917. result += "$" + String(CPURegisters::GetRegisterName(regIdx)) + "\n";
  8918. }
  8919. }
  8920. return result;
  8921. }
  8922. String WinDebugger::CompactChildExpression(const StringImpl& expr, const StringImpl& parentExpr, int callStackIdx)
  8923. {
  8924. DbgCompileUnit* compileUnit = GetCallStackCompileUnit(callStackIdx);
  8925. DbgModule* dbgModule = GetCallStackDbgModule(callStackIdx);
  8926. if (dbgModule == NULL)
  8927. return "!failed";
  8928. DbgLanguage language = DbgLanguage_Unknown;
  8929. if (compileUnit != NULL)
  8930. language = compileUnit->mLanguage;
  8931. BfPassInstance bfPassInstance(mBfSystem);
  8932. BfParser parser(mBfSystem);
  8933. parser.mCompatMode = language != DbgLanguage_Beef;
  8934. auto terminatedExpr = expr + ";";
  8935. parser.SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  8936. parser.Parse(&bfPassInstance);
  8937. BfParser parentParser(mBfSystem);
  8938. auto terminatedParentExpr = parentExpr + ";";
  8939. parentParser.mCompatMode = language != DbgLanguage_Beef;
  8940. parentParser.SetSource(terminatedParentExpr.c_str(), terminatedParentExpr.length());
  8941. parentParser.Parse(&bfPassInstance);
  8942. BfReducer bfReducer;
  8943. bfReducer.mCompatMode = true;
  8944. bfReducer.mAlloc = parser.mAlloc;
  8945. bfReducer.mSystem = mBfSystem;
  8946. bfReducer.mPassInstance = &bfPassInstance;
  8947. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser.mRootNode);
  8948. bfReducer.mVisitorPos.MoveNext();
  8949. bfReducer.mSource = &parser;
  8950. auto exprNode = bfReducer.CreateExpression(parser.mRootNode->GetFirst());
  8951. bfReducer.mAlloc = parentParser.mAlloc;
  8952. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parentParser.mRootNode);
  8953. bfReducer.mVisitorPos.MoveNext();
  8954. auto parentExprNode = bfReducer.CreateExpression(parentParser.mRootNode->GetFirst());
  8955. parser.Close();
  8956. if ((exprNode == NULL) || (parentExprNode == NULL))
  8957. return "!failed";
  8958. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, callStackIdx, -1);
  8959. DwFormatInfo formatInfo;
  8960. formatInfo.mCallStackIdx = callStackIdx;
  8961. String formatFlags;
  8962. String assignExpr;
  8963. if ((exprNode != NULL) && (exprNode->GetSrcEnd() < (int) expr.length()))
  8964. {
  8965. formatFlags = Trim(expr.Substring(exprNode->GetSrcEnd()));
  8966. if (formatFlags.length() > 0)
  8967. {
  8968. String errorString = "Invalid expression";
  8969. if (!ParseFormatInfo(dbgModule, formatFlags, &formatInfo, &bfPassInstance, NULL, &assignExpr, &errorString))
  8970. {
  8971. bfPassInstance.FailAt(errorString, parser.mSourceData, exprNode->GetSrcEnd(), (int) expr.length() - exprNode->GetSrcEnd());
  8972. formatFlags = "";
  8973. }
  8974. }
  8975. }
  8976. dbgExprEvaluator.mExplicitThis = formatInfo.mExplicitThis;
  8977. dbgExprEvaluator.mExplicitThisExpr = parentExprNode;
  8978. DbgTypedValue exprResult = dbgExprEvaluator.Resolve(exprNode);
  8979. BfAstNode* headNode = dbgExprEvaluator.FinalizeExplicitThisReferences(exprNode);
  8980. BfPrinter printer(parser.mRootNode, NULL, NULL);
  8981. printer.mIgnoreTrivia = true;
  8982. printer.mReformatting = true;
  8983. printer.VisitChild(headNode);
  8984. auto result = printer.mOutString;
  8985. if (formatInfo.mNoVisualizers)
  8986. result += ", nv";
  8987. if (formatInfo.mNoMembers)
  8988. result += ", nm";
  8989. if (formatInfo.mNoEdit)
  8990. result += ", ne";
  8991. if (formatInfo.mIgnoreDerivedClassInfo)
  8992. result += ", nd";
  8993. if (formatInfo.mDisplayType == DwDisplayType_Ascii)
  8994. result += ", s";
  8995. if (formatInfo.mDisplayType == DwDisplayType_Utf8)
  8996. result += ", s8";
  8997. if (formatInfo.mDisplayType == DwDisplayType_Utf16)
  8998. result += ", s16";
  8999. if (formatInfo.mDisplayType == DwDisplayType_Utf32)
  9000. result += ", s32";
  9001. return result;
  9002. }
  9003. String WinDebugger::GetProcessInfo()
  9004. {
  9005. AutoCrit autoCrit(mDebugManager->mCritSect);
  9006. if ((mActiveThread == NULL) && (!mIsRunning))
  9007. return "";
  9008. SYSTEM_INFO sysinfo = { 0 };
  9009. GetSystemInfo(&sysinfo);
  9010. FILETIME creationTime = { 0 };
  9011. FILETIME exitTime = { 0 };
  9012. FILETIME kernelTime = { 0 };
  9013. FILETIME userTime = { 0 };
  9014. ::GetProcessTimes(mProcessInfo.hProcess, &creationTime, &exitTime, &kernelTime, &userTime);
  9015. String retStr;
  9016. PROCESS_MEMORY_COUNTERS memInfo = { 0 };
  9017. ::GetProcessMemoryInfo(mProcessInfo.hProcess, &memInfo, sizeof(PROCESS_MEMORY_COUNTERS));
  9018. FILETIME currentTime = { 0 };
  9019. ::GetSystemTimeAsFileTime(&currentTime);
  9020. retStr += StrFormat("VirtualMemory\t%d\n", memInfo.PagefileUsage);
  9021. retStr += StrFormat("WorkingMemory\t%d\n", memInfo.WorkingSetSize);
  9022. retStr += StrFormat("RunningTime\t%lld\n", *(int64*)&currentTime - *(int64*)&creationTime);
  9023. retStr += StrFormat("KernelTime\t%lld\n", *(int64*)&kernelTime / sysinfo.dwNumberOfProcessors);
  9024. retStr += StrFormat("UserTime\t%lld\n", *(int64*)&userTime / sysinfo.dwNumberOfProcessors);
  9025. return retStr;
  9026. }
  9027. String WinDebugger::GetThreadInfo()
  9028. {
  9029. AutoCrit autoCrit(mDebugManager->mCritSect);
  9030. String retStr;
  9031. if ((mActiveThread == NULL) && (!mIsRunning))
  9032. {
  9033. retStr = "";
  9034. }
  9035. else
  9036. {
  9037. if (mActiveThread != NULL)
  9038. retStr = StrFormat("%d", mActiveThread->mThreadId);
  9039. for (auto threadInfo : mThreadList)
  9040. {
  9041. SetAndRestoreValue<WdThreadInfo*> prevThread(mActiveThread, threadInfo);
  9042. retStr += "\n";
  9043. for (int pass = 0; pass < 2; pass++)
  9044. {
  9045. CPURegisters registers;
  9046. PopulateRegisters(&registers);
  9047. String locString = EncodeDataPtr((addr_target)registers.GetPC(), true);
  9048. TryGetThreadName(threadInfo);
  9049. bool hadThreadName = true;
  9050. String threadName = threadInfo->mName;
  9051. if (threadName.IsEmpty())
  9052. {
  9053. hadThreadName = false;
  9054. if (threadInfo->mThreadId == mProcessInfo.dwThreadId)
  9055. threadName = "Main Thread";
  9056. else
  9057. threadName = "Worker Thread";
  9058. }
  9059. bool isInvalid = false;
  9060. addr_target appendAddr = 0;
  9061. for (int stackIdx = 0; true; stackIdx++)
  9062. {
  9063. auto subProgram = mDebugTarget->FindSubProgram(registers.GetPC(), DbgOnDemandKind_LocalOnly);
  9064. if (subProgram != NULL)
  9065. {
  9066. if (subProgram->mLineInfo != NULL)
  9067. {
  9068. DbgModule* module = subProgram->mCompileUnit->mDbgModule;
  9069. DbgModule* linkedModule = module->GetLinkedModule();
  9070. if (linkedModule->mDisplayName.length() > 0)
  9071. {
  9072. locString = linkedModule->mDisplayName + "!" + subProgram->ToString();
  9073. if (!hadThreadName)
  9074. threadName = module->mDisplayName + " thread";
  9075. }
  9076. else
  9077. {
  9078. locString = subProgram->ToString();
  9079. }
  9080. appendAddr = 0;
  9081. break;
  9082. }
  9083. }
  9084. DbgModule* module = mDebugTarget->FindDbgModuleForAddress(registers.GetPC());
  9085. if (module == NULL)
  9086. {
  9087. isInvalid = true;
  9088. break;
  9089. }
  9090. DbgModule* linkedModule = module->GetLinkedModule();
  9091. appendAddr = (addr_target)registers.GetPC();
  9092. locString = linkedModule->mDisplayName + "!" + EncodeDataPtr((addr_target)registers.GetPC(), true);
  9093. if (!hadThreadName)
  9094. threadName = linkedModule->mDisplayName + " thread";
  9095. if ((mActiveThread == mExplicitStopThread) && (mActiveBreakpoint != NULL))
  9096. {
  9097. if ((subProgram == NULL) ||
  9098. (mActiveBreakpoint->mAddr < subProgram->mBlock.mLowPC) ||
  9099. (mActiveBreakpoint->mAddr >= subProgram->mBlock.mHighPC))
  9100. break;
  9101. }
  9102. if (pass == 1) // Just take the first item
  9103. break;
  9104. if (stackIdx == 128)
  9105. break; // Too many!
  9106. addr_target returnAddr;
  9107. if (!mDebugTarget->RollBackStackFrame(&registers, &returnAddr, true))
  9108. {
  9109. isInvalid = true;
  9110. break;
  9111. }
  9112. }
  9113. if ((isInvalid) && (pass == 0))
  9114. continue;
  9115. if (appendAddr != 0)
  9116. {
  9117. String symbolName;
  9118. addr_target offset;
  9119. DbgModule* dwarf;
  9120. if (mDebugTarget->FindSymbolAt(appendAddr, &symbolName, &offset, &dwarf))
  9121. {
  9122. DbgModule* linkedModule = dwarf->GetLinkedModule();
  9123. String demangledName = BfDemangler::Demangle(symbolName, DbgLanguage_Unknown);
  9124. if (!linkedModule->mDisplayName.empty())
  9125. {
  9126. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  9127. }
  9128. locString = demangledName + StrFormat("+0x%X", offset);
  9129. }
  9130. }
  9131. retStr += StrFormat("%d\t%s\t%s", threadInfo->mThreadId, threadName.c_str(), locString.c_str());
  9132. String attrs;
  9133. if (threadInfo->mFrozen)
  9134. {
  9135. attrs += "Fr";
  9136. }
  9137. if (!attrs.IsEmpty())
  9138. {
  9139. retStr += "\t";
  9140. retStr += attrs;
  9141. }
  9142. break;
  9143. }
  9144. }
  9145. }
  9146. return retStr;
  9147. }
  9148. void WinDebugger::SetActiveThread(int threadId)
  9149. {
  9150. AutoCrit autoCrit(mDebugManager->mCritSect);
  9151. if (mThreadMap.TryGetValue(threadId, &mActiveThread))
  9152. {
  9153. BfLogDbg("SetActiveThread %d\n", threadId);
  9154. ClearCallStack();
  9155. }
  9156. else
  9157. {
  9158. BfLogDbg("SetActiveThread %d FAILED\n", threadId);
  9159. }
  9160. }
  9161. int WinDebugger::GetActiveThread()
  9162. {
  9163. AutoCrit autoCrit(mDebugManager->mCritSect);
  9164. if (mActiveThread == NULL)
  9165. return -1;
  9166. return mActiveThread->mThreadId;
  9167. }
  9168. void WinDebugger::FreezeThread(int threadId)
  9169. {
  9170. AutoCrit autoCrit(mDebugManager->mCritSect);
  9171. BF_ASSERT(!IsInRunState());
  9172. auto thread = mThreadMap[threadId];
  9173. if (!thread->mFrozen)
  9174. {
  9175. thread->mFrozen = true;
  9176. ::SuspendThread(thread->mHThread);
  9177. BfLogDbg("SuspendThread %d from FreezeThread\n", thread->mThreadId);
  9178. }
  9179. }
  9180. void WinDebugger::ThawThread(int threadId)
  9181. {
  9182. AutoCrit autoCrit(mDebugManager->mCritSect);
  9183. BF_ASSERT(!IsInRunState());
  9184. auto thread = mThreadMap[threadId];
  9185. if (thread->mFrozen)
  9186. {
  9187. thread->mFrozen = false;
  9188. ::ResumeThread(thread->mHThread);
  9189. BfLogDbg("ResumeThread %d from ThawThread\n", thread->mThreadId);
  9190. }
  9191. }
  9192. bool WinDebugger::IsActiveThreadWaiting()
  9193. {
  9194. AutoCrit autoCrit(mDebugManager->mCritSect);
  9195. return mActiveThread == mDebuggerWaitingThread;
  9196. }
  9197. void WinDebugger::ClearCallStack()
  9198. {
  9199. AutoCrit autoCrit(mDebugManager->mCritSect);
  9200. BfLogDbg("ClearCallstack\n");
  9201. BF_ASSERT(mRunState != RunState_DebugEval);
  9202. for (auto wdStackFrame : mCallStack)
  9203. delete wdStackFrame;
  9204. mCallStack.Clear();
  9205. mIsPartialCallStack = true;
  9206. }
  9207. void WinDebugger::UpdateCallStack(bool slowEarlyOut)
  9208. {
  9209. AutoCrit autoCrit(mDebugManager->mCritSect);
  9210. if (!mIsPartialCallStack)
  9211. return;
  9212. BF_ASSERT(!IsInRunState());
  9213. uint32 tickStart = BFTickCount();
  9214. CPURegisters registers;
  9215. if (mCallStack.size() > 0)
  9216. {
  9217. WdStackFrame* wdStackFrame = mCallStack.back();
  9218. if (wdStackFrame->mIsEnd)
  9219. {
  9220. return;
  9221. }
  9222. memcpy(&registers, &wdStackFrame->mRegisters, sizeof(registers));
  9223. bool regsRolledBack = RollBackStackFrame(&registers, mCallStack.size() == 1);
  9224. // If we can't roll them back then mIsEnd should have been set for the previous frame
  9225. BF_ASSERT(regsRolledBack);
  9226. }
  9227. else
  9228. {
  9229. BF_ASSERT(mIsPartialCallStack);
  9230. mCallStack.Reserve(1024);
  9231. PopulateRegisters(&registers);
  9232. BfLogDbg("UpdateCallStack starting. Thread=%d PC=0x%p\n", mActiveThread->mThreadId, registers.GetPC());
  9233. }
  9234. bool isPartial = false;
  9235. // Incrementally fill callstack structure to avoid stepping slowdown during deep nesting
  9236. for (int fillIdx = 0; fillIdx < (slowEarlyOut ? 10000 : 100000); fillIdx++)
  9237. {
  9238. WdStackFrame* wdStackFrame = new WdStackFrame();
  9239. memcpy(&wdStackFrame->mRegisters, &registers, sizeof(registers));
  9240. wdStackFrame->mIsStart = mCallStack.size() == 0;
  9241. wdStackFrame->mIsEnd = false;
  9242. bool rollbackSuccess = false;
  9243. for (int tryCount = 0; tryCount < 16; tryCount++)
  9244. {
  9245. if (!RollBackStackFrame(&registers, wdStackFrame->mIsStart))
  9246. {
  9247. break;
  9248. }
  9249. if (registers.GetPC() > 0xFFFF)
  9250. {
  9251. rollbackSuccess = true;
  9252. break;
  9253. }
  9254. if (mCallStack.size() > 0)
  9255. break; // Only retry for the first frame
  9256. }
  9257. if (!rollbackSuccess)
  9258. wdStackFrame->mIsEnd = true;
  9259. if (registers.GetSP() <= wdStackFrame->mRegisters.GetSP())
  9260. {
  9261. // SP went the wrong direction, stop rolling back
  9262. wdStackFrame->mIsEnd = true;
  9263. }
  9264. mCallStack.push_back(wdStackFrame);
  9265. if (IsMiniDumpDebugger())
  9266. {
  9267. // Make sure to queue up any debug stuff we need
  9268. UpdateCallStackMethod((int)mCallStack.size() - 1);
  9269. }
  9270. if (wdStackFrame->mIsEnd)
  9271. break;
  9272. // Time-limit callstack generation. Most useful for debug mode.
  9273. if ((slowEarlyOut) && ((fillIdx % 100) == 0))
  9274. {
  9275. uint32 tickEnd = BFTickCount();
  9276. if (tickEnd - tickStart >= 10)
  9277. {
  9278. isPartial = true;
  9279. break;
  9280. }
  9281. }
  9282. }
  9283. if (!isPartial)
  9284. mIsPartialCallStack = false;
  9285. }
  9286. int WinDebugger::GetCallStackCount()
  9287. {
  9288. AutoCrit autoCrit(mDebugManager->mCritSect);
  9289. return (int)mCallStack.size();
  9290. }
  9291. int WinDebugger::GetRequestedStackFrameIdx()
  9292. {
  9293. AutoCrit autoCrit(mDebugManager->mCritSect);
  9294. if ((mActiveThread == mExplicitStopThread) && (mRequestedStackFrameIdx >= -1))
  9295. {
  9296. if (mActiveBreakpoint != NULL)
  9297. mRequestedStackFrameIdx = GetBreakStackFrameIdx();
  9298. if (mRequestedStackFrameIdx == -1)
  9299. mRequestedStackFrameIdx = 0;
  9300. return mRequestedStackFrameIdx;
  9301. }
  9302. int newCallStackIdx = 0;
  9303. while (true)
  9304. {
  9305. if (newCallStackIdx >= (int)mCallStack.size() - 1)
  9306. UpdateCallStack();
  9307. if (newCallStackIdx >= (int)mCallStack.size() - 1)
  9308. break;
  9309. intptr addr;
  9310. String file;
  9311. int hotIdx;
  9312. int defLineStart;
  9313. int defLineEnd;
  9314. int line;
  9315. int column;
  9316. int language;
  9317. int stackSize;
  9318. int8 flags;
  9319. GetStackFrameInfo(newCallStackIdx, &addr, &file, &hotIdx, &defLineStart, &defLineEnd, &line, &column, &language, &stackSize, &flags);
  9320. if (!file.empty())
  9321. return newCallStackIdx;
  9322. newCallStackIdx++;
  9323. }
  9324. return 0;
  9325. }
  9326. int WinDebugger::GetBreakStackFrameIdx()
  9327. {
  9328. AutoCrit autoCrit(mDebugManager->mCritSect);
  9329. if ((mActiveBreakpoint == NULL) || (mRunState != RunState_Breakpoint))
  9330. return -1;
  9331. if ((mBreakStackFrameIdx != -1) || (mActiveThread != mExplicitStopThread))
  9332. return mBreakStackFrameIdx;
  9333. mBreakStackFrameIdx = 0;
  9334. BF_ASSERT(mActiveBreakpoint != NULL);
  9335. if (mCallStack.IsEmpty())
  9336. UpdateCallStack();
  9337. if (!mCallStack.IsEmpty())
  9338. {
  9339. UpdateCallStackMethod(0);
  9340. for (int stackIdx = 0; stackIdx < (int)mCallStack.size(); stackIdx++)
  9341. {
  9342. auto callStackEntry = mCallStack[stackIdx];
  9343. if (callStackEntry->mSubProgram == NULL)
  9344. break;
  9345. if ((mActiveBreakpoint->mAddr < callStackEntry->mSubProgram->mBlock.mLowPC) ||
  9346. (mActiveBreakpoint->mAddr >= callStackEntry->mSubProgram->mBlock.mHighPC))
  9347. break;
  9348. DbgSubprogram* specificSubprogram = callStackEntry->mSubProgram;
  9349. auto dwLineData = callStackEntry->mSubProgram->FindClosestLine(mActiveBreakpoint->mAddr, &specificSubprogram);
  9350. if (dwLineData == NULL)
  9351. break;
  9352. if (mActiveBreakpoint->mLineData == dwLineData)
  9353. {
  9354. mBreakStackFrameIdx = stackIdx;
  9355. break;
  9356. }
  9357. }
  9358. }
  9359. return mBreakStackFrameIdx;
  9360. }
  9361. static const char* SafeString(const char* str)
  9362. {
  9363. if (str == NULL)
  9364. return "???";
  9365. return str;
  9366. }
  9367. void WinDebugger::UpdateRegisterUsage(int stackFrameIdx)
  9368. {
  9369. WdStackFrame* wdStackFrame = mCallStack[stackFrameIdx];
  9370. if (wdStackFrame->mRegForms.size() != 0)
  9371. return;
  9372. auto dwSubprogram = wdStackFrame->mSubProgram;
  9373. if (dwSubprogram == NULL)
  9374. return;
  9375. addr_target addr = dwSubprogram->mBlock.mLowPC;
  9376. const uint8* baseOp = nullptr;
  9377. while (addr < dwSubprogram->mBlock.mHighPC)
  9378. {
  9379. CPUInst inst;
  9380. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  9381. break;
  9382. bool overrideForm = inst.mAddress <= (addr_target)wdStackFrame->mRegisters.GetPC();
  9383. inst.MarkRegsUsed(wdStackFrame->mRegForms, overrideForm);
  9384. addr += inst.GetLength();
  9385. }
  9386. }
  9387. // It's safe to pass an invalid idx in here
  9388. void WinDebugger::UpdateCallStackMethod(int stackFrameIdx)
  9389. {
  9390. if (mCallStack.empty())
  9391. return;
  9392. int startIdx = std::min(stackFrameIdx, (int)mCallStack.size() - 1);
  9393. while (startIdx >= 0)
  9394. {
  9395. WdStackFrame* wdStackFrame = mCallStack[startIdx];
  9396. if (wdStackFrame->mHasGottenSubProgram)
  9397. break;
  9398. startIdx--;
  9399. }
  9400. startIdx++;
  9401. for (int checkFrameIdx = startIdx; checkFrameIdx <= stackFrameIdx; checkFrameIdx++)
  9402. {
  9403. //BF_ASSERT(checkFrameIdx < mCallStack.size());
  9404. if (checkFrameIdx >= mCallStack.size())
  9405. break;
  9406. WdStackFrame* wdStackFrame = mCallStack[checkFrameIdx];
  9407. wdStackFrame->mHasGottenSubProgram = true;
  9408. addr_target pcAddress = (addr_target)wdStackFrame->GetSourcePC();
  9409. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress, DbgOnDemandKind_LocalOnly);
  9410. wdStackFrame->mHasGottenSubProgram = true;
  9411. wdStackFrame->mSubProgram = dwSubprogram;
  9412. if ((dwSubprogram == NULL) && (IsMiniDumpDebugger()))
  9413. {
  9414. // FindSymbolAt will queue up debug info if necessary...
  9415. String symbolName;
  9416. addr_target offset;
  9417. DbgModule* dbgModule;
  9418. mDebugTarget->FindSymbolAt(pcAddress, &symbolName, &offset, &dbgModule);
  9419. }
  9420. // Insert inlines
  9421. int insertIdx = checkFrameIdx + 1;
  9422. while ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL))
  9423. {
  9424. WdStackFrame* inlineStackFrame = new WdStackFrame();
  9425. *inlineStackFrame = *wdStackFrame;
  9426. inlineStackFrame->mInInlineMethod = true;
  9427. wdStackFrame->mInInlineCall = true;
  9428. inlineStackFrame->mSubProgram = dwSubprogram->mInlineeInfo->mInlineParent;
  9429. mCallStack.Insert(insertIdx, inlineStackFrame);
  9430. dwSubprogram = dwSubprogram->mInlineeInfo->mInlineParent;
  9431. insertIdx++;
  9432. checkFrameIdx++;
  9433. }
  9434. }
  9435. }
  9436. void WinDebugger::GetCodeAddrInfo(intptr addr, String* outFile, int* outHotIdx, int* outDefLineStart, int* outDefLineEnd, int* outLine, int* outColumn)
  9437. {
  9438. AutoCrit autoCrit(mDebugManager->mCritSect);
  9439. DbgSubprogram* subProgram = NULL;
  9440. DbgLineData* callingLineData = FindLineDataAtAddress((addr_target)addr, &subProgram);
  9441. if (subProgram != NULL)
  9442. {
  9443. *outHotIdx = subProgram->mCompileUnit->mDbgModule->mHotIdx;
  9444. *outFile = subProgram->GetLineSrcFile(*callingLineData)->GetLocalPath();
  9445. *outLine = callingLineData->mLine;
  9446. *outColumn = callingLineData->mColumn;
  9447. FixupLineDataForSubprogram(subProgram);
  9448. DbgLineData* dwStartLineData = NULL;
  9449. DbgLineData* dwEndLineData = NULL;
  9450. if (subProgram->mLineInfo != NULL)
  9451. {
  9452. if (subProgram->mLineInfo->mLines.size() > 0)
  9453. {
  9454. dwStartLineData = &subProgram->mLineInfo->mLines[0];
  9455. dwEndLineData = &subProgram->mLineInfo->mLines.back();
  9456. }
  9457. }
  9458. else
  9459. {
  9460. if (subProgram->mInlineeInfo != NULL)
  9461. {
  9462. dwStartLineData = &subProgram->mInlineeInfo->mFirstLineData;
  9463. dwEndLineData = &subProgram->mInlineeInfo->mLastLineData;
  9464. }
  9465. }
  9466. if (dwEndLineData != NULL)
  9467. {
  9468. *outDefLineStart = dwStartLineData->mLine;
  9469. *outDefLineEnd = dwEndLineData->mLine;
  9470. }
  9471. }
  9472. }
  9473. void WinDebugger::GetStackAllocInfo(intptr addr, int* outThreadId, int* outStackIdx)
  9474. {
  9475. AutoCrit autoCrit(mDebugManager->mCritSect);
  9476. *outThreadId = 0;
  9477. if (outStackIdx != NULL)
  9478. *outStackIdx = -1;
  9479. if (!IsPaused())
  9480. return;
  9481. for (auto thread : mThreadList)
  9482. {
  9483. NT_TIB64 tib = { 0 };
  9484. if (!ReadMemory((intptr)thread->mThreadLocalBase, sizeof(tib), &tib))
  9485. continue;
  9486. MEMORY_BASIC_INFORMATION stackInfo = { 0 };
  9487. if (VirtualQueryEx(mProcessInfo.hProcess, (void*)(tib.StackBase - 1), &stackInfo, sizeof(MEMORY_BASIC_INFORMATION)) == 0)
  9488. continue;
  9489. if ((addr >= (intptr)stackInfo.AllocationBase) && (addr < (intptr)tib.StackBase))
  9490. {
  9491. *outThreadId = thread->mThreadId;
  9492. if (outStackIdx == NULL)
  9493. return;
  9494. if (mActiveThread == thread)
  9495. {
  9496. UpdateCallStack(false);
  9497. for (int callStackIdx = 0; callStackIdx < (int)mCallStack.size(); callStackIdx++)
  9498. {
  9499. UpdateCallStackMethod(callStackIdx);
  9500. auto stackFrame = mCallStack[callStackIdx];
  9501. if (addr >= (intptr)stackFrame->mRegisters.GetSP())
  9502. {
  9503. *outStackIdx = callStackIdx;
  9504. }
  9505. }
  9506. }
  9507. return;
  9508. }
  9509. }
  9510. }
  9511. String WinDebugger::GetStackFrameInfo(int stackFrameIdx, intptr* addr, String* outFile, int* outHotIdx, int* outDefLineStart, int* outDefLineEnd,
  9512. int* outLine, int* outColumn, int* outLanguage, int* outStackSize, int8* outFlags)
  9513. {
  9514. enum FrameFlags
  9515. {
  9516. FrameFlags_Optimized = 1,
  9517. FrameFlags_HasPendingDebugInfo = 2,
  9518. FrameFlags_CanGetOldSource = 4,
  9519. FrameFlags_WasHotReplaced = 8,
  9520. };
  9521. AutoCrit autoCrit(mDebugManager->mCritSect);
  9522. if (mCallStack.size() == 0)
  9523. UpdateCallStack();
  9524. *addr = 0;
  9525. *outFile = "";
  9526. *outHotIdx = 0;
  9527. *outDefLineStart = -1;
  9528. *outDefLineEnd = -1;
  9529. *outLine = -1;
  9530. *outColumn = 0;
  9531. *outLanguage = 0;
  9532. *outStackSize = 0;
  9533. *outFlags = 0;
  9534. UpdateCallStackMethod(stackFrameIdx);
  9535. if (stackFrameIdx >= mCallStack.size())
  9536. {
  9537. return "";
  9538. }
  9539. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9540. UpdateCallStackMethod(actualStackFrameIdx);
  9541. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9542. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  9543. if (stackFrameIdx == -1)
  9544. pcAddress = mShowPCOverride;
  9545. *addr = pcAddress;
  9546. if (actualStackFrameIdx < (int)mCallStack.size() - 2)
  9547. {
  9548. WdStackFrame* prevStackFrame = mCallStack[actualStackFrameIdx + 1];
  9549. // Inlined methods have no stack frame
  9550. *outStackSize = prevStackFrame->mRegisters.GetSP() - wdStackFrame->mRegisters.GetSP();
  9551. }
  9552. const auto& _CheckHashSrcFile = [&](String& outStr, DbgModule* dbgModule, DbgSrcFile* srcFile)
  9553. {
  9554. if (srcFile->mHashKind != DbgHashKind_None)
  9555. {
  9556. outStr += "#";
  9557. srcFile->GetHash(outStr);
  9558. }
  9559. };
  9560. auto _SetFlags = [&](DbgSubprogram* dwSubprogram)
  9561. {
  9562. DbgModule* dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  9563. if (dwSubprogram->mIsOptimized)
  9564. *outFlags |= FrameFlags_Optimized;
  9565. if (dbgModule->HasPendingDebugInfo())
  9566. *outFlags |= FrameFlags_HasPendingDebugInfo;
  9567. if (dbgModule->CanGetOldSource())
  9568. *outFlags |= FrameFlags_CanGetOldSource;
  9569. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) || (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid))
  9570. *outFlags |= FrameFlags_WasHotReplaced;
  9571. };
  9572. if (wdStackFrame->mInInlineMethod)
  9573. {
  9574. WdStackFrame* nextStackFrame = mCallStack[actualStackFrameIdx - 1];
  9575. auto subProgram = nextStackFrame->mSubProgram;
  9576. _SetFlags(subProgram);
  9577. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  9578. DbgSubprogram* parentSubprogram = subProgram->mInlineeInfo->mInlineParent; // Require it be in the inline parent
  9579. auto foundLine = parentSubprogram->FindClosestLine(subProgram->mBlock.mLowPC, &parentSubprogram);
  9580. if (foundLine != NULL)
  9581. {
  9582. auto srcFile = parentSubprogram->GetLineSrcFile(*foundLine);
  9583. *outFile = srcFile->GetLocalPath();
  9584. _CheckHashSrcFile(*outFile, subProgram->mCompileUnit->mDbgModule, srcFile);
  9585. *outLine = foundLine->mLine;
  9586. }
  9587. *outLanguage = subProgram->GetLanguage();
  9588. *outHotIdx = subProgram->mCompileUnit->mDbgModule->mHotIdx;
  9589. *outColumn = -1;
  9590. DbgSubprogram* callingSubProgram = NULL;
  9591. DbgLineData* callingLineData = FindLineDataAtAddress(nextStackFrame->mSubProgram->mBlock.mLowPC - 1, &callingSubProgram);
  9592. if ((callingLineData != NULL) && (callingSubProgram == wdStackFrame->mSubProgram))
  9593. {
  9594. auto callingSrcFile = callingSubProgram->GetLineSrcFile(*callingLineData);
  9595. *outLanguage = callingSubProgram->mCompileUnit->mLanguage;
  9596. auto srcFile = callingSrcFile;
  9597. *outFile = srcFile->GetLocalPath();
  9598. _CheckHashSrcFile(*outFile, subProgram->mCompileUnit->mDbgModule, srcFile);
  9599. if (*outLine == callingLineData->mLine)
  9600. *outColumn = callingLineData->mColumn;
  9601. }
  9602. String name = wdStackFrame->mSubProgram->ToString();
  9603. DbgModule* dbgModule = wdStackFrame->mSubProgram->mCompileUnit->mDbgModule;
  9604. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  9605. if (!linkedModule->mDisplayName.empty())
  9606. name = linkedModule->mDisplayName + "!" + name;
  9607. return name;
  9608. }
  9609. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  9610. if (dwSubprogram != NULL)
  9611. {
  9612. String demangledName;
  9613. if ((dwSubprogram->mName != NULL) && (strncmp(dwSubprogram->mName, ":Sep@", 5) == 0))
  9614. {
  9615. char* p;
  9616. auto addr = strtoll(dwSubprogram->mName + 5, &p, 16);
  9617. if (addr != 0)
  9618. {
  9619. auto parentSubprogram = mDebugTarget->FindSubProgram(addr);
  9620. if (parentSubprogram != NULL)
  9621. demangledName = parentSubprogram->ToString();
  9622. }
  9623. }
  9624. if (demangledName.IsEmpty())
  9625. {
  9626. dwSubprogram->ToString(demangledName, true);
  9627. }
  9628. DbgSrcFile* dwSrcFile = NULL;
  9629. DbgLineData* dwLineData = NULL;
  9630. FixupLineDataForSubprogram(dwSubprogram);
  9631. addr_target findAddress = wdStackFrame->GetSourcePC();
  9632. DbgSubprogram* specificSubprogram = dwSubprogram;
  9633. dwLineData = dwSubprogram->FindClosestLine(findAddress, &specificSubprogram);
  9634. if (dwLineData != NULL)
  9635. dwSrcFile = dwSubprogram->GetLineSrcFile(*dwLineData);
  9636. DbgLineData* dwStartLineData = NULL;
  9637. DbgLineData* dwEndLineData = NULL;
  9638. if (dwSubprogram->mLineInfo != NULL)
  9639. {
  9640. if (dwSubprogram->mLineInfo->mLines.size() > 0)
  9641. {
  9642. dwStartLineData = &dwSubprogram->mLineInfo->mLines[0];
  9643. dwEndLineData = &dwSubprogram->mLineInfo->mLines.back();
  9644. }
  9645. }
  9646. else
  9647. {
  9648. if (dwSubprogram->mInlineeInfo != NULL)
  9649. {
  9650. dwStartLineData = &dwSubprogram->mInlineeInfo->mFirstLineData;
  9651. dwEndLineData = &dwSubprogram->mInlineeInfo->mLastLineData;
  9652. }
  9653. }
  9654. DbgModule* dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  9655. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  9656. if (!linkedModule->mDisplayName.empty())
  9657. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  9658. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) || (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid))
  9659. demangledName = "#" + demangledName;
  9660. _SetFlags(dwSubprogram);
  9661. if ((dwLineData != NULL) && (dwSrcFile != NULL))
  9662. {
  9663. *outFile = dwSrcFile->GetLocalPath();
  9664. _CheckHashSrcFile(*outFile, dbgModule, dwSrcFile);
  9665. *outHotIdx = dbgModule->mHotIdx;
  9666. *outLine = dwLineData->mLine;
  9667. *outColumn = dwLineData->mColumn;
  9668. *outLanguage = (int)dwSubprogram->mCompileUnit->mLanguage;
  9669. if (dwEndLineData != NULL)
  9670. {
  9671. *outDefLineStart = dwStartLineData->mLine;
  9672. *outDefLineEnd = dwEndLineData->mLine;
  9673. }
  9674. return demangledName;
  9675. }
  9676. else
  9677. {
  9678. return demangledName + StrFormat("+0x%X", pcAddress - dwSubprogram->mBlock.mLowPC);
  9679. }
  9680. }
  9681. else
  9682. {
  9683. String symbolName;
  9684. addr_target offset;
  9685. DbgModule* dbgModule;
  9686. if (mDebugTarget->FindSymbolAt(pcAddress, &symbolName, &offset, &dbgModule))
  9687. {
  9688. if (dbgModule->HasPendingDebugInfo())
  9689. {
  9690. *outFlags |= FrameFlags_HasPendingDebugInfo;
  9691. if (mPendingDebugInfoLoad.ContainsKey(dbgModule))
  9692. {
  9693. String outName = EncodeDataPtr(pcAddress, true);
  9694. if ((dbgModule != NULL) && (!dbgModule->mDisplayName.empty()))
  9695. outName = dbgModule->mDisplayName + "!<Loading...>" + outName;
  9696. return outName;
  9697. }
  9698. }
  9699. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  9700. String demangledName = BfDemangler::Demangle(symbolName, DbgLanguage_Unknown);
  9701. if (!linkedModule->mDisplayName.empty())
  9702. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  9703. return demangledName + StrFormat("+0x%X", offset);
  9704. }
  9705. }
  9706. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress(pcAddress);
  9707. DbgModule* linkedModule = NULL;
  9708. if (dbgModule != NULL)
  9709. {
  9710. linkedModule = dbgModule->GetLinkedModule();
  9711. if (dbgModule->HasPendingDebugInfo())
  9712. *outFlags |= FrameFlags_HasPendingDebugInfo;
  9713. }
  9714. String outName = EncodeDataPtr(pcAddress, true);
  9715. if ((linkedModule != NULL) && (!linkedModule->mDisplayName.empty()))
  9716. outName = linkedModule->mDisplayName + "!" + outName;
  9717. return outName;
  9718. }
  9719. String WinDebugger::Callstack_GetStackFrameOldFileInfo(int stackFrameIdx)
  9720. {
  9721. AutoCrit autoCrit(mDebugManager->mCritSect);
  9722. if (!FixCallStackIdx(stackFrameIdx))
  9723. return "";
  9724. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9725. UpdateCallStackMethod(actualStackFrameIdx);
  9726. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9727. DbgModule* dbgModule = NULL;
  9728. DbgSrcFile* dbgSrcFile = NULL;
  9729. if (wdStackFrame->mInInlineMethod)
  9730. {
  9731. WdStackFrame* nextStackFrame = mCallStack[actualStackFrameIdx - 1];
  9732. auto subProgram = nextStackFrame->mSubProgram;
  9733. dbgModule = subProgram->mCompileUnit->mDbgModule;
  9734. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  9735. DbgSubprogram* parentSubprogram = subProgram->mInlineeInfo->mInlineParent; // Require it be in the inline parent
  9736. auto foundLine = parentSubprogram->FindClosestLine(subProgram->mBlock.mLowPC, &parentSubprogram);
  9737. if (foundLine != NULL)
  9738. dbgSrcFile = parentSubprogram->GetLineSrcFile(*foundLine);
  9739. DbgSubprogram* callingSubProgram = NULL;
  9740. DbgLineData* callingLineData = FindLineDataAtAddress(nextStackFrame->mSubProgram->mBlock.mLowPC - 1, &callingSubProgram);
  9741. if ((callingLineData != NULL) && (callingSubProgram == wdStackFrame->mSubProgram))
  9742. dbgSrcFile = callingSubProgram->GetLineSrcFile(*callingLineData);
  9743. }
  9744. else
  9745. {
  9746. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  9747. if (dwSubprogram != NULL)
  9748. {
  9749. FixupLineDataForSubprogram(dwSubprogram);
  9750. addr_target findAddress = wdStackFrame->GetSourcePC();
  9751. DbgSubprogram* dbgSubprogram = NULL;
  9752. DbgLineData* dwLineData = dwSubprogram->FindClosestLine(findAddress, &dbgSubprogram, &dbgSrcFile);
  9753. dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  9754. }
  9755. }
  9756. if (dbgSrcFile != NULL)
  9757. {
  9758. // Note: we must use mFilePath here, make sure we don't use GetLocalPath()
  9759. return dbgModule->GetOldSourceCommand(dbgSrcFile->mFilePath);
  9760. }
  9761. return "";
  9762. }
  9763. int WinDebugger::GetJmpState(int stackFrameIdx)
  9764. {
  9765. AutoCrit autoCrit(mDebugManager->mCritSect);
  9766. if (!FixCallStackIdx(stackFrameIdx))
  9767. return -1;
  9768. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9769. UpdateCallStackMethod(actualStackFrameIdx);
  9770. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9771. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  9772. CPUInst inst;
  9773. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  9774. return -1;
  9775. return inst.GetJmpState(wdStackFrame->mRegisters.mIntRegs.efl);
  9776. }
  9777. intptr WinDebugger::GetStackFrameCalleeAddr(int stackFrameIdx)
  9778. {
  9779. AutoCrit autoCrit(mDebugManager->mCritSect);
  9780. if (!FixCallStackIdx(stackFrameIdx))
  9781. return -1;
  9782. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9783. UpdateCallStackMethod(actualStackFrameIdx);
  9784. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9785. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  9786. if (stackFrameIdx == -1)
  9787. pcAddress = mShowPCOverride;
  9788. if (wdStackFrame->mInInlineMethod)
  9789. {
  9790. WdStackFrame* inlineStackFrame = mCallStack[actualStackFrameIdx - 1];
  9791. return inlineStackFrame->mSubProgram->mBlock.mLowPC - 1;
  9792. }
  9793. return pcAddress - 1;
  9794. }
  9795. String WinDebugger::GetStackMethodOwner(int stackFrameIdx, int& language)
  9796. {
  9797. AutoCrit autoCrit(mDebugManager->mCritSect);
  9798. if (!FixCallStackIdx(stackFrameIdx))
  9799. return "";
  9800. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9801. if (actualStackFrameIdx >= (int)mCallStack.size())
  9802. actualStackFrameIdx = 0;
  9803. UpdateCallStackMethod(actualStackFrameIdx);
  9804. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9805. if (wdStackFrame->mSubProgram == NULL)
  9806. return "";
  9807. auto parentType = wdStackFrame->mSubProgram->GetParent();
  9808. if (parentType == NULL)
  9809. return "";
  9810. parentType = parentType->GetPrimaryType();
  9811. language = (int)parentType->GetLanguage();
  9812. return parentType->ToString();
  9813. }
  9814. String WinDebugger::FindCodeAddresses(const StringImpl& fileName, int line, int column, bool allowAutoResolve)
  9815. {
  9816. String result;
  9817. if (mDebugTarget == NULL)
  9818. return "";
  9819. DbgSrcFile* srcFile = mDebugTarget->GetSrcFile(fileName);
  9820. if (srcFile == NULL)
  9821. return result;
  9822. bool foundInSequence = false;
  9823. WdBreakpoint* prevBreakpoint = NULL;
  9824. int bestLineOffset = 0x7FFFFFFF;
  9825. for (auto dbgSubprogram : srcFile->mLineDataRefs)
  9826. {
  9827. for (auto& lineData : dbgSubprogram->mLineInfo->mLines)
  9828. {
  9829. auto lineSrcFile = dbgSubprogram->GetLineSrcFile(lineData);
  9830. if (lineSrcFile != srcFile)
  9831. continue;
  9832. int lineOffset = lineData.mLine - line;
  9833. if ((lineOffset >= 0) && (lineOffset <= 12) && (lineOffset <= bestLineOffset))
  9834. {
  9835. if (lineOffset < bestLineOffset)
  9836. {
  9837. bestLineOffset = lineOffset;
  9838. result = "";
  9839. }
  9840. if (!foundInSequence)
  9841. {
  9842. auto addr = dbgSubprogram->GetLineAddr(lineData);
  9843. result += EncodeDataPtr(addr, false) + "\t" + dbgSubprogram->ToString() + "\n";
  9844. }
  9845. }
  9846. // New sequence?
  9847. if (!lineData.IsStackFrameSetup())
  9848. foundInSequence = false;
  9849. }
  9850. }
  9851. return result;
  9852. }
  9853. String WinDebugger::GetAddressSourceLocation(intptr address)
  9854. {
  9855. DbgSubprogram* subProgram = NULL;
  9856. DbgLineData* lineData = FindLineDataAtAddress(address, &subProgram);
  9857. if (lineData != NULL)
  9858. return StrFormat("%s:%d:%d", subProgram->GetLineSrcFile(*lineData)->GetLocalPath().c_str(), lineData->mLine + 1, lineData->mColumn + 1);
  9859. String outSymbol;
  9860. addr_target offset = 0;
  9861. DbgModule* dbgModule;
  9862. if (mDebugTarget->FindSymbolAt(address, &outSymbol, &offset, &dbgModule))
  9863. {
  9864. if (offset < 0x10000)
  9865. {
  9866. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9867. if (offset > 0)
  9868. outSymbol += StrFormat("+%x", offset);
  9869. return outSymbol;
  9870. }
  9871. }
  9872. return StrFormat("0x%@", address);
  9873. }
  9874. String WinDebugger::GetAddressSymbolName(intptr address, bool demangle)
  9875. {
  9876. String outSymbol;
  9877. addr_target offset = 0;
  9878. DbgModule* dbgModule;
  9879. if (mDebugTarget->FindSymbolAt(address, &outSymbol, &offset, &dbgModule))
  9880. {
  9881. if (offset < 0x10000)
  9882. {
  9883. if (demangle)
  9884. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9885. if (offset > 0)
  9886. outSymbol += StrFormat("+%x", offset);
  9887. return outSymbol;
  9888. }
  9889. }
  9890. return StrFormat("0x%@", address);
  9891. }
  9892. String WinDebugger::DisassembleAtRaw(intptr inAddress)
  9893. {
  9894. addr_target address = (addr_target)inAddress;
  9895. const int addrBorder = 1024;
  9896. for (int offset = 0; offset < 8; offset++)
  9897. {
  9898. String result;
  9899. bool addOffset = true;
  9900. bool hadAddr = false;
  9901. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress(address);
  9902. DbgModuleMemoryCache* memCache = NULL;
  9903. defer
  9904. (
  9905. if (dbgModule == NULL)
  9906. delete memCache;
  9907. );
  9908. if ((dbgModule != NULL) && (dbgModule->mOrigImageData == NULL))
  9909. dbgModule = NULL;
  9910. result += "R\n"; // Raw
  9911. addr_target addrStart = address;
  9912. if (dbgModule != NULL)
  9913. {
  9914. dbgModule->ParseSymbolData();
  9915. memCache = dbgModule->mOrigImageData;
  9916. addrStart = BF_MAX((addr_target)dbgModule->mImageBase, address - addrBorder - offset);
  9917. }
  9918. else
  9919. {
  9920. memCache = new DbgModuleMemoryCache(addrStart & (4096 - 1), 4096 * 2);
  9921. }
  9922. //addr_target imageBase = dbgModule->mImageBase;
  9923. //int imageSize = dbgModule->mImageSize;
  9924. addr_target dataAddr = addrStart;
  9925. addr_target addrEnd = addrStart + addrBorder * 2 + 16;
  9926. while (dataAddr < addrEnd)
  9927. {
  9928. if (dataAddr == address)
  9929. hadAddr = true;
  9930. if (dataAddr > address)
  9931. {
  9932. if (!hadAddr)
  9933. {
  9934. if (offset == 7)
  9935. {
  9936. dataAddr = address;
  9937. }
  9938. break;
  9939. }
  9940. }
  9941. String outSymbol;
  9942. addr_target symOffset = 0;
  9943. DbgModule* symDWARF;
  9944. if (mDebugTarget->FindSymbolAt(dataAddr, &outSymbol, &symOffset, &symDWARF))
  9945. {
  9946. if (symOffset == 0)
  9947. {
  9948. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9949. if ((symDWARF != NULL) && (!symDWARF->mDisplayName.empty()))
  9950. outSymbol = symDWARF->GetLinkedModule()->mDisplayName + "!" + outSymbol;
  9951. result += "T " + outSymbol + ":\n";
  9952. }
  9953. }
  9954. CPUInst inst;
  9955. if (!mCPU->Decode(dataAddr, memCache, &inst))
  9956. {
  9957. if ((offset == 7) && (!hadAddr))
  9958. {
  9959. uint8 instData[1];
  9960. memCache->Read(dataAddr, instData, 1);
  9961. int instLen = 1;
  9962. #ifdef BF_DBG_32
  9963. result += StrFormat("D %08X: ", dataAddr);
  9964. #else
  9965. result += StrFormat("D %@: ", dataAddr);
  9966. #endif
  9967. for (int i = 0; i < instLen; i++)
  9968. result += StrFormat("%02X ", instData[i]);
  9969. for (int i = instLen; i < 8; i++)
  9970. result += " ";
  9971. result += "\n";
  9972. dataAddr++;
  9973. continue;
  9974. }
  9975. break;
  9976. }
  9977. int instLen = inst.GetLength();
  9978. #ifdef BF_DBG_32
  9979. result += StrFormat("D %08X: ", dataAddr);
  9980. #else
  9981. result += StrFormat("D %@: ", dataAddr);
  9982. #endif
  9983. uint8 instData[32];
  9984. int showInstLen = BF_MIN(32, instLen);
  9985. memCache->Read(dataAddr, instData, showInstLen);
  9986. for (int i = 0; i < showInstLen; i++)
  9987. result += StrFormat("%02X ", instData[i]);
  9988. for (int i = instLen; i < 8; i++)
  9989. result += " ";
  9990. result += mCPU->InstructionToString(&inst, dataAddr);
  9991. if ((inst.IsCall()) || (inst.IsBranch()))
  9992. {
  9993. addr_target targetAddr = inst.GetTarget();
  9994. if (targetAddr != 0)
  9995. {
  9996. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &symOffset))
  9997. {
  9998. if (symOffset < 0x10000)
  9999. {
  10000. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  10001. result += " ; " + outSymbol;
  10002. if (symOffset > 0)
  10003. result += StrFormat("+%x", symOffset);
  10004. //result += ">";
  10005. }
  10006. }
  10007. }
  10008. }
  10009. result += "\n";
  10010. dataAddr += instLen;
  10011. }
  10012. if (!hadAddr)
  10013. continue;
  10014. return result;
  10015. }
  10016. return "";
  10017. }
  10018. String WinDebugger::DisassembleAt(intptr inAddress)
  10019. {
  10020. BP_ZONE("WinDebugger::DisassembleAt");
  10021. AutoCrit autoCrit(mDebugManager->mCritSect);
  10022. addr_target address = (addr_target)inAddress;
  10023. if (mDebugTarget == NULL)
  10024. return "";
  10025. String result;
  10026. auto dwSubProgram = mDebugTarget->FindSubProgram(address);
  10027. if (dwSubProgram == NULL)
  10028. return DisassembleAtRaw(address);
  10029. dwSubProgram = dwSubProgram->GetRootInlineParent();
  10030. DbgModule* dwarf = dwSubProgram->mCompileUnit->mDbgModule;
  10031. int frameBaseRegister = mDebugTarget->GetFrameBaseRegister(dwSubProgram);
  10032. addr_target addrStart = dwSubProgram->mBlock.mLowPC;
  10033. addr_target addrEnd = dwSubProgram->mBlock.mHighPC;
  10034. auto dwCompileUnit = dwSubProgram->mCompileUnit;
  10035. {
  10036. FixupLineData(dwCompileUnit);
  10037. }
  10038. DbgSrcFile* dwSrcFile = NULL;
  10039. FixupLineDataForSubprogram(dwSubProgram);
  10040. DbgLineData* dwLineData = NULL;
  10041. if (dwSubProgram->mLineInfo != NULL)
  10042. dwLineData = &dwSubProgram->mLineInfo->mLines[0];
  10043. int nextLineDataIdx = 1;
  10044. if (dwSubProgram->mIsOptimized)
  10045. result += "O\n";
  10046. DbgSrcFile* srcFile = NULL;
  10047. int firstLine = 0;
  10048. int curLine = 0;
  10049. if (dwLineData != NULL)
  10050. {
  10051. srcFile = dwSubProgram->GetLineSrcFile(*dwLineData);
  10052. result += "S " + srcFile->GetLocalPath() + "\n";
  10053. if (srcFile->mHashKind != DbgHashKind_None)
  10054. {
  10055. result += "H ";
  10056. srcFile->GetHash(result);
  10057. result += "\n";
  10058. }
  10059. curLine = BF_MAX(0, dwLineData->mLine - 5);
  10060. //for (; curLine <= dwLineData->mLine; curLine++)
  10061. result += StrFormat("L %d %d\n", curLine, dwLineData->mLine - curLine + 1);
  10062. curLine = dwLineData->mLine + 1;
  10063. firstLine = dwLineData->mLine;
  10064. }
  10065. Array<DbgSubprogram*> inlineStack;
  10066. Array<DbgBlock*> blockList;
  10067. blockList.push_back(&dwSubProgram->mBlock);
  10068. addr_target dataAddr = addrStart;
  10069. int decodeFailureCount = 0;
  10070. auto& _PopInlineStack = [&]()
  10071. {
  10072. int depth = inlineStack.size();
  10073. auto curStackEntry = inlineStack.back();
  10074. if (depth > 1)
  10075. result += StrFormat("T <<<%d Inline End ", depth);
  10076. else
  10077. result += "T <<< Inline End ";
  10078. result += curStackEntry->ToString();
  10079. result += "\n";
  10080. inlineStack.pop_back();
  10081. };
  10082. std::function<void(DbgSubprogram* subprogram, int depth)> _UpdateInlineStackHelper = [&](DbgSubprogram* subprogram, int depth)
  10083. {
  10084. int stackIdx = depth - 1;
  10085. if (stackIdx < inlineStack.size())
  10086. {
  10087. auto curStackEntry = inlineStack[stackIdx];
  10088. if (curStackEntry != subprogram)
  10089. _PopInlineStack();
  10090. }
  10091. if (depth > 1)
  10092. {
  10093. _UpdateInlineStackHelper(subprogram->mInlineeInfo->mInlineParent, depth - 1);
  10094. }
  10095. if (stackIdx >= inlineStack.size())
  10096. {
  10097. if (depth > 1)
  10098. result += StrFormat("T >>>%d Inline ", depth);
  10099. else
  10100. result += "T >>> Inline ";
  10101. result += subprogram->ToString();
  10102. result += "\n";
  10103. inlineStack.push_back(subprogram);
  10104. }
  10105. };
  10106. auto _UpdateInlineStack = [&](DbgSubprogram* subprogram)
  10107. {
  10108. if (subprogram == NULL)
  10109. {
  10110. while (!inlineStack.IsEmpty())
  10111. _PopInlineStack();
  10112. return;
  10113. }
  10114. int inlineDepth = subprogram->GetInlineDepth();
  10115. while (inlineDepth < inlineStack.size())
  10116. _PopInlineStack();
  10117. if (inlineDepth > 0)
  10118. _UpdateInlineStackHelper(subprogram, inlineDepth);
  10119. };
  10120. while (dataAddr < addrEnd)
  10121. {
  10122. // Pop off old scopes
  10123. while (blockList.size() > 0)
  10124. {
  10125. auto lastBlock = blockList.back();
  10126. if (dataAddr < lastBlock->mHighPC)
  10127. break;
  10128. blockList.pop_back();
  10129. }
  10130. // Check entry into new child scopes
  10131. auto lastBlock = blockList.back();
  10132. for (auto checkBlock : lastBlock->mSubBlocks)
  10133. {
  10134. if ((dataAddr >= checkBlock->mLowPC) && (dataAddr < checkBlock->mHighPC))
  10135. {
  10136. blockList.push_back(checkBlock);
  10137. break;
  10138. }
  10139. }
  10140. bool allowSourceJump = false;
  10141. if ((dwLineData != NULL) && (dwLineData->mContribSize != 0) && (dataAddr >= dwSubProgram->GetLineAddr(*dwLineData) + dwLineData->mContribSize))
  10142. {
  10143. DbgSubprogram* inlinedSubprogram = NULL;
  10144. auto inlinedLine = dwSubProgram->FindClosestLine(dataAddr, &inlinedSubprogram);
  10145. _UpdateInlineStack(dwSubProgram);
  10146. }
  10147. // Update line data
  10148. while ((dwLineData != NULL) && (dwSubProgram->GetLineAddr(*dwLineData) <= dataAddr))
  10149. {
  10150. _UpdateInlineStack(dwSubProgram->GetLineInlinee(*dwLineData));
  10151. const int lineLimit = 5; // 15
  10152. if (allowSourceJump)
  10153. curLine = dwLineData->mLine;
  10154. auto lineSrcFile = dwSubProgram->GetLineSrcFile(*dwLineData);
  10155. if (lineSrcFile != srcFile)
  10156. {
  10157. srcFile = lineSrcFile;
  10158. result += "S ";
  10159. result += srcFile->GetLocalPath();
  10160. result += "\n";
  10161. // Just show the one line from the new file
  10162. curLine = dwLineData->mLine;
  10163. }
  10164. if (dwLineData->mLine < curLine - 1)
  10165. {
  10166. // Jumping backwards - possibly into inlined method, or possibly in current method.
  10167. // Show previous 6 lines, for context
  10168. curLine = BF_MAX(0, dwLineData->mLine - lineLimit);
  10169. }
  10170. if ((curLine <= firstLine) && (dwLineData->mLine >= firstLine))
  10171. {
  10172. // Jumping from inlined method (declared above) back into main method
  10173. curLine = dwLineData->mLine;
  10174. }
  10175. if (curLine < dwLineData->mLine - lineLimit)
  10176. {
  10177. // Don't show huge span of source - only show the last 6 lines at maximum
  10178. curLine = dwLineData->mLine - lineLimit;
  10179. }
  10180. //for ( ; curLine <= dwLineData->mLine; curLine++)
  10181. result += StrFormat("L %d %d\n", curLine, dwLineData->mLine - curLine + 1);
  10182. curLine = dwLineData->mLine + 1;
  10183. DbgLineData* nextLineData = NULL;
  10184. while (nextLineDataIdx < dwSubProgram->mLineInfo->mLines.mSize)
  10185. {
  10186. nextLineData = &dwSubProgram->mLineInfo->mLines[nextLineDataIdx];
  10187. //TODO:
  10188. /*{
  10189. result += StrFormat("T LineIdx: %d (%@ to %@)", nextLineDataIdx, dwSubProgram->GetLineAddr(*nextLineData), dwSubProgram->GetLineAddr(*nextLineData) + nextLineData->mContribSize);
  10190. auto inlinee = dwSubProgram->GetLineInlinee(*nextLineData);
  10191. if (inlinee != NULL)
  10192. {
  10193. result += StrFormat(" Inlinee: %s Depth: %d", inlinee->mName, inlinee->GetInlineDepth());
  10194. }
  10195. result += "\n";
  10196. }*/
  10197. auto nextLineAddr = dwSubProgram->GetLineAddr(*nextLineData);
  10198. if (nextLineAddr > dataAddr)
  10199. {
  10200. if (nextLineDataIdx + 1 < dwSubProgram->mLineInfo->mLines.mSize)
  10201. {
  10202. auto peekLineData = &dwSubProgram->mLineInfo->mLines[nextLineDataIdx + 1];
  10203. if (peekLineData->mRelAddress == nextLineData->mRelAddress)
  10204. {
  10205. // Use the later entry
  10206. ++nextLineDataIdx;
  10207. continue;
  10208. }
  10209. }
  10210. break;
  10211. }
  10212. // If we go back to an older entry beacuse of a gap then we need to catch back up...
  10213. ++nextLineDataIdx;
  10214. nextLineData = NULL; // Keep searching...
  10215. }
  10216. dwLineData = nextLineData;
  10217. nextLineDataIdx++;
  10218. }
  10219. // Have we gone off the end of the inline function?
  10220. // We may not have an explicit non-inlined line data at the transition point...
  10221. while (!inlineStack.IsEmpty())
  10222. {
  10223. auto subProgram = inlineStack.back();
  10224. if (dataAddr < subProgram->mBlock.mHighPC)
  10225. break;
  10226. _PopInlineStack();
  10227. }
  10228. bool hadDecodeFailure = false;
  10229. CPUInst inst;
  10230. if (!mCPU->Decode(dataAddr, dwarf->mOrigImageData, &inst))
  10231. hadDecodeFailure = true;
  10232. if ((decodeFailureCount == 8) || ((decodeFailureCount > 0) && (!hadDecodeFailure)))
  10233. {
  10234. for (int i = decodeFailureCount; i < 4 + sizeof(addr_target); i++)
  10235. result += " ";
  10236. result += " ???\n";
  10237. decodeFailureCount = 0;
  10238. }
  10239. if (decodeFailureCount == 0)
  10240. {
  10241. #ifdef BF_DBG_32
  10242. result += StrFormat("D %08X: ", dataAddr);
  10243. #else
  10244. result += StrFormat("D %@: ", dataAddr);
  10245. #endif
  10246. }
  10247. if (hadDecodeFailure)
  10248. {
  10249. uint8 byte = 0;
  10250. dwarf->mOrigImageData->Read(dataAddr, &byte, 1);
  10251. result += StrFormat("%02X ", byte);
  10252. dataAddr++;
  10253. decodeFailureCount++;
  10254. continue;
  10255. }
  10256. int instLen = inst.GetLength();
  10257. uint8 instData[32];
  10258. int showInstLen = BF_MIN(32, instLen);
  10259. dwarf->mOrigImageData->Read(dataAddr, instData, showInstLen);
  10260. for (int i = 0; i < showInstLen; i++)
  10261. result += StrFormat("%02X ", instData[i]);
  10262. for (int i = instLen; i < 4 + sizeof(addr_target); i++)
  10263. result += " ";
  10264. result += " ";
  10265. result += mCPU->InstructionToString(&inst, dataAddr);
  10266. int reg;
  10267. int offset;
  10268. if (inst.GetIndexRegisterAndOffset(&reg, &offset))
  10269. {
  10270. for (int blockIdx = (int)blockList.size() - 1; blockIdx >= 0; blockIdx--)
  10271. {
  10272. auto dwBlock = blockList[blockIdx];
  10273. for (auto variable : dwBlock->mVariables)
  10274. {
  10275. int varRegister;
  10276. int varOffset;
  10277. if (mDebugTarget->GetVariableIndexRegisterAndOffset(variable, &varRegister, &varOffset))
  10278. {
  10279. if (varRegister == -1)
  10280. varRegister = frameBaseRegister;
  10281. if ((reg == varRegister) && (offset == varOffset))
  10282. {
  10283. result += " ; ";
  10284. result += variable->mName;
  10285. break;
  10286. }
  10287. }
  10288. }
  10289. }
  10290. }
  10291. else if ((inst.IsCall()) || (inst.IsBranch()) || (inst.IsLoadAddress()))
  10292. {
  10293. addr_target targetAddr = inst.GetTarget();
  10294. if (targetAddr != 0)
  10295. {
  10296. if ((targetAddr >= addrStart) && (targetAddr < addrEnd))
  10297. {
  10298. result += StrFormat("\nJ %s", EncodeDataPtr(targetAddr, false).c_str());
  10299. }
  10300. else
  10301. {
  10302. String outSymbol;
  10303. addr_target offset = 0;
  10304. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &offset))
  10305. {
  10306. if (offset < 0x10000)
  10307. {
  10308. outSymbol = BfDemangler::Demangle(outSymbol, dwSubProgram->GetLanguage());
  10309. result += " ; " + outSymbol;
  10310. if (offset > 0)
  10311. result += StrFormat("+%x", offset);
  10312. }
  10313. }
  10314. }
  10315. }
  10316. }
  10317. result += "\n";
  10318. dataAddr += instLen;
  10319. }
  10320. // Why did we want to "show lines at end"??
  10321. // Show lines at end
  10322. /*if (curLine > 0)
  10323. {
  10324. for (int i = 0; i < 6; i++, curLine++)
  10325. result += StrFormat("L %d\n", curLine);
  10326. }*/
  10327. return result;
  10328. }
  10329. String WinDebugger::FindLineCallAddresses(intptr inAddress)
  10330. {
  10331. String callAddresses;
  10332. addr_target address = (addr_target)inAddress;
  10333. DbgSubprogram* dwSubprogram = NULL;
  10334. DbgLineData* startLineData = FindLineDataAtAddress(address, &dwSubprogram, NULL);
  10335. if (dwSubprogram == NULL)
  10336. return "";
  10337. CPURegisters registers;
  10338. PopulateRegisters(&registers);
  10339. auto inlinerSubprogram = dwSubprogram->GetRootInlineParent();
  10340. FixupLineDataForSubprogram(inlinerSubprogram);
  10341. if (inlinerSubprogram->mLineInfo->mLines.mSize == 0)
  10342. return "";
  10343. auto lineData = &inlinerSubprogram->mLineInfo->mLines[0];
  10344. addr_target addr = dwSubprogram->mBlock.mLowPC;
  10345. addr_target endAddr = dwSubprogram->mBlock.mHighPC;
  10346. DbgSubprogram* checkSubprogram = dwSubprogram;
  10347. DbgLineData* checkLineData = lineData;
  10348. addr_target checkLineAddr = 0;
  10349. int lineIdx = 0;
  10350. while (checkLineData != NULL)
  10351. {
  10352. //auto nextLineData = dwSubprogram->mCompileUnit->mLineDataMap.GetNext(checkLineData);
  10353. ++lineIdx;
  10354. DbgLineData* nextLineData = NULL;
  10355. addr_target nextLineAddr;
  10356. if (lineIdx < inlinerSubprogram->mLineInfo->mLines.size())
  10357. {
  10358. nextLineData = &inlinerSubprogram->mLineInfo->mLines[lineIdx];
  10359. nextLineAddr = dwSubprogram->GetLineAddr(*nextLineData);
  10360. }
  10361. else
  10362. nextLineAddr = inlinerSubprogram->mBlock.mHighPC;
  10363. // This stuff doesn't make sense...
  10364. DbgSubprogram* nextSubProgram;
  10365. if (nextLineData != NULL)
  10366. {
  10367. if (nextLineAddr > dwSubprogram->mBlock.mHighPC)
  10368. break;
  10369. endAddr = nextLineAddr;
  10370. nextSubProgram = mDebugTarget->FindSubProgram(endAddr);
  10371. if (nextSubProgram != NULL)
  10372. {
  10373. auto dbgModule = nextSubProgram->mCompileUnit->mDbgModule;
  10374. dbgModule->ParseSymbolData();
  10375. }
  10376. }
  10377. else
  10378. {
  10379. nextSubProgram = dwSubprogram;
  10380. endAddr = dwSubprogram->mBlock.mHighPC;
  10381. }
  10382. auto _HandleSection = [&]()
  10383. {
  10384. while (addr < endAddr)
  10385. {
  10386. CPUInst inst;
  10387. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  10388. break;
  10389. *registers.GetPCRegisterRef() = addr;
  10390. if (inst.IsCall())
  10391. {
  10392. bool addSymbol = true;
  10393. if (addr < (addr_target)inAddress)
  10394. callAddresses += "-";
  10395. callAddresses += EncodeDataPtr(addr, false);
  10396. addr_target targetAddr = inst.GetTarget(this, &registers);
  10397. if (targetAddr != 0)
  10398. {
  10399. String outSymbol;
  10400. auto subprogram = mDebugTarget->FindSubProgram(targetAddr);
  10401. if (subprogram != NULL)
  10402. {
  10403. CreateFilterName(outSymbol, subprogram);
  10404. addSymbol = true;
  10405. }
  10406. else
  10407. {
  10408. addr_target offset = 0;
  10409. String fullSymbolName;
  10410. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &offset))
  10411. {
  10412. if (offset < 0x200)
  10413. {
  10414. //outSymbol = BfDemangler::Demangle(outSymbol, dwSubprogram->GetLanguage());
  10415. if (outSymbol == "___chkstk_ms")
  10416. addSymbol = false;
  10417. else
  10418. {
  10419. String demangledName = BfDemangler::Demangle(outSymbol, DbgLanguage_C);
  10420. outSymbol.clear();
  10421. CreateFilterName(outSymbol, demangledName.c_str(), DbgLanguage_C);
  10422. }
  10423. }
  10424. else
  10425. outSymbol.clear();
  10426. }
  10427. }
  10428. if (addSymbol)
  10429. {
  10430. if (outSymbol.empty())
  10431. callAddresses += "\tFunc@" + EncodeDataPtr(targetAddr, false);
  10432. else
  10433. callAddresses += "\t" + outSymbol;
  10434. String attrs;
  10435. bool isFiltered = false;
  10436. if (subprogram != NULL)
  10437. {
  10438. subprogram->PopulateSubprogram();
  10439. isFiltered = subprogram->mIsStepFilteredDefault;
  10440. if (isFiltered)
  10441. attrs += "d"; // 'd' for default filtered
  10442. }
  10443. StepFilter* stepFilterPtr = NULL;
  10444. if (mDebugManager->mStepFilters.TryGetValue(outSymbol, &stepFilterPtr))
  10445. isFiltered = stepFilterPtr->IsFiltered(isFiltered);
  10446. if (isFiltered)
  10447. attrs += "f"; // 'f' for filter
  10448. if (!attrs.IsEmpty())
  10449. callAddresses += "\t" + attrs;
  10450. }
  10451. }
  10452. if (addSymbol)
  10453. callAddresses += "\n";
  10454. }
  10455. inst.PartialSimulate(this, &registers);
  10456. addr += inst.GetLength();
  10457. }
  10458. };
  10459. // For inlining - only add calls that are found either directly in our main block (not an inlined block)
  10460. // But add inlined methods when their parent is our current block
  10461. if ((checkSubprogram == dwSubprogram) && (checkLineData->mLine == startLineData->mLine))
  10462. {
  10463. _HandleSection();
  10464. }
  10465. else if ((checkSubprogram->mInlineeInfo != NULL) && (checkSubprogram->mInlineeInfo->mInlineParent == dwSubprogram))
  10466. {
  10467. if (checkLineAddr == checkSubprogram->mBlock.mLowPC)
  10468. {
  10469. addr_target inlineStartAddr = checkSubprogram->mBlock.mLowPC;
  10470. // Find the calling line
  10471. DbgSubprogram* callingSubprogram = dwSubprogram;
  10472. auto checkLineData = dwSubprogram->FindClosestLine(inlineStartAddr, &callingSubprogram);
  10473. if ((checkLineData != NULL) && (checkLineData->mCtxIdx == startLineData->mCtxIdx) && (checkLineData->mLine == startLineData->mLine))
  10474. {
  10475. if (inlineStartAddr <= (addr_target)inAddress)
  10476. callAddresses += "-";
  10477. callAddresses += EncodeDataPtr(inlineStartAddr, false);
  10478. String outSymbol;
  10479. CreateFilterName(outSymbol, checkSubprogram);
  10480. callAddresses += "\t" + outSymbol;
  10481. bool isFiltered = dwSubprogram->mIsStepFilteredDefault;
  10482. StepFilter* stepFilterPtr;
  10483. if (mDebugManager->mStepFilters.TryGetValue(outSymbol, &stepFilterPtr))
  10484. isFiltered = stepFilterPtr->IsFiltered(isFiltered);
  10485. if (isFiltered)
  10486. callAddresses += "\tf"; // 'f' for filter
  10487. callAddresses += "\n";
  10488. }
  10489. // if (checkSubprogram->mBlock.mHighPC < endAddr)
  10490. // {
  10491. // addr = checkSubprogram->mBlock.mHighPC;
  10492. // _HandleSection();
  10493. // }
  10494. }
  10495. // If we have unattributed data after the end of an inlined method, add that
  10496. if ((endAddr > checkSubprogram->mBlock.mHighPC) && (nextSubProgram == dwSubprogram))
  10497. {
  10498. addr = checkSubprogram->mBlock.mHighPC;
  10499. _HandleSection();
  10500. }
  10501. }
  10502. checkLineData = nextLineData;
  10503. checkSubprogram = nextSubProgram;
  10504. checkLineAddr = nextLineAddr;
  10505. addr = endAddr;
  10506. }
  10507. return callAddresses;
  10508. }
  10509. String WinDebugger::GetCurrentException()
  10510. {
  10511. AutoCrit autoCrit(mDebugManager->mCritSect);
  10512. String result = StrFormat("%s\n%08X",
  10513. EncodeDataPtr((addr_target)(intptr)mCurException.ExceptionAddress, true).c_str(),
  10514. mCurException.ExceptionCode);
  10515. String exStr;
  10516. switch (mCurException.ExceptionCode)
  10517. {
  10518. case EXCEPTION_ACCESS_VIOLATION:
  10519. {
  10520. String accessType;
  10521. if (mCurException.ExceptionInformation[0] == 0)
  10522. accessType = "reading from";
  10523. else if (mCurException.ExceptionInformation[0] == 8)
  10524. accessType = "executing";
  10525. else
  10526. accessType = "writing to";
  10527. exStr = StrFormat("EXCEPTION_ACCESS_VIOLATION %s %s", accessType.c_str(), EncodeDataPtr((addr_target)mCurException.ExceptionInformation[1], true).c_str());
  10528. }
  10529. break;
  10530. case EXCEPTION_DATATYPE_MISALIGNMENT:
  10531. exStr = "EXCEPTION_DATATYPE_MISALIGNMENT";
  10532. case EXCEPTION_SINGLE_STEP:
  10533. exStr = "EXCEPTION_SINGLE_STEP";
  10534. break;
  10535. case EXCEPTION_BREAKPOINT:
  10536. exStr = "EXCEPTION_BREAKPOINT";
  10537. break;
  10538. case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
  10539. exStr = "EXCEPTION_ARRAY_BOUNDS_EXCEEDED";
  10540. break;
  10541. case EXCEPTION_FLT_DENORMAL_OPERAND:
  10542. exStr = "EXCEPTION_FLT_DENORMAL_OPERAND";
  10543. break;
  10544. case EXCEPTION_FLT_DIVIDE_BY_ZERO:
  10545. exStr = "EXCEPTION_FLT_DIVIDE_BY_ZERO";
  10546. break;
  10547. case EXCEPTION_FLT_INEXACT_RESULT:
  10548. exStr = "EXCEPTION_FLT_INEXACT_RESULT";
  10549. break;
  10550. case EXCEPTION_FLT_INVALID_OPERATION:
  10551. exStr = "EXCEPTION_FLT_INVALID_OPERATIO";
  10552. break;
  10553. case EXCEPTION_FLT_OVERFLOW:
  10554. exStr = "EXCEPTION_FLT_OVERFLOW";
  10555. break;
  10556. case EXCEPTION_FLT_STACK_CHECK:
  10557. exStr = "EXCEPTION_FLT_STACK_CHECK";
  10558. break;
  10559. case EXCEPTION_FLT_UNDERFLOW:
  10560. exStr = "EXCEPTION_FLT_UNDERFLOW";
  10561. break;
  10562. case EXCEPTION_INT_DIVIDE_BY_ZERO:
  10563. exStr = "EXCEPTION_INT_DIVIDE_BY_ZERO";
  10564. break;
  10565. case EXCEPTION_INT_OVERFLOW:
  10566. exStr = "EXCEPTION_INT_OVERFLOW";
  10567. break;
  10568. case EXCEPTION_PRIV_INSTRUCTION:
  10569. exStr = "EXCEPTION_PRIV_INSTRUCTION";
  10570. break;
  10571. case EXCEPTION_IN_PAGE_ERROR:
  10572. exStr = "EXCEPTION_IN_PAGE_ERROR";
  10573. break;
  10574. case EXCEPTION_ILLEGAL_INSTRUCTION:
  10575. exStr = "EXCEPTION_ILLEGAL_INSTRUCTION";
  10576. break;
  10577. case EXCEPTION_NONCONTINUABLE_EXCEPTION:
  10578. exStr = "EXCEPTION_NONCONTINUABLE_EXCEPTION";
  10579. break;
  10580. case EXCEPTION_STACK_OVERFLOW:
  10581. exStr = "EXCEPTION_STACK_OVERFLOW";
  10582. break;
  10583. case EXCEPTION_INVALID_DISPOSITION:
  10584. exStr = "EXCEPTION_INVALID_DISPOSITION";
  10585. break;
  10586. case EXCEPTION_GUARD_PAGE:
  10587. exStr = "EXCEPTION_GUARD_PAGE";
  10588. break;
  10589. case EXCEPTION_INVALID_HANDLE:
  10590. exStr = "EXCEPTION_INVALID_HANDLE";
  10591. break;
  10592. case CONTROL_C_EXIT:
  10593. exStr = "CONTROL_C_EXIT";
  10594. break;
  10595. default:
  10596. exStr += StrFormat("EXCEPTION %08X", mCurException.ExceptionCode);
  10597. }
  10598. if (mActiveThread != NULL)
  10599. exStr += StrFormat(" in thread %d", mActiveThread->mThreadId);
  10600. if (!exStr.empty())
  10601. result += "\n" + exStr;
  10602. // After we retrieve the exception then we can go back to just being normal 'paused'
  10603. // This allows us to evaluate stuff, Set Next Statement, etc.
  10604. mRunState = RunState_Paused;
  10605. return result.c_str();
  10606. }
  10607. void WinDebugger::SetAliasPath(const StringImpl& origPath, const StringImpl& localPath)
  10608. {
  10609. AutoCrit autoCrit(mDebugManager->mCritSect);
  10610. String fixedOrigPath = FixPathAndCase(origPath);
  10611. String fixedLocalPath = FixPathAndCase(localPath);
  10612. auto origFile = mDebugTarget->AddSrcFile(origPath);
  10613. origFile->mLocalPath = FixPath(localPath);
  10614. mDebugTarget->mLocalToOrigSrcMap[fixedLocalPath] = fixedOrigPath;
  10615. // We invalidate the step filters, because previously-failing 'CheckSourceFileExist' checks may now succeed
  10616. mDebugManager->mStepFilterVersion++;
  10617. }
  10618. String WinDebugger::GetModulesInfo()
  10619. {
  10620. AutoCrit autoCrit(mDebugManager->mCritSect);
  10621. String str;
  10622. for (auto module : mDebugTarget->mDbgModules)
  10623. {
  10624. COFF* coff = (COFF*)module;
  10625. if (module->mHotIdx > 0)
  10626. continue;
  10627. str += module->mDisplayName;
  10628. str += "\t";
  10629. if (module->mLoadState == DbgModuleLoadState_Loaded)
  10630. {
  10631. str += module->mFilePath;
  10632. }
  10633. else if (module->mLoadState == DbgModuleLoadState_NotLoaded)
  10634. {
  10635. str += module->mFilePath;
  10636. str += " (Loading...)";
  10637. }
  10638. else if (module->mLoadState == DbgModuleLoadState_Failed)
  10639. {
  10640. str += "!";
  10641. str += module->mFilePath;
  10642. }
  10643. if (module->mMappedImageFile != NULL)
  10644. {
  10645. str += " (";
  10646. str += module->mMappedImageFile->mFileName;
  10647. str += ")";
  10648. }
  10649. str += "\t";
  10650. str += coff->mPDBPath;
  10651. str += "\t";
  10652. str += module->mVersion;
  10653. str += StrFormat("\t%@-%@\t%dk\t", module->mImageBase, module->mImageBase + module->mImageSize, module->mImageSize / 1024);
  10654. time_t timestamp = coff->mTimeStamp;
  10655. if (timestamp == 0)
  10656. timestamp = GetFileTimeWrite(coff->mFilePath);
  10657. if (timestamp != 0)
  10658. {
  10659. char timeString[256];
  10660. auto time_info = localtime(&timestamp);
  10661. strftime(timeString, sizeof(timeString), "%D %T", time_info);
  10662. str += timeString;
  10663. }
  10664. str += "\n";
  10665. }
  10666. return str;
  10667. }
  10668. void WinDebugger::CancelSymSrv()
  10669. {
  10670. AutoCrit autoCrit(mDebugManager->mCritSect);
  10671. if (mActiveSymSrvRequest != NULL)
  10672. mActiveSymSrvRequest->Cancel();
  10673. }
  10674. bool WinDebugger::HasPendingDebugLoads()
  10675. {
  10676. AutoCrit autoCrit(mDebugManager->mCritSect);
  10677. return (!mPendingImageLoad.IsEmpty()) || (!mPendingDebugInfoLoad.IsEmpty());
  10678. }
  10679. int WinDebugger::LoadImageForModule(const StringImpl &modulePath, const StringImpl& imagePath)
  10680. {
  10681. AutoCrit autoCrit(mDebugManager->mCritSect);
  10682. for (auto dbgModule : mDebugTarget->mDbgModules)
  10683. {
  10684. if (modulePath.Equals(dbgModule->mFilePath, StringImpl::CompareKind_OrdinalIgnoreCase))
  10685. {
  10686. auto coff = (COFF*)dbgModule;
  10687. if (!coff->LoadModuleImage(imagePath))
  10688. {
  10689. mDebugManager->mOutMessages.push_back("error Failed to load image " + imagePath);
  10690. }
  10691. ModuleChanged(dbgModule);
  10692. return 0;
  10693. }
  10694. }
  10695. return 0;
  10696. }
  10697. int WinDebugger::LoadDebugInfoForModule(DbgModule* dbgModule)
  10698. {
  10699. if (!dbgModule->HasPendingDebugInfo())
  10700. return 0;
  10701. if (dbgModule->RequestDebugInfo())
  10702. {
  10703. ClearCallStack(); // Make this re-resolve with debug info
  10704. return 1;
  10705. }
  10706. DbgPendingDebugInfoLoad* dbgPendingDebugInfoLoad = NULL;
  10707. if (mPendingDebugInfoLoad.TryAdd(dbgModule, NULL, &dbgPendingDebugInfoLoad))
  10708. {
  10709. dbgPendingDebugInfoLoad->mModule = dbgModule;
  10710. dbgPendingDebugInfoLoad->mAllowRemote = true;
  10711. return 2;
  10712. }
  10713. dbgPendingDebugInfoLoad->mAllowRemote = true;
  10714. return 0;
  10715. }
  10716. int WinDebugger::LoadDebugInfoForModule(const StringImpl& moduleName)
  10717. {
  10718. AutoCrit autoCrit(mDebugManager->mCritSect);
  10719. for (auto dbgModule : mDebugTarget->mDbgModules)
  10720. {
  10721. String checkModuleName = GetFileName(dbgModule->mFilePath);
  10722. if (moduleName.Equals(checkModuleName, StringImpl::CompareKind_OrdinalIgnoreCase))
  10723. {
  10724. return LoadDebugInfoForModule(dbgModule);
  10725. }
  10726. }
  10727. return 0;
  10728. }
  10729. int WinDebugger::LoadDebugInfoForModule(const StringImpl& modulePath, const StringImpl& debugFileName)
  10730. {
  10731. AutoCrit autoCrit(mDebugManager->mCritSect);
  10732. for (auto dbgModule : mDebugTarget->mDbgModules)
  10733. {
  10734. if (modulePath.Equals(dbgModule->mFilePath, StringImpl::CompareKind_OrdinalIgnoreCase))
  10735. {
  10736. auto coff = (COFF*)dbgModule;
  10737. String err;
  10738. if (!coff->mPDBLoaded)
  10739. {
  10740. dbgModule->mFailMsgPtr = &err;
  10741. if (coff->TryLoadPDB(debugFileName, coff->mWantPDBGuid, coff->mWantAge))
  10742. {
  10743. ModuleChanged(dbgModule);
  10744. }
  10745. dbgModule->mFailMsgPtr = NULL;
  10746. }
  10747. else
  10748. {
  10749. err = StrFormat("Module '%s' already has debug information loaded", GetFileName(modulePath).c_str());
  10750. }
  10751. if (!err.IsEmpty())
  10752. {
  10753. mDebugManager->mOutMessages.push_back("error " + err);
  10754. }
  10755. return 0;
  10756. }
  10757. }
  10758. return 0;
  10759. }
  10760. void WinDebugger::FixupLineData(DbgCompileUnit* compileUnit)
  10761. {
  10762. if (!compileUnit || !compileUnit->mNeedsLineDataFixup)
  10763. return;
  10764. compileUnit->mNeedsLineDataFixup = false;
  10765. }
  10766. static int CompareLineData(const void* lineDataP1, const void* lineDataP2)
  10767. {
  10768. int cmpResult = (int)(((DbgLineData*)lineDataP1)->mRelAddress - ((DbgLineData*)lineDataP2)->mRelAddress);
  10769. if (cmpResult != 0)
  10770. return cmpResult;
  10771. // A larger contrib size means it's the 'outer' inlinee
  10772. cmpResult = -(((DbgLineData*)lineDataP1)->mContribSize - ((DbgLineData*)lineDataP2)->mContribSize);
  10773. if (cmpResult != 0)
  10774. return cmpResult;
  10775. return -(((DbgLineData*)lineDataP1)->mCtxIdx - ((DbgLineData*)lineDataP2)->mCtxIdx);
  10776. }
  10777. void WinDebugger::FixupLineDataForSubprogram(DbgSubprogram* subProgram)
  10778. {
  10779. if ((subProgram == NULL) || (!subProgram->mNeedLineDataFixup))
  10780. return;
  10781. BP_ZONE("FixupLineDataForSubprogram");
  10782. subProgram->mNeedLineDataFixup = false;
  10783. if (subProgram->mInlineeInfo != NULL)
  10784. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  10785. if ((subProgram->mLineInfo == NULL) || (subProgram->mLineInfo->mLines.mSize == 0))
  10786. return;
  10787. //TODO: I think this was covering up a bug in DWARF line encoding? Figure this out
  10788. // if (subProgram->mLineInfo->mLines.mSize >= 2)
  10789. // {
  10790. // DbgLineData* line0 = &subProgram->mLineInfo->mLines[0];
  10791. // DbgLineData* line1 = &subProgram->mLineInfo->mLines[1];
  10792. //
  10793. //
  10794. // if ((line0->mRelAddress == line1->mRelAddress) && (!line0->IsStackFrameSetup()) && (line1->IsStackFrameSetup()))
  10795. // {
  10796. // CPUInst inst;
  10797. // if (mCPU->Decode(line0->mAddress, subProgram->mCompileUnit->mDbgModule->mOrigImageData, &inst))
  10798. // line1->mAddress += inst.GetLength();
  10799. // }
  10800. // }
  10801. qsort(subProgram->mLineInfo->mLines.mVals, subProgram->mLineInfo->mLines.mSize, sizeof(DbgLineData), CompareLineData);
  10802. // If we have multiple lines with the same line/column/context, merge them
  10803. if (!subProgram->mLineInfo->mLines.IsEmpty())
  10804. {
  10805. auto prevLine = &subProgram->mLineInfo->mLines[0];
  10806. for (int i = 1; i < subProgram->mLineInfo->mLines.mSize; i++)
  10807. {
  10808. auto nextLine = &subProgram->mLineInfo->mLines[i];
  10809. if ((nextLine->mLine == prevLine->mLine) && (nextLine->mColumn == prevLine->mColumn) && (nextLine->mCtxIdx == prevLine->mCtxIdx) &&
  10810. (nextLine->mRelAddress == prevLine->mRelAddress + prevLine->mContribSize))
  10811. {
  10812. prevLine->mContribSize += nextLine->mContribSize;
  10813. // This messed up inline cases because mContribSize actually INCLUDES inlined lines so it caused the address to skip too far
  10814. //nextLine->mRelAddress += nextLine->mContribSize;
  10815. //nextLine->mContribSize = 0;
  10816. }
  10817. else
  10818. {
  10819. prevLine = nextLine;
  10820. }
  10821. }
  10822. }
  10823. }
  10824. void WinDebugger::ReserveHotTargetMemory(int size)
  10825. {
  10826. HotTargetMemory hotTargetMemory;
  10827. hotTargetMemory.mOffset = 0;
  10828. hotTargetMemory.mSize = 0;
  10829. hotTargetMemory.mPtr = NULL;
  10830. if (size > 0)
  10831. {
  10832. // In 64-bit mode we have a reserved region on program load that we commit here because the offsets
  10833. // must be within 32-bits of the original EXE image, but in 32-bit mode we don't reserve anything
  10834. // until here
  10835. #ifdef BF_DBG_32
  10836. //hotTargetMemory.mSize = std::max(1024 * 1024, size);
  10837. BF_ASSERT((size & (mPageSize - 1)) == 0);
  10838. hotTargetMemory.mSize = size;
  10839. hotTargetMemory.mPtr = (addr_target)(intptr)VirtualAllocEx(mProcessInfo.hProcess, NULL, hotTargetMemory.mSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
  10840. mDebugTarget->mHotHeap->AddTrackedRegion(hotTargetMemory.mPtr, hotTargetMemory.mSize);
  10841. #else
  10842. hotTargetMemory.mSize = size;
  10843. hotTargetMemory.mPtr = mDebugTarget->mHotHeap->Alloc(size);
  10844. BF_ASSERT(hotTargetMemory.mPtr != 0);
  10845. auto ptr = ::VirtualAllocEx(mProcessInfo.hProcess, (void*)(intptr)hotTargetMemory.mPtr, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  10846. BF_ASSERT(ptr == (void*)(intptr)hotTargetMemory.mPtr);
  10847. #endif
  10848. }
  10849. BfLogDbg("ReserveHotTargetMemory %p %d", hotTargetMemory.mPtr, hotTargetMemory.mSize);
  10850. int err = GetLastError();
  10851. mHotTargetMemory.push_back(hotTargetMemory);
  10852. }
  10853. addr_target WinDebugger::AllocHotTargetMemory(int size, bool canExecute, bool canWrite, int* outAllocSize)
  10854. {
  10855. int prot = PAGE_READWRITE;
  10856. if (canExecute && canWrite)
  10857. prot = PAGE_EXECUTE_READWRITE;
  10858. else if (canExecute)
  10859. prot = PAGE_EXECUTE_READ;
  10860. auto hotTargetMemory = (HotTargetMemory*)&mHotTargetMemory.back();
  10861. if (hotTargetMemory->mPtr == 0)
  10862. {
  10863. Fail("Failed to allocate memory for hot loading");
  10864. return 0;
  10865. }
  10866. size = (size + (mPageSize - 1)) & ~(mPageSize - 1);
  10867. *outAllocSize = size;
  10868. BF_ASSERT(hotTargetMemory->mOffset + size <= hotTargetMemory->mSize);
  10869. addr_target result = hotTargetMemory->mPtr + hotTargetMemory->mOffset;
  10870. ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)result, size, prot, NULL);
  10871. BfLogDbg("AllocHotTargetMemory: %p %d %d %d\n", result, size, canExecute, canWrite);
  10872. hotTargetMemory->mOffset += size;
  10873. return result;
  10874. }
  10875. void WinDebugger::ReleaseHotTargetMemory(addr_target addr, int size)
  10876. {
  10877. #ifdef BF_DBG_32
  10878. ::VirtualFreeEx(mProcessInfo.hProcess, (void*)(intptr)addr, 0, MEM_RELEASE);
  10879. #else
  10880. mDebugTarget->mHotHeap->Release(addr, size);
  10881. ::VirtualFreeEx(mProcessInfo.hProcess, (void*)(intptr)addr, size, MEM_DECOMMIT);
  10882. #endif
  10883. }
  10884. void WinDebugger::CleanupHotHeap()
  10885. {
  10886. mDebugTarget->mLastHotHeapCleanIdx = mDebugTarget->mHotHeap->mBlockAllocIdx;
  10887. // Our criteria for determining whether a hot loaded file is still being used:
  10888. // 1) If we are currently executing a method from that object file.
  10889. // 2) If the symbol map has a symbol with that address.
  10890. // 3) If the static variable map contains a reference - including a conservative scan of the data
  10891. // This handles vdata references
  10892. // This is a conservative check which won't purge hot reloads that contain deleted
  10893. // methods (for example), but it will purge hot reloads where all the changed
  10894. // data has been overwritten.
  10895. // For delegate bindings, the original module declaring the bind creates a "preserve"
  10896. // global such as "bf_hs_preserve@_ZN5TestO4TestEv", whose preserved symbol ensures it
  10897. // doesn't get unloaded. The current version of that method resides in "_ZN5TestO4TestEv",
  10898. // ensuring that the method pointed to by the global variable is valid
  10899. mDebugTarget->mHotHeap->ClearReferencedFlags();
  10900. addr_target lowAddr = mDebugTarget->mHotHeap->mHotAreaStart;
  10901. addr_target highAddr = lowAddr + mDebugTarget->mHotHeap->mHotAreaSize;
  10902. // Do conservative scan through all thread stacks. Stack traces aren't 100% reliable, so we
  10903. // need to do a full conservative scan of any addresses stored in the stack
  10904. // to ensure we don't miss any return addresses
  10905. for (int threadIdx = 0; threadIdx < (int)mThreadList.size(); threadIdx++)
  10906. {
  10907. WdThreadInfo* threadInfo = mThreadList[threadIdx];
  10908. BF_CONTEXT lcContext;
  10909. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  10910. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  10911. addr_target checkStackAddr = BF_CONTEXT_SP(lcContext);
  10912. checkStackAddr &= ~(sizeof(addr_target) - 1);
  10913. // Conservative check on registers
  10914. for (int regNum = 0; regNum < sizeof(BF_CONTEXT)/sizeof(addr_target); regNum++)
  10915. {
  10916. addr_target checkAddr = ((addr_target*)&lcContext)[regNum];
  10917. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  10918. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  10919. }
  10920. // Conservative check on all stack data
  10921. while (checkStackAddr < threadInfo->mStartSP)
  10922. {
  10923. addr_target checkAddrArr[1024];
  10924. int numAddrsChecking = BF_MIN(1024, (int)((threadInfo->mStartSP - checkStackAddr) / sizeof(addr_target)));
  10925. ReadMemory(checkStackAddr, numAddrsChecking * sizeof(addr_target), checkAddrArr);
  10926. checkStackAddr += numAddrsChecking * sizeof(addr_target);
  10927. for (int addrIdx = 0; addrIdx < numAddrsChecking; addrIdx++)
  10928. {
  10929. addr_target checkAddr = checkAddrArr[addrIdx];
  10930. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  10931. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  10932. }
  10933. }
  10934. }
  10935. auto mainModule = mDebugTarget->mTargetBinary;
  10936. for (auto entry : mainModule->mSymbolNameMap)
  10937. {
  10938. auto dwSymbol = entry->mValue;
  10939. addr_target checkAddr = dwSymbol->mAddress;
  10940. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  10941. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  10942. }
  10943. mDebugTarget->CleanupHotHeap();
  10944. BfLogDbg("Hot load memory used: %dk\n", (int)mDebugTarget->mHotHeap->GetUsedSize() / 1024);
  10945. }
  10946. int WinDebugger::EnableWriting(intptr address, int size)
  10947. {
  10948. DWORD oldProt;
  10949. bool success = ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)address, size, PAGE_READWRITE, &oldProt);
  10950. if (!success)
  10951. {
  10952. int err = GetLastError();
  10953. }
  10954. return (int)oldProt;
  10955. }
  10956. int WinDebugger::SetProtection(intptr address, int size, int prot)
  10957. {
  10958. DWORD oldProt;
  10959. ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)address, size, prot, &oldProt);
  10960. return (int)oldProt;
  10961. }
  10962. void WinDebugger::EnableMemCache()
  10963. {
  10964. mMemCacheAddr = 1;
  10965. }
  10966. void WinDebugger::DisableMemCache()
  10967. {
  10968. mMemCacheAddr = 0;
  10969. }
  10970. bool WinDebugger::ReadMemory(intptr address, uint64 length, void* dest, bool local)
  10971. {
  10972. if (local)
  10973. {
  10974. __try
  10975. {
  10976. memcpy(dest, (void*)address, length);
  10977. return true;
  10978. }
  10979. __except(EXCEPTION_EXECUTE_HANDLER)
  10980. {
  10981. return false;
  10982. }
  10983. }
  10984. if (mMemCacheAddr != 0)
  10985. {
  10986. addr_target targetAddr = (addr_target)address;
  10987. if ((targetAddr >= mMemCacheAddr) && (targetAddr + length <= mMemCacheAddr + WD_MEMCACHE_SIZE) && (mMemCacheAddr > 1))
  10988. {
  10989. memcpy(dest, mMemCacheData + (targetAddr - mMemCacheAddr), length);
  10990. return true;
  10991. }
  10992. // We need a new block
  10993. SIZE_T dwReadBytes;
  10994. if (::ReadProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, mMemCacheData, (SIZE_T)WD_MEMCACHE_SIZE, &dwReadBytes) != 0)
  10995. {
  10996. mMemCacheAddr = targetAddr;
  10997. memcpy(dest, mMemCacheData, length);
  10998. return true;
  10999. }
  11000. // Failed, turn off caching
  11001. mMemCacheAddr = 0;
  11002. }
  11003. SIZE_T dwReadBytes;
  11004. if (::ReadProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, dest, (SIZE_T)length, &dwReadBytes) != 0)
  11005. return true;
  11006. int lastErr = ::GetLastError();
  11007. memset(dest, 0, length);
  11008. return false;
  11009. }
  11010. bool WinDebugger::WriteMemory(intptr address, void* src, uint64 length)
  11011. {
  11012. SIZE_T dwBytesWritten = 0;
  11013. int result = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, src, (SIZE_T)length, &dwBytesWritten);
  11014. return result != 0;
  11015. }
  11016. addr_target WinDebugger::GetTLSOffset(int tlsIndex)
  11017. {
  11018. typedef LONG NTSTATUS;
  11019. typedef DWORD KPRIORITY;
  11020. typedef WORD UWORD;
  11021. enum THREADINFOCLASS
  11022. {
  11023. ThreadBasicInformation,
  11024. };
  11025. struct CLIENT_ID
  11026. {
  11027. HANDLE UniqueProcess;
  11028. HANDLE UniqueThread;
  11029. };
  11030. struct
  11031. {
  11032. NTSTATUS mExitStatus;
  11033. void* mTebBaseAddress;
  11034. CLIENT_ID mClientId;
  11035. KAFFINITY mAffinityMask;
  11036. KPRIORITY mPriority;
  11037. KPRIORITY mBasePriority;
  11038. } threadInfo = { 0 };
  11039. ULONG len = 0;
  11040. bool loadedManually = false;
  11041. static HMODULE module = NULL;
  11042. static NTSTATUS(__stdcall *NtQueryInformationThread)(HANDLE ThreadHandle, THREADINFOCLASS ThreadInformationClass, PVOID ThreadInformation, ULONG ThreadInformationLength, PULONG ReturnLength);
  11043. if (module == NULL)
  11044. {
  11045. module = GetModuleHandleA("ntdll.dll");
  11046. NtQueryInformationThread = reinterpret_cast<decltype(NtQueryInformationThread)>(GetProcAddress(module, "NtQueryInformationThread"));
  11047. }
  11048. if (NtQueryInformationThread == NULL)
  11049. return 0;
  11050. NTSTATUS status = NtQueryInformationThread(mActiveThread->mHThread, (THREADINFOCLASS)0, &threadInfo, sizeof(threadInfo), nullptr);
  11051. if (status < 0)
  11052. return 0;
  11053. #ifdef BF_DBG_32
  11054. addr_target tibAddr = ReadMemory<addr_target>((intptr)threadInfo.mTebBaseAddress + 0x0);
  11055. addr_target tlsTable = ReadMemory<addr_target>((intptr)tibAddr + 0x2C);
  11056. #else
  11057. addr_target tlsTable = ReadMemory<addr_target>((intptr)threadInfo.mTebBaseAddress + 0x58);
  11058. #endif
  11059. return ReadMemory<addr_target>(tlsTable + tlsIndex * sizeof(addr_target));
  11060. }
  11061. bool WinDebugger::WriteInstructions(intptr address, void* src, uint64 length)
  11062. {
  11063. SIZE_T dwBytesWritten = 0;
  11064. bool result = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, src, (SIZE_T)length, &dwBytesWritten) != 0;
  11065. result |= ::FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, (SIZE_T)length) != 0;
  11066. BF_ASSERT(result);
  11067. BfLogDbg("WriteInstructions: %p %d\n", address, length);
  11068. return result;
  11069. }
  11070. DbgMemoryFlags WinDebugger::GetMemoryFlags(intptr address)
  11071. {
  11072. MEMORY_BASIC_INFORMATION memBasicInfo;
  11073. if (::VirtualQueryEx(mProcessInfo.hProcess, (void*)address, &memBasicInfo, sizeof(MEMORY_BASIC_INFORMATION)) == 0)
  11074. {
  11075. //BfLogDbg("VirtualQueryEx failed with %d\n", GetLastError());
  11076. return DbgMemoryFlags_None;
  11077. }
  11078. DbgMemoryFlags flags = DbgMemoryFlags_None;
  11079. if (memBasicInfo.AllocationProtect & PAGE_READWRITE)
  11080. {
  11081. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11082. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11083. }
  11084. if (memBasicInfo.AllocationProtect & PAGE_READONLY)
  11085. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11086. if (memBasicInfo.AllocationProtect & PAGE_WRITECOPY)
  11087. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11088. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE)
  11089. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11090. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_READ)
  11091. {
  11092. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11093. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11094. }
  11095. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_READWRITE)
  11096. {
  11097. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11098. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11099. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11100. }
  11101. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_WRITECOPY)
  11102. {
  11103. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11104. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11105. }
  11106. return flags;
  11107. }
  11108. #ifdef BF_DBG_32
  11109. Debugger* Beefy::CreateDebugger32(DebugManager* debugManager, DbgMiniDump* miniDump)
  11110. #else
  11111. Debugger* Beefy::CreateDebugger64(DebugManager* debugManager, DbgMiniDump* miniDump)
  11112. #endif
  11113. {
  11114. if (miniDump != NULL)
  11115. {
  11116. auto debugger = new MiniDumpDebugger(debugManager, miniDump);
  11117. return debugger;
  11118. }
  11119. return new WinDebugger(debugManager);
  11120. }
  11121. #ifdef BF_DBG_32
  11122. void WdAllocTest()
  11123. {
  11124. Array<BeefyDbg32::WdStackFrame*> stackFrameList;
  11125. for (int i = 0; true; i++)
  11126. {
  11127. WdStackFrame* stackFrame = new WdStackFrame();
  11128. stackFrameList.push_back(stackFrame);
  11129. }
  11130. }
  11131. #endif
  11132. #endif //!defined BF32 || !defined BF_DBG_64