WinDebugger.cpp 375 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891
  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, bool hotSwapEnabled)
  868. {
  869. BF_ASSERT(!mIsRunning);
  870. mLaunchPath = launchPath;
  871. mTargetPath = targetPath;
  872. mArgs = args;
  873. mWorkingDir = workingDir;
  874. mEnvBlock = envBlock;
  875. mHotSwapEnabled = hotSwapEnabled;
  876. mDebugTarget = new DebugTarget(this);
  877. }
  878. bool WinDebugger::Attach(int processId, BfDbgAttachFlags attachFlags)
  879. {
  880. BF_ASSERT(!mIsRunning);
  881. mDbgAttachFlags = attachFlags;
  882. mDbgProcessHandle = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)processId);
  883. if (mDbgProcessHandle == 0)
  884. return false;
  885. BOOL is32Bit = false;
  886. if (!IsWow64Process(mDbgProcessHandle, &is32Bit))
  887. {
  888. mDbgProcessHandle = 0;
  889. ::CloseHandle(mDbgProcessHandle);
  890. return false;
  891. }
  892. bool want32Bit = sizeof(intptr_target) == 4;
  893. if (want32Bit != (is32Bit != 0))
  894. {
  895. mDbgProcessHandle = 0;
  896. ::CloseHandle(mDbgProcessHandle);
  897. return false;
  898. }
  899. HMODULE mainModule = 0;
  900. DWORD memNeeded = 0;
  901. ::EnumProcessModules(mDbgProcessHandle, &mainModule, sizeof(HMODULE), &memNeeded);
  902. WCHAR fileName[MAX_PATH] = {0};
  903. GetModuleFileNameExW(mDbgProcessHandle, mainModule, fileName, MAX_PATH);
  904. mLaunchPath = UTF8Encode(fileName);
  905. mTargetPath = mLaunchPath;
  906. mDbgProcessId = processId;
  907. mDbgProcessHandle = 0;
  908. ::CloseHandle(mDbgProcessHandle);
  909. mDebugTarget = new DebugTarget(this);
  910. return true;
  911. }
  912. void WinDebugger::Run()
  913. {
  914. mIsRunning = true;
  915. DWORD localThreadId;
  916. HANDLE hThread = ::CreateThread(NULL, 64 * 1024, (LPTHREAD_START_ROUTINE) &DebugThreadProcThunk, (void*)this, 0, &localThreadId);
  917. CloseHandle(hThread);
  918. }
  919. void WinDebugger::HotLoad(const Array<String>& objectFiles, int hotIdx)
  920. {
  921. AutoCrit autoCrit(mDebugManager->mCritSect);
  922. if (mDebugTarget->mTargetBinary == NULL)
  923. {
  924. Fail("Hot swapping failed because the hot target binary has not yet been loaded.");
  925. return;
  926. }
  927. if (mDebugTarget->mHotHeap == NULL)
  928. {
  929. Fail("There is no hot heap space available for hot swapping.");
  930. return;
  931. }
  932. BfLogDbg("WinDebugger::HotLoad Start %d\n", hotIdx);
  933. SetAndRestoreValue<int> prevHotIdx(mActiveHotIdx, hotIdx);
  934. BF_ASSERT(mHotThreadStates.empty());
  935. mHotThreadStates.Resize(mThreadList.size());
  936. for (int threadIdx = 0; threadIdx < (int)mThreadList.size(); threadIdx++)
  937. {
  938. WdThreadInfo* threadInfo = mThreadList[threadIdx];
  939. SetAndRestoreValue<WdThreadInfo*> prevActiveThread(mActiveThread, threadInfo);
  940. BfLogDbg("SuspendThread %d\n", threadInfo->mThreadId);
  941. ::SuspendThread(threadInfo->mHThread);
  942. mHotThreadStates[threadIdx].mThreadId = threadInfo->mThreadId;
  943. PopulateRegisters(&mHotThreadStates[threadIdx].mRegisters);
  944. }
  945. for (auto address : mTempBreakpoint)
  946. RemoveBreakpoint(address);
  947. mTempBreakpoint.Clear();
  948. mStepBreakpointAddrs.Clear();
  949. for (auto breakpoint : mBreakpoints)
  950. {
  951. DetachBreakpoint(breakpoint);
  952. }
  953. int startingModuleIdx = (int)mDebugTarget->mDbgModules.size();
  954. bool failed = false;
  955. for (auto fileName : objectFiles)
  956. {
  957. BfLogDbg("WinDebugger::HotLoad: %s\n", fileName.c_str());
  958. DbgModule* newBinary = mDebugTarget->HotLoad(fileName, hotIdx);
  959. if ((newBinary != NULL) && (newBinary->mFailed))
  960. failed = true;
  961. }
  962. for (int moduleIdx = startingModuleIdx; moduleIdx < (int)mDebugTarget->mDbgModules.size(); moduleIdx++)
  963. {
  964. auto dbgModule = mDebugTarget->mDbgModules[moduleIdx];
  965. BF_ASSERT(dbgModule->IsObjectFile());
  966. BF_ASSERT(dbgModule->mHotIdx == hotIdx);
  967. dbgModule->FinishHotSwap();
  968. }
  969. for (auto dwarf : mDebugTarget->mDbgModules)
  970. dwarf->RevertWritingEnable();
  971. int blockAllocSinceClean = mDebugTarget->mHotHeap->mBlockAllocIdx - mDebugTarget->mLastHotHeapCleanIdx;
  972. // Clean up the hot heap every 64MB
  973. int blocksBetweenCleans = (64 * 1024 * 1024) / HotHeap::BLOCK_SIZE;
  974. #ifdef _DEBUG
  975. //TODO: This is just for testing
  976. blocksBetweenCleans = 1;
  977. #endif
  978. //TODO: Put this back after we fix the cleanup
  979. if (blockAllocSinceClean >= blocksBetweenCleans)
  980. CleanupHotHeap();
  981. mDebugTarget->RehupSrcFiles();
  982. for (int breakIdx = 0; breakIdx < (int)mBreakpoints.size(); breakIdx++)
  983. {
  984. auto breakpoint = mBreakpoints[breakIdx];
  985. CheckBreakpoint(breakpoint);
  986. }
  987. for (int hotThreadIdx = 0; hotThreadIdx < (int)mHotThreadStates.size(); hotThreadIdx++)
  988. {
  989. auto& hotThreadState = mHotThreadStates[hotThreadIdx];
  990. WdThreadInfo* threadInfo = NULL;
  991. if (!mThreadMap.TryGetValue((uint32)hotThreadState.mThreadId, &threadInfo))
  992. continue;
  993. BfLogDbg("ResumeThread %d\n", threadInfo->mThreadId);
  994. ::ResumeThread(threadInfo->mHThread);
  995. }
  996. mHotThreadStates.Clear();
  997. if (IsPaused())
  998. {
  999. ClearCallStack();
  1000. UpdateCallStack();
  1001. }
  1002. }
  1003. void WinDebugger::InitiateHotResolve(DbgHotResolveFlags flags)
  1004. {
  1005. AutoCrit autoCrit(mDebugManager->mCritSect);
  1006. delete mHotResolveData;
  1007. mHotResolveData = NULL;
  1008. mHotResolveData = new DbgHotResolveData();
  1009. DbgHotScanner* hotScanner = new DbgHotScanner(this);
  1010. hotScanner->Scan(flags);
  1011. delete hotScanner;
  1012. }
  1013. intptr WinDebugger::GetDbgAllocHeapSize()
  1014. {
  1015. if (mDbgHeapData == NULL)
  1016. {
  1017. Beefy::String memName = StrFormat("BFGC_stats_%d", mProcessInfo.dwProcessId);
  1018. mDbgHeapData = new WinDbgHeapData();
  1019. mDbgHeapData->mFileMapping = ::OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, memName.c_str());
  1020. if (mDbgHeapData->mFileMapping == 0)
  1021. {
  1022. delete mDbgHeapData;
  1023. mDbgHeapData = NULL;
  1024. return 0;
  1025. }
  1026. mDbgHeapData->mStats = (WinDbgHeapData::Stats*)MapViewOfFile(mDbgHeapData->mFileMapping, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(WinDbgHeapData::Stats));
  1027. }
  1028. if (mDbgHeapData->mStats == NULL)
  1029. return 0;
  1030. return mDbgHeapData->mStats->mHeapSize;
  1031. }
  1032. String WinDebugger::GetDbgAllocInfo()
  1033. {
  1034. AutoCrit autoCrit(mDebugManager->mCritSect);
  1035. for (auto threadInfo : mThreadList)
  1036. ::SuspendThread(threadInfo->mHThread);
  1037. delete mHotResolveData;
  1038. mHotResolveData = NULL;
  1039. mHotResolveData = new DbgHotResolveData();
  1040. DbgHotScanner* hotScanner = new DbgHotScanner(this);
  1041. hotScanner->Scan(DbgHotResolveFlag_Allocations);
  1042. delete hotScanner;
  1043. String result;
  1044. if (mHotResolveData != NULL)
  1045. {
  1046. DbgExprEvaluator exprEvaluator(this, NULL, NULL, -1, -1);
  1047. exprEvaluator.mDebugTarget = mDebugTarget;
  1048. String typeName;
  1049. result += ":types\n";
  1050. for (int typeId = 0; typeId < mHotResolveData->mTypeData.size(); typeId++)
  1051. {
  1052. auto& typeData = mHotResolveData->mTypeData[typeId];
  1053. if (typeData.mCount > 0)
  1054. {
  1055. auto type = exprEvaluator.GetBeefTypeById(typeId);
  1056. typeName.Clear();
  1057. exprEvaluator.BeefTypeToString(type, typeName);
  1058. if (typeName.IsEmpty())
  1059. typeName = StrFormat("Type #%d", typeId);
  1060. result += StrFormat("type\t%d\t%s\t%lld\t%lld\n", typeId, typeName.c_str(), typeData.mCount, typeData.mSize);
  1061. }
  1062. }
  1063. }
  1064. for (auto threadInfo : mThreadList)
  1065. ::ResumeThread(threadInfo->mHThread);
  1066. return result;
  1067. }
  1068. bool WinDebugger::DoOpenFile(const StringImpl& fileName, const StringImpl& args, const StringImpl& workingDir, const Array<uint8>& envBlock)
  1069. {
  1070. BP_ZONE("WinDebugger::DoOpenFile");
  1071. AutoCrit autoCrit(mDebugManager->mCritSect);
  1072. //gDbgPerfManager->StartRecording();
  1073. STARTUPINFOW si;
  1074. ZeroMemory(&si, sizeof(si));
  1075. si.cb = sizeof(si);
  1076. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  1077. if (mDbgProcessId != 0)
  1078. {
  1079. BOOL success = ::DebugActiveProcess(mDbgProcessId);
  1080. if (!success)
  1081. return false;
  1082. mProcessInfo.dwProcessId = mDbgProcessId;
  1083. }
  1084. else
  1085. {
  1086. BP_ZONE("DoOpenFile_CreateProcessW");
  1087. UTF16String envW;
  1088. DWORD flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS | CREATE_DEFAULT_ERROR_MODE;
  1089. void* envPtr = NULL;
  1090. if (!envBlock.IsEmpty())
  1091. {
  1092. //UTF16?
  1093. if (envBlock[1] == 0)
  1094. {
  1095. envPtr = (void*)&envBlock[0];
  1096. flags |= CREATE_UNICODE_ENVIRONMENT;
  1097. }
  1098. else
  1099. {
  1100. String str8((char*)&envBlock[0], (int)envBlock.size());
  1101. envW = UTF8Decode(str8);
  1102. envPtr = (void*)envW.c_str();
  1103. flags |= CREATE_UNICODE_ENVIRONMENT;
  1104. }
  1105. }
  1106. String cmdLine = "\"";
  1107. cmdLine += fileName;
  1108. cmdLine += "\"";
  1109. if (!args.IsEmpty())
  1110. {
  1111. cmdLine += " ";
  1112. cmdLine += args;
  1113. }
  1114. BOOL worked = CreateProcessW(NULL, (WCHAR*)UTF8Decode(cmdLine).c_str(), NULL, NULL, FALSE,
  1115. flags, envPtr, (WCHAR*)UTF8Decode(workingDir).c_str(), &si, &mProcessInfo);
  1116. if (!worked)
  1117. {
  1118. auto lastError = ::GetLastError();
  1119. if (lastError == ERROR_DIRECTORY)
  1120. {
  1121. mDebugManager->mOutMessages.push_back(StrFormat("error Unable to locate specified working directory '%s'", SlashString(workingDir, false, false).c_str()));
  1122. }
  1123. return false;
  1124. }
  1125. WdThreadInfo* threadInfo = new WdThreadInfo();
  1126. threadInfo->mProcessId = mProcessInfo.dwProcessId;
  1127. threadInfo->mThreadId = mProcessInfo.dwThreadId;
  1128. threadInfo->mHThread = mProcessInfo.hThread;
  1129. threadInfo->mThreadLocalBase = NULL;
  1130. threadInfo->mStartAddress = NULL;
  1131. mThreadMap[mProcessInfo.dwThreadId] = threadInfo;
  1132. mThreadList.push_back(threadInfo);
  1133. }
  1134. mRunState = RunState_Running;
  1135. while (true)
  1136. {
  1137. BP_ZONE("DoOpenFile_WaitForImageBase");
  1138. autoCrit.mCritSect->Unlock();
  1139. DoUpdate();
  1140. autoCrit.mCritSect->Lock();
  1141. ContinueDebugEvent();
  1142. if ((mDebugTarget->mLaunchBinary != NULL) && (mDebugTarget->mLaunchBinary->mOrigImageData != NULL))
  1143. break;
  1144. }
  1145. RehupBreakpoints(true);
  1146. //gDbgPerfManager->StopRecording();
  1147. //gDbgPerfManager->DbgPrint();
  1148. return true;
  1149. }
  1150. void WinDebugger::StopDebugging()
  1151. {
  1152. AutoCrit autoCrit(mDebugManager->mCritSect);
  1153. BfLogDbg("WinDebugger::Terminate\n");
  1154. if (mActiveSymSrvRequest != NULL)
  1155. mActiveSymSrvRequest->Cancel();
  1156. if ((mRunState == RunState_NotStarted) || (mRunState == RunState_Terminated) || (mRunState == RunState_Terminating))
  1157. return;
  1158. if ((mDbgProcessId != 0) && ((mDbgAttachFlags & BfDbgAttachFlag_ShutdownOnExit) == 0))
  1159. {
  1160. for (auto address : mTempBreakpoint)
  1161. RemoveBreakpoint(address);
  1162. for (auto breakpoint : mBreakpoints)
  1163. DetachBreakpoint(breakpoint);
  1164. BfLogDbg("StopDebugging\n");
  1165. ::DebugActiveProcessStop(mDbgProcessId);
  1166. mRunState = RunState_Terminated;
  1167. BfLogDbg("mRunState = RunState_Terminated\n");
  1168. }
  1169. else
  1170. {
  1171. TerminateProcess(mProcessInfo.hProcess, 0);
  1172. mRunState = RunState_Terminating;
  1173. BfLogDbg("mRunState = RunState_Terminating\n");
  1174. }
  1175. }
  1176. void WinDebugger::Terminate()
  1177. {
  1178. AutoCrit autoCrit(mDebugManager->mCritSect);
  1179. BfLogDbg("WinDebugger::Terminate\n");
  1180. if (mActiveSymSrvRequest != NULL)
  1181. mActiveSymSrvRequest->Cancel();
  1182. if ((mRunState == RunState_NotStarted) || (mRunState == RunState_Terminated) || (mRunState == RunState_Terminating))
  1183. return;
  1184. TerminateProcess(mProcessInfo.hProcess, 0);
  1185. mRunState = RunState_Terminating;
  1186. BfLogDbg("mRunState = RunState_Terminating\n");
  1187. }
  1188. static int gDebugUpdateCnt = 0;
  1189. void WinDebugger::Detach()
  1190. {
  1191. BfLogDbg("Debugger Detach\n");
  1192. mDebugManager->mNetManager->CancelAll();
  1193. while ((mIsRunning) || (mDebuggerThreadId != 0))
  1194. {
  1195. mShuttingDown = true;
  1196. Sleep(1);
  1197. }
  1198. for (auto profiler : mProfilerSet)
  1199. profiler->Stop();
  1200. BfLogDbg("Debugger Detach - thread finished\n");
  1201. mPendingProfilerMap.Clear();
  1202. for (auto profiler : mNewProfilerList)
  1203. delete profiler;
  1204. mNewProfilerList.Clear();
  1205. mPendingImageLoad.Clear();
  1206. mPendingDebugInfoLoad.Clear();
  1207. RemoveTempBreakpoints();
  1208. mContinueEvent.Reset();
  1209. if (mDebugTarget != mEmptyDebugTarget)
  1210. delete mDebugTarget;
  1211. mDebugTarget = mEmptyDebugTarget;
  1212. mShuttingDown = false;
  1213. mStepSP = 0;
  1214. ClearCallStack();
  1215. mRunState = RunState_NotStarted;
  1216. mStepType = StepType_None;
  1217. mHadImageFindError = false;
  1218. mIsPartialCallStack = true;
  1219. delete mDebugPendingExpr;
  1220. mDebugPendingExpr = NULL;
  1221. for (auto threadPair : mThreadMap)
  1222. {
  1223. auto threadInfo = threadPair.mValue;
  1224. delete threadInfo;
  1225. }
  1226. mThreadMap.Clear();
  1227. mThreadList.Clear();
  1228. mHotTargetMemory.Clear();
  1229. // We don't need to close the hThread when we have attached to a process
  1230. if (mDbgProcessId == 0)
  1231. {
  1232. CloseHandle(mProcessInfo.hThread);
  1233. CloseHandle(mProcessInfo.hProcess);
  1234. }
  1235. for (auto breakpoint : mBreakpoints)
  1236. {
  1237. if (!mDestroying)
  1238. {
  1239. BF_FATAL("Breakpoints should be deleted already");
  1240. }
  1241. if (breakpoint->mMemoryBreakpointInfo != NULL)
  1242. {
  1243. DetachBreakpoint(breakpoint);
  1244. }
  1245. }
  1246. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  1247. mStepBreakpointAddrs.Clear();
  1248. mIsRunning = false;
  1249. mDbgAttachFlags = BfDbgAttachFlag_None;
  1250. mDbgProcessId = 0;
  1251. delete mDbgHeapData;
  1252. mDbgHeapData = NULL;
  1253. mDbgProcessHandle = 0;
  1254. ClearCallStack();
  1255. mWantsDebugContinue = false;
  1256. mAtBreakThread = NULL;
  1257. mActiveThread = NULL;
  1258. mActiveBreakpoint = NULL;
  1259. mSteppingThread = NULL;
  1260. mExplicitStopThread = NULL;
  1261. mIsContinuingFromException = false;
  1262. mGotStartupEvent = false;
  1263. mIsDebuggerWaiting = false;
  1264. mPhysBreakpointAddrMap.Clear();
  1265. mBreakpointAddrMap.Clear();
  1266. gDebugUpdateCnt = 0;
  1267. }
  1268. Profiler* WinDebugger::StartProfiling()
  1269. {
  1270. return new DbgProfiler(this);
  1271. }
  1272. Profiler* WinDebugger::PopProfiler()
  1273. {
  1274. AutoCrit autoCrit(mDebugManager->mCritSect);
  1275. if (mNewProfilerList.IsEmpty())
  1276. return NULL;
  1277. auto profiler = (DbgProfiler*)mNewProfilerList[0];
  1278. mNewProfilerList.erase(mNewProfilerList.begin());
  1279. return profiler;
  1280. }
  1281. void WinDebugger::AddProfiler(DbgProfiler * profiler)
  1282. {
  1283. AutoCrit autoCrit(mDebugManager->mCritSect);
  1284. mProfilerSet.Add(profiler);
  1285. }
  1286. void WinDebugger::RemoveProfiler(DbgProfiler * profiler)
  1287. {
  1288. AutoCrit autoCrit(mDebugManager->mCritSect);
  1289. mProfilerSet.Remove(profiler);
  1290. }
  1291. void WinDebugger::ReportMemory(MemReporter* memReporter)
  1292. {
  1293. mEmptyDebugTarget->ReportMemory(memReporter);
  1294. if (mDebugTarget != mEmptyDebugTarget)
  1295. mDebugTarget->ReportMemory(memReporter);
  1296. }
  1297. void WinDebugger::ModuleChanged(DbgModule* dbgModule)
  1298. {
  1299. mDebugManager->mOutMessages.push_back(String("dbgInfoLoaded ") + dbgModule->mFilePath);
  1300. }
  1301. bool WinDebugger::DoUpdate()
  1302. {
  1303. if ((mDbgProcessId != 0) && ((mDbgAttachFlags & BfDbgAttachFlag_ShutdownOnExit) == 0))
  1304. ::DebugSetProcessKillOnExit(FALSE);
  1305. else
  1306. ::DebugSetProcessKillOnExit(TRUE);
  1307. //
  1308. {
  1309. AutoCrit autoCrit(mDebugManager->mCritSect);
  1310. auto _ModuleChanged = [&](DbgModule* dbgModule)
  1311. {
  1312. ModuleChanged(dbgModule);
  1313. ClearCallStack(); // We may have actual dbgSubprograms and stuff now...
  1314. };
  1315. for (auto dbgModule : mPendingImageLoad)
  1316. {
  1317. dbgModule->PreCacheImage();
  1318. }
  1319. for (auto kv : mPendingDebugInfoLoad)
  1320. {
  1321. kv.mKey->PreCacheDebugInfo();
  1322. }
  1323. while (!mPendingImageLoad.IsEmpty())
  1324. {
  1325. auto dbgModule = mPendingImageLoad.back();
  1326. mPendingImageLoad.pop_back();
  1327. dbgModule->RequestImage();
  1328. _ModuleChanged(dbgModule);
  1329. }
  1330. if (!mPendingDebugInfoLoad.IsEmpty())
  1331. {
  1332. Array<DbgPendingDebugInfoLoad> pendingList;
  1333. for (auto kv : mPendingDebugInfoLoad)
  1334. pendingList.Add(kv.mValue);
  1335. mPendingDebugInfoLoad.Clear();
  1336. for (auto& entry : pendingList)
  1337. {
  1338. auto dbgModule = entry.mModule;
  1339. entry.mModule->RequestDebugInfo(entry.mAllowRemote);
  1340. // We do a "_ModuleChanged" even if the load failed, so we rehup the callstack and stop
  1341. // saying "<Loading...>"
  1342. _ModuleChanged(entry.mModule);
  1343. }
  1344. }
  1345. }
  1346. if (IsMiniDumpDebugger())
  1347. {
  1348. //
  1349. {
  1350. AutoCrit autoCrit(mDebugManager->mCritSect);
  1351. if (mRunState == RunState_Terminating)
  1352. {
  1353. mRunState = RunState_Terminated;
  1354. return false;
  1355. }
  1356. }
  1357. Sleep(20);
  1358. return false;
  1359. }
  1360. if (mIsDebuggerWaiting)
  1361. {
  1362. if ((IsInRunState()) || (mRunState == RunState_Terminating) || (mRunState == RunState_DebugEval))
  1363. ContinueDebugEvent();
  1364. if (mContinueEvent.WaitFor(8))
  1365. {
  1366. BF_ASSERT(!mWantsDebugContinue); // mWantsDebugContinue should already been reset
  1367. BfLogDbg("::ContinueDebugEvent 1 ThreadId:%d\n", mDebuggerWaitingThread->mThreadId);
  1368. BF_ASSERT_REL(mDebuggerWaitingThread->mIsAtBreakpointAddress == 0);
  1369. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, mIsContinuingFromException ? DBG_EXCEPTION_NOT_HANDLED : DBG_CONTINUE);
  1370. mIsContinuingFromException = false;
  1371. mIsDebuggerWaiting = false;
  1372. mDebuggerWaitingThread = NULL;
  1373. }
  1374. else
  1375. return false;
  1376. }
  1377. if (!WaitForDebugEvent(&mDebugEvent, 8))
  1378. return false;
  1379. gDebugUpdateCnt++;
  1380. static const char* eventNames[] = { "DBG_EVENT ?",
  1381. "EXCEPTION_DEBUG_EVENT",
  1382. "CREATE_THREAD_DEBUG_EVENT",
  1383. "CREATE_PROCESS_DEBUG_EVENT",
  1384. "EXIT_THREAD_DEBUG_EVENT",
  1385. "EXIT_PROCESS_DEBUG_EVENT",
  1386. "LOAD_DLL_DEBUG_EVENT",
  1387. "UNLOAD_DLL_DEBUG_EVENT",
  1388. "OUTPUT_DEBUG_STRING_EVENT",
  1389. "RIP_EVENT"};
  1390. BfLogDbg("WaitForDebugEvent %s ThreadId:%d\n", eventNames[mDebugEvent.dwDebugEventCode], mDebugEvent.dwThreadId);
  1391. BP_ZONE(eventNames[mDebugEvent.dwDebugEventCode]);
  1392. AutoCrit autoCrit(mDebugManager->mCritSect);
  1393. mActiveBreakpoint = NULL;
  1394. mIsDebuggerWaiting = true;
  1395. mWantsDebugContinue = true;
  1396. mRequestedStackFrameIdx = 0;
  1397. mBreakStackFrameIdx = 0;
  1398. mShowPCOverride = 0;
  1399. WdThreadInfo* threadInfo = NULL;
  1400. mThreadMap.TryGetValue(mDebugEvent.dwThreadId, &threadInfo);
  1401. mDebuggerWaitingThread = threadInfo;
  1402. mExplicitStopThread = mDebuggerWaitingThread;
  1403. switch (mDebugEvent.dwDebugEventCode)
  1404. {
  1405. case CREATE_PROCESS_DEBUG_EVENT:
  1406. {
  1407. if (threadInfo == NULL)
  1408. {
  1409. BF_ASSERT(mThreadMap.size() == 0);
  1410. WdThreadInfo* newThreadInfo = new WdThreadInfo();
  1411. newThreadInfo->mProcessId = mDebugEvent.dwProcessId;
  1412. newThreadInfo->mThreadId = mDebugEvent.dwThreadId;
  1413. newThreadInfo->mHThread = mDebugEvent.u.CreateProcessInfo.hThread;
  1414. newThreadInfo->mThreadLocalBase = mDebugEvent.u.CreateProcessInfo.lpThreadLocalBase;
  1415. newThreadInfo->mStartAddress = (void*)mDebugEvent.u.CreateProcessInfo.lpStartAddress;
  1416. BF_CONTEXT lcContext;
  1417. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1418. BF_GetThreadContext(newThreadInfo->mHThread, &lcContext);
  1419. newThreadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1420. mThreadMap[mDebugEvent.dwThreadId] = newThreadInfo;
  1421. mDebuggerWaitingThread = newThreadInfo;
  1422. mThreadList.push_back(mDebuggerWaitingThread);
  1423. UpdateThreadDebugRegisters();
  1424. OutputMessage(StrFormat("Creating thread from CREATE_PROCESS_DEBUG_EVENT %d\n", mDebugEvent.dwThreadId));
  1425. threadInfo = mDebuggerWaitingThread;
  1426. mProcessInfo.dwThreadId = threadInfo->mThreadId;
  1427. mProcessInfo.hThread = threadInfo->mHThread;
  1428. mProcessInfo.hProcess = mDebugEvent.u.CreateProcessInfo.hProcess;
  1429. }
  1430. else
  1431. {
  1432. threadInfo->mThreadLocalBase = mDebugEvent.u.CreateProcessInfo.lpThreadLocalBase;
  1433. threadInfo->mStartAddress = (void*)mDebugEvent.u.CreateProcessInfo.lpStartAddress;
  1434. }
  1435. BF_CONTEXT lcContext;
  1436. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1437. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1438. threadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1439. DbgModule* launchBinary = mDebugTarget->Init(mLaunchPath, mTargetPath, (addr_target)(intptr)mDebugEvent.u.CreateProcessInfo.lpBaseOfImage);
  1440. addr_target gotImageBase = (addr_target)(intptr)mDebugEvent.u.CreateProcessInfo.lpBaseOfImage;
  1441. if (launchBinary->mImageBase != gotImageBase)
  1442. {
  1443. BF_FATAL("Image base didn't match");
  1444. }
  1445. launchBinary->mImageBase = gotImageBase;
  1446. launchBinary->mImageSize = (int)launchBinary->GetImageSize();
  1447. launchBinary->mOrigImageData = new DbgModuleMemoryCache(launchBinary->mImageBase, launchBinary->mImageSize);
  1448. if (launchBinary == mDebugTarget->mTargetBinary)
  1449. mDebugTarget->SetupTargetBinary();
  1450. if (mDebugEvent.u.CreateProcessInfo.hFile != NULL)
  1451. CloseHandle(mDebugEvent.u.CreateProcessInfo.hFile);
  1452. mDbgProcessHandle = mDebugEvent.u.CreateProcessInfo.hProcess;
  1453. mDbgThreadHandle = mDebugEvent.u.CreateProcessInfo.hThread;
  1454. mGotStartupEvent = true;
  1455. mDebugManager->mOutMessages.push_back("modulesChanged");
  1456. }
  1457. break;
  1458. case EXIT_PROCESS_DEBUG_EVENT:
  1459. {
  1460. BfLogDbg("EXIT_PROCESS_DEBUG_EVENT\n");
  1461. DWORD exitCode = mDebugEvent.u.ExitProcess.dwExitCode;
  1462. String exitMessage;
  1463. switch (exitCode)
  1464. {
  1465. case STATUS_DLL_NOT_FOUND:
  1466. exitMessage = "STATUS_DLL_NOT_FOUND";
  1467. break;
  1468. case STATUS_DLL_INIT_FAILED:
  1469. exitMessage = "STATUS_DLL_INIT_FAILED";
  1470. break;
  1471. case STATUS_ENTRYPOINT_NOT_FOUND:
  1472. exitMessage = "STATUS_ENTRYPOINT_NOT_FOUND";
  1473. break;
  1474. }
  1475. String exitCodeStr;
  1476. if ((exitCode >= 0x10000000) && (exitCode <= 0xF7000000))
  1477. exitCodeStr = StrFormat("0x%X", exitCode);
  1478. else
  1479. exitCodeStr = StrFormat("%d", exitCode);
  1480. if (!exitMessage.IsEmpty())
  1481. OutputMessage(StrFormat("Process terminated. ExitCode: %s (%s).\n", exitCodeStr.c_str(), exitMessage.c_str()));
  1482. else
  1483. OutputMessage(StrFormat("Process terminated. ExitCode: %s.\n", exitCodeStr.c_str()));
  1484. mRunState = RunState_Terminated;
  1485. mDebugManager->mOutMessages.push_back("modulesChanged");
  1486. }
  1487. break;
  1488. case LOAD_DLL_DEBUG_EVENT:
  1489. {
  1490. WCHAR moduleNameStr[MAX_PATH] = { 0 };
  1491. GetFinalPathNameByHandleW(mDebugEvent.u.LoadDll.hFile, moduleNameStr, MAX_PATH, FILE_NAME_NORMALIZED);
  1492. std::wstring wow64Dir;
  1493. std::wstring systemDir;
  1494. PWSTR wow64DirPtr = NULL;
  1495. SHGetKnownFolderPath(FOLDERID_SystemX86, KF_FLAG_NO_ALIAS, NULL, &wow64DirPtr);
  1496. if (wow64DirPtr != NULL)
  1497. {
  1498. wow64Dir = wow64DirPtr;
  1499. CoTaskMemFree(wow64DirPtr);
  1500. }
  1501. PWSTR systemDirPtr = NULL;
  1502. SHGetKnownFolderPath(FOLDERID_System, KF_FLAG_NO_ALIAS, NULL, &systemDirPtr);
  1503. if (systemDirPtr != NULL)
  1504. {
  1505. systemDir = systemDirPtr;
  1506. CoTaskMemFree(systemDirPtr);
  1507. }
  1508. if ((mDebugEvent.u.LoadDll.lpImageName != 0) && (mDebugEvent.u.LoadDll.fUnicode))
  1509. {
  1510. addr_target strAddr = ReadMemory<addr_target>((addr_target)(intptr)mDebugEvent.u.LoadDll.lpImageName);
  1511. for (int i = 0; i < MAX_PATH - 1; i++)
  1512. {
  1513. WCHAR c = ReadMemory<WCHAR>(strAddr + i*2);
  1514. moduleNameStr[i] = (WCHAR)c;
  1515. if (c == 0)
  1516. break;
  1517. }
  1518. }
  1519. String origModuleName = UTF8Encode(moduleNameStr);
  1520. String moduleName = origModuleName;
  1521. String loadMsg;
  1522. HANDLE altFileHandle = INVALID_HANDLE_VALUE;
  1523. if (moduleName != origModuleName)
  1524. {
  1525. loadMsg = StrFormat("Loading DLL: %s(%s) @ %s", origModuleName.c_str(), moduleName.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.LoadDll.lpBaseOfDll, true).c_str());
  1526. altFileHandle = ::CreateFileW(UTF8Decode(moduleName).c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  1527. }
  1528. else
  1529. {
  1530. loadMsg = StrFormat("Loading DLL: %s @ %s", moduleName.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.LoadDll.lpBaseOfDll, true).c_str());
  1531. }
  1532. BfLogDbg("LOAD_DLL_DEBUG_EVENT %s\n", moduleName.c_str());
  1533. bool skipLoad = false;
  1534. #ifdef BF_DBG_32
  1535. if (((uintptr)mDebugEvent.u.LoadDll.lpBaseOfDll & 0xFFFFFFFF00000000LL) != 0)
  1536. {
  1537. skipLoad = true;
  1538. loadMsg += " - Skipped";
  1539. }
  1540. #endif
  1541. if (!skipLoad)
  1542. {
  1543. FileHandleStream stream;
  1544. stream.mFileHandle = mDebugEvent.u.LoadDll.hFile;
  1545. if (altFileHandle != INVALID_HANDLE_VALUE)
  1546. stream.mFileHandle = altFileHandle;
  1547. if (mDebugTarget->SetupDyn(moduleName, &stream, (intptr)mDebugEvent.u.LoadDll.lpBaseOfDll) == NULL)
  1548. loadMsg += " - Failed to load";
  1549. stream.mFileHandle = 0;
  1550. }
  1551. OutputMessage(loadMsg + "\n");
  1552. if (altFileHandle != INVALID_HANDLE_VALUE)
  1553. ::CloseHandle(altFileHandle);
  1554. ::CloseHandle(mDebugEvent.u.LoadDll.hFile);
  1555. // Try to bind any breakpoints tied to this DLL
  1556. RehupBreakpoints(true);
  1557. mDebugManager->mOutMessages.push_back("modulesChanged");
  1558. }
  1559. break;
  1560. case UNLOAD_DLL_DEBUG_EVENT:
  1561. {
  1562. bool needsBreakpointRehup = false;
  1563. String name = "???";
  1564. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress((addr_target)(intptr)mDebugEvent.u.UnloadDll.lpBaseOfDll);
  1565. if (dbgModule != NULL)
  1566. {
  1567. name = dbgModule->mFilePath;
  1568. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  1569. {
  1570. auto breakpoint = mBreakpoints[i];
  1571. auto checkBreakpoint = breakpoint;
  1572. bool hasAddr = false;
  1573. while (checkBreakpoint != NULL)
  1574. {
  1575. if ((checkBreakpoint->mAddr >= dbgModule->mImageBase) && (checkBreakpoint->mAddr < dbgModule->mImageBase + dbgModule->mImageSize))
  1576. hasAddr = true;
  1577. checkBreakpoint = (WdBreakpoint*)checkBreakpoint->mLinkedSibling;
  1578. }
  1579. if (hasAddr)
  1580. {
  1581. DetachBreakpoint(breakpoint);
  1582. needsBreakpointRehup = true;
  1583. }
  1584. }
  1585. mDebugTarget->UnloadDyn(dbgModule->mImageBase);
  1586. if (needsBreakpointRehup)
  1587. RehupBreakpoints(true);
  1588. mPendingDebugInfoLoad.Remove(dbgModule);
  1589. mPendingDebugInfoRequests.Remove(dbgModule);
  1590. mDebugManager->mOutMessages.push_back("modulesChanged");
  1591. }
  1592. if (!name.empty())
  1593. OutputMessage(StrFormat("Unloading DLL: %s @ %0s\n", name.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.UnloadDll.lpBaseOfDll, true).c_str()));
  1594. BfLogDbg("UNLOAD_DLL_DEBUG_EVENT %s\n", name.c_str());
  1595. }
  1596. break;
  1597. case OUTPUT_DEBUG_STRING_EVENT:
  1598. {
  1599. const int maxChars = 1024 * 1024;
  1600. int len = BF_MIN(maxChars, (int)mDebugEvent.u.DebugString.nDebugStringLength); // 1MB max
  1601. char* message = new char[len + 1];
  1602. message[0] = 0;
  1603. message[len] = 0;
  1604. ReadMemory((addr_target)(intptr)mDebugEvent.u.DebugString.lpDebugStringData, len, message);
  1605. if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId == mDebugEvalThreadInfo.mThreadId))
  1606. mDebugManager->mOutMessages.push_back(String("dbgEvalMsg ") + message);
  1607. else
  1608. mDebugManager->mOutMessages.push_back(String("msg ") + message);
  1609. BfLogDbg("OUTPUT_DEBUG_STRING_EVENT (BreakAddr:%@): %s\n", threadInfo->mIsAtBreakpointAddress, message);
  1610. BF_ASSERT_REL(threadInfo->mIsAtBreakpointAddress == 0);
  1611. delete [] message;
  1612. }
  1613. break;
  1614. case CREATE_THREAD_DEBUG_EVENT:
  1615. {
  1616. WdThreadInfo* threadInfo = new WdThreadInfo();
  1617. threadInfo->mProcessId = mDebugEvent.dwProcessId;
  1618. threadInfo->mThreadId = mDebugEvent.dwThreadId;
  1619. threadInfo->mHThread = mDebugEvent.u.CreateThread.hThread;
  1620. threadInfo->mThreadLocalBase = mDebugEvent.u.CreateThread.lpThreadLocalBase;
  1621. threadInfo->mStartAddress = (void*)mDebugEvent.u.CreateThread.lpStartAddress;
  1622. BF_CONTEXT lcContext;
  1623. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1624. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1625. threadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1626. mThreadMap[mDebugEvent.dwThreadId] = threadInfo;
  1627. mDebuggerWaitingThread = threadInfo;
  1628. mThreadList.push_back(mDebuggerWaitingThread);
  1629. UpdateThreadDebugRegisters();
  1630. OutputMessage(StrFormat("Creating thread %d\n", mDebugEvent.dwThreadId));
  1631. }
  1632. break;
  1633. case EXIT_THREAD_DEBUG_EVENT:
  1634. {
  1635. OutputMessage(StrFormat("Exiting thread %d\n", mDebugEvent.dwThreadId));
  1636. if (mSteppingThread == threadInfo)
  1637. {
  1638. // We were attempting stepping on this thread, but not anymore!
  1639. ClearStep();
  1640. }
  1641. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_CONTINUE);
  1642. mIsDebuggerWaiting = false;
  1643. mWantsDebugContinue = false;
  1644. if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId == mDebugEvalThreadInfo.mThreadId))
  1645. {
  1646. // Thread terminated while evaluating! Is there a more graceful way of handling this?
  1647. CleanupDebugEval(false);
  1648. mRunState = RunState_Running;
  1649. }
  1650. mThreadList.Remove(mDebuggerWaitingThread);
  1651. delete mDebuggerWaitingThread;
  1652. mDebuggerWaitingThread = NULL;
  1653. mThreadMap.Remove(mDebugEvent.dwThreadId);
  1654. return true;
  1655. }
  1656. break;
  1657. case RIP_EVENT:
  1658. OutputMessage("RIP Event\n");
  1659. break;
  1660. case EXCEPTION_DEBUG_EVENT:
  1661. {
  1662. auto exceptionRecord = &mDebugEvent.u.Exception.ExceptionRecord;
  1663. switch (exceptionRecord->ExceptionCode)
  1664. {
  1665. case STATUS_WX86_BREAKPOINT:
  1666. case EXCEPTION_BREAKPOINT:
  1667. {
  1668. if (mRunState == RunState_Terminating)
  1669. {
  1670. BfLogDbg("Ignoring event because of RunState_Terminating\n");
  1671. break;
  1672. }
  1673. mAtBreakThread = threadInfo;
  1674. mActiveThread = mAtBreakThread;
  1675. bool isHighAddr = false;
  1676. #ifdef BF_DBG_32
  1677. if (((uintptr)exceptionRecord->ExceptionAddress & 0xFFFFFFFF00000000) != 0)
  1678. {
  1679. if (mActiveThread == mThreadList.front())
  1680. {
  1681. // Skip the initial Wow64 ntdll.dll!LdrpDoDebuggerBreak
  1682. mRunState = RunState_Running;
  1683. break;
  1684. }
  1685. isHighAddr = true;
  1686. }
  1687. #endif
  1688. addr_target pcAddress = (addr_target)(intptr)exceptionRecord->ExceptionAddress;
  1689. if (isHighAddr)
  1690. pcAddress = (addr_target)-1;
  1691. //mStoppedAtAddress = pcAddress;
  1692. bool isStepOut = false;
  1693. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto))
  1694. {
  1695. isStepOut = mStepBreakpointAddrs.Contains(pcAddress);
  1696. }
  1697. BF_CONTEXT lcContext;
  1698. lcContext.ContextFlags = BF_CONTEXT_ALL;
  1699. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1700. BfLogDbg("EXCEPTION_BREAKPOINT Thread:%d %p SP:%p\n", mActiveThread->mThreadId, pcAddress, BF_CONTEXT_SP(lcContext));
  1701. uint8 origImageData = 0xCC;
  1702. mDebugTarget->ReadOrigImageData(pcAddress, &origImageData, 1);
  1703. bool wasDebugBreakpoint = origImageData != 0xCC;
  1704. DbgSubprogram* dwSubprogram = NULL;
  1705. DbgLineData* dwLineData = NULL;
  1706. if (!isStepOut)
  1707. {
  1708. dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  1709. if (dwSubprogram == NULL)
  1710. dwSubprogram = mDebugTarget->FindSubProgram(pcAddress, DbgOnDemandKind_LocalOnly);
  1711. }
  1712. bool isLineStart = (dwLineData != NULL) && (dwSubprogram->GetLineAddr(*dwLineData) == pcAddress);
  1713. bool isNonDebuggerBreak = false;
  1714. if (wasDebugBreakpoint)
  1715. {
  1716. // Go ahead and set EIP back one instruction
  1717. BF_CONTEXT_IP(lcContext)--;
  1718. BF_SetThreadContext(threadInfo->mHThread, &lcContext);
  1719. if ((dwSubprogram != NULL) && (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid) &&
  1720. (pcAddress == dwSubprogram->mBlock.mLowPC))
  1721. {
  1722. BfLogDbg("Hit HotReplaceKind_Invalid breakpoint\n");
  1723. mRunState = RunState_Paused;
  1724. mDebugManager->mOutMessages.push_back("error This lambda was replaced by a new version that has incompatible captures. A program restart is required.");
  1725. PhysRemoveBreakpoint(pcAddress);
  1726. break;
  1727. }
  1728. }
  1729. else
  1730. {
  1731. // This was an actual "break" instruction
  1732. BfLogDbg("Non-debugger break\n");
  1733. isNonDebuggerBreak = true;
  1734. auto prevState = mRunState;
  1735. // Make it an "auto" stop, so for example when we have an assert/retry we won't stop inside assembly
  1736. mRequestedStackFrameIdx = -2;
  1737. mRunState = RunState_Paused;
  1738. CheckNonDebuggerBreak();
  1739. if (IsInRunState())
  1740. {
  1741. BF_ASSERT((prevState == RunState_Running) || (prevState == RunState_DebugEval));
  1742. mRunState = prevState;
  1743. break; // Continue as if nothing happened
  1744. }
  1745. if (prevState == RunState_DebugEval)
  1746. mRequestedStackFrameIdx = -1; // Don't show a rolled back stack idx if a debug eval fails
  1747. ClearStep();
  1748. }
  1749. if (threadInfo->mIsBreakRestorePaused)
  1750. {
  1751. // The thread is supposed to be paused, but the IP has been reset
  1752. // so just break here so we'll hit that breakpoint again once we're
  1753. // actually unpaused properly
  1754. BfLogDbg("Ignoring EXCEPTION_BREAKPOINT\n", threadInfo->mThreadId);
  1755. break;
  1756. }
  1757. if ((mRunState == RunState_DebugEval) || (mRunState == RunState_HotStep))
  1758. {
  1759. // If we hit a breakpoint while doing a debug eval, we just remove the breakpoint
  1760. // and expect to reinstate it during a rehup after the evaluation has completed
  1761. WdBreakpoint* breakpoint = (WdBreakpoint*)FindBreakpointAt((uintptr_t) exceptionRecord->ExceptionAddress);
  1762. if (breakpoint != NULL)
  1763. {
  1764. mNeedsRehupBreakpoints = true;
  1765. RemoveBreakpoint(breakpoint->mLineData.GetAddress());
  1766. }
  1767. break;
  1768. }
  1769. bool isDeeper = false;
  1770. int stepBreakAddrIdx = (int)mStepBreakpointAddrs.IndexOf(pcAddress);
  1771. WdBreakpoint* breakpoint = NULL;
  1772. bool ignoreBreakpoint = false;
  1773. if ((mStepType != StepType_None) && (mSteppingThread == mAtBreakThread))
  1774. {
  1775. if (mStepType == StepType_ToTempBreakpoint)
  1776. {
  1777. RemoveTempBreakpoints();
  1778. mRunState = RunState_Paused;
  1779. break;
  1780. }
  1781. if (mContinueFromBreakpointFailed)
  1782. {
  1783. BfLogDbg("Continuing from ContinueFromBreakpointFailed\n");
  1784. SetupStep(mStepType);
  1785. mRunState = RunState_Running;
  1786. break;
  1787. }
  1788. if (!isStepOut)
  1789. breakpoint = (WdBreakpoint*)FindBreakpointAt(pcAddress);
  1790. // Ignore breakpoint if it's on the line we're stepping off of
  1791. if ((breakpoint != NULL) && (breakpoint->mAddr == mStepPC) &&
  1792. (mStepSP == BF_CONTEXT_SP(lcContext)))
  1793. {
  1794. ignoreBreakpoint = true;
  1795. }
  1796. else if ((breakpoint != NULL) && (stepBreakAddrIdx == -1) && (!CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress)))
  1797. {
  1798. ignoreBreakpoint = true;
  1799. }
  1800. if ((stepBreakAddrIdx == -1) && (breakpoint == NULL) && (!isNonDebuggerBreak))
  1801. {
  1802. // If a breakpoint is removed in a prior thread
  1803. BfLogDbg("Ignoring step break (old breakpoint)\n");
  1804. if ((mSteppingThread == mAtBreakThread) && (mStepSwitchedThreads))
  1805. {
  1806. SetupStep(mStepType);
  1807. }
  1808. break;
  1809. }
  1810. if ((stepBreakAddrIdx != -1) && (breakpoint == NULL) && (mSteppingThread != mActiveThread))
  1811. {
  1812. BfLogDbg("Ignoring break (wrong thread)\n");
  1813. ThreadRestorePause(mSteppingThread, mActiveThread);
  1814. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1815. break;
  1816. }
  1817. isDeeper = mStepSP > BF_CONTEXT_SP(lcContext);
  1818. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto))
  1819. {
  1820. isDeeper = mStepSP >= BF_CONTEXT_SP(lcContext);
  1821. BfLogDbg("StepOut Iteration SP:%p StartSP:%p IsDeeper:%d\n", BF_CONTEXT_SP(lcContext), mStepSP, isDeeper);
  1822. }
  1823. if (((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto)) && (breakpoint == NULL) && (isDeeper))
  1824. {
  1825. // We're encountered recursion
  1826. // Make sure we don't already have one of these stored
  1827. BF_ASSERT(mStoredReturnValueAddr == 0);
  1828. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1829. break; // Don't fall through, we don't want to set mIsAtBreakpointAddress
  1830. }
  1831. if (isStepOut)
  1832. {
  1833. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1834. if (mStepType == StepType_StepOut_ThenInto)
  1835. {
  1836. dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  1837. if ((dwLineData != NULL) && (pcAddress == dwSubprogram->GetLineAddr(*dwLineData)))
  1838. {
  1839. // Our step out from a filtered function put us at the start of a new line. Stop here
  1840. // <do nothing>
  1841. }
  1842. else
  1843. {
  1844. // .. otherwise keep going until we get to the start of a new line
  1845. SetupStep(StepType_StepInto);
  1846. mRunState = RunState_Running;
  1847. break;
  1848. }
  1849. }
  1850. if (!mStepInAssembly)
  1851. {
  1852. // Keep stepping out until we find a frame that we have source for
  1853. DbgSubprogram* dwSubprogram = NULL;
  1854. DbgLineData* dwLineData = FindLineDataAtAddress(BF_CONTEXT_IP(lcContext), &dwSubprogram);
  1855. if (dwLineData == NULL)
  1856. {
  1857. SetupStep(StepType_StepOut);
  1858. break;
  1859. }
  1860. if ((dwLineData->mColumn == -1) && (!dwSubprogram->HasValidLines()))
  1861. {
  1862. // This is a method we don't actually want to be in, it has no valid lines!
  1863. SetupStep(StepType_StepOut);
  1864. break;
  1865. }
  1866. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  1867. {
  1868. // We've stepped out, but right into the start of an inlined method, so step out of this inlined method now...
  1869. SetupStep(StepType_StepOut);
  1870. break;
  1871. }
  1872. }
  1873. ClearStep();
  1874. mRunState = RunState_Paused;
  1875. threadInfo->mStoppedAtAddress = pcAddress;
  1876. break;
  1877. }
  1878. mRunState = RunState_Paused;
  1879. if (breakpoint != NULL)
  1880. {
  1881. // While stepping we hit a legit breakpoint
  1882. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  1883. // Ignore breakpoint on return statement if we're return-stepping
  1884. mRunState = RunState_Breakpoint;
  1885. }
  1886. if ((mStepType == StepType_StepInto) && (dwSubprogram != NULL))
  1887. {
  1888. // Don't filter out the current subprogram (would break cases where we explicitly stepped into or hit breakpoint in a filtered subprogram)
  1889. bool isInStartSubprogram = (mStepStartPC >= dwSubprogram->mBlock.mLowPC) && (mStepStartPC < dwSubprogram->mBlock.mHighPC);
  1890. if ((!isInStartSubprogram) && (IsStepFiltered(dwSubprogram, dwLineData)))
  1891. {
  1892. BfLogDbg("Hit step filter\n");
  1893. mRunState = RunState_Running;
  1894. SetupStep(StepType_StepOut_ThenInto);
  1895. break;
  1896. }
  1897. }
  1898. if ((mStepType == StepType_StepOver) && (stepBreakAddrIdx == 0) && (mStepBreakpointAddrs[0] != 0) && (mStepBreakpointAddrs.size() > 1))
  1899. {
  1900. // Break was on the 'call' instruction, not the instruction after it -- means recursion
  1901. BfLogDbg("StepOver detected recursing\n");
  1902. mStepIsRecursing = true;
  1903. if (mTempBreakpoint.Remove(mStepBreakpointAddrs[0]))
  1904. {
  1905. RemoveBreakpoint(mStepBreakpointAddrs[0]);
  1906. }
  1907. mStepBreakpointAddrs[0] = 0;
  1908. mRunState = RunState_Running;
  1909. break;
  1910. }
  1911. if ((mStepType == StepType_StepOver) && (stepBreakAddrIdx > 0) && (mStepBreakpointAddrs[0] != 0) && (isDeeper))
  1912. {
  1913. // This is the first time we've hit the target breakpoint.
  1914. if (HasSteppedIntoCall())
  1915. {
  1916. mStepIsRecursing = true;
  1917. RemoveBreakpoint(mStepBreakpointAddrs[0]);
  1918. mStepBreakpointAddrs[0] = 0;
  1919. //mStepBreakpointAddrs.erase(mStepBreakpointAddrs.begin());
  1920. }
  1921. }
  1922. if ((mStepType == StepType_StepOver) && (mStepIsRecursing) && (stepBreakAddrIdx != -1) && (isDeeper))
  1923. {
  1924. // Decrement so the equality test on "step out" marks us as not being deeper when we
  1925. // hit the expected SP
  1926. BfLogDbg("Converting StepOver to StepOut\n");
  1927. mStepSP--;
  1928. mStepType = StepType_StepOut_ThenInto;
  1929. //SetupStep(StepType_StepOut);
  1930. mRunState = RunState_Running;
  1931. break;
  1932. }
  1933. if ((mStepType == StepType_StepOver) && (!ignoreBreakpoint) && (breakpoint == NULL) && (!mStepInAssembly))
  1934. {
  1935. // Test for stepping over inline method
  1936. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  1937. // mTempBreakpoints will have 2 entries if we are on a 'call' line. If we have an inlined call immediately following a call, then we
  1938. // assume we're hitting a return break
  1939. /*if ((dwSubprogram != NULL) && (dwSubprogram->mInlineParent != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC) && (mTempBreakpoint.size() < 2))
  1940. {
  1941. BfLogDbg("Attempting StepOver of inlined method\n");
  1942. SetupStep(StepType_StepOut);
  1943. mRunState = RunState_Running;
  1944. break;
  1945. } */
  1946. //TODO: The previous logic with the "(mTempBreakpoint.size() < 2)" was causing Try!(Method()); stepovers to enter into Try!. What did we mean by
  1947. // "assume we're hitting a return break"?
  1948. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  1949. {
  1950. RemoveTempBreakpoints();
  1951. BfLogDbg("Attempting StepOver of inlined method\n");
  1952. SetupStep(StepType_StepOut);
  1953. mRunState = RunState_Running;
  1954. break;
  1955. }
  1956. }
  1957. if (mStepType == StepType_StepOut_Inline)
  1958. {
  1959. if (mOrigStepType == StepType_StepOver)
  1960. {
  1961. // For the step over, if we are still inside the source line after an inline then step over again...
  1962. DbgSubprogram* origSubprogram = NULL;
  1963. auto origLineData = FindLineDataAtAddress(mStepStartPC, &origSubprogram);
  1964. DbgSubprogram* curSubprogram = NULL;
  1965. auto curLineData = FindLineDataAtAddress(pcAddress, &curSubprogram);
  1966. if ((origLineData != NULL) &&
  1967. ((origLineData == curLineData) ||
  1968. ((origSubprogram == curSubprogram) && (origLineData->mLine == curLineData->mLine))))
  1969. {
  1970. mRunState = RunState_Running;
  1971. SetupStep(StepType_StepOver);
  1972. break;
  1973. }
  1974. }
  1975. ClearStep();
  1976. break;
  1977. }
  1978. if ((mStepType != StepType_None) && (ignoreBreakpoint) && (!mStepInAssembly) && (stepBreakAddrIdx == -1))
  1979. {
  1980. // Ignore breakpoint by just continuing...
  1981. mRunState = RunState_Running;
  1982. break;
  1983. }
  1984. RemoveTempBreakpoints();
  1985. if ((mStepType != StepType_None) && (!mStepInAssembly) && (!isLineStart) && (stepBreakAddrIdx != -1))
  1986. {
  1987. SetupStep(mStepType);
  1988. mRunState = RunState_Running;
  1989. }
  1990. else
  1991. {
  1992. //if (mStepType != StepType_Return)
  1993. if (stepBreakAddrIdx != -1)
  1994. {
  1995. // Even if we've detected we're at a breakpoint, we mark ourselves as just stepping if we also
  1996. // have a step breakpoint here
  1997. StepLineTryPause(pcAddress, true);
  1998. }
  1999. if (mRunState == RunState_Paused)
  2000. ClearStep();
  2001. }
  2002. if (ignoreBreakpoint)
  2003. {
  2004. SetupStep(mStepType);
  2005. mRunState = RunState_Running;
  2006. }
  2007. if ((mRunState == RunState_Paused) && (breakpoint != NULL))
  2008. {
  2009. // Just do the 'check' here so we can do the logging/condition stuff
  2010. CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress);
  2011. }
  2012. }
  2013. else
  2014. {
  2015. breakpoint = (WdBreakpoint*)FindBreakpointAt((uintptr_t)exceptionRecord->ExceptionAddress);
  2016. if ((breakpoint != NULL) && (!CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress)))
  2017. {
  2018. ClearCallStack();
  2019. BfLogDbg("Skipping conditional breakpoint. Setting mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  2020. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  2021. mRunState = RunState_Running;
  2022. break;
  2023. }
  2024. if (breakpoint != NULL)
  2025. {
  2026. BfLogDbg("Breakpoint hit. mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  2027. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  2028. mRunState = RunState_Breakpoint;
  2029. }
  2030. else if ((stepBreakAddrIdx != -1) || (isNonDebuggerBreak))
  2031. {
  2032. if (mRunState != RunState_DebugEval)
  2033. {
  2034. // Was in mStepBreakpointAddrs list
  2035. if ((isNonDebuggerBreak) || (mStepType == StepType_None) || (mSteppingThread == mAtBreakThread))
  2036. {
  2037. BfLogDbg("Hit mStepBreakpointAddrs breakpoint\n");
  2038. mRunState = RunState_Paused;
  2039. }
  2040. else
  2041. {
  2042. BfLogDbg("Ignored mStepBreakpointAddrs breakpoint (wrong thread)\n");
  2043. mRunState = RunState_Running;
  2044. }
  2045. }
  2046. }
  2047. else
  2048. {
  2049. BfLogDbg("Ignoring break (old or ignored breakpoint)\n");
  2050. mRunState = RunState_Running;
  2051. }
  2052. }
  2053. if ((breakpoint != NULL) && (!ignoreBreakpoint))
  2054. {
  2055. mActiveBreakpoint = breakpoint;
  2056. mBreakStackFrameIdx = -1;
  2057. }
  2058. if ((mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint))
  2059. threadInfo->mStoppedAtAddress = pcAddress;
  2060. }
  2061. break;
  2062. case STATUS_WX86_SINGLE_STEP:
  2063. case EXCEPTION_SINGLE_STEP:
  2064. {
  2065. if (mRunState == RunState_Terminating)
  2066. {
  2067. BfLogDbg("Ignoring event because of RunState_Terminating\n");
  2068. break;
  2069. }
  2070. if ((mStepSwitchedThreads) && (mActiveThread == mSteppingThread) && (mActiveThread->mIsAtBreakpointAddress != NULL))
  2071. {
  2072. ContinueFromBreakpoint();
  2073. break;
  2074. }
  2075. if (mRunState == RunState_HotStep)
  2076. {
  2077. BF_ASSERT(mActiveThread == mDebuggerWaitingThread);
  2078. mRunState = RunState_Paused;
  2079. break;
  2080. }
  2081. mActiveThread = mDebuggerWaitingThread;
  2082. BF_CONTEXT lcContext;
  2083. lcContext.ContextFlags = BF_CONTEXT_ALL;
  2084. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  2085. addr_target pcAddress = BF_CONTEXT_IP(lcContext);
  2086. bool wasUnfilteredStep = mStepType == StepType_StepInto_Unfiltered;
  2087. if (mStepType == StepType_StepInto_UnfilteredSingle)
  2088. {
  2089. wasUnfilteredStep = true;
  2090. mStepType = StepType_StepInto;
  2091. mStepStartPC = pcAddress;
  2092. }
  2093. BfLogDbg("EXCEPTION_SINGLE_STEP Thread:%d PC:%p\n", mActiveThread->mThreadId, exceptionRecord->ExceptionAddress);
  2094. if (lcContext.Dr6 & 0x0F) // Memory breakpoint hit
  2095. {
  2096. WdBreakpoint* foundBreakpoint = NULL;
  2097. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  2098. {
  2099. if ((lcContext.Dr6 & ((intptr_target)1 << memoryWatchSlot)) != 0)
  2100. {
  2101. foundBreakpoint = mMemoryBreakpoints[memoryWatchSlot].mBreakpoint;
  2102. break;
  2103. }
  2104. }
  2105. BF_ASSERT(foundBreakpoint != NULL);
  2106. DbgSubprogram* subprogram = mDebugTarget->FindSubProgram(pcAddress);
  2107. if (CheckConditionalBreakpoint(foundBreakpoint, subprogram, pcAddress))
  2108. {
  2109. if (foundBreakpoint != NULL)
  2110. {
  2111. mDebugManager->mOutMessages.push_back(StrFormat("memoryBreak %s", EncodeDataPtr(foundBreakpoint->mMemoryBreakpointInfo->mMemoryAddress, false).c_str()));
  2112. mRunState = RunState_Paused;
  2113. }
  2114. mActiveBreakpoint = foundBreakpoint;
  2115. mBreakStackFrameIdx = -1;
  2116. RemoveTempBreakpoints();
  2117. BfLogDbg("Memory breakpoint hit: %p\n", foundBreakpoint);
  2118. }
  2119. else
  2120. ClearCallStack();
  2121. break;
  2122. }
  2123. if ((mRunState == RunState_DebugEval) && (mDebugEvalThreadInfo.mThreadId == mDebuggerWaitingThread->mThreadId))
  2124. {
  2125. if ((addr_target)(intptr)exceptionRecord->ExceptionAddress == mDebugEvalSetRegisters.GetPC())
  2126. {
  2127. // This indicates we are returning from kernel mode and our registers are clobbered
  2128. SetRegisters(&mDebugEvalSetRegisters);
  2129. }
  2130. break;
  2131. }
  2132. bool hadBreakpointContinue = true;
  2133. if (threadInfo->mBreakpointAddressContinuing != 0)
  2134. {
  2135. bool wantsBreakpoint = WantsBreakpointAt(threadInfo->mBreakpointAddressContinuing);
  2136. BfLogDbg("Continuing breakpoint at %p WantsReset:%d\n", threadInfo->mBreakpointAddressContinuing, wantsBreakpoint);
  2137. if (wantsBreakpoint)
  2138. {
  2139. PhysSetBreakpoint(threadInfo->mBreakpointAddressContinuing);
  2140. }
  2141. threadInfo->mBreakpointAddressContinuing = NULL;
  2142. hadBreakpointContinue = true;
  2143. ThreadRestoreUnpause();
  2144. }
  2145. if ((mSteppingThread != NULL) && (mSteppingThread != mActiveThread))
  2146. {
  2147. // This SINGLE_STEP happened in the wrong thread - we need the stepping thread to do the stepping!
  2148. // Try again.
  2149. mActiveThread = mSteppingThread;
  2150. SingleStepX86();
  2151. break;
  2152. }
  2153. bool isDeeper = mStepSP > BF_CONTEXT_SP(lcContext);
  2154. if ((mStepSwitchedThreads) && (mStepType == StepType_StepOver) && (isDeeper))
  2155. {
  2156. if (HasSteppedIntoCall())
  2157. {
  2158. // Since we switched threads, we needed to do a hardware step which has placed us inside a
  2159. // call, so we need to step out of that now...
  2160. SetupStep(StepType_StepOut_NoFrame);
  2161. break;
  2162. }
  2163. }
  2164. // If we don't have a mStepBreakpointAddrs set, that means we're stepping through individual instructions --
  2165. // so process the new location here
  2166. if (((mStepType == StepType_StepInto) || (mStepType == StepType_StepInto_Unfiltered) || (mStepType == StepType_StepOver)) && (mStepBreakpointAddrs.size() == 0))
  2167. {
  2168. DbgSubprogram* dwSubprogram = NULL;
  2169. DbgLineData* dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  2170. if ((dwSubprogram != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC) && (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced))
  2171. {
  2172. BfLogDbg("Stepping through hot thunk\n");
  2173. mRunState = RunState_Running;
  2174. SingleStepX86();
  2175. break;
  2176. }
  2177. if ((mStepType == StepType_StepOver) && (!mStepInAssembly))
  2178. {
  2179. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  2180. {
  2181. BfLogDbg("Attempting StepOver of inlined method - SingleStep\n");
  2182. SetupStep(StepType_StepOut);
  2183. mRunState = RunState_Running;
  2184. break;
  2185. }
  2186. }
  2187. // Column of -1 means "Illegal", keep stepping!
  2188. if ((mStepInAssembly) ||
  2189. ((dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dwLineData->mColumn >= 0) &&
  2190. ((dwSubprogram->GetLineAddr(*dwLineData) == pcAddress) || (mStepStopOnNextInstruction))))
  2191. {
  2192. // Hit a line while stepping, we're done!
  2193. mRunState = RunState_Paused;
  2194. StepLineTryPause(pcAddress, false);
  2195. if (mRunState == RunState_Paused)
  2196. {
  2197. if ((mStepType == StepType_StepInto) && (!wasUnfilteredStep) && (!mStepInAssembly) && (dwSubprogram != NULL))
  2198. {
  2199. // Don't filter out the current subprogram (would break cases where we explicitly stepped into or hit breakpoint in a filtered subprogram)
  2200. bool isInStartSubprogram = (mStepStartPC >= dwSubprogram->mBlock.mLowPC) && (mStepStartPC < dwSubprogram->mBlock.mHighPC);
  2201. if ((!isInStartSubprogram) && (IsStepFiltered(dwSubprogram, dwLineData)))
  2202. {
  2203. BfLogDbg("Hit step filter (2)\n");
  2204. mRunState = RunState_Running;
  2205. SetupStep(StepType_StepOut_ThenInto);
  2206. break;
  2207. }
  2208. }
  2209. ClearStep();
  2210. mCurNoInfoStepTries = 0; // Reset
  2211. }
  2212. else
  2213. SetupStep(mStepType);
  2214. }
  2215. else if (dwSubprogram != NULL)
  2216. {
  2217. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && ((mStepType == StepType_StepInto) || (mStepType == StepType_StepInto_Unfiltered)))
  2218. {
  2219. SingleStepX86();
  2220. }
  2221. else
  2222. {
  2223. // Inside a line's instruction, keep going
  2224. SetupStep(mStepType);
  2225. mCurNoInfoStepTries = 0; // Reset
  2226. }
  2227. }
  2228. else if (mStepType == StepType_StepInto_Unfiltered)
  2229. {
  2230. CPUInst inst;
  2231. if (mDebugTarget->DecodeInstruction(pcAddress, &inst))
  2232. {
  2233. if (inst.IsBranch())
  2234. {
  2235. auto target = inst.GetTarget();
  2236. if (target != 0)
  2237. {
  2238. DbgSubprogram* destSubprogram = mDebugTarget->FindSubProgram(target);
  2239. if ((destSubprogram != NULL) && (target == destSubprogram->mBlock.mLowPC))
  2240. {
  2241. // We're jumping to an actual subprogram, so continue stepping here
  2242. mStepType = StepType_StepInto_UnfilteredSingle;
  2243. SingleStepX86();
  2244. break;
  2245. }
  2246. }
  2247. }
  2248. }
  2249. // We requested to step into this method so stop here even if we don't have source
  2250. mRunState = RunState_Paused;
  2251. }
  2252. else
  2253. {
  2254. // No debug info!
  2255. bool doStepOut = false;
  2256. if (mCurNoInfoStepTries < 16)
  2257. {
  2258. mCurNoInfoStepTries++;
  2259. BfLogDbg("NoInfoStepTries: %d\n", mCurNoInfoStepTries);
  2260. if (!SetupStep(mStepType))
  2261. doStepOut = true;
  2262. }
  2263. else
  2264. doStepOut = true;
  2265. if (doStepOut)
  2266. {
  2267. // Step out of current call.
  2268. mStepSP = 0;
  2269. SetupStep(StepType_StepOut_NoFrame);
  2270. // Aggressive stepout - don't monitor BP
  2271. mStepSP = 0;
  2272. }
  2273. }
  2274. }
  2275. else if (!hadBreakpointContinue)
  2276. {
  2277. BF_DBG_FATAL("EXCEPTION_SINGLE_STEP bad debugger state");
  2278. }
  2279. if (mRunState == RunState_Paused)
  2280. threadInfo->mStoppedAtAddress = pcAddress;
  2281. }
  2282. break;
  2283. default:
  2284. {
  2285. bool isSystemException =
  2286. (exceptionRecord->ExceptionCode >= STATUS_ACCESS_VIOLATION) &&
  2287. (exceptionRecord->ExceptionCode <= STATUS_ASSERTION_FAILURE);
  2288. bool isFirstChance = mDebugEvent.u.Exception.dwFirstChance != 0;
  2289. bool handled = false;
  2290. //TODO: Use a user-defined filter here to determine whether to stop or continue
  2291. if ((!isSystemException) && (isFirstChance))
  2292. {
  2293. if (exceptionRecord->ExceptionCode == 0x406D1388) // Visual C
  2294. {
  2295. if ((int32)exceptionRecord->ExceptionInformation[0] == 0x1000)
  2296. {
  2297. struct THREADNAME_INFO
  2298. {
  2299. DWORD dwType; // Must be 0x1000.
  2300. LPCSTR szName; // Pointer to name (in user addr space).
  2301. DWORD dwThreadID; // Thread ID (-1=caller thread).
  2302. DWORD dwFlags; // Reserved for future use, must be zero.
  2303. };
  2304. THREADNAME_INFO* threadNameInfo = (THREADNAME_INFO*)exceptionRecord->ExceptionInformation;
  2305. DwFormatInfo formatInfo;
  2306. formatInfo.mRawString = true;
  2307. String nameStr = ReadString(DbgType_SChar, (intptr)threadNameInfo->szName, false, 1024, formatInfo);
  2308. WdThreadInfo* namingThreadInfo = threadInfo;
  2309. if (threadNameInfo->dwThreadID != (DWORD)-1)
  2310. {
  2311. namingThreadInfo = NULL;
  2312. mThreadMap.TryGetValue(threadNameInfo->dwThreadID, &namingThreadInfo);
  2313. }
  2314. if (namingThreadInfo != NULL)
  2315. {
  2316. namingThreadInfo->mName = nameStr;
  2317. FilterThreadName(namingThreadInfo->mName);
  2318. }
  2319. }
  2320. else if (((int32)exceptionRecord->ExceptionInformation[0] == 0x1001) && ((int32)exceptionRecord->ExceptionInformation[1] == 0x1002))
  2321. {
  2322. struct FailMessage
  2323. {
  2324. addr_target mPtr0; // Unknown
  2325. addr_target mPtr1; // 0
  2326. addr_target mPtr2; // 0
  2327. addr_target mPtr3; // Unknown
  2328. addr_target mErrorStr;
  2329. };
  2330. FailMessage failMessage = ReadMemory<FailMessage>(exceptionRecord->ExceptionInformation[2]);
  2331. DwFormatInfo formatInfo;
  2332. String failStr = ReadString(DbgType_SChar16, failMessage.mErrorStr, false, 8192, formatInfo);
  2333. mDebugManager->mOutMessages.push_back(StrFormat("error Run-Time Check Failure %d - %s", exceptionRecord->ExceptionInformation[6], failStr.c_str()));
  2334. mRunState = RunState_Paused;
  2335. mRequestedStackFrameIdx = -2; // -2 = "auto"
  2336. handled = true;
  2337. }
  2338. }
  2339. if (!handled)
  2340. {
  2341. OutputMessage(StrFormat("Skipping first chance exception %08X at address %@ in thread %d\n", exceptionRecord->ExceptionCode, exceptionRecord->ExceptionAddress, threadInfo->mThreadId));
  2342. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_EXCEPTION_NOT_HANDLED);
  2343. mIsDebuggerWaiting = false;
  2344. }
  2345. }
  2346. else
  2347. {
  2348. BfLogDbg("EXCEPTION in thread %d at %p\n", threadInfo->mThreadId, exceptionRecord->ExceptionAddress);
  2349. OutputDebugStrF("EXCEPTION\n");
  2350. mActiveThread = threadInfo;
  2351. memcpy(&mCurException, exceptionRecord, sizeof(EXCEPTION_RECORD));
  2352. if (mRunState == RunState_DebugEval)
  2353. {
  2354. if ((intptr)mCurException.ExceptionAddress == 42)
  2355. {
  2356. BfLogDbg("RunState_DebugEval_Done\n");
  2357. OutputDebugStrF(" RunState_DebugEval_Done\n");
  2358. }
  2359. else
  2360. {
  2361. BfLogDbg("Exception at 0x%@ in thread %d, exception code 0x%08X",
  2362. mCurException.ExceptionAddress, mActiveThread->mThreadId, mCurException.ExceptionCode);
  2363. mDebugPendingExpr->mException = StrFormat("Exception at 0x%@ in thread %d, exception code 0x%08X",
  2364. mCurException.ExceptionAddress, mActiveThread->mThreadId, mCurException.ExceptionCode);
  2365. }
  2366. mRunState = RunState_DebugEval_Done;
  2367. mExplicitStopThread = mActiveThread;
  2368. mRequestedStackFrameIdx = mDebugPendingExpr->mCallStackIdx;
  2369. }
  2370. else
  2371. {
  2372. mRunState = RunState_Exception;
  2373. }
  2374. }
  2375. }
  2376. break;
  2377. }
  2378. }
  2379. break;
  2380. }
  2381. if ((mDebugEvalThreadInfo.mThreadId != 0) && (mRunState != RunState_DebugEval) && (mRunState != RunState_DebugEval_Done))
  2382. {
  2383. CleanupDebugEval();
  2384. }
  2385. // Stepping done?
  2386. if (mStepType == StepType_None)
  2387. {
  2388. mLastValidStepIntoPC = 0;
  2389. }
  2390. BF_ASSERT(mDebuggerWaitingThread != NULL);
  2391. return true;
  2392. }
  2393. void WinDebugger::Update()
  2394. {
  2395. AutoCrit autoCrit(mDebugManager->mCritSect);
  2396. // if (mRunState == RunState_DebugEval)
  2397. // ContinueDebugEvent();
  2398. if (mRunState == RunState_DebugEval_Done)
  2399. {
  2400. if (mDebugPendingExpr != NULL)
  2401. {
  2402. mDebugPendingExpr->mIdleTicks++;
  2403. if (mDebugPendingExpr->mIdleTicks >= 2)
  2404. {
  2405. BfLogDbg("Finishing pending expr in thread %d\n", mDebugEvalThreadInfo.mThreadId);
  2406. mRunState = RunState_Paused;
  2407. CleanupDebugEval();
  2408. }
  2409. }
  2410. }
  2411. else if (mDebugPendingExpr != NULL)
  2412. {
  2413. mDebugPendingExpr->mIdleTicks = 0;
  2414. }
  2415. }
  2416. void WinDebugger::ContinueDebugEvent()
  2417. {
  2418. AutoCrit autoCrit(mDebugManager->mCritSect);
  2419. BF_ASSERT(mRunState != RunState_DebugEval_Done);
  2420. if (!mWantsDebugContinue)
  2421. return;
  2422. if (!TryRunContinue())
  2423. return;
  2424. // if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId != mDebugEvalThreadInfo.mThreadId))
  2425. // {
  2426. // // Don't process the 'mIsAtBreakpointAddress' stuff
  2427. // mWantsDebugContinue = false;
  2428. // mContinueEvent.Set();
  2429. // return;
  2430. // }
  2431. if ((mDebuggerWaitingThread->mIsAtBreakpointAddress == 0) && (mDebuggerWaitingThread->mStoppedAtAddress != 0))
  2432. {
  2433. auto breakpoint = FindBreakpointAt(mDebuggerWaitingThread->mStoppedAtAddress);
  2434. if (breakpoint != NULL)
  2435. {
  2436. mDebuggerWaitingThread->mIsAtBreakpointAddress = mDebuggerWaitingThread->mStoppedAtAddress;
  2437. }
  2438. }
  2439. if (mDebuggerWaitingThread->mIsAtBreakpointAddress != 0)
  2440. {
  2441. if (!ContinueFromBreakpoint())
  2442. {
  2443. BfLogDbg("ContinueFromBreakpoint failed\n");
  2444. ClearCallStack();
  2445. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  2446. mDebuggerWaitingThread->mIsAtBreakpointAddress = 0;
  2447. mWantsDebugContinue = false;
  2448. mContinueFromBreakpointFailed = true;
  2449. mContinueEvent.Set();
  2450. return;
  2451. }
  2452. }
  2453. if ((mRunState == RunState_Breakpoint) || (mRunState == RunState_Paused))
  2454. {
  2455. ClearCallStack();
  2456. mRunState = RunState_Running;
  2457. }
  2458. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  2459. mWantsDebugContinue = false;
  2460. BF_ASSERT_REL(mDebuggerWaitingThread->mIsAtBreakpointAddress == 0);
  2461. mContinueEvent.Set();
  2462. }
  2463. static BOOL CALLBACK WdEnumWindowsProc(HWND hwnd, LPARAM lParam)
  2464. {
  2465. HWND owner = GetWindow(hwnd, GW_OWNER);
  2466. if (!IsWindowVisible(hwnd))
  2467. return TRUE;
  2468. DWORD processId = 0;
  2469. DWORD threadId = GetWindowThreadProcessId(hwnd, &processId);
  2470. if (processId != ((WinDebugger*)gDebugger)->mProcessInfo.dwProcessId)
  2471. return TRUE;
  2472. SetForegroundWindow(hwnd);
  2473. return TRUE;
  2474. }
  2475. void WinDebugger::ForegroundTarget()
  2476. {
  2477. EnumWindows(WdEnumWindowsProc, 0);
  2478. }
  2479. static int gFindLineDataAt = 0;
  2480. DbgLineData* WinDebugger::FindLineDataAtAddress(addr_target address, DbgSubprogram** outSubProgram, DbgSrcFile** outSrcFile, int* outLineIdx, DbgOnDemandKind onDemandKind)
  2481. {
  2482. gFindLineDataAt++;
  2483. BP_ZONE("WinDebugger::FindLineDataAtAddress");
  2484. auto dwSubprogram = mDebugTarget->FindSubProgram((addr_target)address, onDemandKind);
  2485. if (dwSubprogram == NULL)
  2486. return NULL;
  2487. FixupLineDataForSubprogram(dwSubprogram);
  2488. auto lineData = dwSubprogram->FindClosestLine(address, outSubProgram, outSrcFile, outLineIdx);
  2489. return lineData;
  2490. }
  2491. DbgLineData* WinDebugger::FindLineDataInSubprogram(addr_target address, DbgSubprogram* dwSubprogram)
  2492. {
  2493. auto dwCompileUnit = dwSubprogram->mCompileUnit;
  2494. FixupLineDataForSubprogram(dwSubprogram);
  2495. auto lineData = dwSubprogram->FindClosestLine(address);
  2496. return lineData;
  2497. }
  2498. bool WinDebugger::IsStepFiltered(DbgSubprogram* dbgSubprogram, DbgLineData* dbgLineData)
  2499. {
  2500. if (mIsStepIntoSpecific)
  2501. return false;
  2502. if (dbgSubprogram->mStepFilterVersion != mDebugManager->mStepFilterVersion)
  2503. {
  2504. String filterName;
  2505. CreateFilterName(filterName, dbgSubprogram);
  2506. dbgSubprogram->PopulateSubprogram();
  2507. bool doDefault = false;
  2508. StepFilter* stepFilterPtr;
  2509. if (mDebugManager->mStepFilters.TryGetValue(filterName, &stepFilterPtr))
  2510. {
  2511. switch (stepFilterPtr->mFilterKind)
  2512. {
  2513. case BfStepFilterKind_Default:
  2514. doDefault = true;
  2515. break;
  2516. case BfStepFilterKind_Filtered:
  2517. dbgSubprogram->mIsStepFiltered = true;
  2518. break;
  2519. case BfStepFilterKind_NotFiltered:
  2520. dbgSubprogram->mIsStepFiltered = false;
  2521. break;
  2522. }
  2523. }
  2524. else
  2525. {
  2526. doDefault = true;
  2527. }
  2528. if (doDefault)
  2529. {
  2530. dbgSubprogram->mIsStepFiltered = dbgSubprogram->mIsStepFilteredDefault;
  2531. }
  2532. dbgSubprogram->mStepFilterVersion = mDebugManager->mStepFilterVersion;
  2533. }
  2534. if (!dbgSubprogram->mIsStepFiltered)
  2535. {
  2536. if (dbgLineData != NULL)
  2537. {
  2538. auto dbgSrcFile = dbgSubprogram->GetLineSrcFile(*dbgLineData);
  2539. if (dbgSrcFile->mStepFilterVersion != mDebugManager->mStepFilterVersion)
  2540. {
  2541. dbgSrcFile->mFileExistKind = dbgSubprogram->mCompileUnit->mDbgModule->CheckSourceFileExist(dbgSrcFile->GetLocalPath());
  2542. dbgSrcFile->mStepFilterVersion = mDebugManager->mStepFilterVersion;
  2543. }
  2544. switch (dbgSrcFile->mFileExistKind)
  2545. {
  2546. case DbgFileExistKind_NotFound:
  2547. return true;
  2548. case DbgFileExistKind_HasOldSourceCommand:
  2549. if (mDebugManager->mStepOverExternalFiles)
  2550. return true;
  2551. }
  2552. }
  2553. }
  2554. return dbgSubprogram->mIsStepFiltered;
  2555. }
  2556. void WinDebugger::RemoveTempBreakpoints()
  2557. {
  2558. BfLogDbg("RemoveTempBreakpoints\n");
  2559. for (auto address : mTempBreakpoint)
  2560. {
  2561. RemoveBreakpoint(address);
  2562. // if (FindBreakpointAt(address) == NULL)
  2563. // {
  2564. // RemoveBreakpoint(address);
  2565. // }
  2566. // else
  2567. // {
  2568. // BfLogDbg("Ignoring remove on temp breakpoint %p\n", address);
  2569. // }
  2570. }
  2571. mTempBreakpoint.Clear();
  2572. mStepBreakpointAddrs.Clear();
  2573. }
  2574. void WinDebugger::RehupBreakpoints(bool doFlush)
  2575. {
  2576. BfLogDbg("RehupBreakpoints\n");
  2577. // First pass- detach breakpoints that need to be rebound
  2578. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  2579. {
  2580. auto breakpoint = mBreakpoints[i];
  2581. while (breakpoint != NULL)
  2582. {
  2583. if (((breakpoint->mSrcFile != NULL) && (breakpoint->mSrcFile->mDeferredRefs.size() > 0)) ||
  2584. (!breakpoint->mSymbolName.IsEmpty()))
  2585. {
  2586. // This breakpoint was already bound, but we loaded a debug module that also had this file so rebind it
  2587. DetachBreakpoint(breakpoint);
  2588. }
  2589. breakpoint = (WdBreakpoint*)breakpoint->mLinkedSibling;
  2590. }
  2591. }
  2592. // Second pass- actually set breakpoints
  2593. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  2594. {
  2595. auto breakpoint = mBreakpoints[i];
  2596. while (breakpoint != NULL)
  2597. {
  2598. CheckBreakpoint(breakpoint);
  2599. if (breakpoint->mAddr != 0)
  2600. SetBreakpoint(breakpoint->mAddr, true);
  2601. breakpoint = (WdBreakpoint*)breakpoint->mLinkedSibling;
  2602. }
  2603. }
  2604. mNeedsRehupBreakpoints = false;
  2605. }
  2606. bool WinDebugger::WantsBreakpointAt(addr_target address)
  2607. {
  2608. if (mTempBreakpoint.Contains(address))
  2609. return true;
  2610. for (auto breakpoint : mBreakpoints)
  2611. {
  2612. WdBreakpoint* checkBreakpoint = breakpoint;
  2613. while (checkBreakpoint != NULL)
  2614. {
  2615. if (address == checkBreakpoint->mAddr)
  2616. return true;
  2617. checkBreakpoint = (WdBreakpoint*)checkBreakpoint->mLinkedSibling;
  2618. }
  2619. }
  2620. return false;
  2621. }
  2622. void WinDebugger::CheckBreakpoint(WdBreakpoint* wdBreakpoint, DbgSrcFile* srcFile, int lineNum, int hotIdx)
  2623. {
  2624. BP_ZONE("WinDebugger::CheckBreakpoint:atLoc");
  2625. if (hotIdx == -1)
  2626. {
  2627. BF_ASSERT(wdBreakpoint->mPendingHotBindIdx == -1);
  2628. }
  2629. WdBreakpoint* headBreakpoint = wdBreakpoint;
  2630. headBreakpoint->mPendingHotBindIdx = -1;
  2631. bool foundInSequence = false;
  2632. DbgSubprogram* lastFoundSubprogram = NULL;
  2633. int highestHotIdx = -1;
  2634. bool foundLine = false;
  2635. int bestLineNum = -1;
  2636. int bestLineOffset = 0x7FFFFFFF;
  2637. auto _CheckLineInfo = [&](DbgSubprogram* dbgSubprogram, DbgLineInfo* dbgLineInfo)
  2638. {
  2639. // Scan first so we can determine if we want to do fix up line data or not.
  2640. bool hasNear = false;
  2641. int maxLineDist = 6;
  2642. for (int lineIdx = 0; lineIdx < dbgLineInfo->mLines.mSize; lineIdx++)
  2643. {
  2644. auto lineData = &dbgLineInfo->mLines[lineIdx];
  2645. auto& ctx = dbgLineInfo->mContexts[lineData->mCtxIdx];
  2646. if (ctx.mSrcFile != srcFile)
  2647. continue;
  2648. int lineOffset = lineData->mLine - lineNum;
  2649. if ((lineOffset >= 0) && (lineOffset <= maxLineDist))
  2650. hasNear = true;
  2651. }
  2652. if (!hasNear)
  2653. return;
  2654. FixupLineDataForSubprogram(dbgSubprogram);
  2655. for (int lineIdx = 0; lineIdx < dbgLineInfo->mLines.mSize; lineIdx++)
  2656. {
  2657. //TODO: Do fixup lineData... ?
  2658. auto lineData = &dbgLineInfo->mLines[lineIdx];
  2659. auto& ctx = dbgLineInfo->mContexts[lineData->mCtxIdx];
  2660. if (ctx.mSrcFile != srcFile)
  2661. continue;
  2662. // if (ctx.mInlinee != NULL)
  2663. // {
  2664. // if (lineIdx + 1 < dbgLineInfo->mLines.mSize)
  2665. // {
  2666. // auto nextLineData = &dbgLineInfo->mLines[lineIdx + 1];
  2667. // if (nextLineData->mRelAddress == lineData->mRelAddress)
  2668. // {
  2669. // // Use the later entry (same logic from DisassembleAt)
  2670. // continue;
  2671. // }
  2672. // }
  2673. // }
  2674. if ((lineData->mColumn == -1) && (wdBreakpoint->mInstrOffset == -1))
  2675. continue;
  2676. int lineOffset = lineData->mLine - lineNum;
  2677. if (lineOffset == 0)
  2678. {
  2679. foundLine = true;
  2680. auto address = dbgSubprogram->GetLineAddr(*lineData);
  2681. auto subProgram = mDebugTarget->FindSubProgram(address);
  2682. if (subProgram->mNeedLineDataFixup)
  2683. FixupLineDataForSubprogram(subProgram);
  2684. if (subProgram != NULL)
  2685. highestHotIdx = BF_MAX(highestHotIdx, subProgram->mCompileUnit->mDbgModule->mHotIdx);
  2686. if ((foundInSequence) && (subProgram != lastFoundSubprogram))
  2687. foundInSequence = false;
  2688. if ((subProgram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && (address < subProgram->mBlock.mLowPC + sizeof(HotJumpOp)))
  2689. {
  2690. // If this breakpoint ends up on the hot jmp instruction
  2691. continue;
  2692. }
  2693. if (!foundInSequence)
  2694. {
  2695. lastFoundSubprogram = subProgram;
  2696. if ((subProgram != NULL) && (subProgram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && (address == subProgram->mBlock.mLowPC))
  2697. {
  2698. // This instruction is actually the hot jump, we don't need a breakpoint here
  2699. foundInSequence = true;
  2700. continue;
  2701. }
  2702. if (wdBreakpoint->mSrcFile != NULL)
  2703. {
  2704. wdBreakpoint = new WdBreakpoint();
  2705. // Insert at head
  2706. wdBreakpoint->mLinkedSibling = headBreakpoint->mLinkedSibling;
  2707. headBreakpoint->mLinkedSibling = wdBreakpoint;
  2708. wdBreakpoint->mRequestedLineNum = headBreakpoint->mRequestedLineNum;
  2709. wdBreakpoint->mLineNum = headBreakpoint->mLineNum;
  2710. wdBreakpoint->mColumn = headBreakpoint->mColumn;
  2711. wdBreakpoint->mInstrOffset = headBreakpoint->mInstrOffset;
  2712. wdBreakpoint->mIsLinkedSibling = true;
  2713. wdBreakpoint->mHead = headBreakpoint;
  2714. }
  2715. if (wdBreakpoint->mInstrOffset > 0)
  2716. {
  2717. for (int instIdx = 0; instIdx < wdBreakpoint->mInstrOffset; instIdx++)
  2718. {
  2719. CPUInst inst;
  2720. if (!mDebugTarget->DecodeInstruction(address, &inst))
  2721. break;
  2722. address += inst.mSize;
  2723. }
  2724. }
  2725. wdBreakpoint->mSrcFile = ctx.mSrcFile;
  2726. wdBreakpoint->mLineData = DbgLineDataEx(lineData, subProgram);
  2727. wdBreakpoint->mBreakpointType = BreakpointType_User;
  2728. wdBreakpoint->mAddr = address;
  2729. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mStoppedAtAddress == address))
  2730. {
  2731. BfLogDbg("CheckBreakpoint setting mIsAtBreakpointAddress = %p\n", address);
  2732. mDebuggerWaitingThread->mIsAtBreakpointAddress = address;
  2733. }
  2734. BfLogDbg("Breakpoint %p found at %s in %s\n", wdBreakpoint, subProgram->mName, GetFileName(subProgram->mCompileUnit->mDbgModule->mFilePath).c_str());
  2735. mBreakpointAddrMap.ForceAdd(address, wdBreakpoint);
  2736. SetBreakpoint(address);
  2737. foundInSequence = true;
  2738. }
  2739. }
  2740. else
  2741. {
  2742. //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
  2743. // multiple places so we need to ensure this will break on them all
  2744. foundInSequence = false;
  2745. }
  2746. if ((lineOffset >= 0) && (lineOffset <= maxLineDist) && (lineOffset <= bestLineOffset))
  2747. {
  2748. if (lineOffset < bestLineOffset)
  2749. {
  2750. bestLineNum = lineData->mLine;
  2751. bestLineOffset = lineOffset;
  2752. }
  2753. }
  2754. }
  2755. };
  2756. for (int pass = 0; pass < 2; pass++)
  2757. {
  2758. if (lineNum == -1)
  2759. break;
  2760. bestLineNum = -1;
  2761. bestLineOffset = 0x7FFFFFFF;
  2762. if (hotIdx >= 0)
  2763. {
  2764. if (hotIdx >= srcFile->mHotReplacedDbgLineInfo.size())
  2765. return;
  2766. auto hotReplacedLineInfo = srcFile->mHotReplacedDbgLineInfo[hotIdx];
  2767. for (auto& hotReplacedEntry : hotReplacedLineInfo->mEntries)
  2768. {
  2769. _CheckLineInfo(hotReplacedEntry.mSubprogram, hotReplacedEntry.mLineInfo);
  2770. }
  2771. }
  2772. else
  2773. {
  2774. for (auto subprogram : srcFile->mLineDataRefs)
  2775. _CheckLineInfo(subprogram, subprogram->mLineInfo);
  2776. }
  2777. if (foundLine)
  2778. break;
  2779. // Don't allow the breakpoint to be inexactly bound -- only match on pass 0
  2780. if (hotIdx != -1)
  2781. break;
  2782. if (bestLineNum == -1)
  2783. break;
  2784. lineNum = bestLineNum;
  2785. wdBreakpoint->mLineNum = bestLineNum;
  2786. }
  2787. int highestCheckHotIdx = highestHotIdx - 1;
  2788. if (hotIdx != -1)
  2789. highestCheckHotIdx = hotIdx - 1;
  2790. for (int hotFileIdx = highestCheckHotIdx; hotFileIdx >= 0; hotFileIdx--)
  2791. {
  2792. auto& hotReplacedDbgLineData = wdBreakpoint->mSrcFile->mHotReplacedDbgLineInfo;
  2793. // Only try to bind to an old hot version if we haven't unloaded the hot module
  2794. if ((hotFileIdx < (int)hotReplacedDbgLineData.size()) && (hotReplacedDbgLineData[hotFileIdx]->mEntries.size() > 0))
  2795. {
  2796. headBreakpoint->mPendingHotBindIdx = hotFileIdx;
  2797. break;
  2798. }
  2799. }
  2800. }
  2801. void WinDebugger::HotBindBreakpoint(Breakpoint* breakpoint, int lineNum, int hotIdx)
  2802. {
  2803. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  2804. CheckBreakpoint(wdBreakpoint, wdBreakpoint->mSrcFile, lineNum, hotIdx);
  2805. }
  2806. void WinDebugger::CheckBreakpoint(WdBreakpoint* wdBreakpoint)
  2807. {
  2808. if (!mGotStartupEvent)
  2809. return;
  2810. if (wdBreakpoint->mThreadId == 0) // Not bound to threadId yet...
  2811. {
  2812. return;
  2813. }
  2814. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  2815. {
  2816. if (wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap != 0)
  2817. return;
  2818. if (mFreeMemoryBreakIndices.size() == 0)
  2819. return;
  2820. if ((IsInRunState()) || (mActiveThread == NULL))
  2821. return;
  2822. int wantBytes[4];
  2823. int wantBindCount = 0;
  2824. int bytesLeft = wdBreakpoint->mMemoryBreakpointInfo->mByteCount;
  2825. addr_target curAddr = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress;
  2826. while (bytesLeft > 0)
  2827. {
  2828. if (wantBindCount >= mFreeMemoryBreakIndices.size())
  2829. return;
  2830. int curByteCount = 1;
  2831. #ifdef BF_DBG_64
  2832. if ((bytesLeft >= 8) && ((curAddr & 7) == 0))
  2833. curByteCount = 8;
  2834. else
  2835. #endif
  2836. if ((bytesLeft >= 4) && ((curAddr & 3) == 0))
  2837. curByteCount = 4;
  2838. else if ((bytesLeft >= 2) && ((curAddr & 1) == 0))
  2839. curByteCount = 2;
  2840. wantBytes[wantBindCount++] = curByteCount;
  2841. bytesLeft -= curByteCount;
  2842. curAddr += curByteCount;
  2843. }
  2844. addr_target curOfs = 0;
  2845. for (int i = 0; i < wantBindCount; i++)
  2846. {
  2847. int memoryBreakIdx = mFreeMemoryBreakIndices.back();
  2848. mFreeMemoryBreakIndices.pop_back();
  2849. mMemoryBreakpoints[memoryBreakIdx].mBreakpoint = wdBreakpoint;
  2850. mMemoryBreakpoints[memoryBreakIdx].mAddress = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress + curOfs;
  2851. mMemoryBreakpoints[memoryBreakIdx].mByteCount = wantBytes[i];
  2852. mMemoryBreakpoints[memoryBreakIdx].mOfs = curOfs;
  2853. curOfs += wantBytes[i];
  2854. mMemoryBreakpointVersion++;
  2855. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap |= 1<<memoryBreakIdx;
  2856. }
  2857. UpdateThreadDebugRegisters();
  2858. }
  2859. if (wdBreakpoint->mAddr != 0)
  2860. return;
  2861. if (!wdBreakpoint->mSymbolName.IsEmpty())
  2862. {
  2863. auto headBreakpoint = wdBreakpoint->GetHeadBreakpoint();
  2864. String symbolName = wdBreakpoint->mSymbolName;
  2865. bool onlyBindFirst = false;
  2866. if (symbolName.StartsWith("-"))
  2867. {
  2868. symbolName.Remove(0);
  2869. onlyBindFirst = true;
  2870. }
  2871. for (auto dbgModule : mDebugTarget->mDbgModules)
  2872. {
  2873. dbgModule->ParseSymbolData();
  2874. addr_target targetAddr = -1;
  2875. auto entry = dbgModule->mSymbolNameMap.Find(symbolName.c_str());
  2876. if (entry != NULL)
  2877. {
  2878. DbgSymbol* dwSymbol = entry->mValue;
  2879. targetAddr = dwSymbol->mAddress;
  2880. }
  2881. if (targetAddr == -1)
  2882. {
  2883. if (symbolName == ".")
  2884. {
  2885. targetAddr = mDebugTarget->mLaunchBinary->mImageBase + mDebugTarget->mLaunchBinary->mEntryPoint;
  2886. onlyBindFirst = true;
  2887. }
  2888. }
  2889. if (targetAddr != -1)
  2890. {
  2891. if (wdBreakpoint->mAddr == 0)
  2892. {
  2893. wdBreakpoint->mAddr = targetAddr;
  2894. wdBreakpoint->mBreakpointType = BreakpointType_User;
  2895. mBreakpointAddrMap.ForceAdd(wdBreakpoint->mAddr, wdBreakpoint);
  2896. SetBreakpoint(wdBreakpoint->mAddr);
  2897. }
  2898. else
  2899. {
  2900. wdBreakpoint = new WdBreakpoint();
  2901. // Insert at head
  2902. wdBreakpoint->mLinkedSibling = headBreakpoint->mLinkedSibling;
  2903. headBreakpoint->mLinkedSibling = wdBreakpoint;
  2904. wdBreakpoint->mSymbolName = headBreakpoint->mSymbolName;
  2905. wdBreakpoint->mIsLinkedSibling = true;
  2906. wdBreakpoint->mHead = headBreakpoint;
  2907. }
  2908. if (onlyBindFirst)
  2909. break;
  2910. }
  2911. }
  2912. return;
  2913. }
  2914. BP_ZONE("WinDebugger::CheckBreakpoint");
  2915. // Rehup if we load a DLL that also uses this file we bound to (thus the mDeferredRefs check)
  2916. if (wdBreakpoint->mSrcFile == NULL)
  2917. {
  2918. DbgSrcFile* srcFile = mDebugTarget->GetSrcFile(wdBreakpoint->mFilePath);
  2919. if (srcFile == NULL)
  2920. return;
  2921. for (auto& deferredSrcFileRef : srcFile->mDeferredRefs)
  2922. {
  2923. deferredSrcFileRef.mDbgModule->ParseCompileUnit(deferredSrcFileRef.mCompileUnitId);
  2924. }
  2925. srcFile->mDeferredRefs.Clear();
  2926. CheckBreakpoint(wdBreakpoint, srcFile, wdBreakpoint->mRequestedLineNum, -1);
  2927. }
  2928. }
  2929. bool WinDebugger::IsMemoryBreakpointSizeValid(addr_target addr, int size)
  2930. {
  2931. int wantBindCount = 0;
  2932. int bytesLeft = size;
  2933. addr_target curAddr = addr;
  2934. for (int i = 0; i < 4; i++)
  2935. {
  2936. int curByteCount = 1;
  2937. #ifdef BF_DBG_64
  2938. if ((bytesLeft >= 8) && ((curAddr & 7) == 0))
  2939. curByteCount = 8;
  2940. else
  2941. #endif
  2942. if ((bytesLeft >= 4) && ((curAddr & 3) == 0))
  2943. curByteCount = 4;
  2944. else if ((bytesLeft >= 2) && ((curAddr & 1) == 0))
  2945. curByteCount = 2;
  2946. bytesLeft -= curByteCount;
  2947. curAddr += curByteCount;
  2948. if (bytesLeft == 0)
  2949. return true;
  2950. }
  2951. return false;
  2952. }
  2953. bool WinDebugger::HasMemoryBreakpoint(addr_target addr, int size)
  2954. {
  2955. for (int i = 0; i < 4; i++)
  2956. {
  2957. if ((mMemoryBreakpoints[i].mAddress == addr) &&
  2958. (mMemoryBreakpoints[i].mOfs == 0) &&
  2959. (mMemoryBreakpoints[i].mBreakpoint->mMemoryBreakpointInfo->mByteCount == size))
  2960. return true;
  2961. }
  2962. return false;
  2963. }
  2964. Breakpoint* WinDebugger::CreateBreakpoint(const StringImpl& fileName, int lineNum, int wantColumn, int instrOffset)
  2965. {
  2966. AutoCrit autoCrit(mDebugManager->mCritSect);
  2967. BfLogDbg("CreateBreakpoint %s %d %d\n", fileName.c_str(), lineNum, wantColumn);
  2968. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  2969. wdBreakpoint->mFilePath = FixPathAndCase(fileName);
  2970. wdBreakpoint->mRequestedLineNum = lineNum;
  2971. wdBreakpoint->mLineNum = lineNum;
  2972. wdBreakpoint->mColumn = wantColumn;
  2973. wdBreakpoint->mInstrOffset = instrOffset;
  2974. mBreakpoints.push_back(wdBreakpoint);
  2975. BfLogDbg("CreateBreakpoint Created %p\n", wdBreakpoint);
  2976. return wdBreakpoint;
  2977. }
  2978. void WinDebugger::CheckBreakpoint(Breakpoint* checkBreakpoint)
  2979. {
  2980. AutoCrit autoCrit(mDebugManager->mCritSect);
  2981. CheckBreakpoint((WdBreakpoint*)checkBreakpoint);
  2982. }
  2983. Breakpoint* WinDebugger::CreateMemoryBreakpoint(intptr addr, int byteCount)
  2984. {
  2985. AutoCrit autoCrit(mDebugManager->mCritSect);
  2986. BfLogDbg("CreateMemoryBreakpoint %p %d\n", addr, byteCount);
  2987. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  2988. WdMemoryBreakpointInfo* memoryBreakInfo = new WdMemoryBreakpointInfo();
  2989. memoryBreakInfo->mMemoryAddress = addr;
  2990. memoryBreakInfo->mByteCount = byteCount;
  2991. wdBreakpoint->mMemoryBreakpointInfo = memoryBreakInfo;
  2992. mBreakpoints.push_back(wdBreakpoint);
  2993. CheckBreakpoint(wdBreakpoint);
  2994. return wdBreakpoint;
  2995. }
  2996. Breakpoint* WinDebugger::CreateSymbolBreakpoint(const StringImpl& symbolName)
  2997. {
  2998. AutoCrit autoCrit(mDebugManager->mCritSect);
  2999. BfLogDbg("CreateSymbolBreakpoint %s\n", symbolName.c_str());
  3000. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  3001. wdBreakpoint->mSymbolName = symbolName;
  3002. mBreakpoints.push_back(wdBreakpoint);
  3003. CheckBreakpoint(wdBreakpoint);
  3004. return wdBreakpoint;
  3005. }
  3006. Breakpoint* WinDebugger::CreateAddressBreakpoint(intptr inAddress)
  3007. {
  3008. AutoCrit autoCrit(mDebugManager->mCritSect);
  3009. BfLogDbg("CreateAddressBreakpoint %p\n", inAddress);
  3010. addr_target address = (addr_target)inAddress;
  3011. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  3012. wdBreakpoint->mAddr = address;
  3013. mBreakpointAddrMap.ForceAdd(wdBreakpoint->mAddr, wdBreakpoint);
  3014. SetBreakpoint(address);
  3015. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mStoppedAtAddress == address))
  3016. {
  3017. BfLogDbg("CreateAddressBreakpoint setting mIsAtBreakpointAddress = %p\n", address);
  3018. mDebuggerWaitingThread->mIsAtBreakpointAddress = address;
  3019. }
  3020. mBreakpoints.push_back(wdBreakpoint);
  3021. return wdBreakpoint;
  3022. }
  3023. void WinDebugger::DeleteBreakpoint(Breakpoint* breakpoint)
  3024. {
  3025. AutoCrit autoCrit(mDebugManager->mCritSect);
  3026. if (breakpoint == mActiveBreakpoint)
  3027. mActiveBreakpoint = NULL;
  3028. BfLogDbg("WinDebugger::DeleteBreakpoint %p Count:%d\n", breakpoint, mBreakpoints.size());
  3029. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3030. if (wdBreakpoint->mCondition != NULL)
  3031. {
  3032. if (!wdBreakpoint->mIsLinkedSibling)
  3033. delete wdBreakpoint->mCondition;
  3034. }
  3035. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  3036. {
  3037. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  3038. {
  3039. if (mMemoryBreakpoints[memoryWatchSlot].mBreakpoint == wdBreakpoint)
  3040. {
  3041. mFreeMemoryBreakIndices.push_back(memoryWatchSlot);
  3042. mMemoryBreakpoints[memoryWatchSlot] = WdMemoryBreakpointBind();
  3043. mMemoryBreakpointVersion++;
  3044. UpdateThreadDebugRegisters();
  3045. }
  3046. }
  3047. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap = 0;
  3048. }
  3049. if (wdBreakpoint->mAddr != 0)
  3050. {
  3051. mBreakpointAddrMap.Remove(wdBreakpoint->mAddr, wdBreakpoint);
  3052. RemoveBreakpoint(wdBreakpoint->mAddr);
  3053. for (auto thread : mThreadList)
  3054. {
  3055. if (thread->mIsAtBreakpointAddress == wdBreakpoint->mAddr)
  3056. thread->mIsAtBreakpointAddress = NULL;
  3057. if (thread->mBreakpointAddressContinuing == wdBreakpoint->mAddr)
  3058. thread->mBreakpointAddressContinuing = NULL;
  3059. }
  3060. }
  3061. if (!wdBreakpoint->mIsLinkedSibling)
  3062. {
  3063. mBreakpoints.Remove(wdBreakpoint);
  3064. }
  3065. if (wdBreakpoint->mLinkedSibling != NULL)
  3066. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  3067. delete wdBreakpoint;
  3068. }
  3069. void WinDebugger::DetachBreakpoint(Breakpoint* breakpoint)
  3070. {
  3071. AutoCrit autoCrit(mDebugManager->mCritSect);
  3072. BfLogDbg("WinDebugger::DetachBreakpoint %p\n", breakpoint);
  3073. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3074. if (wdBreakpoint->mAddr != 0)
  3075. {
  3076. mBreakpointAddrMap.Remove(wdBreakpoint->mAddr, wdBreakpoint);
  3077. RemoveBreakpoint(wdBreakpoint->mAddr);
  3078. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mIsAtBreakpointAddress == wdBreakpoint->mAddr))
  3079. mDebuggerWaitingThread->mIsAtBreakpointAddress = NULL;
  3080. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mBreakpointAddressContinuing == wdBreakpoint->mAddr))
  3081. mDebuggerWaitingThread->mBreakpointAddressContinuing = NULL;
  3082. wdBreakpoint->mLineData = DbgLineDataEx();
  3083. wdBreakpoint->mAddr = 0;
  3084. }
  3085. if (wdBreakpoint->mCondition != NULL)
  3086. {
  3087. delete wdBreakpoint->mCondition->mDbgEvaluationContext;
  3088. wdBreakpoint->mCondition->mDbgEvaluationContext = NULL;
  3089. }
  3090. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  3091. {
  3092. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  3093. {
  3094. if (mMemoryBreakpoints[memoryWatchSlot].mBreakpoint == wdBreakpoint)
  3095. {
  3096. mFreeMemoryBreakIndices.push_back(memoryWatchSlot);
  3097. mMemoryBreakpoints[memoryWatchSlot] = WdMemoryBreakpointBind();
  3098. mMemoryBreakpointVersion++;
  3099. UpdateThreadDebugRegisters();
  3100. }
  3101. }
  3102. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap = 0;
  3103. }
  3104. if (wdBreakpoint->mLinkedSibling != NULL)
  3105. {
  3106. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  3107. wdBreakpoint->mLinkedSibling = NULL;
  3108. }
  3109. wdBreakpoint->mSrcFile = NULL;
  3110. wdBreakpoint->mPendingHotBindIdx = -1;
  3111. }
  3112. void WinDebugger::MoveBreakpoint(Breakpoint* breakpoint, int lineNum, int wantColumn, bool rebindNow)
  3113. {
  3114. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3115. AutoCrit autoCrit(mDebugManager->mCritSect);
  3116. DetachBreakpoint(wdBreakpoint);
  3117. //TODO: This doesn't actually rebind correctly while the app is running
  3118. if ((lineNum != -1) && (wantColumn != -1))
  3119. {
  3120. wdBreakpoint->mRequestedLineNum = lineNum;
  3121. wdBreakpoint->mLineNum = lineNum;
  3122. wdBreakpoint->mColumn = wantColumn;
  3123. }
  3124. if (rebindNow)
  3125. CheckBreakpoint(wdBreakpoint);
  3126. }
  3127. void WinDebugger::MoveMemoryBreakpoint(Breakpoint* breakpoint, intptr addr, int byteCount)
  3128. {
  3129. AutoCrit autoCrit(mDebugManager->mCritSect);
  3130. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3131. DetachBreakpoint(wdBreakpoint);
  3132. wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress = addr;
  3133. wdBreakpoint->mMemoryBreakpointInfo->mByteCount = byteCount;
  3134. CheckBreakpoint(wdBreakpoint);
  3135. }
  3136. void WinDebugger::DisableBreakpoint(Breakpoint* breakpoint)
  3137. {
  3138. AutoCrit autoCrit(mDebugManager->mCritSect);
  3139. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3140. DetachBreakpoint(wdBreakpoint);
  3141. delete wdBreakpoint->mMemoryBreakpointInfo;
  3142. wdBreakpoint->mMemoryBreakpointInfo = NULL;
  3143. }
  3144. void WinDebugger::SetBreakpointCondition(Breakpoint* breakpoint, const StringImpl& conditionExpr)
  3145. {
  3146. AutoCrit autoCrit(mDebugManager->mCritSect);
  3147. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3148. BF_ASSERT(!wdBreakpoint->mIsLinkedSibling);
  3149. if (conditionExpr.empty())
  3150. {
  3151. delete wdBreakpoint->mCondition;
  3152. WdBreakpoint* curBreakpoint = wdBreakpoint;
  3153. wdBreakpoint->mCondition = NULL;
  3154. }
  3155. else
  3156. {
  3157. delete wdBreakpoint->mCondition;
  3158. auto condition = new WdBreakpointCondition();
  3159. condition->mExpr = conditionExpr;
  3160. wdBreakpoint->mCondition = condition;
  3161. }
  3162. }
  3163. void WinDebugger::SetBreakpointLogging(Breakpoint* breakpoint, const StringImpl& logging, bool breakAfterLogging)
  3164. {
  3165. AutoCrit autoCrit(mDebugManager->mCritSect);
  3166. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3167. BF_ASSERT(!wdBreakpoint->mIsLinkedSibling);
  3168. wdBreakpoint->mLogging = logging;
  3169. wdBreakpoint->mBreakAfterLogging = breakAfterLogging;
  3170. }
  3171. bool WinDebugger::CheckConditionalBreakpoint(WdBreakpoint* breakpoint, DbgSubprogram* dbgSubprogram, addr_target pcAddress)
  3172. {
  3173. // What was this assertion for?
  3174. //BF_ASSERT(mCallStack.size() == 0);
  3175. auto headBreakpoint = breakpoint->GetHeadBreakpoint();
  3176. if (headBreakpoint->mThreadId != -1)
  3177. {
  3178. if ((mActiveThread != NULL) && (mActiveThread->mThreadId != headBreakpoint->mThreadId))
  3179. return false;
  3180. }
  3181. auto _SplitExpr = [&](const StringImpl& expr, StringImpl& outExpr, StringImpl& outSubject)
  3182. {
  3183. int crPos = expr.IndexOf('\n');
  3184. if (crPos != -1)
  3185. {
  3186. outExpr += expr.Substring(0, crPos);
  3187. outSubject += expr.Substring(crPos + 1);
  3188. }
  3189. else
  3190. {
  3191. outExpr += expr;
  3192. }
  3193. };
  3194. if (headBreakpoint->mCondition != NULL)
  3195. {
  3196. ClearCallStack();
  3197. auto conditional = headBreakpoint->mCondition;
  3198. if (conditional->mDbgEvaluationContext == NULL)
  3199. {
  3200. CPURegisters registers;
  3201. PopulateRegisters(&registers);
  3202. auto pcAddress = registers.GetPC();
  3203. DbgSubprogram* subprogram = mDebugTarget->FindSubProgram(pcAddress);
  3204. if (subprogram == NULL)
  3205. {
  3206. return false;
  3207. }
  3208. StringT<256> expr;
  3209. StringT<256> subjectExpr;
  3210. if (breakpoint->mMemoryBreakpointInfo != NULL)
  3211. {
  3212. subjectExpr += "*";
  3213. }
  3214. _SplitExpr(conditional->mExpr, expr, subjectExpr);
  3215. DbgLanguage language = DbgLanguage_Unknown;
  3216. if (expr.StartsWith("@Beef:"))
  3217. {
  3218. expr.Remove(0, 6);
  3219. language = DbgLanguage_Beef;
  3220. }
  3221. else if (expr.StartsWith("@C:"))
  3222. {
  3223. expr.Remove(0, 3);
  3224. language = DbgLanguage_C;
  3225. }
  3226. conditional->mDbgEvaluationContext = new DbgEvaluationContext(this, subprogram->mCompileUnit->mDbgModule, expr);
  3227. if (language != DbgLanguage_Unknown)
  3228. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mLanguage = language;
  3229. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mSubjectExpr = subjectExpr;
  3230. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mDbgCompileUnit = subprogram->mCompileUnit;
  3231. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mCallStackIdx = 0;
  3232. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mExpressionFlags = (DwEvalExpressionFlags)(DwEvalExpressionFlag_AllowSideEffects);
  3233. }
  3234. WdStackFrame* wdStackFrame = new WdStackFrame();
  3235. PopulateRegisters(&wdStackFrame->mRegisters);
  3236. mCallStack.Add(wdStackFrame);
  3237. DbgTypedValue result = conditional->mDbgEvaluationContext->EvaluateInContext(DbgTypedValue());
  3238. ClearCallStack();
  3239. if ((result.mType != NULL) && (result.mType->mTypeCode == DbgType_Bitfield))
  3240. result.mType = result.mType->mTypeParam;
  3241. if (conditional->mDbgEvaluationContext->mPassInstance->HasFailed())
  3242. {
  3243. String errorStr = "FAILED";
  3244. for (auto error : conditional->mDbgEvaluationContext->mPassInstance->mErrors)
  3245. {
  3246. if (!error->mIsWarning)
  3247. errorStr = error->mError;
  3248. }
  3249. String condError = StrFormat("error Conditional breakpoint expression '%s' failed: %s", conditional->mExpr.c_str(), errorStr.c_str());
  3250. mDebugManager->mOutMessages.push_back(condError);
  3251. return true;
  3252. }
  3253. else if (conditional->mDbgEvaluationContext->mDbgExprEvaluator->mBlockedSideEffects)
  3254. {
  3255. mDebugManager->mOutMessages.push_back(StrFormat("error Conditional breakpoint expression '%s' contained function calls, which is not allowed", conditional->mExpr.c_str()));
  3256. return true;
  3257. }
  3258. else if ((!result) || (!result.mType->IsBoolean()))
  3259. {
  3260. mDebugManager->mOutMessages.push_back(StrFormat("error Conditional breakpoint expression '%s' must result in a boolean value", conditional->mExpr.c_str()));
  3261. return true;
  3262. }
  3263. else if (!result.mBool)
  3264. return false;
  3265. }
  3266. headBreakpoint->mHitCount++;
  3267. switch (headBreakpoint->mHitCountBreakKind)
  3268. {
  3269. case DbgHitCountBreakKind_Equals:
  3270. if (headBreakpoint->mHitCount != headBreakpoint->mTargetHitCount)
  3271. return false;
  3272. break;
  3273. case DbgHitCountBreakKind_GreaterEquals:
  3274. if (headBreakpoint->mHitCount < headBreakpoint->mTargetHitCount)
  3275. return false;
  3276. break;
  3277. case DbgHitCountBreakKind_Multiple:
  3278. if ((headBreakpoint->mHitCount % headBreakpoint->mTargetHitCount) != 0)
  3279. return false;
  3280. break;
  3281. }
  3282. mActiveBreakpoint = breakpoint;
  3283. mBreakStackFrameIdx = -1;
  3284. if (!headBreakpoint->mLogging.IsEmpty())
  3285. {
  3286. ClearCallStack();
  3287. DwFormatInfo formatInfo;
  3288. formatInfo.mCallStackIdx = 0;
  3289. DbgCompileUnit* dbgCompileUnit = NULL;
  3290. if (dbgSubprogram == NULL)
  3291. dbgSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3292. if (dbgSubprogram != NULL)
  3293. {
  3294. dbgCompileUnit = dbgSubprogram->mCompileUnit;
  3295. formatInfo.mLanguage = dbgSubprogram->GetLanguage();
  3296. }
  3297. auto prevRunState = mRunState;
  3298. mRunState = RunState_Paused; // We need to be paused to avoid certain errors in the eval
  3299. String displayString;
  3300. String expr;
  3301. _SplitExpr(headBreakpoint->mLogging, expr, formatInfo.mSubjectExpr);
  3302. if (expr.StartsWith("@Beef:"))
  3303. {
  3304. expr.Remove(0, 6);
  3305. formatInfo.mLanguage = DbgLanguage_Beef;
  3306. }
  3307. else if (expr.StartsWith("@C:"))
  3308. {
  3309. expr.Remove(0, 3);
  3310. formatInfo.mLanguage = DbgLanguage_C;
  3311. }
  3312. ProcessEvalString(dbgCompileUnit, DbgTypedValue(), expr, displayString, formatInfo, NULL, false);
  3313. mRunState = prevRunState;
  3314. displayString.Insert(0, "log ");
  3315. displayString.Append("\n");
  3316. mDebugManager->mOutMessages.push_back(displayString);
  3317. if (!headBreakpoint->mBreakAfterLogging)
  3318. return false;
  3319. }
  3320. return true;
  3321. }
  3322. void WinDebugger::CleanupDebugEval(bool restoreRegisters)
  3323. {
  3324. BfLogDbg("CleanupDebugEval ThreadId=%d\n", mDebugEvalThreadInfo.mThreadId);
  3325. WdThreadInfo* evalThreadInfo = NULL;
  3326. if (mThreadMap.TryGetValue(mDebugEvalThreadInfo.mThreadId, &evalThreadInfo))
  3327. {
  3328. if ((restoreRegisters) && (!mDbgBreak))
  3329. {
  3330. SetAndRestoreValue<WdThreadInfo*> activeThread(mActiveThread, evalThreadInfo);
  3331. RestoreAllRegisters();
  3332. // if (mRunState == RunState_Running_ToTempBreakpoint)
  3333. // mRunState = RunState_Paused;
  3334. }
  3335. evalThreadInfo->mStartSP = mDebugEvalThreadInfo.mStartSP;
  3336. evalThreadInfo->mStoppedAtAddress = mDebugEvalThreadInfo.mStoppedAtAddress;
  3337. evalThreadInfo->mIsAtBreakpointAddress = mDebugEvalThreadInfo.mIsAtBreakpointAddress;
  3338. evalThreadInfo->mBreakpointAddressContinuing = mDebugEvalThreadInfo.mBreakpointAddressContinuing;
  3339. }
  3340. delete mDebugPendingExpr;
  3341. mDebugPendingExpr = NULL;
  3342. mDebugEvalThreadInfo = WdThreadInfo();
  3343. OutputRawMessage("rehupLoc");
  3344. }
  3345. bool WinDebugger::FixCallStackIdx(int& callStackIdx)
  3346. {
  3347. callStackIdx = BF_MAX(callStackIdx, 0);
  3348. if (mCallStack.IsEmpty())
  3349. UpdateCallStack();
  3350. int stackSize = (int)mCallStack.size();
  3351. while (callStackIdx >= mCallStack.size())
  3352. {
  3353. UpdateCallStack();
  3354. if (stackSize == (int)mCallStack.size())
  3355. break; // Didn't change
  3356. stackSize = (int)mCallStack.size();
  3357. }
  3358. if (callStackIdx >= stackSize)
  3359. {
  3360. callStackIdx = 0;
  3361. return false;
  3362. }
  3363. return true;
  3364. }
  3365. bool WinDebugger::HasLineInfoAt(addr_target address)
  3366. {
  3367. BP_ZONE("WinDebugger::HasLineInfoAt");
  3368. DbgSubprogram* dbgSubprogram = NULL;
  3369. auto dwLineData = FindLineDataAtAddress(address, &dbgSubprogram);
  3370. return (dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dbgSubprogram->GetLineAddr(*dwLineData) == address);
  3371. }
  3372. void WinDebugger::StepLineTryPause(addr_target address, bool requireExactMatch)
  3373. {
  3374. if (mStepInAssembly)
  3375. return;
  3376. if (mStepLineData.mLineData != NULL)
  3377. {
  3378. DbgSubprogram* dbgSubprogram = NULL;
  3379. DbgSrcFile* dbgSrcFile = NULL;
  3380. auto dwLineData = FindLineDataAtAddress(address, &dbgSubprogram, &dbgSrcFile);
  3381. if ((dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && ((!requireExactMatch) || (dbgSubprogram->GetLineAddr(*dwLineData) == address)))
  3382. {
  3383. // "Invalid" line
  3384. if (dwLineData->mColumn == -1)
  3385. {
  3386. SetupStep(mStepType);
  3387. mRunState = RunState_Running;
  3388. return;
  3389. }
  3390. // If we're on the same line but a different column or a <= address then keep it keep looking
  3391. if ((dbgSrcFile == mStepLineData.GetSrcFile()) &&
  3392. ((!requireExactMatch) || (dwLineData != mStepLineData.mLineData) || (address <= mStepStartPC)) &&
  3393. (dwLineData->mLine == mStepLineData.mLineData->mLine))
  3394. {
  3395. SetupStep(mStepType);
  3396. mRunState = RunState_Running;
  3397. return;
  3398. }
  3399. }
  3400. }
  3401. mRunState = RunState_Paused;
  3402. }
  3403. void WinDebugger::BreakAll()
  3404. {
  3405. AutoCrit autoCrit(mDebugManager->mCritSect);
  3406. ::DebugBreakProcess(mProcessInfo.hProcess);
  3407. }
  3408. void WinDebugger::StepInto(bool inAssembly)
  3409. {
  3410. AutoCrit autoCrit(mDebugManager->mCritSect);
  3411. if (!TryRunContinue())
  3412. return;
  3413. BfLogDbg("StepInto\n");
  3414. mCurNoInfoStepTries = 0; // Reset
  3415. mStepInAssembly = inAssembly;
  3416. SetupStep(StepType_StepInto);
  3417. ContinueDebugEvent();
  3418. }
  3419. void WinDebugger::StepIntoSpecific(intptr inAddr)
  3420. {
  3421. addr_target addr = (addr_target)inAddr;
  3422. AutoCrit autoCrit(mDebugManager->mCritSect);
  3423. if (!TryRunContinue())
  3424. return;
  3425. BfLogDbg("StepIntoSpecific %p\n", addr);
  3426. mCurNoInfoStepTries = 0; // Reset
  3427. mStepInAssembly = false;
  3428. SetupStep(StepType_StepInto);
  3429. mIsStepIntoSpecific = true;
  3430. mStepType = StepType_StepInto_Unfiltered;
  3431. if (mStepStartPC != addr)
  3432. {
  3433. RemoveTempBreakpoints();
  3434. SetTempBreakpoint(addr);
  3435. mStepBreakpointAddrs.push_back(addr);
  3436. }
  3437. ContinueDebugEvent();
  3438. }
  3439. void WinDebugger::PushValue(CPURegisters* registers, int64 val)
  3440. {
  3441. addr_target* regSP = registers->GetSPRegisterRef();
  3442. *regSP -= sizeof(addr_target);
  3443. WriteMemory<addr_target>(*regSP, (addr_target)val);
  3444. }
  3445. void WinDebugger::PushValue(CPURegisters* registers, const DbgTypedValue& typedValue)
  3446. {
  3447. addr_target* regSP = registers->GetSPRegisterRef();
  3448. int byteCount = typedValue.mType->GetByteCount();
  3449. if ((byteCount == 8) || (sizeof(addr_target) == 8))
  3450. {
  3451. *regSP -= sizeof(int64);
  3452. addr_target val = typedValue.mInt64;
  3453. if (typedValue.mType->IsCompositeType())
  3454. val = typedValue.mSrcAddress;
  3455. WriteMemory<int64>(*regSP, val);
  3456. }
  3457. else
  3458. {
  3459. *regSP -= sizeof(int32);
  3460. addr_target val = typedValue.mInt32;
  3461. if (typedValue.mType->IsCompositeType())
  3462. val = typedValue.mSrcAddress;
  3463. WriteMemory<int32>(*regSP, val);
  3464. }
  3465. }
  3466. void WinDebugger::SetThisRegister(CPURegisters* registers, addr_target val)
  3467. {
  3468. #if BF_DBG_32
  3469. registers->mIntRegs.ecx = val;
  3470. #else
  3471. registers->mIntRegs.rcx = val;
  3472. #endif
  3473. }
  3474. void WinDebugger::AddParamValue(int paramIdx, bool hadThis, CPURegisters* registers, const DbgTypedValue& typedValue)
  3475. {
  3476. #if BF_DBG_32
  3477. PushValue(registers, typedValue);
  3478. #else
  3479. int regIdx = paramIdx + (hadThis ? 1 : 0);
  3480. if (typedValue.mType->IsFloat())
  3481. {
  3482. PushValue(registers, typedValue);
  3483. if (regIdx < 4)
  3484. {
  3485. if (typedValue.mType->mTypeCode == DbgType_Single)
  3486. {
  3487. registers->mXmmRegsArray[regIdx].f[0] = typedValue.mSingle;
  3488. }
  3489. else
  3490. {
  3491. registers->mXmmDRegsArray[regIdx].d[0] = typedValue.mDouble;
  3492. }
  3493. }
  3494. }
  3495. else
  3496. {
  3497. PushValue(registers, typedValue);
  3498. if (regIdx < 4)
  3499. {
  3500. int64 val;
  3501. if (typedValue.mType->IsCompositeType())
  3502. val = typedValue.mSrcAddress;
  3503. else
  3504. val = typedValue.mPtr;
  3505. if (regIdx == 0)
  3506. registers->mIntRegs.rcx = val;
  3507. else if (regIdx == 1)
  3508. registers->mIntRegs.rdx = val;
  3509. else if (regIdx == 2)
  3510. registers->mIntRegs.r8 = val;
  3511. else if (regIdx == 3)
  3512. registers->mIntRegs.r9 = val;
  3513. }
  3514. }
  3515. #endif
  3516. }
  3517. bool WinDebugger::CheckNeedsSRetArgument(DbgType* retType)
  3518. {
  3519. if (!retType->IsCompositeType())
  3520. return false;
  3521. if (retType->GetByteCount() == 0)
  3522. return false;
  3523. //TODO: Change when we change the calling convention
  3524. if (retType->GetLanguage() == DbgLanguage_Beef)
  3525. return true;
  3526. int retSize = retType->GetByteCount();
  3527. //TODO: Check for 'POD' type?
  3528. if ((retSize == 1) || (retSize == 2) || (retSize == 4) || (retSize == sizeof(addr_target)))
  3529. return false;
  3530. return true;
  3531. }
  3532. DbgTypedValue WinDebugger::ReadReturnValue(CPURegisters* registers, DbgType* type)
  3533. {
  3534. DbgTypedValue retValue;
  3535. if (type->IsFloat())
  3536. {
  3537. retValue.mType = type;
  3538. #if BF_DBG_32
  3539. retValue.mDouble = ConvertFloat80ToDouble(registers->mFpMmRegsArray[0].fp.fp80);
  3540. if (type->mSize == 4)
  3541. retValue.mSingle = (float)retValue.mDouble;
  3542. #else
  3543. if (retValue.mType->mTypeCode == DbgType_Single)
  3544. retValue.mSingle = registers->mXmmRegsArray[0].f[0];
  3545. else
  3546. retValue.mDouble = registers->mXmmDRegsArray[0].d[0];
  3547. #endif
  3548. }
  3549. else if (type->IsCompositeType())
  3550. {
  3551. retValue.mType = type;
  3552. if (CheckNeedsSRetArgument(type))
  3553. {
  3554. #ifdef BF_DBG_32
  3555. retValue.mSrcAddress = mSavedContext.Esp - BF_ALIGN(type->GetByteCount(), 16);
  3556. #else
  3557. retValue.mSrcAddress = mSavedContext.Rsp - BF_ALIGN(type->GetByteCount(), 16);
  3558. #endif
  3559. }
  3560. else
  3561. {
  3562. #ifdef BF_DBG_32
  3563. retValue.mInt32 = mSavedContext.Eax;
  3564. #else
  3565. retValue.mInt64 = mSavedContext.Rax;
  3566. #endif
  3567. }
  3568. }
  3569. else
  3570. {
  3571. #ifdef BF_DBG_32
  3572. retValue.mType = type;
  3573. retValue.mInt32 = registers->mIntRegs.eax;
  3574. if (type->mSize == 8)
  3575. (&retValue.mInt32)[1] = registers->mIntRegs.edx;
  3576. #else
  3577. retValue.mType = type;
  3578. retValue.mInt64 = registers->mIntRegs.rax;
  3579. #endif
  3580. return retValue;
  3581. }
  3582. return retValue;
  3583. }
  3584. bool WinDebugger::SetRegisters(CPURegisters* registers)
  3585. {
  3586. BF_CONTEXT lcContext;
  3587. lcContext.ContextFlags = BF_CONTEXT_CONTROL | BF_CONTEXT_INTEGER | BF_CONTEXT_FLOATING_POINT | BF_CONTEXT_EXTENDED_REGISTERS | BF_CONTEXT_SEGMENTS;
  3588. lcContext.ContextFlags |= BF_CONTEXT_EXCEPTION_REQUEST;
  3589. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  3590. #ifdef BF_DBG_32
  3591. lcContext.Eax = registers->mIntRegs.eax;
  3592. lcContext.Ecx = registers->mIntRegs.ecx;
  3593. lcContext.Edx = registers->mIntRegs.edx;
  3594. lcContext.Ebx = registers->mIntRegs.ebx;
  3595. lcContext.Esp = registers->mIntRegs.esp;
  3596. lcContext.Ebp = registers->mIntRegs.ebp;
  3597. lcContext.Esi = registers->mIntRegs.esi;
  3598. lcContext.Edi = registers->mIntRegs.edi;
  3599. lcContext.Eip = registers->mIntRegs.eip;
  3600. lcContext.EFlags = registers->mIntRegs.efl;
  3601. BF_ASSERT(sizeof(lcContext.FloatSave.RegisterArea) == sizeof(registers->mFpMmRegsArray));
  3602. memcpy(lcContext.FloatSave.RegisterArea, registers->mFpMmRegsArray, sizeof(lcContext.FloatSave.RegisterArea));
  3603. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 32*sizeof(float));
  3604. memcpy(&lcContext.ExtendedRegisters[160], registers->mXmmRegsArray, sizeof(registers->mXmmRegsArray));
  3605. #else
  3606. lcContext.Rax = registers->mIntRegs.rax;
  3607. lcContext.Rcx = registers->mIntRegs.rcx;
  3608. lcContext.Rdx = registers->mIntRegs.rdx;
  3609. lcContext.Rbx = registers->mIntRegs.rbx;
  3610. lcContext.Rsp = registers->mIntRegs.rsp;
  3611. lcContext.Rbp = registers->mIntRegs.rbp;
  3612. lcContext.Rsi = registers->mIntRegs.rsi;
  3613. lcContext.Rdi = registers->mIntRegs.rdi;
  3614. lcContext.Rip = registers->mIntRegs.rip;
  3615. lcContext.EFlags = (DWORD)registers->mIntRegs.efl;
  3616. lcContext.R8 = registers->mIntRegs.r8;
  3617. lcContext.R9 = registers->mIntRegs.r9;
  3618. lcContext.R10 = registers->mIntRegs.r10;
  3619. lcContext.R11 = registers->mIntRegs.r11;
  3620. lcContext.R12 = registers->mIntRegs.r12;
  3621. lcContext.R13 = registers->mIntRegs.r13;
  3622. lcContext.R14 = registers->mIntRegs.r14;
  3623. lcContext.R15 = registers->mIntRegs.r15;
  3624. for (int i = 0; i < 8; i++)
  3625. {
  3626. memcpy(&lcContext.FltSave.FloatRegisters[i], &registers->mFpMmRegsArray[i], 10);
  3627. }
  3628. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 64 * sizeof(float));
  3629. memcpy(BF_CONTEXT_XMMDATA(lcContext), registers->mXmmRegsArray, sizeof(registers->mXmmRegsArray));
  3630. #endif
  3631. //lcContext.ContextFlags |= BF_CONTEXT_EXCEPTION_REQUEST;
  3632. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  3633. return (lcContext.ContextFlags & (BF_CONTEXT_EXCEPTION_ACTIVE | BF_CONTEXT_SERVICE_ACTIVE)) == 0;
  3634. }
  3635. void WinDebugger::SaveAllRegisters()
  3636. {
  3637. BfLogDbg("SaveAllRegisters setting mSavedAtBreakpointAddress = %p\n", mActiveThread->mIsAtBreakpointAddress);
  3638. mSavedAtBreakpointAddress = mActiveThread->mIsAtBreakpointAddress;
  3639. mSavedBreakpointAddressContinuing = mActiveThread->mBreakpointAddressContinuing;
  3640. mSavedContext.ContextFlags = BF_CONTEXT_ALL;
  3641. BF_GetThreadContext(mActiveThread->mHThread, &mSavedContext);
  3642. }
  3643. void WinDebugger::RestoreAllRegisters()
  3644. {
  3645. BfLogDbg("RestoreAllRegisters setting mIsAtBreakpointAddress = %p\n", mSavedAtBreakpointAddress);
  3646. mActiveThread->mIsAtBreakpointAddress = mSavedAtBreakpointAddress;
  3647. mActiveThread->mBreakpointAddressContinuing = mSavedBreakpointAddressContinuing;
  3648. BF_SetThreadContext(mActiveThread->mHThread, &mSavedContext);
  3649. #ifdef BF_DBG_32
  3650. //TODO: Find the test that this was required for...
  3651. // if (mActiveThread->mIsAtBreakpointAddress == mSavedContext.Eip)
  3652. // {
  3653. // if (mRunState == RunState_Running_ToTempBreakpoint)
  3654. // mRunState = RunState_Paused;
  3655. // }
  3656. // else
  3657. // {
  3658. // SetTempBreakpoint(mSavedContext.Eip);
  3659. // mRunState = RunState_Running_ToTempBreakpoint;
  3660. // mStepType = StepType_ToTempBreakpoint;
  3661. // mSteppingThread = mActiveThread;
  3662. // }
  3663. #endif
  3664. }
  3665. void WinDebugger::OutputMessage(const StringImpl& msg)
  3666. {
  3667. if (this == NULL)
  3668. return;
  3669. AutoCrit autoCrit(mDebugManager->mCritSect);
  3670. mDebugManager->mOutMessages.push_back("msg " + msg);
  3671. }
  3672. void WinDebugger::OutputRawMessage(const StringImpl& msg)
  3673. {
  3674. if (this == NULL)
  3675. return;
  3676. AutoCrit autoCrit(mDebugManager->mCritSect);
  3677. mDebugManager->mOutMessages.push_back(msg);
  3678. }
  3679. void WinDebugger::SetRunState(RunState runState)
  3680. {
  3681. mRunState = runState;
  3682. }
  3683. bool WinDebugger::TryRunContinue()
  3684. {
  3685. if (mRunState == RunState_Exception)
  3686. {
  3687. mIsContinuingFromException = true;
  3688. mRunState = RunState_Paused;
  3689. }
  3690. if (((mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint)) && (mNeedsRehupBreakpoints))
  3691. RehupBreakpoints(true);
  3692. return true;
  3693. }
  3694. void WinDebugger::ClearStep()
  3695. {
  3696. BfLogDbg("ClearStep\n");
  3697. RemoveTempBreakpoints();
  3698. mOrigStepType = StepType_None;
  3699. mStepType = StepType_None;
  3700. mStepStartPC = 0;
  3701. mStepSP = 0;
  3702. mStepPC = 0;
  3703. mIsStepIntoSpecific = false;
  3704. mStepIsRecursing = false;
  3705. mStepStopOnNextInstruction = false;
  3706. mStepLineData = DbgLineDataEx();
  3707. }
  3708. bool WinDebugger::SetupStep(StepType stepType)
  3709. {
  3710. BP_ZONE("SetupStep");
  3711. RemoveTempBreakpoints();
  3712. if (mNeedsRehupBreakpoints)
  3713. RehupBreakpoints(true);
  3714. if (mOrigStepType == StepType_None)
  3715. mOrigStepType = stepType;
  3716. mStepType = stepType;
  3717. mSteppingThread = mActiveThread;
  3718. mStepSwitchedThreads = false;
  3719. mContinueFromBreakpointFailed = false;
  3720. CPURegisters registers;
  3721. PopulateRegisters(&registers);
  3722. addr_target pcAddress = registers.GetPC();
  3723. if (mStepLineData.IsNull())
  3724. {
  3725. DbgSubprogram* dbgSubprogram = NULL;
  3726. auto dbgLineData = FindLineDataAtAddress(pcAddress, &dbgSubprogram);
  3727. mStepLineData = DbgLineDataEx(dbgLineData, dbgSubprogram);
  3728. mStepStartPC = registers.GetPC();
  3729. }
  3730. bool isDeeper = mStepSP > registers.GetSP();
  3731. 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);
  3732. mStepSP = registers.GetSP();
  3733. mStepPC = registers.GetPC();
  3734. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_NoFrame) || (mStepType == StepType_StepOut_ThenInto))
  3735. {
  3736. if (mStepType != StepType_StepOut_NoFrame)
  3737. {
  3738. // Test for stepping out of an inline method
  3739. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3740. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL))
  3741. {
  3742. DbgSubprogram* topSubprogram = dwSubprogram->GetRootInlineParent();
  3743. if ((mOrigStepType == StepType_StepInto) || (mOrigStepType == StepType_StepInto_Unfiltered))
  3744. {
  3745. mStepType = mOrigStepType;
  3746. }
  3747. else
  3748. {
  3749. mStepType = StepType_StepOut_Inline;
  3750. // Set up pcAddress to detect recursion
  3751. //TODO: We can't set a physical breakpoint here because we will immediately hit it when attempting to step over an inlined method.
  3752. // An inlined method can't recurse anyway, but store the pcAddress in mTempBreakpoints because we still check that for recursion
  3753. // SetTempBreakpoint(pcAddress);
  3754. //mTempBreakpoint.push_back(pcAddress);
  3755. mStepBreakpointAddrs.push_back(pcAddress);
  3756. }
  3757. addr_target endAddress = dwSubprogram->mBlock.mHighPC;
  3758. if (dwSubprogram->mHasLineAddrGaps)
  3759. {
  3760. // Keep bumping out the address as long as we can find lines that contain the nextPC
  3761. addr_target nextAddr = pcAddress;
  3762. for (auto& lineInfo : topSubprogram->mLineInfo->mLines)
  3763. {
  3764. auto lineAddr = topSubprogram->GetLineAddr(lineInfo);
  3765. if ((nextAddr >= lineAddr) && (nextAddr < lineAddr + lineInfo.mContribSize))
  3766. {
  3767. auto ctx = topSubprogram->mLineInfo->mContexts[lineInfo.mCtxIdx];
  3768. if (ctx.mInlinee == dwSubprogram)
  3769. {
  3770. nextAddr = lineAddr + lineInfo.mContribSize;
  3771. }
  3772. }
  3773. }
  3774. if (nextAddr != pcAddress)
  3775. endAddress = nextAddr;
  3776. }
  3777. BfLogDbg("Stepping out of inlined method, end address: %p\n", endAddress);
  3778. SetTempBreakpoint(endAddress);
  3779. mStepBreakpointAddrs.push_back(endAddress);
  3780. addr_target decodeAddress = dwSubprogram->mBlock.mLowPC;
  3781. while (decodeAddress < endAddress)
  3782. {
  3783. CPUInst inst;
  3784. if (!mDebugTarget->DecodeInstruction(decodeAddress, &inst))
  3785. break;
  3786. addr_target targetAddress = inst.GetTarget();
  3787. // We need to find a targetAddress
  3788. if ((targetAddress != 0) &&
  3789. !((targetAddress >= dwSubprogram->mBlock.mLowPC) && (targetAddress < dwSubprogram->mBlock.mHighPC)) &&
  3790. ((targetAddress >= topSubprogram->mBlock.mLowPC) && (targetAddress < topSubprogram->mBlock.mHighPC)))
  3791. {
  3792. BfLogDbg("Stepping out of inlined method, branch address: %p\n", targetAddress);
  3793. SetTempBreakpoint(targetAddress);
  3794. mStepBreakpointAddrs.push_back(targetAddress);
  3795. }
  3796. decodeAddress += inst.GetLength();
  3797. }
  3798. return true;
  3799. }
  3800. }
  3801. if ((mStepType != StepType_StepOut_NoFrame) && (RollBackStackFrame(&registers, true)))
  3802. {
  3803. bool isStackAdjust = false;
  3804. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3805. if (dwSubprogram != NULL)
  3806. {
  3807. if ((strcmp(dwSubprogram->mName, "_chkstk") == 0) ||
  3808. (strcmp(dwSubprogram->mName, "__chkstk") == 0) ||
  3809. (strcmp(dwSubprogram->mName, "_alloca_probe") == 0))
  3810. isStackAdjust = true;
  3811. }
  3812. pcAddress = registers.GetPC();
  3813. if (isStackAdjust)
  3814. {
  3815. // We set it to zero so we never detect an "isDeeper" condition which would skip over the return-location breakpoint
  3816. mStepSP = 0;
  3817. }
  3818. else
  3819. {
  3820. addr_target oldAddress = pcAddress;
  3821. CPUInst inst;
  3822. while (true)
  3823. {
  3824. if (mStepInAssembly)
  3825. break;
  3826. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  3827. break;
  3828. if ((inst.IsBranch()) || (inst.IsCall()) || (inst.IsReturn()))
  3829. break;
  3830. #ifdef BF_DBG_32
  3831. if (!inst.StackAdjust(mStepSP))
  3832. break;
  3833. #endif
  3834. DbgSubprogram* checkSubprogram = NULL;
  3835. auto checkLineData = FindLineDataAtAddress(pcAddress, &checkSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  3836. if (checkLineData == NULL)
  3837. break;
  3838. if (checkSubprogram->GetLineAddr(*checkLineData) == pcAddress)
  3839. break;
  3840. pcAddress += inst.GetLength();
  3841. }
  3842. if (pcAddress != oldAddress)
  3843. {
  3844. BfLogDbg("Adjusting stepout address from %p to %p\n", oldAddress, pcAddress);
  3845. }
  3846. }
  3847. BfLogDbg("SetupStep Stepout SetTempBreakpoint %p\n", pcAddress);
  3848. SetTempBreakpoint(pcAddress);
  3849. mStepBreakpointAddrs.push_back(pcAddress);
  3850. if (mStepType != StepType_StepOut_ThenInto)
  3851. mStepType = StepType_StepOut;
  3852. }
  3853. else
  3854. {
  3855. // Try to handle the case where we just entered this call so the return address is the first entry on the stack
  3856. addr_target* regSP = registers.GetSPRegisterRef();
  3857. pcAddress = ReadMemory<addr_target>(*regSP);
  3858. *regSP += sizeof(addr_target);
  3859. if (mDebugTarget->FindSubProgram(pcAddress) != NULL)
  3860. {
  3861. BfLogDbg("SetupStep Stepout SetTempBreakpoint (2) %p\n", pcAddress);
  3862. SetTempBreakpoint(pcAddress);
  3863. mStepBreakpointAddrs.push_back(pcAddress);
  3864. if (mOrigStepType == StepType_StepInto)
  3865. mStepType = StepType_StepInto;
  3866. else
  3867. mStepType = StepType_StepOver;
  3868. return true;
  3869. }
  3870. else
  3871. {
  3872. // Just do stepovers until we eventually step out
  3873. //BF_DBG_FATAL("StepOut Failed");
  3874. BfLogDbg("StepOut Failed\n");
  3875. if (mLastValidStepIntoPC != 0)
  3876. {
  3877. BfLogDbg("Using mLastValidStepIntoPC: %p\n", mLastValidStepIntoPC);
  3878. if (mOrigStepType == StepType_StepInto)
  3879. mStepType = StepType_StepInto;
  3880. else
  3881. mStepType = StepType_StepOver;
  3882. SetTempBreakpoint(mLastValidStepIntoPC);
  3883. mStepBreakpointAddrs.push_back(0);
  3884. mStepBreakpointAddrs.push_back(mLastValidStepIntoPC);
  3885. mLastValidStepIntoPC = 0;
  3886. return true;
  3887. }
  3888. else
  3889. {
  3890. BfLogDbg("Stopping");
  3891. mStepType = StepType_None;
  3892. mRunState = RunState_Paused;
  3893. return true;
  3894. }
  3895. }
  3896. }
  3897. }
  3898. if ((mStepType != StepType_StepOut) && (mStepType != StepType_StepOut_ThenInto))
  3899. {
  3900. if (mDebuggerWaitingThread != mSteppingThread)
  3901. {
  3902. // We've switched threads, so there's a possible race condition:
  3903. // This new thread may already have an EXCEPTION_BREAKPOINT queued up so the PC is actually
  3904. // located one byte past the BREAK instruction, which is one byte into whatever instruction
  3905. // was previously there. We can't insert normal BREAK instructions because we don't know
  3906. // if the current PC is actually at an instruction start, so we do a single step with a
  3907. // slower stack call check to see if we need to step out after a "step over"
  3908. BfLogDbg("Step - switched threads mIsAtBreakpointAddress:%p\n", mSteppingThread->mIsAtBreakpointAddress);
  3909. mStepSwitchedThreads = true;
  3910. SingleStepX86();
  3911. return true;
  3912. }
  3913. bool breakOnNext = false;
  3914. int instIdx = 0;
  3915. for (instIdx = 0; true; instIdx++)
  3916. {
  3917. bool isAtLine = false;
  3918. DbgSubprogram* dwSubprogram = NULL;
  3919. auto dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  3920. isAtLine = (instIdx > 0) && (dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dwSubprogram->GetLineAddr(*dwLineData) == pcAddress);
  3921. // "Never step into" line
  3922. if ((dwLineData != NULL) && (dwLineData->mColumn == -2) && (stepType == StepType_StepInto))
  3923. stepType = StepType_StepOver;
  3924. CPUInst inst;
  3925. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  3926. {
  3927. BfLogDbg("Decode failed, set up SingleStepX86 %p\n", pcAddress);
  3928. SingleStepX86();
  3929. mStepStopOnNextInstruction = true;
  3930. return true;
  3931. }
  3932. if (instIdx > 256)
  3933. {
  3934. BfLogDbg("Too many SetupStep iterations");
  3935. breakOnNext = true;
  3936. }
  3937. if ((inst.IsReturn()) && (instIdx == 0) && (!mStepInAssembly))
  3938. {
  3939. // Do actual STEP OUT so we set up proper "stepping over unimportant post-return instructions"
  3940. if (stepType == StepType_StepInto)
  3941. return SetupStep(StepType_StepOut_ThenInto);
  3942. else
  3943. return SetupStep(StepType_StepOut);
  3944. }
  3945. if ((breakOnNext) || (mStepInAssembly) || (isAtLine) || (inst.IsBranch()) || (inst.IsCall()) || (inst.IsReturn()))
  3946. {
  3947. if (((instIdx == 0) || (mStepInAssembly)) && (!breakOnNext))
  3948. {
  3949. if ((stepType == StepType_StepOver) && (inst.IsCall()))
  3950. {
  3951. // Continue - sets a breakpoint on the call line to detect recursion.
  3952. // The next loop through will set a breakpoint on the line after the return
  3953. BfLogDbg("StepHadCall\n");
  3954. breakOnNext = true;
  3955. BfLogDbg("StepHadCall setting mIsAtBreakpointAddress = %p\n", pcAddress);
  3956. mSteppingThread->mIsAtBreakpointAddress = pcAddress;
  3957. SetTempBreakpoint(pcAddress);
  3958. mStepBreakpointAddrs.push_back(pcAddress);
  3959. }
  3960. else
  3961. {
  3962. if (inst.IsCall())
  3963. {
  3964. if ((mLastValidStepIntoPC == 0) || (dwSubprogram != NULL))
  3965. mLastValidStepIntoPC = pcAddress + inst.mSize;
  3966. }
  3967. if ((dwLineData != NULL) && (inst.IsBranch()))
  3968. {
  3969. addr_target targetAddr = inst.GetTarget();
  3970. if (targetAddr < dwSubprogram->GetLineAddr(*dwLineData))
  3971. {
  3972. // Jumping backwards, stop at next instruction
  3973. mStepStopOnNextInstruction = true;
  3974. }
  3975. }
  3976. bool isPrefixOnly = false;
  3977. if ((mStepInAssembly) && (stepType == StepType_StepOver) && (inst.IsRep(isPrefixOnly)))
  3978. {
  3979. if (isPrefixOnly)
  3980. {
  3981. CPUInst nextInst;
  3982. if (mDebugTarget->DecodeInstruction(pcAddress + inst.GetLength(), &nextInst))
  3983. {
  3984. if (nextInst.IsBranch())
  3985. {
  3986. // repne jmp - this appears in __chkstk (for example)
  3987. // We don't have a good way to "step over" this one, so just do a single step
  3988. }
  3989. else
  3990. {
  3991. // Step over the rep + target instruction
  3992. auto doneAddr = pcAddress + inst.GetLength() + nextInst.GetLength();
  3993. BfLogDbg("SetupStep SetTempBreakpoint %p\n", doneAddr);
  3994. SetTempBreakpoint(doneAddr);
  3995. mStepBreakpointAddrs.push_back(doneAddr);
  3996. break;
  3997. }
  3998. }
  3999. }
  4000. else
  4001. {
  4002. // Step over the instruction
  4003. auto doneAddr = pcAddress + inst.GetLength();
  4004. BfLogDbg("SetupStep SetTempBreakpoint %p\n", doneAddr);
  4005. SetTempBreakpoint(doneAddr);
  4006. mStepBreakpointAddrs.push_back(doneAddr);
  4007. break;
  4008. }
  4009. }
  4010. // Just step a single instruction
  4011. BfLogDbg("SetupStep SingleStepX86 %p\n", pcAddress);
  4012. SingleStepX86();
  4013. if (inst.IsReturn())
  4014. mStepStopOnNextInstruction = true;
  4015. break;
  4016. }
  4017. }
  4018. else
  4019. {
  4020. // Move us to this instruction so we can hardware single-step into it
  4021. BfLogDbg("SetupStep SetTempBreakpoint %p\n", pcAddress);
  4022. SetTempBreakpoint(pcAddress);
  4023. mStepBreakpointAddrs.push_back(pcAddress);
  4024. break;
  4025. }
  4026. }
  4027. // Not an interesting instruction - move to next
  4028. pcAddress += inst.mSize;
  4029. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress >= dwSubprogram->mBlock.mHighPC))
  4030. {
  4031. auto endAddress = dwSubprogram->mBlock.mHighPC;
  4032. BfLogDbg("Stepping past end of inlined method, end address: %p\n", endAddress);
  4033. mStepType = StepType_StepOut_Inline;
  4034. SetTempBreakpoint(endAddress);
  4035. mStepBreakpointAddrs.push_back(endAddress);
  4036. return true;
  4037. }
  4038. }
  4039. if (instIdx > 1)
  4040. BfLogDbg("SetupStep instIdx: %d\n", instIdx);
  4041. }
  4042. return true;
  4043. }
  4044. void WinDebugger::CheckNonDebuggerBreak()
  4045. {
  4046. enum MessageType
  4047. {
  4048. MessageType_None = 0,
  4049. MessageType_Error = 1,
  4050. MessageType_ProfilerCmd = 2
  4051. };
  4052. CPURegisters registers;
  4053. PopulateRegisters(&registers);
  4054. addr_target pcAddress = registers.GetPC();
  4055. addr_target debugMessageDataAddr = (addr_target)-1;
  4056. if (mDebugTarget->mTargetBinary != NULL)
  4057. {
  4058. mDebugTarget->mTargetBinary->ParseSymbolData();
  4059. debugMessageDataAddr = mDebugTarget->FindSymbolAddr("gBfDebugMessageData");
  4060. }
  4061. if (debugMessageDataAddr != (addr_target)-1)
  4062. {
  4063. struct BfDebugMessageData
  4064. {
  4065. int mMessageType; // 0 = none, 1 = error
  4066. int mStackWindbackCount;
  4067. int mBufParamLen;
  4068. addr_target mBufParam;
  4069. addr_target mPCOverride;
  4070. };
  4071. BfDebugMessageData messageData = ReadMemory<BfDebugMessageData>(debugMessageDataAddr);
  4072. WriteMemory<int>(debugMessageDataAddr, 0); // Zero out type so we won't trigger again
  4073. if (messageData.mMessageType != 0)
  4074. {
  4075. llvm::SmallVector<char, 4096> strBuf;
  4076. int strLen = messageData.mBufParamLen;
  4077. strBuf.resize(strLen + 1);
  4078. char* str = &strBuf[0];
  4079. str[strLen] = 0;
  4080. if (ReadMemory(messageData.mBufParam, strLen, str))
  4081. {
  4082. if (messageData.mMessageType == MessageType_Error)
  4083. {
  4084. mRequestedStackFrameIdx = messageData.mStackWindbackCount;
  4085. if (messageData.mPCOverride != 0)
  4086. {
  4087. mShowPCOverride = messageData.mPCOverride;
  4088. mRequestedStackFrameIdx = -2;
  4089. }
  4090. mDebugManager->mOutMessages.push_back(StrFormat("error %s", str));
  4091. }
  4092. else if (messageData.mMessageType == MessageType_ProfilerCmd)
  4093. {
  4094. // It's important to set this here, because we unlock the critSect during StopSampling and we can't have the
  4095. // IDE thinking that we're actually paused when it checks the mRunState
  4096. mRunState = RunState_Running;
  4097. char* cmd = strtok(str, "\t");
  4098. if (strcmp(cmd, "StartSampling") == 0)
  4099. {
  4100. char* sessionIdStr = strtok(NULL, "\t");
  4101. char* threadIdStr = strtok(NULL, "\t");
  4102. char* sampleRateStr = strtok(NULL, "\t");
  4103. char* descStr = strtok(NULL, "\t");
  4104. if (threadIdStr != NULL)
  4105. {
  4106. int threadId = atoi(threadIdStr);
  4107. int sampleRate = atoi(sampleRateStr);
  4108. int sessionId = atoi(sessionIdStr);
  4109. Profiler** profilerPtr;
  4110. if (mPendingProfilerMap.TryAdd(sessionId, NULL, &profilerPtr))
  4111. {
  4112. DbgProfiler* profiler = new DbgProfiler(this);
  4113. if (descStr != NULL)
  4114. profiler->mDescription = descStr;
  4115. if (sampleRate > 0)
  4116. profiler->mSamplesPerSecond = sampleRate;
  4117. profiler->Start();
  4118. *profilerPtr = profiler;
  4119. mDebugManager->mOutMessages.push_back("newProfiler");
  4120. mNewProfilerList.push_back(profiler);
  4121. }
  4122. }
  4123. }
  4124. else if (strcmp(cmd, "StopSampling") == 0)
  4125. {
  4126. char* sessionIdStr = strtok(NULL, "\t");
  4127. if (sessionIdStr != NULL)
  4128. {
  4129. int sessionId = atoi(sessionIdStr);
  4130. Profiler* profiler;
  4131. if (mPendingProfilerMap.Remove(sessionId, &profiler))
  4132. {
  4133. if (profiler->IsSampling())
  4134. {
  4135. // Need to unlock so we don't deadlock
  4136. mDebugManager->mCritSect.Unlock();
  4137. profiler->Stop();
  4138. mDebugManager->mCritSect.Lock();
  4139. }
  4140. }
  4141. }
  4142. }
  4143. else if (strcmp(cmd, "ClearSampling") == 0)
  4144. {
  4145. for (auto& kv : mPendingProfilerMap)
  4146. {
  4147. auto profiler = kv.mValue;
  4148. profiler->Clear();
  4149. }
  4150. }
  4151. else if (strcmp(cmd, "ClearOutput") == 0)
  4152. {
  4153. mDebugManager->mOutMessages.push_back("clearOutput");
  4154. }
  4155. }
  4156. return;
  4157. }
  4158. }
  4159. }
  4160. intptr_target objAddr;
  4161. if (mDebugTarget->IsObjectAccessBreak(pcAddress, &registers, &objAddr))
  4162. {
  4163. String errorStr = "error Attempted to access deleted object";
  4164. String objectAddr = EncodeDataPtr((addr_target)objAddr, true);
  4165. errorStr += StrFormat("\x1LEAK\t(System.Object)%s\n (%s)%s\n", objectAddr.c_str(), "System.Object", objectAddr.c_str());
  4166. mDebugManager->mOutMessages.push_back(errorStr);
  4167. return;
  4168. }
  4169. bool showMainThread = false;
  4170. String symbol;
  4171. addr_target offset;
  4172. DbgModule* dbgModule;
  4173. if (mDebugTarget->FindSymbolAt(pcAddress, &symbol, &offset, &dbgModule))
  4174. {
  4175. if ((symbol == "DbgBreakPoint") || (symbol == "RtlUserThreadStart") || (symbol == "RtlUserThreadStart@8"))
  4176. {
  4177. showMainThread = true;
  4178. }
  4179. }
  4180. #ifdef BF_DBG_32
  4181. else if ((dbgModule != NULL) && (dbgModule->mDisplayName.Equals("kernel32.dll", StringImpl::CompareKind_OrdinalIgnoreCase)))
  4182. {
  4183. showMainThread = true;
  4184. }
  4185. #endif
  4186. if (showMainThread)
  4187. {
  4188. // This is a manual break, show the main thread
  4189. mActiveThread = mThreadList.front();
  4190. if (mDebugPendingExpr != NULL)
  4191. {
  4192. for (auto thread : mThreadList)
  4193. {
  4194. if (thread->mThreadId == mDebugEvalThreadInfo.mThreadId)
  4195. {
  4196. mActiveThread = thread;
  4197. break;
  4198. }
  4199. }
  4200. }
  4201. }
  4202. }
  4203. bool WinDebugger::HasSteppedIntoCall()
  4204. {
  4205. // Some calls (like __chkstk) actually push results to the stack, so we need to check
  4206. // if we're REALLY deeper or not, by rolling back the callstack once
  4207. CPURegisters registers;
  4208. PopulateRegisters(&registers);
  4209. if (RollBackStackFrame(&registers, true))
  4210. {
  4211. // If the previous frames SP is equal or deeper than our step start then we are indeed inside a call!
  4212. if (mStepSP >= registers.GetSP())
  4213. return true;
  4214. }
  4215. return false;
  4216. }
  4217. void WinDebugger::StepOver(bool inAssembly)
  4218. {
  4219. AutoCrit autoCrit(mDebugManager->mCritSect);
  4220. BfLogDbg("StepOver\n");
  4221. if (!TryRunContinue())
  4222. return;
  4223. mCurNoInfoStepTries = 0; // Reset
  4224. mStepInAssembly = inAssembly;
  4225. SetupStep(StepType_StepOver);
  4226. ContinueDebugEvent();
  4227. }
  4228. void WinDebugger::StepOut(bool inAssembly)
  4229. {
  4230. AutoCrit autoCrit(mDebugManager->mCritSect);
  4231. BfLogDbg("StepOut\n");
  4232. if (!TryRunContinue())
  4233. return;
  4234. mCurNoInfoStepTries = 0; // Reset
  4235. mStepInAssembly = inAssembly;
  4236. SetupStep(StepType_StepOut);
  4237. ContinueDebugEvent();
  4238. }
  4239. void WinDebugger::SetNextStatement(bool inAssembly, const StringImpl& fileName, int64 lineNumOrAsmAddr, int wantColumn)
  4240. {
  4241. AutoCrit autoCrit(mDebugManager->mCritSect);
  4242. DbgSubprogram* subProgram = NULL;
  4243. if (!inAssembly)
  4244. {
  4245. if (mCallStack.size() == 0)
  4246. UpdateCallStack();
  4247. if (mCallStack.size() > 0)
  4248. {
  4249. UpdateCallStackMethod(0);
  4250. subProgram = mCallStack[0]->mSubProgram;
  4251. }
  4252. if (subProgram == NULL)
  4253. return;
  4254. }
  4255. DbgSubprogram* rootInlineParent = NULL;
  4256. if (subProgram != NULL)
  4257. rootInlineParent = subProgram->GetRootInlineParent();
  4258. String result;
  4259. if (mDebugTarget == NULL)
  4260. return;
  4261. DbgSrcFile* srcFile = NULL;
  4262. if (!fileName.IsEmpty())
  4263. {
  4264. srcFile = mDebugTarget->GetSrcFile(fileName);
  4265. if (srcFile == NULL)
  4266. return;
  4267. }
  4268. addr_target pcAddress = 0;
  4269. if (inAssembly)
  4270. {
  4271. pcAddress = lineNumOrAsmAddr;
  4272. }
  4273. else
  4274. {
  4275. int lineNum = (int)lineNumOrAsmAddr;
  4276. addr_target bestAddr[2] = { 0, 0 };
  4277. int checkLineNum[2] = { lineNum - 1, lineNum };
  4278. auto _CheckLineInfo = [&](DbgSubprogram* dbgSubprogram, DbgLineInfo* dbgLineInfo)
  4279. {
  4280. for (int iPass = 0; iPass < 2; ++iPass)
  4281. {
  4282. int bestLineOffset = 0x7FFFFFFF;
  4283. for (auto& lineData : dbgLineInfo->mLines)
  4284. {
  4285. auto addr = dbgSubprogram->GetLineAddr(lineData);
  4286. if ((addr < subProgram->mBlock.mLowPC) || (addr >= subProgram->mBlock.mHighPC))
  4287. continue;
  4288. int lineOffset = lineData.mLine - checkLineNum[iPass];
  4289. if ((lineOffset >= 0) && (lineOffset <= 6) && (lineOffset <= bestLineOffset))
  4290. {
  4291. if (lineOffset < bestLineOffset)
  4292. {
  4293. bestLineOffset = lineOffset;
  4294. bestAddr[iPass] = addr;
  4295. }
  4296. }
  4297. }
  4298. }
  4299. };
  4300. for (int checkHotIdx = -1; checkHotIdx < (int)srcFile->mHotReplacedDbgLineInfo.size(); checkHotIdx++)
  4301. {
  4302. if (checkHotIdx >= 0)
  4303. {
  4304. auto hotReplacedLineInfo = srcFile->mHotReplacedDbgLineInfo[checkHotIdx];
  4305. for (auto& hotReplacedEntry : hotReplacedLineInfo->mEntries)
  4306. {
  4307. _CheckLineInfo(hotReplacedEntry.mSubprogram, hotReplacedEntry.mLineInfo);
  4308. }
  4309. }
  4310. else
  4311. {
  4312. for (auto subprogram : srcFile->mLineDataRefs)
  4313. _CheckLineInfo(subprogram, subprogram->mLineInfo);
  4314. }
  4315. if (bestAddr[1] != 0)
  4316. break;
  4317. }
  4318. if (bestAddr[1] != 0)
  4319. {
  4320. const int kMaxAddrDist = 64; // within reasonable range
  4321. if ((bestAddr[0] != 0) && (bestAddr[1] - bestAddr[0] <= kMaxAddrDist))
  4322. {
  4323. addr_target addrStart = bestAddr[0];
  4324. addr_target addrEnd = bestAddr[1];
  4325. addr_target addr = addrStart;
  4326. BF_ASSERT(addrEnd - addr <= kMaxAddrDist);
  4327. addr_target lastOp = 0;
  4328. while (addr < addrEnd)
  4329. {
  4330. CPUInst inst;
  4331. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  4332. break;
  4333. lastOp = addr;
  4334. addr += inst.GetLength();
  4335. }
  4336. }
  4337. pcAddress = (uint64)bestAddr[1];
  4338. }
  4339. }
  4340. if (pcAddress)
  4341. {
  4342. BF_ASSERT(mActiveThread->mBreakpointAddressContinuing == 0);
  4343. mActiveThread->mIsAtBreakpointAddress = 0;
  4344. mActiveThread->mStoppedAtAddress = pcAddress;
  4345. if (mCallStack.size() == 0)
  4346. UpdateCallStack();
  4347. CPURegisters* regs = &mCallStack.front()->mRegisters;
  4348. *regs->GetPCRegisterRef() = pcAddress;
  4349. SetRegisters(regs);
  4350. WdBreakpoint* breakpoint = (WdBreakpoint*)FindBreakpointAt(pcAddress);
  4351. if (breakpoint != NULL)
  4352. {
  4353. BfLogDbg("SetNextStatement setting mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  4354. mActiveThread->mIsAtBreakpointAddress = breakpoint->mAddr;
  4355. }
  4356. }
  4357. }
  4358. bool WinDebugger::PopulateRegisters(CPURegisters* registers, BF_CONTEXT& lcContext)
  4359. {
  4360. #ifdef BF_DBG_32
  4361. registers->mIntRegs.eax = lcContext.Eax;
  4362. registers->mIntRegs.ecx = lcContext.Ecx;
  4363. registers->mIntRegs.edx = lcContext.Edx;
  4364. registers->mIntRegs.ebx = lcContext.Ebx;
  4365. registers->mIntRegs.esp = lcContext.Esp;
  4366. registers->mIntRegs.ebp = lcContext.Ebp;
  4367. registers->mIntRegs.esi = lcContext.Esi;
  4368. registers->mIntRegs.edi = lcContext.Edi;
  4369. registers->mIntRegs.eip = lcContext.Eip;
  4370. registers->mIntRegs.efl = lcContext.EFlags;
  4371. BF_ASSERT(sizeof(lcContext.FloatSave.RegisterArea) == sizeof(registers->mFpMmRegsArray));
  4372. memcpy(registers->mFpMmRegsArray, lcContext.FloatSave.RegisterArea, sizeof(lcContext.FloatSave.RegisterArea));
  4373. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 32 * sizeof(float));
  4374. memcpy(registers->mXmmRegsArray, &lcContext.ExtendedRegisters[160], sizeof(registers->mXmmRegsArray));
  4375. #else
  4376. registers->mIntRegs.rax = lcContext.Rax;
  4377. registers->mIntRegs.rcx = lcContext.Rcx;
  4378. registers->mIntRegs.rdx = lcContext.Rdx;
  4379. registers->mIntRegs.rbx = lcContext.Rbx;
  4380. registers->mIntRegs.rsp = lcContext.Rsp;
  4381. registers->mIntRegs.rbp = lcContext.Rbp;
  4382. registers->mIntRegs.rsi = lcContext.Rsi;
  4383. registers->mIntRegs.rdi = lcContext.Rdi;
  4384. registers->mIntRegs.rip = lcContext.Rip;
  4385. registers->mIntRegs.efl = lcContext.EFlags;
  4386. registers->mIntRegs.r8 = lcContext.R8;
  4387. registers->mIntRegs.r9 = lcContext.R9;
  4388. registers->mIntRegs.r10 = lcContext.R10;
  4389. registers->mIntRegs.r11 = lcContext.R11;
  4390. registers->mIntRegs.r12 = lcContext.R12;
  4391. registers->mIntRegs.r13 = lcContext.R13;
  4392. registers->mIntRegs.r14 = lcContext.R14;
  4393. registers->mIntRegs.r15 = lcContext.R15;
  4394. registers->mIntRegs.gs = lcContext.SegGs;
  4395. for (int i = 0; i < 8; i++)
  4396. {
  4397. memcpy(&registers->mFpMmRegsArray[i], &lcContext.FltSave.FloatRegisters[i], 10);
  4398. }
  4399. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 64 * sizeof(float));
  4400. memcpy(registers->mXmmRegsArray, BF_CONTEXT_XMMDATA(lcContext), sizeof(registers->mXmmRegsArray));
  4401. #endif
  4402. return (lcContext.ContextFlags & (BF_CONTEXT_EXCEPTION_ACTIVE | BF_CONTEXT_SERVICE_ACTIVE)) == 0;
  4403. }
  4404. bool WinDebugger::PopulateRegisters(CPURegisters* registers)
  4405. {
  4406. /*static bool sCheckedProcessorFeatures = false;
  4407. static bool sMmxAvailable = false;
  4408. static bool sXmmAvailable = false;
  4409. if (!sCheckedProcessorFeatures)
  4410. {
  4411. //CDH we don't do anything with these yet since we grab BF_CONTEXT_ALL anyway, but could be useful
  4412. sMmxAvailable = ::IsProcessorFeaturePresent(PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  4413. sXmmAvailable = ::IsProcessorFeaturePresent(PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  4414. sCheckedProcessorFeatures = true;
  4415. }*/
  4416. BF_ASSERT(registers != nullptr);
  4417. BF_CONTEXT lcContext;
  4418. lcContext.ContextFlags = BF_CONTEXT_ALL | BF_CONTEXT_EXCEPTION_REQUEST;
  4419. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4420. return PopulateRegisters(registers, lcContext);
  4421. }
  4422. bool WinDebugger::RollBackStackFrame(CPURegisters* registers, bool isStackStart)
  4423. {
  4424. BF_ASSERT(registers != nullptr);
  4425. return mDebugTarget->RollBackStackFrame(registers, NULL, isStackStart);
  4426. }
  4427. bool WinDebugger::SetHotJump(DbgSubprogram* oldSubprogram, addr_target newTarget, int newTargetSize)
  4428. {
  4429. BfLogDbg("SetHotJump %s %p->%p\n", oldSubprogram->mName, oldSubprogram->mBlock.mLowPC, newTarget);
  4430. //AutoCrit autoCrit(mDebugManager->mCritSect);
  4431. BF_ASSERT(mDebugManager->mCritSect.mLockCount == 1);
  4432. addr_target jmpInstStart = oldSubprogram->mBlock.mLowPC;
  4433. addr_target jmpInstEnd = jmpInstStart + sizeof(HotJumpOp);
  4434. if (jmpInstEnd > oldSubprogram->mBlock.mHighPC)
  4435. {
  4436. if ((oldSubprogram->mBlock.mHighPC - oldSubprogram->mBlock.mLowPC == 1) &&
  4437. (newTargetSize == 1))
  4438. return true; // Special case for just stub 'ret' methods
  4439. String err = StrFormat("Failed to hot replace method, method '%s' too small to insert hot thunk", oldSubprogram->ToString().c_str());
  4440. Fail(err);
  4441. return false;
  4442. }
  4443. if (oldSubprogram->mHotReplaceKind != DbgSubprogram::HotReplaceKind_Replaced)
  4444. {
  4445. for (int hotThreadIdx = 0; hotThreadIdx < (int)mHotThreadStates.size(); hotThreadIdx++)
  4446. {
  4447. auto& hotThreadState = mHotThreadStates[hotThreadIdx];
  4448. WdThreadInfo* threadInfo = NULL;
  4449. if (!mThreadMap.TryGetValue((uint32)hotThreadState.mThreadId, &threadInfo))
  4450. continue;
  4451. int tryStart = GetTickCount();
  4452. while ((hotThreadState.mRegisters.GetPC() >= jmpInstStart) && (hotThreadState.mRegisters.GetPC() < jmpInstEnd))
  4453. {
  4454. if (GetTickCount() - tryStart >= 8000)
  4455. {
  4456. Fail("Failed to hot replace method, can't move past prelude");
  4457. return false;
  4458. }
  4459. BfLogDbg("SetHotJump skipping through %p\n", hotThreadState.mRegisters.GetPC());
  4460. bool removedBreakpoint = false;
  4461. mActiveThread = threadInfo;
  4462. if ((mActiveThread->mStoppedAtAddress >= jmpInstStart) && (mActiveThread->mStoppedAtAddress < jmpInstEnd))
  4463. {
  4464. for (addr_target addr = jmpInstStart; addr < jmpInstEnd; addr++)
  4465. {
  4466. if (mPhysBreakpointAddrMap.ContainsKey(addr))
  4467. {
  4468. removedBreakpoint = true;
  4469. RemoveBreakpoint(addr);
  4470. }
  4471. }
  4472. }
  4473. RunState oldRunState = mRunState;
  4474. mRunState = RunState_HotStep;
  4475. if (mWantsDebugContinue)
  4476. {
  4477. mWantsDebugContinue = false;
  4478. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4479. mContinueEvent.Set();
  4480. }
  4481. BF_CONTEXT lcContext;
  4482. lcContext.ContextFlags = BF_CONTEXT_ALL;
  4483. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4484. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  4485. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  4486. ::ResumeThread(mActiveThread->mHThread);
  4487. BfLogDbg("ResumeThread %d\n", mActiveThread->mThreadId);
  4488. while (mRunState != RunState_Terminated)
  4489. {
  4490. mDebugManager->mCritSect.Unlock();
  4491. Sleep(0);
  4492. mDebugManager->mCritSect.Lock();
  4493. if (IsPaused())
  4494. break;
  4495. if (mWantsDebugContinue)
  4496. {
  4497. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4498. mWantsDebugContinue = false;
  4499. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4500. mContinueEvent.Set();
  4501. }
  4502. }
  4503. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4504. ::SuspendThread(mActiveThread->mHThread);
  4505. BfLogDbg("SuspendThread %d\n", mActiveThread->mThreadId);
  4506. mRunState = oldRunState;
  4507. if ((mRunState != RunState_Terminated) && (mRunState != RunState_Terminating))
  4508. {
  4509. if (!IsPaused())
  4510. {
  4511. BF_ASSERT(mWantsDebugContinue);
  4512. mWantsDebugContinue = false;
  4513. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4514. mContinueEvent.Set();
  4515. }
  4516. }
  4517. PopulateRegisters(&hotThreadState.mRegisters);
  4518. }
  4519. }
  4520. }
  4521. HotJumpOp jumpOp;
  4522. jumpOp.mOpCode = 0xE9;
  4523. jumpOp.mRelTarget = newTarget - oldSubprogram->mBlock.mLowPC - sizeof(HotJumpOp);
  4524. WriteMemory(oldSubprogram->mBlock.mLowPC, jumpOp);
  4525. ::FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)oldSubprogram->mBlock.mLowPC, sizeof(HotJumpOp));
  4526. return true;
  4527. }
  4528. DbgSubprogram* WinDebugger::TryFollowHotJump(DbgSubprogram* subprogram, addr_target addr)
  4529. {
  4530. if (subprogram->mHotReplaceKind != DbgSubprogram::HotReplaceKind_Replaced)
  4531. return subprogram;
  4532. if (addr != subprogram->mBlock.mLowPC)
  4533. return subprogram;
  4534. auto dbgModule = subprogram->mCompileUnit->mDbgModule;
  4535. HotJumpOp jumpOp = ReadMemory<HotJumpOp>(addr);
  4536. if (jumpOp.mOpCode != 0xE9)
  4537. return subprogram;
  4538. addr_target jumpAddr = addr + jumpOp.mRelTarget + sizeof(HotJumpOp);
  4539. auto jumpSubprogram = mDebugTarget->FindSubProgram(jumpAddr);
  4540. if (jumpSubprogram == NULL)
  4541. return subprogram;
  4542. return jumpSubprogram;
  4543. }
  4544. bool WinDebugger::ShouldShowStaticMember(DbgType* dbgType, DbgVariable* member)
  4545. {
  4546. // If locationData is non-null, that means it was added in addition to the static declaration in the CV type info,
  4547. // so only add the names from the type definition
  4548. auto flavor = dbgType->mCompileUnit->mDbgModule->mDbgFlavor;
  4549. return ((((dbgType->IsNamespace()) || (flavor != DbgFlavor_MS)) && ((member->mLocationData != NULL) || member->mIsConst)) ||
  4550. ((flavor == DbgFlavor_MS) && (member->mLocationData == NULL)));
  4551. }
  4552. String WinDebugger::GetMemberList(DbgType* dbgType, const StringImpl& expr, bool isPtr, bool isStatic, bool forceCast, bool isSplat, bool isReadOnly)
  4553. {
  4554. auto dbgModule = dbgType->GetDbgModule();
  4555. dbgType->PopulateType();
  4556. auto language = dbgType->GetLanguage();
  4557. if (!isStatic)
  4558. {
  4559. String retVal;
  4560. bool needsNewline = false;
  4561. bool isBfObject = false;
  4562. if (dbgType->IsBfObjectPtr())
  4563. {
  4564. isBfObject = true;
  4565. dbgType = dbgType->mTypeParam;
  4566. }
  4567. int baseIdx = 0;
  4568. for (auto baseTypeEntry : dbgType->mBaseTypes)
  4569. {
  4570. auto baseType = baseTypeEntry->mBaseType;
  4571. if ((baseType->mSize > 0) || (baseType->mTypeCode != DbgType_Struct) || (strcmp(baseType->mTypeName, "ValueType") != 0))
  4572. {
  4573. String baseTypeStr = baseType->ToStringRaw(language);
  4574. if (baseIdx > 0)
  4575. retVal += "\n";
  4576. if (isSplat)
  4577. retVal += "[base]\t((" + baseTypeStr + ")" + expr + "), nv";
  4578. else if (dbgType->WantsRefThis())
  4579. retVal += "[base]\t((" + baseTypeStr + ")this), nd, na, nv, this=" + expr;
  4580. else
  4581. retVal += "[base]\t((" + baseTypeStr + "*)this), nd, na, nv, this=" + expr;
  4582. if (isReadOnly)
  4583. retVal += ", ne";
  4584. }
  4585. needsNewline = true;
  4586. baseIdx++;
  4587. }
  4588. String thisExpr = expr;
  4589. String castString;
  4590. if (dbgType->IsBfObject())
  4591. {
  4592. auto ptrType = dbgType->GetDbgModule()->GetPointerType(dbgType);
  4593. castString = ptrType->ToStringRaw(language);
  4594. }
  4595. else
  4596. castString = dbgType->ToStringRaw(language);
  4597. bool hadStatics = false;
  4598. for (auto member : dbgType->mMemberList)
  4599. {
  4600. if (member->mMemberOffset < 0)
  4601. continue;
  4602. if (member->mIsStatic)
  4603. {
  4604. if (ShouldShowStaticMember(dbgType, member))
  4605. hadStatics = true;
  4606. }
  4607. else
  4608. {
  4609. bool ignoreMember = false;
  4610. if (member->mName != NULL)
  4611. {
  4612. if ((member->mName[0] == '?') ||
  4613. (member->mName[0] == '$') ||
  4614. (strncmp(member->mName, "_vptr$", 6) == 0))
  4615. ignoreMember = true;
  4616. }
  4617. if (!ignoreMember)
  4618. {
  4619. if (needsNewline)
  4620. retVal += "\n";
  4621. if (member->mName == NULL)
  4622. {
  4623. retVal += GetMemberList(member->mType, expr, isPtr, isStatic, forceCast, isSplat, isReadOnly);
  4624. }
  4625. else
  4626. {
  4627. retVal += String(member->mName);
  4628. if (isSplat)
  4629. {
  4630. retVal += "\t(" + thisExpr + ")." + String(member->mName);
  4631. // We don't want to rely on this being enforced here. For one, ref types shouldn't get ", ne" added,
  4632. // and this doesn't solve the issue of attempting to assign via the Immediate window
  4633. /*if (isReadOnly)
  4634. retVal += ", ne";*/
  4635. }
  4636. else
  4637. {
  4638. if (forceCast)
  4639. retVal += "\t((" + castString + ")this)." + String(member->mName);
  4640. else if ((member->mName[0] >= '0') && (member->mName[0] <= '9')) // Numbered tuple member?
  4641. retVal += "\tthis." + String(member->mName);
  4642. else
  4643. retVal += "\t" + String(member->mName);
  4644. retVal += ", this=" + thisExpr;
  4645. // if (isReadOnly)
  4646. // retVal += ", ne";
  4647. }
  4648. }
  4649. needsNewline = true;
  4650. }
  4651. }
  4652. }
  4653. if (hadStatics)
  4654. {
  4655. if (needsNewline)
  4656. retVal += "\n";
  4657. retVal += "Static values\t" + castString;
  4658. }
  4659. return retVal;
  4660. }
  4661. else
  4662. {
  4663. if (dbgType->IsBfObjectPtr())
  4664. dbgType = dbgType->mTypeParam;
  4665. String retVal;
  4666. String memberPrefix = expr;
  4667. bool needsNewline = false;
  4668. bool hadStatics = false;
  4669. for (auto member : dbgType->mMemberList)
  4670. {
  4671. if (member->mIsStatic)
  4672. {
  4673. if (ShouldShowStaticMember(dbgType, member))
  4674. {
  4675. if (needsNewline)
  4676. retVal += "\n";
  4677. retVal += String(member->mName) + "\t" + memberPrefix + "." + String(member->mName);
  4678. needsNewline = true;
  4679. }
  4680. }
  4681. }
  4682. return retVal;
  4683. }
  4684. return "";
  4685. }
  4686. bool WinDebugger::ParseFormatInfo(DbgModule* dbgModule, const StringImpl& formatInfoStr, DwFormatInfo* formatInfo, BfPassInstance* bfPassInstance, int* assignExprOffset, String* assignExprString, String* errorString, DbgTypedValue contextTypedValue)
  4687. {
  4688. String formatFlags = formatInfoStr;
  4689. if (assignExprOffset != NULL)
  4690. *assignExprOffset = -1;
  4691. while (formatFlags.length() > 0)
  4692. {
  4693. formatFlags = Trim(formatFlags);
  4694. if (formatFlags.IsEmpty())
  4695. break;
  4696. if (formatFlags[0] != ',')
  4697. {
  4698. return false;
  4699. }
  4700. else
  4701. {
  4702. int nextComma = formatFlags.IndexOf(',', 1);
  4703. int quotePos = formatFlags.IndexOf('"', 1);
  4704. if ((quotePos != -1) && (quotePos < nextComma))
  4705. {
  4706. int nextQuotePos = formatFlags.IndexOf('"', quotePos + 1);
  4707. if (nextQuotePos != -1)
  4708. nextComma = formatFlags.IndexOf(',', nextQuotePos + 1);
  4709. }
  4710. if (nextComma == -1)
  4711. nextComma = formatFlags.length();
  4712. String formatCmd = formatFlags.Substring(1, nextComma - 1);
  4713. formatCmd = Trim(formatCmd);
  4714. bool hadError = false;
  4715. if (strncmp(formatCmd.c_str(), "this=", 5) == 0)
  4716. {
  4717. formatCmd = formatFlags.Substring(1);
  4718. formatCmd = Trim(formatCmd);
  4719. String thisExpr = formatCmd.Substring(5);
  4720. if (thisExpr.empty())
  4721. break;
  4722. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, thisExpr, formatInfo);
  4723. formatInfo->mExplicitThis = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4724. if (dbgEvaluationContext.HadError())
  4725. {
  4726. if (errorString != NULL)
  4727. *errorString = dbgEvaluationContext.GetErrorStr();
  4728. return false;
  4729. }
  4730. formatFlags = thisExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4731. continue;
  4732. }
  4733. else if (strncmp(formatCmd.c_str(), "count=", 6) == 0)
  4734. {
  4735. formatCmd = formatFlags.Substring(1);
  4736. formatCmd = Trim(formatCmd);
  4737. String countExpr = formatCmd.Substring(6);
  4738. if (countExpr.empty())
  4739. break;
  4740. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4741. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4742. if ((countValue) && (countValue.mType->IsInteger()))
  4743. formatInfo->mOverrideCount = (intptr)countValue.GetInt64();
  4744. if (dbgEvaluationContext.HadError())
  4745. {
  4746. if (errorString != NULL)
  4747. *errorString = dbgEvaluationContext.GetErrorStr();
  4748. return false;
  4749. }
  4750. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4751. continue;
  4752. }
  4753. else if (strncmp(formatCmd.c_str(), "maxcount=", 9) == 0)
  4754. {
  4755. formatCmd = formatFlags.Substring(1);
  4756. formatCmd = Trim(formatCmd);
  4757. String countExpr = formatCmd.Substring(9);
  4758. if (countExpr.empty())
  4759. break;
  4760. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4761. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4762. if ((countValue) && (countValue.mType->IsInteger()))
  4763. formatInfo->mMaxCount = (intptr)countValue.GetInt64();
  4764. if (dbgEvaluationContext.HadError())
  4765. {
  4766. if (errorString != NULL)
  4767. *errorString = dbgEvaluationContext.GetErrorStr();
  4768. return false;
  4769. }
  4770. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4771. continue;
  4772. }
  4773. else if (strncmp(formatCmd.c_str(), "arraysize=", 10) == 0)
  4774. {
  4775. formatCmd = formatFlags.Substring(1);
  4776. formatCmd = Trim(formatCmd);
  4777. String countExpr = formatCmd.Substring(10);
  4778. if (countExpr.empty())
  4779. break;
  4780. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4781. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4782. if ((countValue) && (countValue.mType->IsInteger()))
  4783. formatInfo->mArrayLength = (intptr)countValue.GetInt64();
  4784. if (dbgEvaluationContext.HadError())
  4785. {
  4786. if (errorString != NULL)
  4787. *errorString = dbgEvaluationContext.GetErrorStr();
  4788. return false;
  4789. }
  4790. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4791. continue;
  4792. }
  4793. else if (strncmp(formatCmd.c_str(), "assign=", 7) == 0)
  4794. {
  4795. formatCmd = formatFlags.Substring(1);
  4796. formatCmd = Trim(formatCmd);
  4797. String assignExpr = formatCmd.Substring(7);
  4798. if (assignExpr.empty())
  4799. break;
  4800. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, assignExpr, formatInfo);
  4801. if (dbgEvaluationContext.HadError())
  4802. {
  4803. if (errorString != NULL)
  4804. *errorString = dbgEvaluationContext.GetErrorStr();
  4805. return false;
  4806. }
  4807. if (assignExprOffset != NULL)
  4808. {
  4809. //TODO: Keep track of the offset directly, this is a hack
  4810. *assignExprOffset = (int)formatInfoStr.IndexOf("assign=") + 7;
  4811. }
  4812. if (assignExprString != NULL)
  4813. *assignExprString = dbgEvaluationContext.mExprNode->ToString();
  4814. formatFlags = assignExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4815. continue;
  4816. }
  4817. else if (strncmp(formatCmd.c_str(), "refid=", 6) == 0)
  4818. {
  4819. formatInfo->mReferenceId = formatCmd.Substring(6);
  4820. if (formatInfo->mReferenceId[0] == '\"')
  4821. formatInfo->mReferenceId = formatInfo->mReferenceId.Substring(1, formatInfo->mReferenceId.length() - 2);
  4822. }
  4823. else if (strncmp(formatCmd.c_str(), "_=", 2) == 0)
  4824. {
  4825. formatInfo->mSubjectExpr = formatCmd.Substring(2);
  4826. if (formatInfo->mSubjectExpr[0] == '\"')
  4827. formatInfo->mSubjectExpr = formatInfo->mSubjectExpr.Substring(1, formatInfo->mSubjectExpr.length() - 2);
  4828. }
  4829. else if (strncmp(formatCmd.c_str(), "expectedType=", 13) == 0)
  4830. {
  4831. formatInfo->mExpectedType = formatCmd.Substring(13);
  4832. if (formatInfo->mExpectedType[0] == '\"')
  4833. formatInfo->mExpectedType = formatInfo->mExpectedType.Substring(1, formatInfo->mExpectedType.length() - 2);
  4834. }
  4835. else if (strncmp(formatCmd.c_str(), "namespaceSearch=", 16) == 0)
  4836. {
  4837. formatInfo->mNamespaceSearch = formatCmd.Substring(16);
  4838. if (formatInfo->mNamespaceSearch[0] == '\"')
  4839. formatInfo->mNamespaceSearch = formatInfo->mNamespaceSearch.Substring(1, formatInfo->mNamespaceSearch.length() - 2);
  4840. }
  4841. else if (formatCmd == "d")
  4842. {
  4843. formatInfo->mDisplayType = DwDisplayType_Decimal;
  4844. }
  4845. else if (formatCmd == "x")
  4846. {
  4847. formatInfo->mDisplayType = DwDisplayType_HexLower;
  4848. }
  4849. else if (formatCmd == "X")
  4850. {
  4851. formatInfo->mDisplayType = DwDisplayType_HexUpper;
  4852. }
  4853. else if (formatCmd == "s")
  4854. {
  4855. formatInfo->mHidePointers = true;
  4856. formatInfo->mDisplayType = DwDisplayType_Ascii;
  4857. }
  4858. else if (formatCmd == "s8")
  4859. {
  4860. formatInfo->mHidePointers = true;
  4861. formatInfo->mDisplayType = DwDisplayType_Utf8;
  4862. }
  4863. else if (formatCmd == "s16")
  4864. {
  4865. formatInfo->mHidePointers = true;
  4866. formatInfo->mDisplayType = DwDisplayType_Utf16;
  4867. }
  4868. else if (formatCmd == "s32")
  4869. {
  4870. formatInfo->mHidePointers = true;
  4871. formatInfo->mDisplayType = DwDisplayType_Utf32;
  4872. }
  4873. else if (formatCmd == "nd")
  4874. {
  4875. formatInfo->mIgnoreDerivedClassInfo = true;
  4876. }
  4877. else if (formatCmd == "na")
  4878. {
  4879. formatInfo->mHidePointers = true;
  4880. }
  4881. else if (formatCmd == "nm")
  4882. {
  4883. formatInfo->mNoMembers = true;
  4884. }
  4885. else if (formatCmd == "ne")
  4886. {
  4887. formatInfo->mNoEdit = true;
  4888. }
  4889. else if (formatCmd == "nv")
  4890. {
  4891. formatInfo->mNoVisualizers = true;
  4892. }
  4893. else if (formatCmd == "rawStr")
  4894. {
  4895. formatInfo->mRawString = true;
  4896. }
  4897. else if (((!formatCmd.IsEmpty()) && ((formatCmd[0] >= '0') && (formatCmd[0] <= '9'))) ||
  4898. (formatCmd.StartsWith("(")))
  4899. {
  4900. String countExpr = formatCmd;
  4901. if (countExpr.empty())
  4902. break;
  4903. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4904. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4905. if ((countValue) && (countValue.mType->IsInteger()))
  4906. formatInfo->mArrayLength = (intptr)countValue.GetInt64();
  4907. if (dbgEvaluationContext.HadError())
  4908. {
  4909. if (errorString != NULL)
  4910. *errorString = dbgEvaluationContext.GetErrorStr();
  4911. return false;
  4912. }
  4913. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4914. continue;
  4915. }
  4916. else
  4917. hadError = true;
  4918. if (hadError)
  4919. {
  4920. if (errorString != NULL)
  4921. *errorString = "Invalid format flags";
  4922. return false;
  4923. }
  4924. formatFlags = formatFlags.Substring(nextComma);
  4925. }
  4926. }
  4927. return true;
  4928. }
  4929. String WinDebugger::MaybeQuoteFormatInfoParam(const StringImpl& str)
  4930. {
  4931. bool needsQuote = false;
  4932. for (int i = 0; i < (int)str.length(); i++)
  4933. {
  4934. char c = str[i];
  4935. if (c == ',')
  4936. needsQuote = true;
  4937. }
  4938. if (!needsQuote)
  4939. return str;
  4940. String qStr = "\"";
  4941. qStr += str;
  4942. qStr += "\"";
  4943. return qStr;
  4944. }
  4945. DbgTypedValue WinDebugger::EvaluateInContext(DbgCompileUnit* dbgCompileUnit, const DbgTypedValue& contextTypedValue, const StringImpl& subExpr, DwFormatInfo* formatInfo, String* outReferenceId, String* outErrors)
  4946. {
  4947. DbgEvaluationContext dbgEvaluationContext(this, dbgCompileUnit->mDbgModule, subExpr, formatInfo, contextTypedValue);
  4948. dbgEvaluationContext.mDbgExprEvaluator->mDbgCompileUnit = dbgCompileUnit;
  4949. if (formatInfo != NULL)
  4950. {
  4951. dbgEvaluationContext.mDbgExprEvaluator->mLanguage = formatInfo->mLanguage;
  4952. dbgEvaluationContext.mDbgExprEvaluator->mSubjectExpr = formatInfo->mSubjectExpr;
  4953. }
  4954. dbgEvaluationContext.mDbgExprEvaluator->mReferenceId = outReferenceId;
  4955. auto result = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4956. if ((formatInfo != NULL) && (dbgEvaluationContext.mDbgExprEvaluator->mCountResultOverride != -1))
  4957. formatInfo->mOverrideCount = dbgEvaluationContext.mDbgExprEvaluator->mCountResultOverride;
  4958. if (dbgEvaluationContext.mPassInstance->HasFailed())
  4959. {
  4960. if (outErrors != NULL)
  4961. {
  4962. int errIdx = 0;
  4963. for (auto err : dbgEvaluationContext.mPassInstance->mErrors)
  4964. {
  4965. if (errIdx > 0)
  4966. (*outErrors) += "\n";
  4967. (*outErrors) += err->mError;
  4968. errIdx++;
  4969. }
  4970. }
  4971. return DbgTypedValue();
  4972. }
  4973. return result;
  4974. }
  4975. void WinDebugger::DbgVisFailed(DebugVisualizerEntry* debugVis, const StringImpl& evalString, const StringImpl& errors)
  4976. {
  4977. bool onlyMemError = errors.StartsWith("Failed to read") && !errors.Contains('\n');
  4978. if ((!debugVis->mShowedError) && (!onlyMemError))
  4979. {
  4980. debugVis->mShowedError = true;
  4981. String errStr = StrFormat("DbgVis '%s' failed while evaluating condition '%s'\n", debugVis->mName.c_str(), evalString.c_str());
  4982. String spacedErrors = errors;
  4983. spacedErrors.Insert(0, " ");
  4984. spacedErrors.Replace("\n", "\n ");
  4985. errStr += spacedErrors;
  4986. OutputMessage(errStr);
  4987. }
  4988. }
  4989. bool WinDebugger::EvalCondition(DebugVisualizerEntry* debugVis, DbgCompileUnit* dbgCompileUnit, DbgTypedValue typedVal, DwFormatInfo& formatInfo, const StringImpl& condition, const Array<String>& dbgVisWildcardCaptures, String& errorStr)
  4990. {
  4991. DwFormatInfo displayStrFormatInfo = formatInfo;
  4992. displayStrFormatInfo.mHidePointers = false;
  4993. displayStrFormatInfo.mRawString = false;
  4994. String errors;
  4995. const String conditionStr = mDebugManager->mDebugVisualizers->DoStringReplace(condition, dbgVisWildcardCaptures);
  4996. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, typedVal, conditionStr, &displayStrFormatInfo, NULL, &errors);
  4997. if ((!evalResult) || (!evalResult.mType->IsBoolean()))
  4998. {
  4999. if (formatInfo.mRawString)
  5000. return false;
  5001. errorStr += "<DbgVis Failed>";
  5002. DbgVisFailed(debugVis, conditionStr, errors);
  5003. return false;
  5004. }
  5005. return evalResult.mBool;
  5006. }
  5007. String WinDebugger::GetArrayItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgType* valueType, DbgTypedValue& curNode, int& count, String* outContinuationData)
  5008. {
  5009. DbgEvaluationContext conditionEvaluationContext(this, dbgCompileUnit, debugVis->mCondition);
  5010. String addrs;
  5011. bool checkLeft = true;
  5012. int usedCount = 0;
  5013. while (usedCount < count)
  5014. {
  5015. DbgTypedValue condVal = conditionEvaluationContext.EvaluateInContext(curNode);
  5016. if (!condVal)
  5017. break;
  5018. if (condVal.mBool)
  5019. {
  5020. auto val = curNode;
  5021. if (valueType == NULL)
  5022. {
  5023. String typeAddr = val.mType->ToStringRaw();
  5024. // RPad
  5025. typeAddr.Append(' ', sizeof(addr_target) * 2 - typeAddr.length());
  5026. addrs += typeAddr;
  5027. }
  5028. String addr = EncodeDataPtr(val.mPtr, false);
  5029. addrs += addr;
  5030. usedCount++;
  5031. }
  5032. curNode.mPtr += curNode.mType->mTypeParam->GetStride();
  5033. }
  5034. count = usedCount;
  5035. if (outContinuationData != NULL)
  5036. {
  5037. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(valueType, false) +
  5038. EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  5039. }
  5040. return addrs;
  5041. }
  5042. String WinDebugger::GetLinkedListItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, addr_target endNodePtr, DbgType* valueType, DbgTypedValue& curNode, int& count, String* outContinuationData)
  5043. {
  5044. DbgEvaluationContext nextEvaluationContext(this, dbgCompileUnit, debugVis->mNextPointer);
  5045. DbgEvaluationContext valueEvaluationContext(this, dbgCompileUnit, debugVis->mValuePointer);
  5046. String addrs;
  5047. bool checkLeft = true;
  5048. int mapIdx;
  5049. for (mapIdx = 0; mapIdx < count; mapIdx++)
  5050. {
  5051. if (curNode.mPtr == endNodePtr)
  5052. break;
  5053. DbgTypedValue val = valueEvaluationContext.EvaluateInContext(curNode);
  5054. if (!val)
  5055. break;
  5056. if (val.mPtr == 0)
  5057. break;
  5058. if (valueType == NULL)
  5059. {
  5060. String typeAddr = val.mType->ToStringRaw();
  5061. // RPad
  5062. typeAddr.Append(' ', sizeof(addr_target)*2 - typeAddr.length());
  5063. addrs += typeAddr;
  5064. }
  5065. String addr = EncodeDataPtr(val.mPtr, false);
  5066. addrs += addr;
  5067. curNode = nextEvaluationContext.EvaluateInContext(curNode);
  5068. }
  5069. count = mapIdx;
  5070. if (outContinuationData != NULL)
  5071. {
  5072. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(endNodePtr, false) + EncodeDataPtr(valueType, false) +
  5073. EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  5074. }
  5075. return addrs;
  5076. }
  5077. String WinDebugger::GetDictionaryItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgTypedValue dictValue, int bucketIdx, int nodeIdx, int& count, String* outContinuationData)
  5078. {
  5079. //DbgEvaluationContext bucketsEvaluationContext(this, dbgModule, debugVis->mBuckets);
  5080. DbgEvaluationContext nextEvaluationContext(this, dbgCompileUnit->mDbgModule, debugVis->mNextPointer);
  5081. DbgTypedValue bucketsPtr = EvaluateInContext(dbgCompileUnit, dictValue, debugVis->mBuckets);
  5082. DbgTypedValue entriesPtr = EvaluateInContext(dbgCompileUnit, dictValue, debugVis->mEntries);
  5083. if ((!bucketsPtr) || (!entriesPtr))
  5084. {
  5085. count = -1;
  5086. return "";
  5087. }
  5088. int entrySize = entriesPtr.mType->mTypeParam->GetStride();
  5089. int bucketIdxSize = bucketsPtr.mType->mTypeParam->GetStride();
  5090. String addrs;
  5091. bool checkLeft = true;
  5092. int encodeCount = 0;
  5093. while (encodeCount < count)
  5094. {
  5095. if (nodeIdx != -1)
  5096. {
  5097. DbgTypedValue entryValue;
  5098. entryValue.mSrcAddress = entriesPtr.mPtr + (nodeIdx * entrySize);
  5099. entryValue.mType = entriesPtr.mType->mTypeParam;
  5100. addrs += EncodeDataPtr(entryValue.mSrcAddress, false);
  5101. DbgTypedValue nextValue = nextEvaluationContext.EvaluateInContext(entryValue);
  5102. if ((!nextValue) || (!nextValue.mType->IsInteger()))
  5103. {
  5104. break;
  5105. }
  5106. nodeIdx = (int)nextValue.GetInt64();
  5107. encodeCount++;
  5108. }
  5109. else
  5110. {
  5111. if (bucketIdxSize == 4)
  5112. nodeIdx = ReadMemory<int>(bucketsPtr.mPtr + bucketIdx * sizeof(int32));
  5113. else
  5114. nodeIdx = (int)ReadMemory<int64>(bucketsPtr.mPtr + bucketIdx * sizeof(int64));
  5115. bucketIdx++;
  5116. }
  5117. }
  5118. count = encodeCount;
  5119. //count = mapIdx;
  5120. if (outContinuationData != NULL)
  5121. {
  5122. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(dictValue.mType, false) + EncodeDataPtr(dictValue.mSrcAddress, false) +
  5123. EncodeDataPtr((addr_target)bucketIdx, false) + EncodeDataPtr((addr_target)nodeIdx, false);
  5124. }
  5125. return addrs;
  5126. }
  5127. String WinDebugger::GetTreeItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, Array<addr_target>& parentList, DbgType*& valueType, DbgTypedValue& curNode, int count, String* outContinuationData)
  5128. {
  5129. DbgEvaluationContext leftEvaluationContext(this, dbgCompileUnit, debugVis->mLeftPointer);
  5130. DbgEvaluationContext rightEvaluationContext(this, dbgCompileUnit, debugVis->mRightPointer);
  5131. DbgEvaluationContext valueEvaluationContext(this, dbgCompileUnit, debugVis->mValuePointer);
  5132. DbgEvaluationContext conditionEvaluationContext(this, dbgCompileUnit, debugVis->mCondition);
  5133. String addrs;
  5134. bool checkLeft = true;
  5135. if ((curNode.mPtr & 2) != 0) // Flag from continuation
  5136. {
  5137. checkLeft = false;
  5138. curNode.mPtr &= (addr_target)~2;
  5139. }
  5140. HashSet<intptr> seenAddrs;
  5141. for (int mapIdx = 0; mapIdx < count; mapIdx++)
  5142. {
  5143. DbgTypedValue readNode;
  5144. while (true)
  5145. {
  5146. bool checkNode = (curNode.mPtr & 1) == 0;
  5147. readNode = curNode;
  5148. readNode.mPtr &= (addr_target)~1;
  5149. if (checkLeft)
  5150. {
  5151. DbgTypedValue leftValue = leftEvaluationContext.EvaluateInContext(readNode);
  5152. bool isEmpty = leftValue.mPtr == NULL;
  5153. if ((leftValue) && (conditionEvaluationContext.HasExpression()))
  5154. {
  5155. auto condValue = conditionEvaluationContext.EvaluateInContext(leftValue);
  5156. if (condValue)
  5157. isEmpty = !condValue.mBool;
  5158. }
  5159. if (isEmpty)
  5160. {
  5161. checkLeft = false;
  5162. break; // Handle node
  5163. }
  5164. parentList.push_back(curNode.mPtr);
  5165. curNode = leftValue;
  5166. }
  5167. else if (checkNode)
  5168. {
  5169. break; // Handle node
  5170. }
  5171. else
  5172. {
  5173. DbgTypedValue rightValue = rightEvaluationContext.EvaluateInContext(readNode);
  5174. bool isEmpty = rightValue.mPtr == NULL;
  5175. if ((rightValue) && (conditionEvaluationContext.HasExpression()))
  5176. {
  5177. auto condValue = conditionEvaluationContext.EvaluateInContext(rightValue);
  5178. if (condValue)
  5179. isEmpty = !condValue.mBool;
  5180. }
  5181. if (!isEmpty)
  5182. {
  5183. curNode = rightValue;
  5184. checkLeft = true;
  5185. }
  5186. else
  5187. {
  5188. if (parentList.size() == 0)
  5189. {
  5190. // Failed
  5191. break;
  5192. }
  5193. curNode.mPtr = parentList.back();
  5194. parentList.pop_back();
  5195. continue; // Don't check against seenAddrs
  5196. }
  5197. }
  5198. if (!seenAddrs.Add(curNode.mPtr))
  5199. {
  5200. // Failed!
  5201. return "";
  5202. }
  5203. }
  5204. DbgTypedValue val = valueEvaluationContext.EvaluateInContext(readNode);
  5205. if (valueType == NULL)
  5206. valueType = val.mType;
  5207. String addr = EncodeDataPtr(val.mPtr, false);
  5208. addrs += addr;
  5209. curNode.mPtr |= 1; // Node handled
  5210. }
  5211. if (!checkLeft)
  5212. curNode.mPtr |= 2;
  5213. if (outContinuationData != NULL)
  5214. {
  5215. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(valueType, false) + EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  5216. for (auto parent : parentList)
  5217. *outContinuationData += EncodeDataPtr(parent, false);
  5218. }
  5219. return addrs;
  5220. }
  5221. String WinDebugger::GetCollectionContinuation(const StringImpl& continuationData, int callStackIdx, int count)
  5222. {
  5223. DbgCompileUnit* dbgCompileUnit = GetCallStackCompileUnit(callStackIdx);;
  5224. if (!IsPaused())
  5225. return "";
  5226. const char* dataPtr = continuationData.c_str();
  5227. DebugVisualizerEntry* debugVis = (DebugVisualizerEntry*)DecodeLocalDataPtr(dataPtr);
  5228. if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_TreeItems)
  5229. {
  5230. DbgType* valueType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5231. DbgTypedValue curNode;
  5232. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5233. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5234. Array<addr_target> parentList;
  5235. String newContinuationData;
  5236. while (*dataPtr != 0)
  5237. parentList.push_back(DecodeTargetDataPtr(dataPtr));
  5238. String retVal = GetTreeItems(dbgCompileUnit, debugVis, parentList, valueType, curNode, count, &newContinuationData);
  5239. retVal += "\n" + newContinuationData;
  5240. return retVal;
  5241. }
  5242. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_LinkedList)
  5243. {
  5244. addr_target endNodePtr = DecodeTargetDataPtr(dataPtr);
  5245. DbgType* valueType = (DbgType*) DecodeLocalDataPtr(dataPtr);
  5246. DbgTypedValue curNode;
  5247. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5248. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5249. String newContinuationData;
  5250. if (count < 0)
  5251. count = 3;
  5252. String retVal = GetLinkedListItems(dbgCompileUnit, debugVis, endNodePtr, valueType, curNode, count, &newContinuationData);
  5253. retVal += "\n" + newContinuationData;
  5254. return retVal;
  5255. }
  5256. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Array)
  5257. {
  5258. DbgType* valueType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5259. DbgTypedValue curNode;
  5260. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5261. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5262. String newContinuationData;
  5263. if (count < 0)
  5264. count = 3;
  5265. String retVal = GetArrayItems(dbgCompileUnit, debugVis, valueType, curNode, count, &newContinuationData);
  5266. retVal += "\n" + newContinuationData;
  5267. return retVal;
  5268. }
  5269. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Dictionary)
  5270. {
  5271. DbgTypedValue dictValue;
  5272. dictValue.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5273. dictValue.mSrcAddress = DecodeTargetDataPtr(dataPtr);
  5274. int bucketIdx = (int)DecodeTargetDataPtr(dataPtr);
  5275. int nodeIdx = (int)DecodeTargetDataPtr(dataPtr);
  5276. String newContinuationData;
  5277. String retVal = GetDictionaryItems(dbgCompileUnit, debugVis, dictValue, bucketIdx, nodeIdx, count, &newContinuationData);
  5278. retVal += "\n" + newContinuationData;
  5279. return retVal;
  5280. }
  5281. return "";
  5282. }
  5283. template <typename T>
  5284. static String IntTypeToString(T val, const StringImpl& name, DwDisplayInfo* displayInfo, DwFormatInfo& formatInfo)
  5285. {
  5286. auto intDisplayType = displayInfo->mIntDisplayType;
  5287. if (formatInfo.mDisplayType == DwDisplayType_Decimal)
  5288. intDisplayType = DwIntDisplayType_Decimal;
  5289. else if (formatInfo.mDisplayType == DwDisplayType_HexUpper)
  5290. intDisplayType = DwIntDisplayType_HexadecimalUpper;
  5291. else if (formatInfo.mDisplayType == DwDisplayType_HexLower)
  5292. intDisplayType = DwIntDisplayType_HexadecimalLower;
  5293. if (intDisplayType == DwIntDisplayType_Binary)
  5294. {
  5295. String binary;
  5296. for (int i = 0; i < sizeof(T) * 8; i++)
  5297. {
  5298. if ((i != 0) && (i % 4 == 0))
  5299. binary = "'" + binary;
  5300. if ((i != 0) && (i % 16 == 0))
  5301. binary = "'" + binary;
  5302. binary = ((val & ((T)1 << i)) ? "1" : "0") + binary;
  5303. }
  5304. return StrFormat("0b'%s\n%s", binary.c_str(), name.c_str());
  5305. }
  5306. if (intDisplayType == DwIntDisplayType_Octal)
  5307. {
  5308. String format;
  5309. if (sizeof(T) == 8)
  5310. {
  5311. format = StrFormat("0o%%lo\n%s", name.c_str());
  5312. }
  5313. else
  5314. format = StrFormat("0o%%0%do\n%s", sizeof(val) * 2, name.c_str());
  5315. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5316. }
  5317. if (intDisplayType == DwIntDisplayType_HexadecimalUpper)
  5318. {
  5319. String format;
  5320. if (sizeof(T) == 8)
  5321. {
  5322. format = StrFormat("0x%%l@\n%s", name.c_str());
  5323. }
  5324. else
  5325. format = StrFormat("0x%%0%dX\n%s", sizeof(val) * 2, name.c_str());
  5326. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5327. }
  5328. //TODO: Implement HexadecimalLower
  5329. if (intDisplayType == DwIntDisplayType_HexadecimalLower)
  5330. {
  5331. String format;
  5332. if (sizeof(T) == 8)
  5333. {
  5334. format = StrFormat("0x%%l@\n%s", name.c_str());
  5335. }
  5336. else
  5337. format = StrFormat("0x%%0%dX\n%s", sizeof(val) * 2, name.c_str());
  5338. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5339. }
  5340. if (std::is_unsigned<T>::value)
  5341. {
  5342. if (sizeof(T) == 8)
  5343. {
  5344. if (val > 0x7FFFFFFFF)
  5345. return StrFormat("%llu\n%s\n:editVal\t%lluUL", val, name.c_str(), val);
  5346. else
  5347. return StrFormat("%llu\n%s", val, name.c_str());
  5348. }
  5349. else
  5350. return StrFormat("%u\n%s", val, name.c_str());
  5351. }
  5352. else
  5353. {
  5354. if (sizeof(T) == 8)
  5355. {
  5356. if ((val > 0x7FFFFFFFF) || (val < -0x80000000LL))
  5357. return StrFormat("%lld\n%s\n:editVal\t%lldL", val, name.c_str(), val);
  5358. else
  5359. return StrFormat("%lld\n%s", val, name.c_str(), val);
  5360. }
  5361. else
  5362. return StrFormat("%d\n%s", val, name.c_str());
  5363. }
  5364. }
  5365. DwDisplayInfo* WinDebugger::GetDisplayInfo(const StringImpl& referenceId)
  5366. {
  5367. DwDisplayInfo* displayInfo = &mDebugManager->mDefaultDisplayInfo;
  5368. if (!referenceId.empty())
  5369. {
  5370. mDebugManager->mDisplayInfos.TryGetValue(referenceId, &displayInfo);
  5371. }
  5372. return displayInfo;
  5373. }
  5374. static String WrapWithModifiers(const StringImpl& origName, DbgType* dbgType, DbgLanguage language)
  5375. {
  5376. if (language == DbgLanguage_Unknown)
  5377. language = dbgType->GetLanguage();
  5378. String name = origName;
  5379. while (true)
  5380. {
  5381. if (dbgType->mTypeCode == DbgType_Const)
  5382. {
  5383. if (language == DbgLanguage_Beef)
  5384. name = "readonly " + name;
  5385. else
  5386. name = "const " + name;
  5387. dbgType = dbgType->mTypeParam;
  5388. }
  5389. else if (dbgType->mTypeCode == DbgType_Volatile)
  5390. {
  5391. name = "volatile " + name;
  5392. dbgType = dbgType->mTypeParam;
  5393. }
  5394. else if (dbgType->mTypeCode == DbgType_TypeDef)
  5395. {
  5396. dbgType = dbgType->mTypeParam;
  5397. }
  5398. else if (dbgType->mTypeCode == DbgType_Ref)
  5399. {
  5400. if (language == DbgLanguage_Beef)
  5401. name = "ref " + name;
  5402. else
  5403. name = name + "&";
  5404. dbgType = dbgType->mTypeParam;
  5405. }
  5406. else if (dbgType->mTypeCode == DbgType_Bitfield)
  5407. {
  5408. return dbgType->ToString(language);
  5409. }
  5410. else
  5411. return name;
  5412. }
  5413. }
  5414. DebugVisualizerEntry* WinDebugger::FindVisualizerForType(DbgType* dbgType, Array<String>* wildcardCaptures)
  5415. {
  5416. auto entry = mDebugManager->mDebugVisualizers->FindEntryForType(dbgType->ToString(DbgLanguage_Unknown, true), dbgType->mCompileUnit->mDbgModule->mDbgFlavor, wildcardCaptures);
  5417. if (entry == NULL)
  5418. {
  5419. dbgType = dbgType->GetPrimaryType();
  5420. dbgType->PopulateType();
  5421. for (auto baseTypeEntry : dbgType->mBaseTypes)
  5422. {
  5423. entry = FindVisualizerForType(baseTypeEntry->mBaseType, wildcardCaptures);
  5424. if (entry != NULL)
  5425. break;
  5426. }
  5427. }
  5428. return entry;
  5429. }
  5430. #define GET_FROM(ptr, T) *((T*)(ptr += sizeof(T)) - 1)
  5431. String WinDebugger::ReadString(DbgTypeCode charType, intptr addr, bool isLocalAddr, intptr maxLength, DwFormatInfo& formatInfo)
  5432. {
  5433. int origMaxLength = maxLength;
  5434. if (addr == 0)
  5435. return "";
  5436. BP_ZONE("WinDebugger::ReadString");
  5437. String retVal = "\"";
  5438. bool wasTerminated = false;
  5439. String valString;
  5440. intptr maxShowSize = 255;
  5441. if (maxLength == -1)
  5442. maxLength = formatInfo.mOverrideCount;
  5443. else if (formatInfo.mOverrideCount != -1)
  5444. maxLength = BF_MIN(formatInfo.mOverrideCount, maxLength);
  5445. if (formatInfo.mMaxCount != -1)
  5446. maxLength = BF_MIN(formatInfo.mMaxCount, maxLength);
  5447. if (maxLength == -1)
  5448. maxLength = 8 * 1024 * 1024; // Is 8MB crazy?
  5449. if (!formatInfo.mRawString)
  5450. maxLength = BF_MIN(maxLength, maxShowSize);
  5451. //EnableMemCache();
  5452. bool readFailed = false;
  5453. intptr strPtr = addr;
  5454. int charLen = 1;
  5455. if ((charType == DbgType_SChar16) || (charType == DbgType_UChar16))
  5456. charLen = 2;
  5457. else if ((charType == DbgType_SChar32) || (charType == DbgType_UChar32))
  5458. charLen = 4;
  5459. bool isUTF8 = formatInfo.mDisplayType == DwDisplayType_Utf8;
  5460. int readSize = BF_MIN(1024, maxLength * charLen);
  5461. uint8 buf[1024];
  5462. uint8* bufPtr = NULL;
  5463. uint8* bufEnd = NULL;
  5464. bool hasHighAscii = false;
  5465. int i;
  5466. for (i = 0; i < maxLength; i++)
  5467. {
  5468. if (bufPtr >= bufEnd)
  5469. {
  5470. while (true)
  5471. {
  5472. if (readSize < charLen)
  5473. {
  5474. readFailed = true;
  5475. break;
  5476. }
  5477. if (ReadMemory(strPtr, readSize, buf, isLocalAddr))
  5478. break;
  5479. readSize /= 2;
  5480. }
  5481. if (readFailed)
  5482. break;
  5483. bufPtr = buf;
  5484. bufEnd = buf + readSize;
  5485. }
  5486. switch (charLen)
  5487. {
  5488. case 1:
  5489. {
  5490. char c = GET_FROM(bufPtr, char);
  5491. if ((c != 0) || (formatInfo.mOverrideCount != -1))
  5492. {
  5493. if ((uint8)c >= 0x80)
  5494. hasHighAscii = true;
  5495. valString.Append(c);
  5496. }
  5497. else
  5498. wasTerminated = true;
  5499. }
  5500. break;
  5501. case 2:
  5502. {
  5503. uint16 c16 = GET_FROM(bufPtr, uint16);
  5504. if ((c16 != 0) || (formatInfo.mOverrideCount != -1))
  5505. {
  5506. char str[8];
  5507. u8_toutf8(str, 8, c16);
  5508. valString += str;
  5509. }
  5510. else
  5511. wasTerminated = true;
  5512. }
  5513. break;
  5514. case 4:
  5515. {
  5516. uint32 c32 = GET_FROM(bufPtr, uint32);
  5517. if ((c32 != 0) || (formatInfo.mOverrideCount != -1))
  5518. {
  5519. char str[8];
  5520. u8_toutf8(str, 8, c32);
  5521. valString += str;
  5522. }
  5523. else
  5524. wasTerminated = true;
  5525. }
  5526. break;
  5527. }
  5528. if ((wasTerminated) && (formatInfo.mOverrideCount != -1))
  5529. {
  5530. valString += '\x00';
  5531. wasTerminated = false;
  5532. }
  5533. if ((wasTerminated) || (readFailed))
  5534. {
  5535. break;
  5536. }
  5537. strPtr += charLen;
  5538. }
  5539. //DisableMemCache();
  5540. if (formatInfo.mOverrideCount != -1)
  5541. {
  5542. if (i == formatInfo.mOverrideCount)
  5543. wasTerminated = true;
  5544. }
  5545. if (strPtr == addr + origMaxLength)
  5546. wasTerminated = true;
  5547. if (valString.length() == formatInfo.mOverrideCount)
  5548. wasTerminated = true;
  5549. // if (formatInfo.mDisplayType == DwDisplayType_Ascii)
  5550. // {
  5551. // // Our encoding for retVal is already assumed to be UTF8, so the special case here actually Ascii
  5552. // valString = UTF8Encode(ToWString(valString));
  5553. // }
  5554. if (formatInfo.mRawString)
  5555. {
  5556. if ((formatInfo.mDisplayType == DwDisplayType_Utf8) || (!hasHighAscii))
  5557. return valString;
  5558. String utf8Str;
  5559. for (int i = 0; i < (int)valString.length(); i++)
  5560. {
  5561. char c = valString[i];
  5562. if ((uint8)c >= 0x80)
  5563. {
  5564. utf8Str += (char)(0xC0 | (((uint8)c & 0xFF) >> 6));
  5565. utf8Str += (char)(0x80 | ((uint8)c & 0x3F));
  5566. }
  5567. else
  5568. utf8Str += c;
  5569. }
  5570. return utf8Str;
  5571. }
  5572. if ((readFailed) && (valString.IsEmpty()))
  5573. return "< Failed to read string >";
  5574. retVal += SlashString(valString, true, true, formatInfo.mLanguage == DbgLanguage_Beef);
  5575. // We could go over 'maxShowSize' if we have a lot of slashed chars. An uninitialized string can be filled with '\xcc' chars
  5576. if ((!formatInfo.mRawString) && ((int)retVal.length() > maxShowSize))
  5577. {
  5578. retVal = retVal.Substring(0, maxShowSize);
  5579. wasTerminated = false;
  5580. }
  5581. if (wasTerminated)
  5582. retVal += "\"";
  5583. else
  5584. retVal += "...";
  5585. return retVal;
  5586. }
  5587. void WinDebugger::ProcessEvalString(DbgCompileUnit* dbgCompileUnit, DbgTypedValue useTypedValue, String& evalStr, String& displayString, DwFormatInfo& formatInfo, DebugVisualizerEntry* debugVis, bool limitLength)
  5588. {
  5589. for (int i = 0; i < (int)evalStr.length(); i++)
  5590. {
  5591. char c = evalStr[i];
  5592. char nextC = 0;
  5593. if (i < (int)evalStr.length() - 1)
  5594. nextC = evalStr[i + 1];
  5595. if ((c == '{') && (nextC != '{'))
  5596. {
  5597. // Evaluate
  5598. int endIdx = i;
  5599. for (; endIdx < (int)evalStr.length(); endIdx++)
  5600. {
  5601. //TODO: Do better parsing - this paren could be inside a string, for example
  5602. if (evalStr[endIdx] == '}')
  5603. break;
  5604. }
  5605. DwFormatInfo displayStrFormatInfo = formatInfo;
  5606. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + (int)displayString.length();
  5607. displayStrFormatInfo.mHidePointers = false;
  5608. if ((limitLength) && (displayStrFormatInfo.mTotalSummaryLength > 255))
  5609. {
  5610. displayString += "...";
  5611. }
  5612. else
  5613. {
  5614. String evalString = evalStr.Substring(i + 1, endIdx - i - 1);
  5615. String errors;
  5616. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, useTypedValue, evalString, &displayStrFormatInfo, NULL, &errors);
  5617. if (evalResult)
  5618. {
  5619. if (displayStrFormatInfo.mNoEdit)
  5620. formatInfo.mNoEdit = true;
  5621. String result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  5622. if ((formatInfo.mRawString) && (limitLength))
  5623. {
  5624. displayString = result;
  5625. return;
  5626. }
  5627. int crPos = result.IndexOf('\n');
  5628. if (crPos != -1)
  5629. displayString += result.Substring(0, crPos);
  5630. else
  5631. displayString += result;
  5632. }
  5633. else if (debugVis != NULL)
  5634. {
  5635. displayString += "<DbgVis Failed>";
  5636. DbgVisFailed(debugVis, evalString, errors);
  5637. }
  5638. else
  5639. {
  5640. displayString += "<Eval Failed>";
  5641. }
  5642. }
  5643. i = endIdx;
  5644. continue;
  5645. }
  5646. else if ((c == '{') && (nextC == '{'))
  5647. {
  5648. // Skip next paren
  5649. i++;
  5650. }
  5651. else if ((c == '}') && (nextC == '}'))
  5652. {
  5653. // Skip next paren
  5654. i++;
  5655. }
  5656. displayString += c;
  5657. }
  5658. }
  5659. static bool IsNormalChar(uint32 c)
  5660. {
  5661. return (c < 0x80);
  5662. }
  5663. String WinDebugger::DbgTypedValueToString(const DbgTypedValue& origTypedValue, const StringImpl& expr, DwFormatInfo& formatInfo, DbgExprEvaluator* optEvaluator, bool fullPrecision)
  5664. {
  5665. BP_ZONE("WinDebugger::DbgTypedValueToString");
  5666. DbgTypedValue typedValue = origTypedValue;
  5667. auto dbgCompileUnit = typedValue.mType->mCompileUnit;
  5668. auto dbgModule = typedValue.mType->GetDbgModule();
  5669. auto language = origTypedValue.mType->GetLanguage();
  5670. if (language == DbgLanguage_Unknown)
  5671. language = formatInfo.mLanguage;
  5672. formatInfo.mLanguage = language;
  5673. bool isBeef = language == DbgLanguage_Beef;
  5674. char str[32];
  5675. bool readFailed = false;
  5676. bool isCompositeType = false;
  5677. bool isSizedArray = false;
  5678. bool isEnum = false;
  5679. int64 enumVal = 0;
  5680. String result;
  5681. DwDisplayInfo* displayInfo = GetDisplayInfo(formatInfo.mReferenceId);
  5682. DbgType* origValueType = typedValue.mType;
  5683. bool origHadRef = false;
  5684. DbgType* dwValueType = typedValue.mType->RemoveModifiers(&origHadRef);
  5685. if (dwValueType == NULL)
  5686. dwValueType = dbgModule->GetPrimitiveType(DbgType_Void, language);
  5687. else
  5688. dwValueType = dwValueType->GetPrimaryType();
  5689. if (dwValueType->mTypeCode == DbgType_TypeDef)
  5690. {
  5691. DbgTypedValue realTypedVal = typedValue;
  5692. realTypedVal.mType = dwValueType->mTypeParam;
  5693. return DbgTypedValueToString(realTypedVal, expr, formatInfo, optEvaluator);
  5694. }
  5695. if (formatInfo.mRawString)
  5696. {
  5697. if ((dwValueType->mTypeCode != DbgType_Struct) && (dwValueType->mTypeCode != DbgType_Class) && (dwValueType->mTypeCode != DbgType_Ptr) && (dwValueType->mTypeCode != DbgType_SizedArray))
  5698. return "";
  5699. }
  5700. auto _ShowArraySummary = [&](String& retVal, addr_target ptrVal, int64 arraySize, DbgType* innerType)
  5701. {
  5702. String displayString;
  5703. displayString += "{";
  5704. for (int idx = 0; idx < arraySize; idx++)
  5705. {
  5706. if (formatInfo.mTotalSummaryLength + retVal.length() + displayString.length() > 255)
  5707. {
  5708. displayString += "...";
  5709. break;
  5710. }
  5711. if ((idx != 0) && (!displayString.EndsWith('{')))
  5712. displayString += ", ";
  5713. DwFormatInfo displayStrFormatInfo = formatInfo;
  5714. displayStrFormatInfo.mExpandItemDepth = 1;
  5715. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + retVal.length() + displayString.length();
  5716. displayStrFormatInfo.mHidePointers = false;
  5717. displayStrFormatInfo.mArrayLength = -1;
  5718. // Why did we have this "na" on here? It made "void*[3]" type things show up as "{,,}"
  5719. //String evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + StrFormat(")[%d], na", idx);
  5720. String evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + StrFormat(")[%lld]", idx);
  5721. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, typedValue, evalStr, &displayStrFormatInfo);
  5722. String result;
  5723. if (evalResult)
  5724. {
  5725. result = DbgTypedValueToString(evalResult, evalStr, displayStrFormatInfo, NULL);
  5726. int crPos = result.IndexOf('\n');
  5727. if (crPos != -1)
  5728. result.RemoveToEnd(crPos);
  5729. }
  5730. else
  5731. result = "???";
  5732. displayString += result;
  5733. }
  5734. displayString += "}";
  5735. retVal += displayString;
  5736. };
  5737. if (formatInfo.mArrayLength != -1)
  5738. {
  5739. if (formatInfo.mRawString)
  5740. return "";
  5741. if (dwValueType->IsPointer())
  5742. {
  5743. String retVal;
  5744. addr_target ptrVal = (addr_target)typedValue.mPtr;
  5745. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  5746. {
  5747. retVal = EncodeDataPtr(ptrVal, true) + " ";
  5748. retVal += dwValueType->mTypeParam->ToString(language);
  5749. retVal += StrFormat("[%lld] ", (int64)formatInfo.mArrayLength);
  5750. }
  5751. _ShowArraySummary(retVal, ptrVal, formatInfo.mArrayLength, dwValueType->mTypeParam);
  5752. String idxStr = "[{0}]";
  5753. DbgType* innerType = dwValueType->mTypeParam;
  5754. retVal += "\n" + dwValueType->ToString(language);
  5755. String evalStr = "*((" + typedValue.mType->ToStringRaw(language) + ")" + EncodeDataPtr(ptrVal, true) + " + {0})";
  5756. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, (int)BF_MAX(formatInfo.mArrayLength, 0), 10000) +
  5757. "\t" + idxStr + "\t" + evalStr;
  5758. return retVal;
  5759. }
  5760. else
  5761. {
  5762. DwFormatInfo newFormatInfo = formatInfo;
  5763. newFormatInfo.mArrayLength = -1;
  5764. String retVal = DbgTypedValueToString(typedValue, expr, newFormatInfo, optEvaluator);
  5765. int crPos = (int)retVal.IndexOf('\n');
  5766. if (crPos != -1)
  5767. retVal = "!Array length flag not valid with this type" + retVal.Substring(crPos);
  5768. return retVal;
  5769. }
  5770. }
  5771. switch (dwValueType->mTypeCode)
  5772. {
  5773. case DbgType_Void:
  5774. return "\nvoid";
  5775. case DbgType_Bool:
  5776. {
  5777. if (typedValue.mUInt8 == 0)
  5778. return "false\n" + WrapWithModifiers("bool", origValueType, language);
  5779. else if (typedValue.mUInt8 == 1)
  5780. return "true\n" + WrapWithModifiers("bool", origValueType, language);
  5781. else
  5782. return StrFormat("true (%d)\n", typedValue.mUInt8) + WrapWithModifiers("bool", origValueType, language);
  5783. }
  5784. break;
  5785. case DbgType_UChar:
  5786. if (language != DbgLanguage_Beef)
  5787. return IntTypeToString<uint8>(typedValue.mUInt8, WrapWithModifiers("uint8_t", origValueType, language), displayInfo, formatInfo);
  5788. case DbgType_SChar:
  5789. {
  5790. if (typedValue.mInt8 != 0)
  5791. {
  5792. char str[2] = {(char)typedValue.mInt8};
  5793. result = SlashString(str, formatInfo.mDisplayType == DwDisplayType_Utf8, true);
  5794. if (!IsNormalChar(typedValue.mUInt8))
  5795. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt8);
  5796. else
  5797. result = StrFormat("'%s'\n", result.c_str());
  5798. }
  5799. else
  5800. result = "'\\0'\n";
  5801. return result + WrapWithModifiers("char", origValueType, language);
  5802. }
  5803. break;
  5804. case DbgType_UChar16:
  5805. if (language != DbgLanguage_Beef)
  5806. return IntTypeToString<int16>(typedValue.mUInt8, WrapWithModifiers("uint16_t", origValueType, language), displayInfo, formatInfo);
  5807. case DbgType_SChar16:
  5808. {
  5809. if (typedValue.mInt16 != 0)
  5810. {
  5811. u8_toutf8(str, 8, typedValue.mUInt32);
  5812. result = SlashString(str, true, true);
  5813. if (!IsNormalChar(typedValue.mUInt32))
  5814. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt16);
  5815. else
  5816. result = StrFormat("'%s'\n", result.c_str());
  5817. }
  5818. else
  5819. result = "'\\0'\n";
  5820. return result + WrapWithModifiers(isBeef ? "char16" : "int16_t", origValueType, language);
  5821. }
  5822. break;
  5823. case DbgType_UChar32:
  5824. case DbgType_SChar32:
  5825. {
  5826. if (typedValue.mInt32 != 0)
  5827. {
  5828. u8_toutf8(str, 8, typedValue.mUInt32);
  5829. result = SlashString(str, true, true);
  5830. if (!IsNormalChar(typedValue.mUInt32))
  5831. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt32);
  5832. else
  5833. result = StrFormat("'%s'\n", result.c_str());
  5834. }
  5835. else
  5836. result = "'\\0'\n";
  5837. return result + WrapWithModifiers(isBeef ? "char32" : "int32_t", origValueType, language);
  5838. }
  5839. break;
  5840. case DbgType_i8:
  5841. return IntTypeToString<int8>(typedValue.mInt8, WrapWithModifiers(isBeef ? "int8" : "int8_t", origValueType, language), displayInfo, formatInfo);
  5842. case DbgType_u8:
  5843. return IntTypeToString<uint8>(typedValue.mUInt8, WrapWithModifiers(isBeef ? "uint8" : "uint8_t", origValueType, language), displayInfo, formatInfo);
  5844. case DbgType_i16:
  5845. return IntTypeToString<int16>(typedValue.mInt16, WrapWithModifiers(isBeef ? "int16" : "int16_t", origValueType, language), displayInfo, formatInfo);
  5846. case DbgType_u16:
  5847. return IntTypeToString<uint16>(typedValue.mUInt16, WrapWithModifiers(isBeef ? "uint16" : "uint16_t", origValueType, language), displayInfo, formatInfo);
  5848. case DbgType_i32:
  5849. return IntTypeToString<int32>(typedValue.mInt32, WrapWithModifiers(isBeef ? "int32" : "int32_t", origValueType, language), displayInfo, formatInfo);
  5850. case DbgType_u32:
  5851. return IntTypeToString<uint32>(typedValue.mUInt32, WrapWithModifiers(isBeef ? "uint32" : "uint32_t", origValueType, language), displayInfo, formatInfo);
  5852. case DbgType_i64:
  5853. return IntTypeToString<int64>(typedValue.mInt64, WrapWithModifiers(isBeef ? "int64" : "int64_t", origValueType, language), displayInfo, formatInfo);
  5854. case DbgType_u64:
  5855. return IntTypeToString<uint64>(typedValue.mUInt64, WrapWithModifiers(isBeef ? "uint64" : "uint64_t", origValueType, language), displayInfo, formatInfo);
  5856. case DbgType_RegGroup:
  5857. {
  5858. if ((typedValue.mRegNum >= CPUReg_M128_XMMREG_FIRST) && (typedValue.mRegNum <= CPUReg_M128_XMMREG_LAST))
  5859. {
  5860. int callStackIdx = formatInfo.mCallStackIdx;
  5861. FixCallStackIdx(callStackIdx);
  5862. UpdateRegisterUsage(callStackIdx);
  5863. WdStackFrame* wdStackFrame = mCallStack[callStackIdx];
  5864. RegForm regForm = RegForm_Unknown;
  5865. if (typedValue.mRegNum < (int)wdStackFrame->mRegForms.size())
  5866. regForm = wdStackFrame->mRegForms[typedValue.mRegNum];
  5867. int xmmMajor = typedValue.mRegNum - CPUReg_M128_XMMREG_FIRST;
  5868. String headerStr;
  5869. String xmmType = "__m128";
  5870. int xmmCount = 4;
  5871. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2) ||
  5872. (regForm == RegForm_Long) || (regForm == RegForm_Long2) ||
  5873. (regForm == RegForm_ULong) || (regForm == RegForm_ULong2))
  5874. xmmCount = 2;
  5875. //TODO: add byte, short, int, etc...
  5876. if (optEvaluator)
  5877. {
  5878. DwMmDisplayType mmDwMmDisplayType = displayInfo->mMmDisplayType;
  5879. if (mmDwMmDisplayType == DwMmDisplayType_Default)
  5880. {
  5881. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2))
  5882. mmDwMmDisplayType = DwMmDisplayType_Double;
  5883. else if (regForm == RegForm_Int4)
  5884. mmDwMmDisplayType = DwMmDisplayType_Int;
  5885. }
  5886. //TODO: Add support for int types
  5887. if (mmDwMmDisplayType == DwMmDisplayType_Double)
  5888. {
  5889. xmmType = "__m128d";
  5890. xmmCount = 2;
  5891. double xmmRegVals[2];
  5892. CPURegisters* regs = optEvaluator->GetRegisters();
  5893. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5894. {
  5895. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5896. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_Double);
  5897. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5898. xmmRegVals[xmmMinor] = xmmReg.mDouble;
  5899. }
  5900. headerStr = StrFormat("(%f, %f)", xmmRegVals[0], xmmRegVals[1]);
  5901. }
  5902. else if (mmDwMmDisplayType == DwMmDisplayType_Byte)
  5903. {
  5904. int xmmRegVals[4];
  5905. xmmCount = 4;
  5906. CPURegisters* regs = optEvaluator->GetRegisters();
  5907. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5908. {
  5909. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5910. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i32);
  5911. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5912. xmmRegVals[xmmMinor] = xmmReg.mInt8;
  5913. }
  5914. headerStr = StrFormat("(%d, %d, %d, %d)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  5915. }
  5916. else if (mmDwMmDisplayType == DwMmDisplayType_Short)
  5917. {
  5918. int xmmRegVals[4];
  5919. xmmCount = 4;
  5920. CPURegisters* regs = optEvaluator->GetRegisters();
  5921. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5922. {
  5923. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5924. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i32);
  5925. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5926. xmmRegVals[xmmMinor] = xmmReg.mInt16;
  5927. }
  5928. headerStr = StrFormat("(%d, %d, %d, %d)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  5929. }
  5930. else if (mmDwMmDisplayType == DwMmDisplayType_Int)
  5931. {
  5932. int xmmRegVals[4];
  5933. xmmCount = 4;
  5934. CPURegisters* regs = optEvaluator->GetRegisters();
  5935. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5936. {
  5937. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5938. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i32);
  5939. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5940. xmmRegVals[xmmMinor] = xmmReg.mInt32;
  5941. }
  5942. headerStr = StrFormat("(%d, %d, %d, %d)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  5943. }
  5944. else // Float
  5945. {
  5946. float xmmRegVals[4];
  5947. xmmCount = 4;
  5948. CPURegisters* regs = optEvaluator->GetRegisters();
  5949. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5950. {
  5951. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5952. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_Single);
  5953. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5954. xmmRegVals[xmmMinor] = xmmReg.mSingle;
  5955. }
  5956. headerStr = StrFormat("(%f, %f, %f, %f)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  5957. }
  5958. }
  5959. else
  5960. {
  5961. headerStr = StrFormat("XMM%d", xmmMajor);
  5962. }
  5963. result = headerStr + "\n" + xmmType;
  5964. for (int i = 0; i < xmmCount; i++)
  5965. result += WrapWithModifiers(StrFormat("\n[%d]\t$xmm%d_%d", i, xmmMajor, i, language), origValueType, language);
  5966. return result;
  5967. }
  5968. else
  5969. {
  5970. switch (typedValue.mRegNum)
  5971. {
  5972. case CPUReg_CAT_ALLREGS:
  5973. {
  5974. return "ALLREGS\n__allregs\niregs\t$iregs\nflags\t$flags\nfpregs\t$fpregs\nmmregs\t$mmregs\nxmmregs\t$xmmregs";
  5975. }
  5976. break;
  5977. case CPUReg_CAT_IREGS:
  5978. {
  5979. #ifdef BF_DBG_32
  5980. String headerStr;
  5981. if (optEvaluator)
  5982. {
  5983. CPURegisters* regs = optEvaluator->GetRegisters();
  5984. 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)",
  5985. (uint32)regs->mIntRegs.eax, (uint32)regs->mIntRegs.ebx, (uint32)regs->mIntRegs.ecx, (uint32)regs->mIntRegs.edx,
  5986. (uint32)regs->mIntRegs.esi, (uint32)regs->mIntRegs.edi, (uint32)regs->mIntRegs.esp, (uint32)regs->mIntRegs.ebp,
  5987. (uint32)regs->mIntRegs.eip, (uint32)regs->mIntRegs.efl);
  5988. }
  5989. else
  5990. {
  5991. headerStr = "IREGS";
  5992. }
  5993. 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());
  5994. #else
  5995. String headerStr;
  5996. if (optEvaluator)
  5997. {
  5998. CPURegisters* regs = optEvaluator->GetRegisters();
  5999. 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)",
  6000. (uint64)regs->mIntRegs.rax, (uint64)regs->mIntRegs.rbx, (uint64)regs->mIntRegs.rcx, (uint64)regs->mIntRegs.rdx,
  6001. (uint64)regs->mIntRegs.rsi, (uint64)regs->mIntRegs.rdi, (uint64)regs->mIntRegs.rsp, (uint64)regs->mIntRegs.rbp,
  6002. (uint64)regs->mIntRegs.rip,
  6003. (uint64)regs->mIntRegs.r8, (uint64)regs->mIntRegs.r9, (uint64)regs->mIntRegs.r10, (uint64)regs->mIntRegs.r11,
  6004. (uint64)regs->mIntRegs.r12, (uint64)regs->mIntRegs.r13, (uint64)regs->mIntRegs.r14, (uint64)regs->mIntRegs.r15,
  6005. (uint32)regs->mIntRegs.efl);
  6006. }
  6007. else
  6008. {
  6009. headerStr = "IREGS";
  6010. }
  6011. 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());
  6012. #endif
  6013. }
  6014. break;
  6015. case CPUReg_CAT_FPREGS:
  6016. {
  6017. String headerStr;
  6018. if (optEvaluator)
  6019. {
  6020. CPURegisters* regs = optEvaluator->GetRegisters();
  6021. headerStr = "(";
  6022. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6023. {
  6024. if (i)
  6025. headerStr += ", ";
  6026. double val = ConvertFloat80ToDouble(regs->mFpMmRegsArray[i].fp.fp80);
  6027. headerStr += StrFormat("%f", val);
  6028. }
  6029. headerStr += ")";
  6030. }
  6031. else
  6032. {
  6033. headerStr = "FPREGS";
  6034. }
  6035. result = StrFormat("%s\n__fpregs", headerStr.c_str());
  6036. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6037. result += StrFormat("\n[%d]\t$st%d", i, i);
  6038. return result;
  6039. }
  6040. break;
  6041. case CPUReg_CAT_MMREGS:
  6042. {
  6043. String headerStr;
  6044. if (optEvaluator)
  6045. {
  6046. CPURegisters* regs = optEvaluator->GetRegisters();
  6047. headerStr = "(";
  6048. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6049. {
  6050. if (i)
  6051. headerStr += ", ";
  6052. uint64 val = regs->mFpMmRegsArray[i].mm;
  6053. headerStr += StrFormat("0x%016llx", val);
  6054. }
  6055. headerStr += ")";
  6056. }
  6057. else
  6058. {
  6059. headerStr = "MMREGS";
  6060. }
  6061. result = StrFormat("%s\n__mmregs", headerStr.c_str());
  6062. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6063. result += StrFormat("\n[%d]\t$mm%d", i, i);
  6064. return result;
  6065. }
  6066. break;
  6067. case CPUReg_CAT_XMMREGS:
  6068. {
  6069. String headerStr = StrFormat("XMMREGS[%d]", CPURegisters::kNumXmmRegs); // these are too big to put a useful header for the entire category
  6070. result = StrFormat("%s\n__xmmregs", headerStr.c_str());
  6071. for (int i = 0; i < CPURegisters::kNumXmmRegs; ++i)
  6072. result += StrFormat("\n[%d]\t$xmm%d", i, i);
  6073. return result;
  6074. }
  6075. break;
  6076. case CPUReg_CAT_FLAGS:
  6077. {
  6078. String headerStr;
  6079. if (optEvaluator)
  6080. {
  6081. CPURegisters* regs = optEvaluator->GetRegisters();
  6082. #ifdef BF_DBG_32
  6083. #define FLAGVAR(abbr, name) int flag##abbr = ((regs->mIntRegs.efl & ((uint64)1 << CPURegisters::GetFlagBitForRegister(X86Reg_FLAG_##abbr##_##name))) != 0) ? 1 : 0
  6084. FLAGVAR(CF, CARRY);
  6085. FLAGVAR(PF, PARITY);
  6086. FLAGVAR(AF, ADJUST);
  6087. FLAGVAR(ZF, ZERO);
  6088. FLAGVAR(SF, SIGN);
  6089. FLAGVAR(IF, INTERRUPT);
  6090. FLAGVAR(DF, DIRECTION);
  6091. FLAGVAR(OF, OVERFLOW);
  6092. #undef FLAGVAR
  6093. #else
  6094. #define FLAGVAR(abbr, name) int flag##abbr = ((regs->mIntRegs.efl & ((uint64)1 << CPURegisters::GetFlagBitForRegister(X64Reg_FLAG_##abbr##_##name))) != 0) ? 1 : 0
  6095. FLAGVAR(CF, CARRY);
  6096. FLAGVAR(PF, PARITY);
  6097. FLAGVAR(AF, ADJUST);
  6098. FLAGVAR(ZF, ZERO);
  6099. FLAGVAR(SF, SIGN);
  6100. FLAGVAR(IF, INTERRUPT);
  6101. FLAGVAR(DF, DIRECTION);
  6102. FLAGVAR(OF, OVERFLOW);
  6103. #undef FLAGVAR
  6104. #endif
  6105. headerStr = StrFormat("(CF=%d, PF=%d, AF=%d, ZF=%d, SF=%d, IF=%d, DF=%d, OF=%d)",
  6106. flagCF, flagPF, flagAF, flagZF, flagSF, flagIF, flagDF, flagOF);
  6107. }
  6108. else
  6109. {
  6110. headerStr = "FLAGS";
  6111. }
  6112. 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",
  6113. headerStr.c_str());
  6114. }
  6115. break;
  6116. default:
  6117. BF_ASSERT(false && "unknown category register");
  6118. return "UNKNOWNCATEGORY\n__unknown\n";
  6119. }
  6120. }
  6121. }
  6122. break;
  6123. case DbgType_Single:
  6124. {
  6125. DwFloatDisplayType floatDisplayType = displayInfo->mFloatDisplayType;
  6126. if (floatDisplayType == DwFloatDisplayType_Default)
  6127. floatDisplayType = DwFloatDisplayType_Minimal;
  6128. if (floatDisplayType == DwFloatDisplayType_Minimal)
  6129. ExactMinimalFloatToStr(typedValue.mSingle, str);
  6130. else if (floatDisplayType == DwFloatDisplayType_Full)
  6131. sprintf(str, "%1.9g", typedValue.mSingle);
  6132. else if (floatDisplayType == DwFloatDisplayType_HexUpper)
  6133. sprintf(str, "0x%04X", typedValue.mUInt32);
  6134. else //if (floatDisplayType == DwFloatDisplayType_HexLower)
  6135. sprintf(str, "0x%04x", typedValue.mUInt32);
  6136. return StrFormat("%s\n%s", str, WrapWithModifiers("float", origValueType, language).c_str());
  6137. }
  6138. case DbgType_Double:
  6139. {
  6140. DwFloatDisplayType floatDisplayType = displayInfo->mFloatDisplayType;
  6141. if (floatDisplayType == DwFloatDisplayType_Default)
  6142. floatDisplayType = DwFloatDisplayType_Minimal;
  6143. if (floatDisplayType == DwFloatDisplayType_Minimal)
  6144. ExactMinimalDoubleToStr(typedValue.mDouble, str);
  6145. else if (floatDisplayType == DwFloatDisplayType_Full)
  6146. sprintf(str, "%1.17g", typedValue.mDouble);
  6147. else if (floatDisplayType == DwFloatDisplayType_HexUpper)
  6148. sprintf(str, "0x%08llX", typedValue.mUInt64);
  6149. else //if (floatDisplayType == DwFloatDisplayType_HexLower)
  6150. sprintf(str, "0x%08llx", typedValue.mUInt64);
  6151. return StrFormat("%s\n%s", str, WrapWithModifiers("double", origValueType, language).c_str());
  6152. }
  6153. case DbgType_Subroutine:
  6154. if (typedValue.mCharPtr != NULL)
  6155. return StrFormat("%s\nfunc", typedValue.mCharPtr);
  6156. else
  6157. return "\nfunc";
  6158. case DbgType_RawText:
  6159. return StrFormat("%s\nrawtext", typedValue.mCharPtr);
  6160. case DbgType_Ptr:
  6161. {
  6162. addr_target ptrVal = (addr_target)typedValue.mPtr;
  6163. String retVal;
  6164. DbgType* innerType = dwValueType->mTypeParam;
  6165. if (innerType == NULL)
  6166. return EncodeDataPtr(ptrVal, true) + "\nvoid*";
  6167. bool isChar = false;
  6168. DbgType* unmodInnerType = innerType->RemoveModifiers();
  6169. if (unmodInnerType != NULL)
  6170. {
  6171. if (language == DbgLanguage_Beef)
  6172. {
  6173. if ((unmodInnerType->mTypeCode == DbgType_UChar) ||
  6174. (unmodInnerType->mTypeCode == DbgType_UChar16) ||
  6175. (unmodInnerType->mTypeCode == DbgType_UChar32))
  6176. isChar = true;
  6177. }
  6178. else
  6179. {
  6180. if ((unmodInnerType->mTypeCode == DbgType_SChar) ||
  6181. (unmodInnerType->mTypeCode == DbgType_SChar16) ||
  6182. (unmodInnerType->mTypeCode == DbgType_SChar32))
  6183. isChar = true;
  6184. }
  6185. }
  6186. if ((isChar) && (formatInfo.mArrayLength == -1))
  6187. {
  6188. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6189. retVal = EncodeDataPtr(ptrVal, true);
  6190. int strLen = formatInfo.mOverrideCount;
  6191. if (typedValue.mIsLiteral)
  6192. {
  6193. if (strLen == -1)
  6194. strLen = 0x7FFFFFFF;
  6195. if (typedValue.mDataLen > 0)
  6196. strLen = BF_MIN(strLen, typedValue.mDataLen);
  6197. else
  6198. strLen = BF_MIN(strLen, strlen(typedValue.mCharPtr));
  6199. }
  6200. SetAndRestoreValue<intptr> prevOverrideLen(formatInfo.mOverrideCount, strLen);
  6201. String strResult = ReadString(unmodInnerType->mTypeCode, typedValue.mLocalIntPtr, typedValue.mIsLiteral, strLen, formatInfo);
  6202. if (formatInfo.mRawString)
  6203. return strResult;
  6204. if (!strResult.IsEmpty())
  6205. {
  6206. if (!retVal.IsEmpty())
  6207. retVal += " ";
  6208. retVal += strResult;
  6209. }
  6210. retVal += "\n" + origValueType->ToString(language);
  6211. return retVal;
  6212. }
  6213. else if ((unmodInnerType != NULL) &&
  6214. ((unmodInnerType->mTypeCode == DbgType_Class) || (unmodInnerType->mTypeCode == DbgType_Struct) || (unmodInnerType->mTypeCode == DbgType_Union)))
  6215. {
  6216. isCompositeType = true;
  6217. }
  6218. else if ((unmodInnerType != NULL) && (unmodInnerType->mTypeCode == DbgType_SizedArray))
  6219. {
  6220. isSizedArray = true;
  6221. }
  6222. else if (unmodInnerType->mTypeCode == DbgType_Subroutine)
  6223. {
  6224. if (formatInfo.mRawString)
  6225. return "";
  6226. addr_target funcPtr = (addr_target)typedValue.mPtr;
  6227. String retVal;
  6228. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6229. retVal = EncodeDataPtr(funcPtr, true);
  6230. String symbolName;
  6231. addr_target offset;
  6232. DbgModule* dwarf;
  6233. static String demangledName;
  6234. auto subProgram = mDebugTarget->FindSubProgram(funcPtr);
  6235. if (subProgram != NULL)
  6236. {
  6237. demangledName = subProgram->ToString();
  6238. }
  6239. else if (mDebugTarget->FindSymbolAt(funcPtr, &symbolName, &offset, &dwarf))
  6240. {
  6241. demangledName = BfDemangler::Demangle(symbolName, language);
  6242. if (offset != 0)
  6243. demangledName += StrFormat("+%d", offset);
  6244. }
  6245. else
  6246. {
  6247. auto dbgModule = mDebugTarget->FindDbgModuleForAddress(funcPtr);
  6248. if (dbgModule != NULL)
  6249. demangledName += dbgModule->GetLinkedModule()->mDisplayName + "!";
  6250. demangledName += StrFormat("0x%@", funcPtr);
  6251. }
  6252. retVal += " {";
  6253. retVal += demangledName;
  6254. retVal += "}";
  6255. retVal += "\n" + origValueType->ToString(language);
  6256. return retVal;
  6257. }
  6258. else if (unmodInnerType->mTypeCode == DbgType_Void)
  6259. {
  6260. if (formatInfo.mRawString)
  6261. return "";
  6262. addr_target ptr = (addr_target)typedValue.mPtr;
  6263. String symbolName;
  6264. addr_target offset;
  6265. DbgModule* dwarf;
  6266. String demangledName;
  6267. retVal += demangledName = StrFormat("0x%@", ptr);
  6268. if (mDebugTarget->FindSymbolAt(ptr, &symbolName, &offset, &dwarf))
  6269. {
  6270. if (offset == 0)
  6271. {
  6272. retVal += " {";
  6273. retVal += BfDemangler::Demangle(symbolName, language);
  6274. retVal += "}";
  6275. }
  6276. }
  6277. retVal += "\n" + origValueType->ToString(language);
  6278. return retVal;
  6279. }
  6280. else
  6281. {
  6282. if (formatInfo.mRawString)
  6283. return "";
  6284. addr_target ptrVal = (addr_target)typedValue.mPtr;
  6285. String retVal;
  6286. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6287. retVal = EncodeDataPtr(ptrVal, true);
  6288. if (ptrVal != 0)
  6289. {
  6290. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, NULL, -1, -1);
  6291. DbgTypedValue innerTypedVal = dbgExprEvaluator.ReadTypedValue(NULL, innerType, typedValue.mPtr, DbgAddrType_Target);
  6292. if (innerTypedVal)
  6293. {
  6294. DwFormatInfo defaultFormatInfo;
  6295. defaultFormatInfo.mLanguage = formatInfo.mLanguage;
  6296. defaultFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + 2; // Take into accout the necessary {}'s
  6297. defaultFormatInfo.mExpandItemDepth++;
  6298. String innerStr = DbgTypedValueToString(innerTypedVal, "", defaultFormatInfo, &dbgExprEvaluator);
  6299. int crIdx = innerStr.IndexOf('\n');
  6300. if (crIdx != -1)
  6301. {
  6302. String innerDataStr = innerStr.Substring(0, crIdx);
  6303. if (!innerDataStr.empty())
  6304. {
  6305. if (!retVal.empty())
  6306. retVal += " ";
  6307. retVal += "{" + innerDataStr + "}";
  6308. }
  6309. }
  6310. else
  6311. {
  6312. retVal += "{ ??? }";
  6313. }
  6314. }
  6315. }
  6316. retVal += "\n" + origValueType->ToString(language);
  6317. innerType->PopulateType();
  6318. if ((ptrVal != 0) &&
  6319. ((!innerType->mMemberList.IsEmpty()) || (innerType->mSize > 0) || (innerType->mTypeParam != NULL)))
  6320. {
  6321. String ptrDataStr = StrFormat("(%s)", dwValueType->ToStringRaw(language).c_str()) + EncodeDataPtr(typedValue.mPtr, true);
  6322. retVal += "\n*\t";
  6323. // Why did we have this? It messed up a pointer to sized array
  6324. /*if (language == DbgLanguage_Beef)
  6325. retVal += "this";
  6326. else*/
  6327. retVal += "*this";
  6328. if (!formatInfo.mReferenceId.empty())
  6329. retVal += ", refid=" + MaybeQuoteFormatInfoParam(formatInfo.mReferenceId);
  6330. retVal += ", this=" + ptrDataStr;
  6331. }
  6332. return retVal;
  6333. }
  6334. break;
  6335. }
  6336. case DbgType_Union:
  6337. case DbgType_Class:
  6338. case DbgType_Struct:
  6339. isCompositeType = true;
  6340. break;
  6341. case DbgType_Enum:
  6342. enumVal = typedValue.GetInt64();
  6343. isEnum = true;
  6344. break;
  6345. case DbgType_SizedArray:
  6346. {
  6347. isSizedArray = true;
  6348. }
  6349. break;
  6350. default:
  6351. break;
  6352. }
  6353. if (isSizedArray)
  6354. {
  6355. String retVal;
  6356. addr_target ptrVal = 0;
  6357. DbgType* arrayType = dwValueType;
  6358. DbgType* innerType = dwValueType->mTypeParam;
  6359. if (dwValueType->mTypeCode == DbgType_SizedArray)
  6360. {
  6361. ptrVal = (addr_target)typedValue.mSrcAddress;
  6362. }
  6363. else
  6364. {
  6365. BF_ASSERT(dwValueType->mTypeCode == DbgType_Ptr);
  6366. arrayType = innerType;
  6367. innerType = arrayType->mTypeParam;
  6368. ptrVal = typedValue.mPtr;
  6369. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6370. retVal = EncodeDataPtr(ptrVal, true) + " ";
  6371. }
  6372. if (ptrVal == 0)
  6373. ptrVal = typedValue.mPtr;
  6374. intptr arraySize = 0;
  6375. intptr innerSize = innerType->GetStride();
  6376. if (innerSize > 0)
  6377. arraySize = arrayType->GetStride() / innerSize;
  6378. else
  6379. {
  6380. // Failure!
  6381. }
  6382. String idxStr = "[{0}]";
  6383. if (innerType->IsChar(language))
  6384. {
  6385. String strVal = ReadString(innerType->mTypeCode, typedValue.mSrcAddress, false, arraySize, formatInfo);
  6386. if (formatInfo.mRawString)
  6387. return strVal;
  6388. retVal += strVal;
  6389. }
  6390. else
  6391. {
  6392. if (formatInfo.mRawString)
  6393. return "";
  6394. _ShowArraySummary(retVal, ptrVal, arraySize, innerType);
  6395. }
  6396. retVal += "\n" + origValueType->ToString(language);
  6397. String referenceId = dwValueType->ToString(language);
  6398. String evalStr;
  6399. // Why did we have the "na"? Do we not want to show addresses for all members?
  6400. evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + ")[{0}], refid=" + MaybeQuoteFormatInfoParam(referenceId + ".[]");
  6401. if (typedValue.mIsReadOnly)
  6402. evalStr += ", ne";
  6403. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, (int)BF_MAX(arraySize, 0), 10000) +
  6404. "\t" + idxStr + "\t" + evalStr;
  6405. return retVal;
  6406. }
  6407. dwValueType->PopulateType();
  6408. if (isEnum)
  6409. {
  6410. String retVal;
  6411. int64 bitsLeft = enumVal;
  6412. int valueCount = 0;
  6413. String editVal;
  6414. dwValueType = dwValueType->GetPrimaryType();
  6415. dwValueType->PopulateType();
  6416. while ((bitsLeft != 0) || (valueCount == 0))
  6417. {
  6418. DbgVariable* bestMatch = NULL;
  6419. for (auto member : dwValueType->mMemberList)
  6420. {
  6421. if (member->mConstValue == bitsLeft)
  6422. {
  6423. bestMatch = member;
  6424. break;
  6425. }
  6426. }
  6427. if (bestMatch == NULL)
  6428. {
  6429. for (auto member : dwValueType->mMemberList)
  6430. {
  6431. if ((member->mConstValue != 0) &&
  6432. ((member->mConstValue & bitsLeft) == member->mConstValue))
  6433. {
  6434. bestMatch = member;
  6435. break;
  6436. }
  6437. }
  6438. }
  6439. if (bestMatch == NULL)
  6440. break;
  6441. if (valueCount > 0)
  6442. {
  6443. retVal += " | ";
  6444. if (language == DbgLanguage_C)
  6445. editVal += " | ";
  6446. }
  6447. if (language == DbgLanguage_Beef)
  6448. retVal += ".";
  6449. retVal += bestMatch->mName;
  6450. if (language == DbgLanguage_C)
  6451. {
  6452. if (dwValueType->mParent != NULL)
  6453. {
  6454. editVal += dwValueType->mParent->ToString(language);
  6455. editVal += "::";
  6456. }
  6457. editVal += bestMatch->mName;
  6458. }
  6459. valueCount++;
  6460. bitsLeft &= ~bestMatch->mConstValue;
  6461. }
  6462. if ((valueCount == 0) || (bitsLeft != 0))
  6463. {
  6464. if (valueCount > 0)
  6465. retVal += " | ";
  6466. retVal += StrFormat("%lld", bitsLeft);
  6467. if (language == DbgLanguage_C)
  6468. {
  6469. if (valueCount > 0)
  6470. editVal += " | ";
  6471. editVal += StrFormat("%lld", bitsLeft);
  6472. }
  6473. }
  6474. retVal += "\n" + origValueType->ToString();
  6475. if (language == DbgLanguage_C)
  6476. {
  6477. retVal += "\n:editVal\t";
  6478. retVal += editVal;
  6479. }
  6480. retVal += "\n:canEdit";
  6481. return retVal;
  6482. }
  6483. else if (isCompositeType)
  6484. {
  6485. addr_target ptrVal;
  6486. if (dwValueType->IsPointer())
  6487. ptrVal = (addr_target)typedValue.mPtr;
  6488. else
  6489. ptrVal = (addr_target)typedValue.mSrcAddress;
  6490. String retVal;
  6491. if ((!typedValue.mIsLiteral) && (dwValueType->IsPointer()) &&
  6492. ((!formatInfo.mHidePointers) || (ptrVal == 0)))
  6493. retVal = EncodeDataPtr(ptrVal, true);
  6494. DbgType* innerType = dwValueType;
  6495. bool wasPtr = false;
  6496. if (innerType->mTypeCode == DbgType_Ptr)
  6497. {
  6498. wasPtr = true;
  6499. innerType = dwValueType->mTypeParam;
  6500. innerType = innerType->RemoveModifiers();
  6501. }
  6502. innerType = innerType->GetPrimaryType();
  6503. addr_target dataPtr = wasPtr ? typedValue.mPtr : typedValue.mSrcAddress;
  6504. DbgType* actualType = NULL;
  6505. bool useActualRawType = false;
  6506. bool isBfObject = innerType->IsBfObject();
  6507. bool hasCPPVTable = false;
  6508. if (!isBfObject)
  6509. hasCPPVTable = innerType->HasCPPVTable();
  6510. int bfObjectFlags = 0;
  6511. addr_target classVDataPtr = 0;
  6512. bool isAppendBfObject = false;
  6513. bool isStackBfObject = false;
  6514. bool isDeletedBfObject = false;
  6515. bool isCompositeWithoutAddress = false;
  6516. if (innerType->IsBfPayloadEnum())
  6517. {
  6518. if (formatInfo.mRawString)
  6519. return "";
  6520. auto tagMember = innerType->mMemberList.mTail;
  6521. int tagIdx = 0;
  6522. if (dataPtr == -1)
  6523. {
  6524. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, "(int)" + expr, &formatInfo);
  6525. auto dscValue = dbgEvaluationContext.EvaluateInContext(DbgTypedValue());
  6526. tagIdx = dscValue.mInt32;
  6527. }
  6528. else if (!ReadMemory((intptr)ptrVal + tagMember->mMemberOffset, tagMember->mType->mSize, (void*)&tagIdx))
  6529. {
  6530. return StrFormat("!Failed to read from 0x%@", ptrVal);
  6531. }
  6532. char findStr[16];
  6533. findStr[0] = '_';
  6534. itoa(tagIdx, findStr + 1, 10);
  6535. int len = strlen(findStr);
  6536. findStr[len] = '_';
  6537. len++;
  6538. if (!retVal.empty())
  6539. retVal += " ";
  6540. int startIdx = 0;
  6541. for (auto member : innerType->mMemberList)
  6542. {
  6543. if (strncmp(member->mName, findStr, len) == 0)
  6544. {
  6545. retVal += ".";
  6546. retVal += member->mName + len;
  6547. String tupleExpr;
  6548. DbgTypedValue tupleVal;
  6549. if (dataPtr == -1)
  6550. {
  6551. tupleVal.mSrcAddress = -1;
  6552. tupleVal.mType = member->mType;
  6553. //tupleExpr = "$" + expr + "$u";
  6554. tupleVal.mVariable = typedValue.mVariable;
  6555. tupleExpr = "(" + member->mType->ToStringRaw() + ")(" + expr + ")";
  6556. }
  6557. else
  6558. {
  6559. tupleVal.mType = member->mType;
  6560. tupleVal.mSrcAddress = ptrVal;
  6561. }
  6562. DwFormatInfo displayStrFormatInfo = formatInfo;
  6563. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + (int)retVal.length();
  6564. displayStrFormatInfo.mExpandItemDepth++;
  6565. displayStrFormatInfo.mHidePointers = false;
  6566. retVal += DbgTypedValueToString(tupleVal, tupleExpr, displayStrFormatInfo, NULL);
  6567. int idx = (int)retVal.IndexOf('\n');
  6568. if (idx != -1)
  6569. {
  6570. if ((idx > 2) && (strncmp(retVal.c_str() + idx - 2, "()", 2) == 0))
  6571. {
  6572. // Take off a terminating "()" on the value, if there is one
  6573. retVal.Remove(idx - 2, 2);
  6574. }
  6575. String typeName = innerType->ToString(DbgLanguage_Unknown, true);
  6576. typeName += " ";
  6577. retVal.Insert(idx + 1, typeName);
  6578. }
  6579. return retVal;
  6580. }
  6581. }
  6582. }
  6583. if (isBfObject)
  6584. {
  6585. classVDataPtr = ReadMemory<addr_target>(ptrVal);
  6586. mDebugTarget->GetCompilerSettings();
  6587. if (mDebugTarget->mBfObjectHasFlags)
  6588. {
  6589. bfObjectFlags = ((int)classVDataPtr) & 0xFF;
  6590. if ((bfObjectFlags & BfObjectFlag_Deleted) != 0)
  6591. isDeletedBfObject = true;
  6592. if ((bfObjectFlags & BfObjectFlag_AppendAlloc) != 0)
  6593. isAppendBfObject = true;
  6594. if ((bfObjectFlags & (BfObjectFlag_StackAlloc | BfObjectFlag_Allocated)) == BfObjectFlag_StackAlloc)
  6595. isStackBfObject = true;
  6596. classVDataPtr &= ~0xFF;
  6597. }
  6598. }
  6599. if (!formatInfo.mIgnoreDerivedClassInfo)
  6600. {
  6601. if (isBfObject)
  6602. {
  6603. dbgModule->ParseSymbolData();
  6604. String symbolName;
  6605. addr_target symOffset;
  6606. if ((mDebugTarget->FindSymbolAt(classVDataPtr, &symbolName, &symOffset)) && (symOffset < 0x100))
  6607. {
  6608. String mangledClassName;
  6609. const char* symEnd = "sBfClassVData";
  6610. int symEndLen = strlen(symEnd);
  6611. if (((int)symbolName.length() > symEndLen) && (strstr(symbolName.c_str(), symEnd) != NULL))
  6612. mangledClassName = symbolName;
  6613. // If we have flags then we may be pointing past the _typeData, actually. We could fix this by masking out
  6614. // the flags area, but we need to be sure we are running a build that supports flags
  6615. symEnd = "sBfTypeData";
  6616. symEndLen = strlen(symEnd);
  6617. if (((int) symbolName.length() > symEndLen) && (strstr(symbolName.c_str(), symEnd) != NULL))
  6618. mangledClassName = symbolName;
  6619. if (mangledClassName.length() > 0)
  6620. {
  6621. String className = BfDemangler::Demangle(mangledClassName, innerType->GetLanguage(), BfDemangler::Flag_RawDemangle);
  6622. for (int i = 0; i < className.length() - 3; i++)
  6623. {
  6624. if ((className[i] == 'b') &&
  6625. (className[i + 1] == 'f') &&
  6626. (className[i + 2] == '.'))
  6627. {
  6628. bool matches;
  6629. if (i == 0)
  6630. matches = true;
  6631. else
  6632. {
  6633. char prevC = className[i - 1];
  6634. if ((prevC == ' ') ||
  6635. (prevC == ',') ||
  6636. (prevC == '<'))
  6637. {
  6638. matches = true;
  6639. }
  6640. }
  6641. if (matches)
  6642. className.Remove(i, 3);
  6643. }
  6644. }
  6645. int lastDot = (int)className.LastIndexOf('.');
  6646. if (lastDot > 0)
  6647. className = className.Substring(0, lastDot);
  6648. const char* arrPrefix = "System.Array1<";
  6649. if (strncmp(className.c_str(), arrPrefix, strlen(arrPrefix)) == 0)
  6650. {
  6651. className = className.Substring(strlen(arrPrefix), className.length() - strlen(arrPrefix) - 1);
  6652. className += "[]";
  6653. }
  6654. auto typeEntry = dbgModule->GetLinkedModule()->mTypeMap.Find(className.c_str(), DbgLanguage_BeefUnfixed);
  6655. if (typeEntry != NULL)
  6656. {
  6657. actualType = typeEntry->mValue;
  6658. if (!actualType->IsBfObject())
  6659. {
  6660. if (actualType->mTypeCode == DbgType_Ptr)
  6661. {
  6662. actualType = actualType->mTypeParam;
  6663. }
  6664. }
  6665. }
  6666. }
  6667. }
  6668. }
  6669. else if (hasCPPVTable)
  6670. {
  6671. dbgModule->ParseSymbolData();
  6672. addr_target classVDataPtr = ReadMemory<addr_target>(ptrVal);
  6673. String symbolName;
  6674. addr_target offset = 0;
  6675. if (mDebugTarget->FindSymbolAt(classVDataPtr, &symbolName, &offset, NULL))
  6676. {
  6677. // On GNU, vtable indices can "go negative" for things like RTTI and virtual inheritance, so
  6678. // we can't rely on an exact vtable address lookup
  6679. if (offset < 0x200)
  6680. {
  6681. DbgLanguage lang = innerType->GetLanguage();
  6682. const char* symStart = (innerType->mCompileUnit->mDbgModule->mDbgFlavor == DbgFlavor_GNU) ? "_ZTV" : "??_7";
  6683. if (strncmp(symbolName.c_str(), symStart, strlen(symStart)) == 0)
  6684. {
  6685. //String mangledClassName = symbolName.Substring(1);
  6686. String className = BfDemangler::Demangle(symbolName, lang);
  6687. int vtableNameIdx = (int)className.IndexOf("::`vftable'");
  6688. if (vtableNameIdx != -1)
  6689. className = className.Substring(0, vtableNameIdx);
  6690. auto typeEntry = dbgModule->mTypeMap.Find(className.c_str(), DbgLanguage_C);
  6691. if (typeEntry != NULL)
  6692. {
  6693. actualType = typeEntry->mValue;
  6694. if ((int)className.IndexOf('<') != -1)
  6695. useActualRawType = true;
  6696. int thisOffset = 0;
  6697. if (!DbgExprEvaluator::TypeIsSubTypeOf(actualType, innerType, &thisOffset))
  6698. {
  6699. // This catches virtual inheritance cases where we can't downcast
  6700. actualType = NULL;
  6701. }
  6702. }
  6703. }
  6704. }
  6705. }
  6706. }
  6707. }
  6708. DbgType* displayType = origValueType;
  6709. String displayString;
  6710. bool wantsCustomExpandedItems = false;
  6711. DebugVisualizerEntry* debugVis = NULL;
  6712. Array<String> dbgVisWildcardCaptures;
  6713. DbgType* dwUseType = (actualType != NULL) ? actualType : innerType;
  6714. //auto ptrDataType = dwValueType;
  6715. //TODO: Changed this from the above to account for COFF types where 'this' is always a fwd reference, does this cause any issues?
  6716. auto ptrDataType = innerType;
  6717. String ptrDataStr;
  6718. if (/*(!innerType->IsBfObject()) &&*/ (!ptrDataType->IsPointer()))
  6719. {
  6720. if ((dataPtr != 0) || (ptrDataType->GetByteCount() > sizeof(addr_target)))
  6721. {
  6722. bool wantsRefThis = ptrDataType->WantsRefThis();
  6723. ptrDataType = ptrDataType->GetDbgModule()->GetPointerType(ptrDataType);
  6724. if (wantsRefThis)
  6725. ptrDataStr += "*";
  6726. }
  6727. else
  6728. {
  6729. // Data is inline - must be int-sized or less
  6730. isCompositeWithoutAddress = true;
  6731. dataPtr = typedValue.mPtr;
  6732. }
  6733. }
  6734. String ptrDataTypeStr = ptrDataType->ToStringRaw();
  6735. ptrDataStr += StrFormat("(%s)", ptrDataTypeStr.c_str()) + EncodeDataPtr(dataPtr, true);
  6736. DbgType* dwUsePtrType = dwUseType;
  6737. String ptrUseDataStr;
  6738. if (!dwUsePtrType->IsPointer())
  6739. {
  6740. bool wantsRefThis = dwUsePtrType->WantsRefThis();
  6741. dwUsePtrType = dwUsePtrType->GetDbgModule()->GetPointerType(dwUsePtrType);
  6742. if (wantsRefThis)
  6743. ptrUseDataStr += "*";
  6744. }
  6745. String ptrUseDataTypeStr = dwUsePtrType->ToStringRaw();
  6746. ptrUseDataStr += StrFormat("(%s)", ptrUseDataTypeStr.c_str()) + EncodeDataPtr(dataPtr, true);
  6747. if ((origTypedValue.mSrcAddress == -1) && (origTypedValue.mVariable != NULL))
  6748. {
  6749. ptrDataStr = origTypedValue.mVariable->mName;
  6750. if (!origTypedValue.mType->RemoveModifiers()->Equals(origTypedValue.mVariable->mType->RemoveModifiers()))
  6751. {
  6752. //ptrDataStr = StrFormat("(%s)%s", origTypedValue.mType->ToString().c_str(), origTypedValue.mVariable->mName);
  6753. ptrDataStr = expr;
  6754. }
  6755. ptrUseDataStr = ptrDataStr;
  6756. }
  6757. bool isNull = wasPtr && (dataPtr == 0);
  6758. bool isBadSrc = !wasPtr && (dataPtr == 0) && (!dwValueType->IsValuelessType());
  6759. if ((ptrVal == 0) && (dwValueType->IsTypedPrimitive()))
  6760. {
  6761. DbgTypedValue rawVal;
  6762. rawVal.mInt64 = origTypedValue.mInt64;
  6763. rawVal.mType = dwValueType->GetRootBaseType();
  6764. ptrDataStr = "(" + dwUseType->ToStringRaw() + ")";
  6765. ptrDataStr += DbgTypedValueToString(rawVal, expr, formatInfo, optEvaluator, fullPrecision);
  6766. int editValIdx = ptrDataStr.IndexOf(":editVal");
  6767. if (editValIdx != -1)
  6768. ptrDataStr.Remove(0, editValIdx + 9);
  6769. int crPos = (int)ptrDataStr.IndexOf('\n');
  6770. if (crPos != -1)
  6771. ptrDataStr.RemoveToEnd(crPos);
  6772. ptrUseDataStr = ptrDataStr;
  6773. if ((origTypedValue.mRegNum != -1) && (!expr.IsEmpty()) && (!formatInfo.mExplicitThis))
  6774. {
  6775. // There's no address, use direct local identifier
  6776. ptrDataStr = expr;
  6777. ptrUseDataStr = expr;
  6778. }
  6779. // This keeps 'function' types from showing null as "<null parent>"
  6780. isBadSrc = false;
  6781. }
  6782. else if ((ptrVal == 0) && (dwValueType->IsCompositeType()))
  6783. {
  6784. }
  6785. DbgTypedValue useTypedValue = typedValue;
  6786. if ((origHadRef) || ((typedValue.mType->HasPointer()) && (!dwUseType->HasPointer())))
  6787. {
  6788. useTypedValue.mSrcAddress = useTypedValue.mPtr;
  6789. useTypedValue.mPtr = 0;
  6790. if (dwUseType->IsTypedPrimitive())
  6791. {
  6792. int byteCount = dwUseType->GetByteCount();
  6793. if (byteCount <= sizeof(intptr))
  6794. {
  6795. ReadMemory(useTypedValue.mSrcAddress, byteCount, &useTypedValue.mPtr);
  6796. }
  6797. }
  6798. }
  6799. useTypedValue.mType = dwUseType;
  6800. if ((!formatInfo.mNoVisualizers) && (!isNull) && (!isBadSrc))
  6801. {
  6802. if (language == DbgLanguage_Beef)
  6803. dwUseType->FixName();
  6804. debugVis = FindVisualizerForType(dwUseType, &dbgVisWildcardCaptures);
  6805. }
  6806. bool hadCustomDisplayString = false;
  6807. if (debugVis != NULL)
  6808. {
  6809. auto& displayStringList = formatInfo.mRawString ? debugVis->mStringViews : debugVis->mDisplayStrings;
  6810. for (auto displayEntry : displayStringList)
  6811. {
  6812. if (!displayEntry->mCondition.empty())
  6813. {
  6814. if (!EvalCondition(debugVis, dbgCompileUnit, useTypedValue, formatInfo, displayEntry->mCondition, dbgVisWildcardCaptures, displayString))
  6815. continue;
  6816. }
  6817. hadCustomDisplayString = true;
  6818. String displayStr = mDebugManager->mDebugVisualizers->DoStringReplace(displayEntry->mString, dbgVisWildcardCaptures);
  6819. if (displayString.length() > 0)
  6820. displayString += " ";
  6821. ProcessEvalString(dbgCompileUnit, useTypedValue, displayStr, displayString, formatInfo, debugVis, true);
  6822. if (formatInfo.mRawString)
  6823. return displayString;
  6824. break;
  6825. }
  6826. if ((!debugVis->mExpandItems.empty()) || (debugVis->mCollectionType != DebugVisualizerEntry::CollectionType_None))
  6827. {
  6828. wantsCustomExpandedItems = true;
  6829. }
  6830. }
  6831. if (formatInfo.mRawString)
  6832. return "";
  6833. bool isTuple = (dwUseType->mName != NULL) && (dwUseType->mName[0] == '(') && (language == DbgLanguage_Beef);
  6834. if (isBadSrc)
  6835. {
  6836. displayString += "<null parent>";
  6837. }
  6838. else if ((!isNull) && (!formatInfo.mNoVisualizers) && (!hadCustomDisplayString))
  6839. {
  6840. // Create our own custom display
  6841. String firstRet;
  6842. String bigRet = isTuple ? "(" : "{ ";
  6843. int memberIdx = 0;
  6844. DbgType* summaryType = dwUseType;
  6845. bool summaryDone = false;
  6846. bool truncatedMemberList = false;
  6847. DbgTypedValue summaryTypedValue = useTypedValue;
  6848. String summaryDataStr = ptrDataStr;
  6849. String splatStr;
  6850. if (dataPtr == -1)
  6851. splatStr = expr;
  6852. while (summaryType != NULL)
  6853. {
  6854. summaryType->PopulateType();
  6855. if ((summaryType->IsTypedPrimitive()) &&
  6856. ((summaryType->mBaseTypes.IsEmpty()) || (!summaryType->mBaseTypes.front()->mBaseType->IsTypedPrimitive())))
  6857. {
  6858. if (formatInfo.mTotalSummaryLength + (int)displayString.length() > 255)
  6859. {
  6860. truncatedMemberList = true;
  6861. summaryDone = true;
  6862. bigRet += "...";
  6863. }
  6864. else
  6865. {
  6866. DwFormatInfo displayStrFormatInfo = formatInfo;
  6867. displayStrFormatInfo.mExpandItemDepth = 1;
  6868. displayStrFormatInfo.mTotalSummaryLength += (int)displayString.length();
  6869. displayStrFormatInfo.mHidePointers = false;
  6870. DbgType* primType = summaryType->mTypeParam;
  6871. String result;
  6872. if (primType->IsInteger())
  6873. formatInfo.mTypeKindFlags = (DbgTypeKindFlags)(formatInfo.mTypeKindFlags | DbgTypeKindFlag_Int);
  6874. if ((dataPtr != 0) && (dataPtr != -1))
  6875. {
  6876. String evalString = "(" + primType->ToString() + ")" + ptrDataStr;
  6877. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, origTypedValue, evalString, &displayStrFormatInfo);
  6878. if (evalResult)
  6879. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  6880. }
  6881. else
  6882. {
  6883. DbgTypedValue evalResult = origTypedValue;
  6884. evalResult.mType = primType;
  6885. String evalString = "(" + primType->ToString() + ")" + expr;
  6886. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  6887. }
  6888. if (formatInfo.mRawString)
  6889. return result;
  6890. int crPos = result.IndexOf('\n');
  6891. if (crPos != -1)
  6892. result.RemoveToEnd(crPos);
  6893. if (memberIdx == 0)
  6894. firstRet = result;
  6895. bigRet += result;
  6896. memberIdx++;
  6897. }
  6898. }
  6899. for (auto member : summaryType->mMemberList)
  6900. {
  6901. if (!member->mIsStatic)
  6902. {
  6903. if (formatInfo.mTotalSummaryLength + retVal.length() + bigRet.length() > 255)
  6904. {
  6905. truncatedMemberList = true;
  6906. summaryDone = true;
  6907. bigRet += "...";
  6908. break;
  6909. }
  6910. if (member->mName != NULL)
  6911. {
  6912. if (member->mName[0] == '$')
  6913. continue;
  6914. if (!isdigit(*member->mName))
  6915. {
  6916. if (memberIdx != 0)
  6917. bigRet += isTuple ? ", " : " ";
  6918. if ((!isTuple) || (member->mName[0] != '_'))
  6919. {
  6920. bigRet += String(member->mName);
  6921. bigRet += isTuple ? ":" : "=";
  6922. }
  6923. }
  6924. else
  6925. {
  6926. if (memberIdx != 0)
  6927. bigRet += ", ";
  6928. }
  6929. DwFormatInfo displayStrFormatInfo = formatInfo;
  6930. displayStrFormatInfo.mExpandItemDepth = 1;
  6931. displayStrFormatInfo.mHidePointers = false;
  6932. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + retVal.length() + bigRet.length();
  6933. String evalString;
  6934. if (dataPtr != -1)
  6935. {
  6936. if ((member->mName[0] >= '0') && (member->mName[0] <= '9'))
  6937. evalString += "this.";
  6938. evalString += String(member->mName); // +", this=" + summaryDataStr;
  6939. }
  6940. else
  6941. {
  6942. evalString = "(";
  6943. evalString += splatStr;
  6944. evalString += ").";
  6945. evalString += member->mName;
  6946. }
  6947. String referenceId;
  6948. String result;
  6949. if (!member->mType->IsValuelessType())
  6950. {
  6951. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, summaryTypedValue, evalString, &displayStrFormatInfo, &referenceId);
  6952. if (evalResult)
  6953. {
  6954. displayStrFormatInfo.mReferenceId = referenceId;
  6955. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  6956. int crPos = result.IndexOf('\n');
  6957. if (crPos != -1)
  6958. result.RemoveToEnd(crPos);
  6959. }
  6960. else
  6961. result = "???";
  6962. }
  6963. if (member->mType->IsInteger())
  6964. formatInfo.mTypeKindFlags = (DbgTypeKindFlags)(formatInfo.mTypeKindFlags | DbgTypeKindFlag_Int);
  6965. if (formatInfo.mRawString)
  6966. return result;
  6967. if (memberIdx == 0)
  6968. firstRet = result;
  6969. bigRet += result;
  6970. //formatInfo.mEmbeddedDisplayCount = displayStrFormatInfo.mEmbeddedDisplayCount;
  6971. memberIdx++;
  6972. }
  6973. else
  6974. {
  6975. //TODO: Handle C++ unions?
  6976. }
  6977. }
  6978. }
  6979. if (truncatedMemberList)
  6980. break;
  6981. // Find first base class with members
  6982. DbgType* nextSummaryType = NULL;
  6983. for (auto checkBase : summaryType->mBaseTypes)
  6984. {
  6985. auto checkBaseType = checkBase->mBaseType;
  6986. checkBaseType = checkBaseType->GetPrimaryType();
  6987. checkBaseType->PopulateType();
  6988. if ((checkBaseType->GetByteCount() > 0) || (checkBaseType->IsPrimitiveType()))
  6989. {
  6990. if (!splatStr.empty())
  6991. {
  6992. splatStr = "(" + checkBaseType->ToString() + ")" + splatStr;
  6993. }
  6994. else
  6995. {
  6996. summaryTypedValue.mType = checkBaseType;
  6997. }
  6998. nextSummaryType = checkBaseType;
  6999. break;
  7000. }
  7001. }
  7002. summaryType = nextSummaryType;
  7003. if (summaryType == NULL)
  7004. break;
  7005. // Don't add the Object members
  7006. if ((summaryType->GetBaseType() == NULL) && (summaryType->IsBfObject()))
  7007. break;
  7008. // If we don't have many members then find a base class with some members to show
  7009. if ((memberIdx != 0) && (displayString.length() >= 255))
  7010. {
  7011. truncatedMemberList = true;
  7012. bigRet += "...";
  7013. break;
  7014. }
  7015. }
  7016. bigRet += isTuple ? ")" : " }";
  7017. if (displayString.length() > 0)
  7018. displayString += " ";
  7019. if ((memberIdx == 1) && (!truncatedMemberList) && (firstRet.IndexOf('{') == -1) && (!isTuple))
  7020. displayString += "{ " + firstRet + " }";
  7021. else
  7022. displayString += bigRet;
  7023. }
  7024. DbgType* memberListType = actualType;
  7025. bool memberListForceCast = false;
  7026. if (actualType != NULL)
  7027. {
  7028. String valTypeName = displayType->ToString();
  7029. String actualTypeName = actualType->ToString(DbgLanguage_Unknown, true);
  7030. String actualUseTypeName = actualTypeName;
  7031. if ((int)actualTypeName.IndexOf('^') != -1)
  7032. useActualRawType = true;
  7033. if (useActualRawType)
  7034. actualUseTypeName = actualType->ToStringRaw();
  7035. if (displayString.empty())
  7036. {
  7037. // Nothing to display
  7038. }
  7039. else
  7040. {
  7041. if (!retVal.empty())
  7042. retVal += " ";
  7043. retVal += displayString;
  7044. }
  7045. retVal += "\n" + valTypeName;
  7046. if ((innerType->IsBaseBfObject()) || (innerType->IsInterface()))
  7047. {
  7048. if (actualType != innerType)
  7049. {
  7050. retVal += " {" + actualTypeName + "}";
  7051. memberListForceCast = true;
  7052. }
  7053. }
  7054. else
  7055. {
  7056. if (actualType != innerType)
  7057. {
  7058. retVal += " {" + actualTypeName + "}";
  7059. retVal += "\n";
  7060. if (!wantsCustomExpandedItems)
  7061. {
  7062. retVal += "[" + actualTypeName + "]\t((" + actualUseTypeName;
  7063. if (!actualType->IsBfObject())
  7064. retVal += "*";
  7065. retVal += ")this), nd, na, nv, this=" + ptrDataStr;
  7066. memberListType = innerType;
  7067. }
  7068. }
  7069. }
  7070. }
  7071. else
  7072. {
  7073. if ((formatInfo.mHidePointers) && (formatInfo.mIgnoreDerivedClassInfo))
  7074. {
  7075. displayType = innerType;
  7076. if (displayString.empty())
  7077. retVal += displayType->ToString(DbgLanguage_Unknown, true);
  7078. }
  7079. if (!displayString.empty())
  7080. {
  7081. if (!retVal.empty())
  7082. retVal += " ";
  7083. retVal += displayString;
  7084. }
  7085. else
  7086. {
  7087. if (formatInfo.mRawString)
  7088. return "";
  7089. }
  7090. retVal += "\n" + displayType->ToString(DbgLanguage_Unknown, true);
  7091. memberListType = innerType;
  7092. }
  7093. if ((isBfObject) && (mDebugTarget->mBfObjectHasFlags) && (!formatInfo.mNoVisualizers) && (!formatInfo.mRawString))
  7094. {
  7095. int stackTraceLen = 1;
  7096. addr_target stackTraceAddr = ptrVal + sizeof(addr_target);
  7097. if ((bfObjectFlags & BfObjectFlag_AllocInfo) != 0)
  7098. {
  7099. addr_target objectSize = ReadMemory<addr_target>(ptrVal + sizeof(addr_target));
  7100. addr_target largeAllocInfo = ReadMemory<addr_target>(ptrVal + objectSize);
  7101. stackTraceLen = largeAllocInfo & 0xFFFF;
  7102. stackTraceAddr = ptrVal + objectSize + sizeof(addr_target);
  7103. }
  7104. else if ((bfObjectFlags & BfObjectFlag_AllocInfo_Short) != 0)
  7105. {
  7106. addr_target dbgAllocInfo = ReadMemory<addr_target>(ptrVal + sizeof(addr_target));
  7107. stackTraceLen = dbgAllocInfo & 0xFF;
  7108. stackTraceAddr = ptrVal + (dbgAllocInfo >> 16);
  7109. }
  7110. if (stackTraceLen == 1)
  7111. {
  7112. retVal += StrFormat("\n[AllocStackTrace]\t*(System.CallStackAddr*)%s, nm", EncodeDataPtr(stackTraceAddr, true).c_str());
  7113. }
  7114. else if (stackTraceLen > 0)
  7115. {
  7116. retVal += StrFormat("\n[AllocStackTrace]\t(System.CallStackAddr*)%s, %d, na", EncodeDataPtr(stackTraceAddr, true).c_str(), stackTraceLen);
  7117. }
  7118. }
  7119. retVal += StrFormat("\n:language\t%d", language);
  7120. if (formatInfo.mNoMembers)
  7121. {
  7122. //
  7123. }
  7124. else if (wantsCustomExpandedItems)
  7125. {
  7126. HandleCustomExpandedItems(retVal, dbgCompileUnit, debugVis, dwUseType, dwValueType, ptrUseDataStr, ptrDataStr, useTypedValue, dbgVisWildcardCaptures, formatInfo);
  7127. }
  7128. else if ((!isNull) && (!isBadSrc))
  7129. {
  7130. if (dataPtr == -1)
  7131. {
  7132. //String splatName = ((origTypedValue.mSrcAddress == -1) && (origTypedValue.mVariable != NULL)) ? origTypedValue.mVariable->mName : expr;
  7133. String splatName = expr;
  7134. retVal += "\n" + GetMemberList(memberListType, splatName, wasPtr, false, false, true, origTypedValue.mIsReadOnly);
  7135. }
  7136. else
  7137. {
  7138. retVal += "\n" + GetMemberList(memberListType, ptrDataStr, wasPtr, false, memberListForceCast, isCompositeWithoutAddress, origTypedValue.mIsReadOnly);
  7139. }
  7140. }
  7141. if (formatInfo.mExpandItemDepth > 0)
  7142. return retVal;
  7143. if (isAppendBfObject)
  7144. retVal += "\n:appendAlloc";
  7145. if (isStackBfObject)
  7146. retVal += "\n:stack";
  7147. if (isDeletedBfObject)
  7148. retVal += "\n:deleted";
  7149. if ((debugVis != NULL) && (!debugVis->mAction.empty()))
  7150. {
  7151. String rawActionStr = mDebugManager->mDebugVisualizers->DoStringReplace(debugVis->mAction, dbgVisWildcardCaptures);
  7152. String actionStr;
  7153. ProcessEvalString(dbgCompileUnit, useTypedValue, rawActionStr, actionStr, formatInfo, debugVis, true);
  7154. retVal += "\n:action\t" + actionStr;
  7155. }
  7156. if ((!typedValue.mIsLiteral) && (dwValueType->IsPointer()))
  7157. {
  7158. retVal += "\n:editVal\t" + EncodeDataPtr(ptrVal, true);
  7159. }
  7160. return retVal;
  7161. }
  7162. return "Unknown Type\n" + origValueType->ToString();
  7163. }
  7164. void WinDebugger::HandleCustomExpandedItems(String& retVal, DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgType* dwUseType, DbgType* dwValueType, String& ptrUseDataStr, String& ptrDataStr, DbgTypedValue useTypedValue, Array<String>& dbgVisWildcardCaptures, DwFormatInfo& formatInfo)
  7165. {
  7166. auto debugVisualizers = mDebugManager->mDebugVisualizers;
  7167. auto dbgModule = dbgCompileUnit->mDbgModule;
  7168. if (formatInfo.mExpandItemDepth > 10) // Avoid crashing on circular ExpandItems
  7169. return;
  7170. auto language = formatInfo.mLanguage;
  7171. bool isReadOnly = false;
  7172. if (useTypedValue.mIsReadOnly)
  7173. isReadOnly = true;
  7174. for (auto entry : debugVis->mExpandItems)
  7175. {
  7176. if (!entry->mCondition.empty())
  7177. {
  7178. String error;
  7179. if (!EvalCondition(debugVis, dbgCompileUnit, useTypedValue, formatInfo, entry->mCondition, dbgVisWildcardCaptures, error))
  7180. {
  7181. if (!error.empty())
  7182. retVal += "\n" + entry->mName + "\t@!<DbgVis Failed>@!";
  7183. continue;
  7184. }
  7185. }
  7186. String replacedStr = debugVisualizers->DoStringReplace(entry->mValue, dbgVisWildcardCaptures);
  7187. retVal += "\n" + entry->mName + "\t" + replacedStr + ", this=(" + ptrUseDataStr + ")";
  7188. }
  7189. String referenceId = dwUseType->ToString();
  7190. if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_ExpandedItem)
  7191. {
  7192. DbgTypedValue itemValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7193. if (itemValue)
  7194. {
  7195. DwFormatInfo itemFormatInfo = formatInfo;
  7196. itemFormatInfo.mExpandItemDepth++;
  7197. String itemRetVal = DbgTypedValueToString(itemValue, "", itemFormatInfo, NULL);
  7198. int crIdx = (int)itemRetVal.IndexOf('\n');
  7199. if (crIdx != -1)
  7200. {
  7201. crIdx = (int)itemRetVal.IndexOf('\n', crIdx + 1);
  7202. if (crIdx != -1)
  7203. retVal += itemRetVal.Substring(crIdx);
  7204. }
  7205. }
  7206. }
  7207. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Array)
  7208. {
  7209. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7210. Array<int> lowerDimSizes;
  7211. for (auto lowerDim : debugVis->mLowerDimSizes)
  7212. {
  7213. DbgTypedValue lowerDimValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(lowerDim, dbgVisWildcardCaptures), &formatInfo);
  7214. int dimSize = 0;
  7215. if ((lowerDimValue) && (lowerDimValue.mType->IsInteger()))
  7216. dimSize = (int)lowerDimValue.GetInt64();
  7217. dimSize = BF_MAX(dimSize, 1);
  7218. lowerDimSizes.push_back(dimSize);
  7219. }
  7220. if ((sizeValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7221. {
  7222. if (!debugVis->mCondition.IsEmpty())
  7223. {
  7224. int size = (int)sizeValue.GetInt64();
  7225. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7226. DbgTypedValue curNode = headPointer;
  7227. Array<addr_target> parentList;
  7228. String continuationData;
  7229. int totalSize = 2;
  7230. auto valueType = headPointer.mType;
  7231. String addrs = GetArrayItems(dbgCompileUnit, debugVis, valueType, headPointer, totalSize, &continuationData);
  7232. String firstAddr;
  7233. String secondAddr;
  7234. bool hasSecondAddr = valueType == NULL;
  7235. if (addrs.length() > 0)
  7236. {
  7237. const char* addrsPtr = addrs.c_str();
  7238. firstAddr = addrs.Substring(0, sizeof(addr_target) * 2);
  7239. if (hasSecondAddr)
  7240. secondAddr = addrs.Substring(sizeof(addr_target) * 2, sizeof(addr_target) * 2);
  7241. }
  7242. String evalStr;
  7243. if (valueType != NULL)
  7244. {
  7245. evalStr = "(" + valueType->ToStringRaw();
  7246. if (!valueType->IsPointer())
  7247. evalStr += "*";
  7248. evalStr += ")0x{1}";
  7249. }
  7250. else
  7251. {
  7252. evalStr += "({1})0x{2}";
  7253. }
  7254. if (!debugVis->mShowElementAddrs)
  7255. evalStr.Insert(0, "*");
  7256. if (addrs.length() > 0)
  7257. {
  7258. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7259. if (isReadOnly)
  7260. evalStr += ", ne";
  7261. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, BF_MAX(size, 0), 10000) +
  7262. "\t[{0}]\t" + evalStr + "\t" + firstAddr;
  7263. if (hasSecondAddr)
  7264. retVal += "\t" + secondAddr;
  7265. if (size != 0)
  7266. {
  7267. retVal += "\n:addrs\t" + addrs;
  7268. if (valueType == NULL)
  7269. retVal += "\n:addrsEntrySize\t2";
  7270. if (continuationData.length() > 0)
  7271. retVal += "\n:continuation\t" + continuationData;
  7272. }
  7273. }
  7274. }
  7275. else if (lowerDimSizes.size() == 1)
  7276. {
  7277. int dimSize1 = lowerDimSizes[0];
  7278. String evalStr = "(" + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7279. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7280. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7281. if (isReadOnly)
  7282. evalStr += ", ne";
  7283. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64() / dimSize1, 50000) +
  7284. "\t[{0}]\t" + evalStr;
  7285. }
  7286. else if (lowerDimSizes.size() == 2)
  7287. {
  7288. int dimSize1 = lowerDimSizes[0];
  7289. int dimSize2 = lowerDimSizes[1];
  7290. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7291. if ((headPointer.mType != NULL) && (headPointer.mType->IsPointer()))
  7292. {
  7293. String evalStr = StrFormat("((%s[%d]*)", headPointer.mType->mTypeParam->ToStringRaw(language).c_str(), dimSize2) + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7294. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7295. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7296. if (isReadOnly)
  7297. evalStr += ", ne";
  7298. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64() / dimSize1 / dimSize2, 50000) +
  7299. "\t[{0}]\t" + evalStr;
  7300. }
  7301. }
  7302. else if (lowerDimSizes.size() == 3)
  7303. {
  7304. int dimSize1 = lowerDimSizes[0];
  7305. int dimSize2 = lowerDimSizes[1];
  7306. int dimSize3 = lowerDimSizes[2];
  7307. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7308. if ((headPointer.mType != NULL) && (headPointer.mType->IsPointer()))
  7309. {
  7310. String evalStr = StrFormat("((%s[%d][%d]*)", headPointer.mType->mTypeParam->ToStringRaw(language).c_str(), dimSize2, dimSize3) + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7311. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7312. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7313. if (isReadOnly)
  7314. evalStr += ", ne";
  7315. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64() / dimSize1 / dimSize2 / dimSize3, 50000) +
  7316. "\t[{0}]\t" + evalStr;
  7317. }
  7318. }
  7319. else
  7320. {
  7321. String evalStr = "*(" + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) + " + {0}), this=" + ptrUseDataStr;
  7322. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7323. if (isReadOnly)
  7324. evalStr += ", ne";
  7325. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64(), 50000) +
  7326. "\t[{0}]\t" + evalStr;
  7327. }
  7328. }
  7329. }
  7330. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_IndexItems)
  7331. {
  7332. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7333. if ((sizeValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7334. {
  7335. String evalStr = debugVis->mValuePointer + ", this=" + ptrUseDataStr;
  7336. evalStr.Replace("$i", "{0}");
  7337. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7338. if (isReadOnly)
  7339. evalStr += ", ne";
  7340. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64(), 50000) +
  7341. "\t[{0}]\t" + evalStr;
  7342. }
  7343. }
  7344. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_LinkedList)
  7345. {
  7346. DbgType* valueType = NULL;
  7347. if (!debugVis->mValueType.empty())
  7348. {
  7349. valueType = dbgModule->FindType(debugVisualizers->DoStringReplace(debugVis->mValueType, dbgVisWildcardCaptures), dwValueType);
  7350. if (valueType != NULL)
  7351. valueType = valueType->ResolveTypeDef();
  7352. }
  7353. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mHeadPointer, dbgVisWildcardCaptures), &formatInfo);
  7354. if (headPointer)
  7355. {
  7356. DbgTypedValue endPointer;
  7357. if (!debugVis->mEndPointer.empty())
  7358. endPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mEndPointer, dbgVisWildcardCaptures), &formatInfo);
  7359. DbgTypedValue nextPointer = EvaluateInContext(dbgCompileUnit, headPointer, debugVisualizers->DoStringReplace(debugVis->mNextPointer, dbgVisWildcardCaptures), &formatInfo);
  7360. int size = -1;
  7361. if (!debugVis->mSize.empty())
  7362. {
  7363. auto sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7364. if (sizeValue)
  7365. size = (int)sizeValue.GetInt64();
  7366. }
  7367. DbgTypedValue curNode = headPointer;
  7368. Array<addr_target> parentList;
  7369. String continuationData;
  7370. int totalSize = 2;
  7371. String addrs = GetLinkedListItems(dbgCompileUnit, debugVis, endPointer.mPtr, valueType, curNode, totalSize, &continuationData);
  7372. String firstAddr;
  7373. String secondAddr;
  7374. bool hasSecondAddr = valueType == NULL;
  7375. if (addrs.length() > 0)
  7376. {
  7377. const char* addrsPtr = addrs.c_str();
  7378. firstAddr = addrs.Substring(0, sizeof(addr_target)*2);
  7379. if (hasSecondAddr)
  7380. secondAddr = addrs.Substring(sizeof(addr_target)*2, sizeof(addr_target)*2);
  7381. }
  7382. String evalStr;
  7383. if (valueType != NULL)
  7384. {
  7385. evalStr = "(" + valueType->ToStringRaw();
  7386. if (!valueType->IsPointer())
  7387. evalStr += "*";
  7388. evalStr += ")0x{1}";
  7389. }
  7390. else
  7391. {
  7392. evalStr += "({1})0x{2}";
  7393. }
  7394. if (!debugVis->mShowElementAddrs)
  7395. evalStr.Insert(0, "*");
  7396. if (addrs.length() > 0)
  7397. {
  7398. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7399. if (isReadOnly)
  7400. evalStr += ", ne";
  7401. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, size, 10000) +
  7402. "\t[{0}]\t" + evalStr + "\t" + firstAddr;
  7403. if (hasSecondAddr)
  7404. retVal += "\t" + secondAddr;
  7405. if (size != 0)
  7406. {
  7407. retVal += "\n:addrs\t" + addrs;
  7408. if (valueType == NULL)
  7409. retVal += "\n:addrsEntrySize\t2";
  7410. if (continuationData.length() > 0)
  7411. retVal += "\n:continuation\t" + continuationData;
  7412. }
  7413. }
  7414. }
  7415. }
  7416. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_TreeItems)
  7417. {
  7418. DbgType* valueType = NULL;
  7419. if (!debugVis->mValueType.empty())
  7420. {
  7421. valueType = dbgModule->FindType(debugVisualizers->DoStringReplace(debugVis->mValueType, dbgVisWildcardCaptures), dwValueType);
  7422. if (valueType != NULL)
  7423. valueType = valueType->ResolveTypeDef();
  7424. }
  7425. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7426. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mHeadPointer, dbgVisWildcardCaptures), &formatInfo);
  7427. if (sizeValue)
  7428. sizeValue.mType = sizeValue.mType->RemoveModifiers();
  7429. if ((sizeValue) && (headPointer) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7430. {
  7431. DbgTypedValue curNode = headPointer;
  7432. Array<addr_target> parentList;
  7433. String continuationData;
  7434. int getItemCount = (int)BF_MIN(sizeValue.GetInt64(), 32LL);
  7435. String addrs = GetTreeItems(dbgCompileUnit, debugVis, parentList, valueType, curNode, getItemCount, &continuationData);
  7436. addr_target firstAddr = 0;
  7437. addr_target secondAddr = 0;
  7438. bool hasSecondAddr = valueType == NULL;
  7439. if (addrs.length() > 0)
  7440. {
  7441. const char* addrsPtr = addrs.c_str();
  7442. firstAddr = DecodeTargetDataPtr(addrsPtr);
  7443. if (hasSecondAddr)
  7444. secondAddr = DecodeTargetDataPtr(addrsPtr);
  7445. }
  7446. String evalStr;
  7447. if (valueType != NULL)
  7448. {
  7449. evalStr = "*(" + valueType->ToStringRaw();
  7450. if (!valueType->IsPointer())
  7451. evalStr += "*";
  7452. evalStr += ")0x{1}";
  7453. }
  7454. else
  7455. {
  7456. evalStr += "*(_T_{1}*)0x{2}";
  7457. }
  7458. int size = (int)sizeValue.GetInt64();
  7459. if (addrs.length() == 0)
  7460. {
  7461. evalStr = ""; // Failed
  7462. }
  7463. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7464. if (isReadOnly)
  7465. evalStr += ", ne";
  7466. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, size, 10000) +
  7467. "\t[{0}]\t" + evalStr + "\t" + EncodeDataPtr(firstAddr, false);
  7468. if (hasSecondAddr)
  7469. retVal += "\t" + EncodeDataPtr(secondAddr, false);
  7470. if (addrs.length() > 0)
  7471. {
  7472. retVal += "\n:addrs\t" + addrs;
  7473. if (continuationData.length() > 0)
  7474. retVal += "\n:continuation\t" + continuationData;
  7475. }
  7476. }
  7477. }
  7478. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Dictionary)
  7479. {
  7480. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7481. DbgTypedValue entriesPtrValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mEntries, dbgVisWildcardCaptures), &formatInfo);
  7482. if (sizeValue)
  7483. sizeValue.mType = sizeValue.mType->RemoveModifiers();
  7484. if ((sizeValue) && (entriesPtrValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7485. {
  7486. String continuationData;
  7487. DbgType* valueType = entriesPtrValue.mType;
  7488. int getItemCount = (int)std::min(sizeValue.GetInt64(), 2LL);
  7489. DbgType* useTypedValType = useTypedValue.mType;
  7490. addr_target useTypedValPtr = useTypedValue.mPtr;
  7491. addr_target useTypedValAddr = useTypedValue.mSrcAddress;
  7492. String addrs = GetDictionaryItems(dbgCompileUnit, debugVis, useTypedValue, 0, -1, getItemCount, &continuationData);
  7493. addr_target firstAddr = 0;
  7494. if (addrs.length() > 0)
  7495. {
  7496. const char* addrsPtr = addrs.c_str();
  7497. firstAddr = DecodeTargetDataPtr(addrsPtr);
  7498. }
  7499. String evalStr = "((" + valueType->ToStringRaw() + ")0x{1}), na";
  7500. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7501. if (isReadOnly)
  7502. evalStr += ", ne";
  7503. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64(), 10000) +
  7504. "\t[{0}]\t" + evalStr + "\t" + EncodeDataPtr(firstAddr, false);
  7505. if (addrs.length() > 0)
  7506. {
  7507. retVal += "\n:addrs\t" + addrs;
  7508. if (continuationData.length() > 0)
  7509. retVal += "\n:continuation\t" + continuationData;
  7510. }
  7511. }
  7512. }
  7513. if (formatInfo.mExpandItemDepth == 0)
  7514. {
  7515. //retVal += "\n[Raw View]\tthis, this=" + ptrDataStr + ", nv";
  7516. retVal += "\n[Raw View]\t" + ptrDataStr + ", nv";
  7517. }
  7518. }
  7519. bool WinDebugger::IsPaused()
  7520. {
  7521. return (mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint) || (mRunState == RunState_Exception) || (mRunState == RunState_DebugEval_Done);
  7522. }
  7523. DbgTypedValue WinDebugger::GetRegister(const StringImpl& regName, DbgLanguage language, CPURegisters* registers, Array<RegForm>* regForms)
  7524. {
  7525. int regNum = -1;
  7526. String lwrRegName(regName);
  7527. _strlwr((char*)lwrRegName.c_str());
  7528. // int regs
  7529. #ifdef BF_DBG_32
  7530. DbgTypeCode regType = DbgType_i32;
  7531. if (lwrRegName == "eax")
  7532. regNum = X86Reg_EAX;
  7533. else if (lwrRegName == "ecx")
  7534. regNum = X86Reg_ECX;
  7535. else if (lwrRegName == "edx")
  7536. regNum = X86Reg_EDX;
  7537. else if (lwrRegName == "ebx")
  7538. regNum = X86Reg_EBX;
  7539. else if (lwrRegName == "esp")
  7540. regNum = X86Reg_ESP;
  7541. else if (lwrRegName == "ebp")
  7542. regNum = X86Reg_EBP;
  7543. else if (lwrRegName == "esi")
  7544. regNum = X86Reg_ESI;
  7545. else if (lwrRegName == "edi")
  7546. regNum = X86Reg_EDI;
  7547. else if (lwrRegName == "eip")
  7548. regNum = X86Reg_EIP;
  7549. else if (lwrRegName == "efl")
  7550. regNum = X86Reg_EFL;
  7551. #else
  7552. DbgTypeCode regType = DbgType_i64;
  7553. if (lwrRegName == "rax")
  7554. regNum = X64Reg_RAX;
  7555. else if (lwrRegName == "rcx")
  7556. regNum = X64Reg_RCX;
  7557. else if (lwrRegName == "rdx")
  7558. regNum = X64Reg_RDX;
  7559. else if (lwrRegName == "rbx")
  7560. regNum = X64Reg_RBX;
  7561. else if (lwrRegName == "rsp")
  7562. regNum = X64Reg_RSP;
  7563. else if (lwrRegName == "rbp")
  7564. regNum = X64Reg_RBP;
  7565. else if (lwrRegName == "rsi")
  7566. regNum = X64Reg_RSI;
  7567. else if (lwrRegName == "rdi")
  7568. regNum = X64Reg_RDI;
  7569. else if (lwrRegName == "rip")
  7570. regNum = X64Reg_RIP;
  7571. else if (lwrRegName == "r8")
  7572. regNum = X64Reg_R8;
  7573. else if (lwrRegName == "r9")
  7574. regNum = X64Reg_R9;
  7575. else if (lwrRegName == "r10")
  7576. regNum = X64Reg_R10;
  7577. else if (lwrRegName == "r11")
  7578. regNum = X64Reg_R11;
  7579. else if (lwrRegName == "r12")
  7580. regNum = X64Reg_R12;
  7581. else if (lwrRegName == "r13")
  7582. regNum = X64Reg_R13;
  7583. else if (lwrRegName == "r14")
  7584. regNum = X64Reg_R14;
  7585. else if (lwrRegName == "r15")
  7586. regNum = X64Reg_R15;
  7587. else
  7588. {
  7589. regType = DbgType_i32;
  7590. if (lwrRegName == "eax")
  7591. regNum = X64Reg_RAX;
  7592. else if (lwrRegName == "ecx")
  7593. regNum = X64Reg_RCX;
  7594. else if (lwrRegName == "edx")
  7595. regNum = X64Reg_RDX;
  7596. else if (lwrRegName == "ebx")
  7597. regNum = X64Reg_RBX;
  7598. else if (lwrRegName == "efl")
  7599. regNum = X64Reg_EFL;
  7600. else if (lwrRegName == "esi")
  7601. regNum = X64Reg_RSI;
  7602. else if (lwrRegName == "edi")
  7603. regNum = X64Reg_RDI;
  7604. else if (lwrRegName == "r8d")
  7605. regNum = X64Reg_R8;
  7606. else if (lwrRegName == "r9d")
  7607. regNum = X64Reg_R9;
  7608. else if (lwrRegName == "r10d")
  7609. regNum = X64Reg_R10;
  7610. else if (lwrRegName == "r11d")
  7611. regNum = X64Reg_R11;
  7612. else if (lwrRegName == "r12d")
  7613. regNum = X64Reg_R12;
  7614. else if (lwrRegName == "r13d")
  7615. regNum = X64Reg_R13;
  7616. else if (lwrRegName == "r14d")
  7617. regNum = X64Reg_R14;
  7618. else if (lwrRegName == "r15d")
  7619. regNum = X64Reg_R15;
  7620. else
  7621. {
  7622. regType = DbgType_i16;
  7623. if (lwrRegName == "ax")
  7624. regNum = X64Reg_RAX;
  7625. else if (lwrRegName == "cx")
  7626. regNum = X64Reg_RCX;
  7627. else if (lwrRegName == "dx")
  7628. regNum = X64Reg_RDX;
  7629. else if (lwrRegName == "bx")
  7630. regNum = X64Reg_RBX;
  7631. else if (lwrRegName == "si")
  7632. regNum = X64Reg_RSI;
  7633. else if (lwrRegName == "di")
  7634. regNum = X64Reg_RDI;
  7635. else if (lwrRegName == "r8w")
  7636. regNum = X64Reg_R8;
  7637. else if (lwrRegName == "r9w")
  7638. regNum = X64Reg_R9;
  7639. else if (lwrRegName == "r10w")
  7640. regNum = X64Reg_R10;
  7641. else if (lwrRegName == "r11w")
  7642. regNum = X64Reg_R11;
  7643. else if (lwrRegName == "r12w")
  7644. regNum = X64Reg_R12;
  7645. else if (lwrRegName == "r13w")
  7646. regNum = X64Reg_R13;
  7647. else if (lwrRegName == "r14w")
  7648. regNum = X64Reg_R14;
  7649. else if (lwrRegName == "r15w")
  7650. regNum = X64Reg_R15;
  7651. else
  7652. {
  7653. regType = DbgType_i8;
  7654. if (lwrRegName == "al")
  7655. regNum = X64Reg_RAX;
  7656. else if (lwrRegName == "cl")
  7657. regNum = X64Reg_RCX;
  7658. else if (lwrRegName == "dl")
  7659. regNum = X64Reg_RDX;
  7660. else if (lwrRegName == "bl")
  7661. regNum = X64Reg_RBX;
  7662. else if (lwrRegName == "sil")
  7663. regNum = X64Reg_RSI;
  7664. else if (lwrRegName == "dil")
  7665. regNum = X64Reg_RDI;
  7666. else if (lwrRegName == "r8b")
  7667. regNum = X64Reg_R8;
  7668. else if (lwrRegName == "r9b")
  7669. regNum = X64Reg_R9;
  7670. else if (lwrRegName == "r10b")
  7671. regNum = X64Reg_R10;
  7672. else if (lwrRegName == "r11b")
  7673. regNum = X64Reg_R11;
  7674. else if (lwrRegName == "r12b")
  7675. regNum = X64Reg_R12;
  7676. else if (lwrRegName == "r13b")
  7677. regNum = X64Reg_R13;
  7678. else if (lwrRegName == "r14b")
  7679. regNum = X64Reg_R14;
  7680. else if (lwrRegName == "r15b")
  7681. regNum = X64Reg_R15;
  7682. }
  7683. }
  7684. }
  7685. #endif
  7686. auto dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  7687. if (regNum != -1)
  7688. {
  7689. DbgTypedValue typedVal;
  7690. typedVal.mType = dbgModule->GetPrimitiveType(regType, language);
  7691. typedVal.mInt64 = registers->mIntRegsArray[regNum];
  7692. typedVal.mRegNum = regNum;
  7693. return typedVal;
  7694. }
  7695. // st regs
  7696. if ((lwrRegName.length() == 3) && (lwrRegName[0] == 's') && (lwrRegName[1] == 't') && (lwrRegName[2] >= '0') && (lwrRegName[2] <= '7'))
  7697. {
  7698. regNum = CPUReg_FPSTREG_FIRST + (lwrRegName[2] - '0');
  7699. }
  7700. if (regNum != -1)
  7701. {
  7702. DbgTypedValue typedVal;
  7703. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Double, language);
  7704. typedVal.mDouble = ConvertFloat80ToDouble(registers->mFpMmRegsArray[regNum - CPUReg_FPSTREG_FIRST].fp.fp80);
  7705. typedVal.mRegNum = regNum;
  7706. return typedVal;
  7707. }
  7708. // mm regs
  7709. if ((lwrRegName.length() == 3) && (lwrRegName[0] == 'm') && (lwrRegName[1] == 'm') && (lwrRegName[2] >= '0') && (lwrRegName[2] <= '7'))
  7710. {
  7711. regNum = CPUReg_MMREG_FIRST + (lwrRegName[2] - '0');
  7712. }
  7713. if (regNum != -1)
  7714. {
  7715. DbgTypedValue typedVal;
  7716. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_i64, language);
  7717. typedVal.mInt64 = registers->mFpMmRegsArray[regNum - CPUReg_MMREG_FIRST].mm;
  7718. typedVal.mRegNum = regNum;
  7719. return typedVal;
  7720. }
  7721. // xmm regs
  7722. #ifdef BF_DBG_32
  7723. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '7') &&
  7724. (lwrRegName[4] == '_') && (lwrRegName[5] >= '0') && (lwrRegName[5] <= '3'))
  7725. {
  7726. regNum = CPUReg_XMMREG_FIRST + ((lwrRegName[3] - '0') * 4) + (lwrRegName[5] - '0');
  7727. }
  7728. #else
  7729. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '9') &&
  7730. (lwrRegName[4] == '_') && (lwrRegName[5] >= '0') && (lwrRegName[5] <= '3'))
  7731. {
  7732. regNum = CPUReg_XMMREG_FIRST + ((lwrRegName[3] - '0') * 4) + (lwrRegName[5] - '0');
  7733. }
  7734. if ((lwrRegName.length() == 7) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] == '1') && (lwrRegName[4] >= '0') && (lwrRegName[4] <= '9') &&
  7735. (lwrRegName[5] == '_') && (lwrRegName[6] >= '0') && (lwrRegName[6] <= '3'))
  7736. {
  7737. regNum = CPUReg_XMMREG_FIRST + ((10 + (lwrRegName[4] - '0')) * 4) + (lwrRegName[6] - '0');
  7738. }
  7739. #endif
  7740. if (regNum != -1)
  7741. {
  7742. int xmmMajor = (regNum - CPUReg_XMMREG_FIRST) >> 2;
  7743. int xmmMinor = (regNum - CPUReg_XMMREG_FIRST) & 3;
  7744. DwMmDisplayType mmDisplayType = GetDisplayInfo(StrFormat("$XMM%d", xmmMajor))->mMmDisplayType;
  7745. RegForm regForm = RegForm_Unknown;
  7746. if (regForms != NULL)
  7747. {
  7748. int regFormIdx = CPUReg_M128_XMMREG_FIRST + xmmMajor;
  7749. if (regFormIdx < (int)regForms->size())
  7750. regForm = (*regForms)[regFormIdx];
  7751. }
  7752. if (mmDisplayType == DwMmDisplayType_Default)
  7753. {
  7754. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2))
  7755. mmDisplayType = DwMmDisplayType_Double;
  7756. else if (regForm == RegForm_Int4)
  7757. mmDisplayType = DwMmDisplayType_Int;
  7758. }
  7759. //TODO: Add int types
  7760. if (mmDisplayType == DwMmDisplayType_Double)
  7761. {
  7762. DbgTypedValue typedVal;
  7763. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Double, language);
  7764. typedVal.mDouble = registers->mXmmDRegsArray[xmmMajor].d[xmmMinor];
  7765. typedVal.mRegNum = regNum;
  7766. return typedVal;
  7767. }
  7768. if ((mmDisplayType == DwMmDisplayType_Byte) || (mmDisplayType == DwMmDisplayType_Short) || (mmDisplayType == DwMmDisplayType_Int))
  7769. {
  7770. DbgTypedValue typedVal;
  7771. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_i32, language);
  7772. typedVal.mInt32 = registers->mXmmIRegsARray[xmmMajor].i[xmmMinor];
  7773. typedVal.mRegNum = regNum;
  7774. return typedVal;
  7775. }
  7776. DbgTypedValue typedVal;
  7777. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Single, language);
  7778. typedVal.mSingle = registers->mXmmRegsArray[xmmMajor].f[xmmMinor];
  7779. typedVal.mRegNum = regNum;
  7780. return typedVal;
  7781. }
  7782. #ifdef BF_DBG_32
  7783. if ((lwrRegName.length() == 4) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '7'))
  7784. {
  7785. regNum = CPUReg_M128_XMMREG_FIRST + (lwrRegName[3] - '0');
  7786. }
  7787. #else
  7788. if ((lwrRegName.length() == 4) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '9'))
  7789. {
  7790. regNum = CPUReg_M128_XMMREG_FIRST + (lwrRegName[3] - '0');
  7791. }
  7792. if ((lwrRegName.length() == 5) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] == '1') && (lwrRegName[4] >= '0') && (lwrRegName[4] <= '5'))
  7793. {
  7794. regNum = CPUReg_M128_XMMREG_FIRST + 10 + (lwrRegName[4] - '0');
  7795. }
  7796. #endif
  7797. if (regNum != -1)
  7798. {
  7799. DbgTypedValue typedVal;
  7800. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_RegGroup, language);
  7801. 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)
  7802. typedVal.mRegNum = regNum;
  7803. return typedVal;
  7804. }
  7805. // flags
  7806. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'f') && (lwrRegName[1] == 'l') && (lwrRegName[2] == 'a') && (lwrRegName[3] == 'g') && (lwrRegName[5] == 'f'))
  7807. {
  7808. switch(lwrRegName[4])
  7809. {
  7810. case 'c': regNum = CPUReg_FLAG_CF_CARRY; break;
  7811. case 'p': regNum = CPUReg_FLAG_PF_PARITY; break;
  7812. case 'a': regNum = CPUReg_FLAG_AF_ADJUST; break;
  7813. case 'z': regNum = CPUReg_FLAG_ZF_ZERO; break;
  7814. case 's': regNum = CPUReg_FLAG_SF_SIGN; break;
  7815. case 'i': regNum = CPUReg_FLAG_IF_INTERRUPT; break;
  7816. case 'd': regNum = CPUReg_FLAG_DF_DIRECTION; break;
  7817. case 'o': regNum = CPUReg_FLAG_OF_OVERFLOW; break;
  7818. default: break;
  7819. }
  7820. }
  7821. if (regNum != -1)
  7822. {
  7823. int flagBit = CPURegisters::GetFlagBitForRegister(regNum);
  7824. BF_ASSERT(flagBit >= 0);
  7825. DbgTypedValue typedVal;
  7826. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Bool, language);
  7827. typedVal.mBool = (registers->mIntRegs.efl & ((uint64)1 << flagBit)) != 0;
  7828. typedVal.mRegNum = regNum;
  7829. return typedVal;
  7830. }
  7831. // categories
  7832. if (lwrRegName == "allregs")
  7833. regNum = CPUReg_CAT_ALLREGS;
  7834. else if (lwrRegName == "iregs")
  7835. regNum = CPUReg_CAT_IREGS;
  7836. else if (lwrRegName == "fpregs")
  7837. regNum = CPUReg_CAT_FPREGS;
  7838. else if (lwrRegName == "mmregs")
  7839. regNum = CPUReg_CAT_MMREGS;
  7840. else if (lwrRegName == "xmmregs")
  7841. regNum = CPUReg_CAT_XMMREGS;
  7842. else if (lwrRegName == "flags")
  7843. regNum = CPUReg_CAT_FLAGS;
  7844. if (regNum != -1)
  7845. {
  7846. DbgTypedValue typedVal;
  7847. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_RegGroup, language);
  7848. 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)
  7849. typedVal.mRegNum = regNum;
  7850. return typedVal;
  7851. }
  7852. return DbgTypedValue();
  7853. }
  7854. DbgModule* WinDebugger::GetCallStackDbgModule(int callStackIdx)
  7855. {
  7856. if ((mRunState == RunState_NotStarted) || (!IsPaused()))
  7857. return mEmptyDebugTarget->GetMainDbgModule();
  7858. if (callStackIdx == -1)
  7859. return mDebugTarget->GetMainDbgModule();
  7860. FixCallStackIdx(callStackIdx);
  7861. if (callStackIdx >= mCallStack.size())
  7862. return mDebugTarget->GetMainDbgModule();
  7863. UpdateCallStackMethod(callStackIdx);
  7864. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  7865. if (subProgram != NULL)
  7866. return subProgram->mCompileUnit->mDbgModule;
  7867. auto dbgModule = mDebugTarget->FindDbgModuleForAddress(mCallStack[callStackIdx]->mRegisters.GetPC());
  7868. if (dbgModule != NULL)
  7869. return dbgModule;
  7870. return mDebugTarget->GetMainDbgModule();
  7871. }
  7872. DbgSubprogram* WinDebugger::GetCallStackSubprogram(int callStackIdx)
  7873. {
  7874. if ((IsInRunState()) || (mRunState == RunState_NotStarted) || (callStackIdx == -1))
  7875. return NULL;
  7876. if (callStackIdx >= (int)mCallStack.size())
  7877. UpdateCallStack();
  7878. if (mCallStack.IsEmpty())
  7879. return NULL;
  7880. if (callStackIdx >= (int)mCallStack.size())
  7881. callStackIdx = 0;
  7882. UpdateCallStackMethod(callStackIdx);
  7883. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  7884. return subProgram;
  7885. }
  7886. DbgCompileUnit* WinDebugger::GetCallStackCompileUnit(int callStackIdx)
  7887. {
  7888. if ((IsInRunState()) || (mRunState == RunState_NotStarted) || (callStackIdx == -1))
  7889. return NULL;
  7890. if (callStackIdx >= (int)mCallStack.size())
  7891. UpdateCallStack();
  7892. if (mCallStack.IsEmpty())
  7893. return NULL;
  7894. if (callStackIdx >= (int)mCallStack.size())
  7895. callStackIdx = 0;
  7896. UpdateCallStackMethod(callStackIdx);
  7897. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  7898. if (subProgram == NULL)
  7899. return NULL;
  7900. return subProgram->mCompileUnit;
  7901. }
  7902. String WinDebugger::EvaluateContinue(DbgPendingExpr* pendingExpr, BfPassInstance& bfPassInstance)
  7903. {
  7904. DbgModule* dbgModule = NULL;
  7905. DbgCompileUnit* dbgCompileUnit = NULL;
  7906. if (pendingExpr->mThreadId == -1)
  7907. {
  7908. if ((pendingExpr->mFormatInfo.mLanguage == DbgLanguage_Beef) && (mDebugTarget != NULL) && (mDebugTarget->mTargetBinary != NULL))
  7909. dbgModule = mDebugTarget->mTargetBinary;
  7910. else
  7911. dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  7912. }
  7913. else
  7914. {
  7915. dbgModule = GetCallStackDbgModule(pendingExpr->mCallStackIdx);
  7916. if ((dbgModule != NULL) &&(!dbgModule->mDebugTarget->mIsEmpty))
  7917. dbgCompileUnit = GetCallStackCompileUnit(pendingExpr->mCallStackIdx);
  7918. }
  7919. if (dbgModule == NULL)
  7920. dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  7921. if (!pendingExpr->mException.empty())
  7922. {
  7923. RestoreAllRegisters();
  7924. return "!" + pendingExpr->mException;
  7925. }
  7926. DwAutoComplete autoComplete;
  7927. if (bfPassInstance.HasFailed())
  7928. {
  7929. // Don't allow pending calls if we've already failed in the calling Evaluate()
  7930. pendingExpr->mExpressionFlags = (DwEvalExpressionFlags)(pendingExpr->mExpressionFlags & ~DwEvalExpressionFlag_AllowCalls);
  7931. }
  7932. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, pendingExpr->mCallStackIdx, pendingExpr->mCursorPos);
  7933. dbgExprEvaluator.mLanguage = pendingExpr->mFormatInfo.mLanguage;
  7934. dbgExprEvaluator.mReferenceId = &pendingExpr->mReferenceId;
  7935. dbgExprEvaluator.mExpressionFlags = pendingExpr->mExpressionFlags;
  7936. dbgExprEvaluator.mExplicitThis = pendingExpr->mFormatInfo.mExplicitThis;
  7937. dbgExprEvaluator.mSubjectExpr = pendingExpr->mFormatInfo.mSubjectExpr;
  7938. dbgExprEvaluator.mNamespaceSearchStr = pendingExpr->mFormatInfo.mNamespaceSearch;
  7939. dbgExprEvaluator.mExpectingTypeName = pendingExpr->mFormatInfo.mExpectedType;
  7940. dbgExprEvaluator.mCallResults = &pendingExpr->mCallResults;
  7941. if ((pendingExpr->mExpressionFlags & DwEvalExpressionFlag_ValidateOnly) != 0)
  7942. {
  7943. dbgExprEvaluator.mValidateOnly = true;
  7944. }
  7945. if (pendingExpr->mCursorPos != -1)
  7946. {
  7947. dbgExprEvaluator.mAutoComplete = &autoComplete;
  7948. }
  7949. dbgExprEvaluator.mDbgCompileUnit = dbgCompileUnit;
  7950. DbgTypedValue exprResult;
  7951. if (pendingExpr->mExplitType != NULL)
  7952. {
  7953. exprResult.mHasNoValue = true;
  7954. exprResult.mType = pendingExpr->mExplitType;
  7955. }
  7956. else if (pendingExpr->mExprNode != NULL)
  7957. {
  7958. exprResult = dbgExprEvaluator.Resolve(pendingExpr->mExprNode);
  7959. }
  7960. if (dbgExprEvaluator.mCreatedPendingCall)
  7961. {
  7962. BF_ASSERT(mRunState == RunState_DebugEval);
  7963. //ContinueDebugEvent();
  7964. return "!pending";
  7965. }
  7966. if (dbgExprEvaluator.mCountResultOverride != -1)
  7967. pendingExpr->mFormatInfo.mOverrideCount = dbgExprEvaluator.mCountResultOverride;
  7968. String val;
  7969. if (bfPassInstance.HasFailed())
  7970. {
  7971. BfLogDbgExpr("Evaluate Failed: %s\n", bfPassInstance.mErrors[0]->mError.c_str());
  7972. val = StrFormat("!%d\t%d\t%s", bfPassInstance.mErrors[0]->GetSrcStart(), bfPassInstance.mErrors[0]->GetSrcLength(), bfPassInstance.mErrors[0]->mError.c_str());
  7973. }
  7974. else if (dbgExprEvaluator.mBlockedSideEffects)
  7975. {
  7976. BfLogDbgExpr("Evaluate blocked side effects\n");
  7977. val = "!sideeffects";
  7978. }
  7979. else if (!exprResult)
  7980. {
  7981. if (exprResult.mType != NULL)
  7982. {
  7983. BfLogDbgExpr("Evaluate success\n");
  7984. String typeName = exprResult.mType->ToString();
  7985. DbgType* rawType = exprResult.mType;
  7986. if (rawType->IsBfObjectPtr())
  7987. rawType = rawType->mTypeParam;
  7988. String typeNameRaw = rawType->ToStringRaw();
  7989. val = typeName + "\n" + typeName;
  7990. val += "\n" + GetMemberList(exprResult.mType, typeNameRaw, false, true, false, false, exprResult.mIsReadOnly);
  7991. if (exprResult.mType->mTypeCode == DbgType_Namespace)
  7992. {
  7993. val += "\n:type\tnamespace";
  7994. }
  7995. else
  7996. {
  7997. auto type = exprResult.mType;
  7998. if (type->IsPointer())
  7999. type = type->mTypeParam;
  8000. if (type->IsBfObject())
  8001. val += "\n:type\tclass";
  8002. else
  8003. val += "\n:type\tvaluetype";
  8004. }
  8005. if (!pendingExpr->mReferenceId.empty())
  8006. val += "\n:referenceId\t" + pendingExpr->mReferenceId;
  8007. }
  8008. else
  8009. val = "!";
  8010. }
  8011. else if ((pendingExpr->mExpressionFlags & (DwEvalExpressionFlag_MemoryAddress)) != 0)
  8012. {
  8013. DbgType* resultType = exprResult.mType->RemoveModifiers();
  8014. if ((resultType->IsInteger()) || (resultType->IsPointerOrRef()))
  8015. {
  8016. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", 0);
  8017. }
  8018. else
  8019. {
  8020. if (exprResult.mSrcAddress != 0)
  8021. val = StrFormat("!Type '%s' is invalid. A pointer or address value is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  8022. else
  8023. val = StrFormat("!Type '%s' is invalid. A pointer or address value is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  8024. }
  8025. }
  8026. else if ((pendingExpr->mExpressionFlags & (DwEvalExpressionFlag_MemoryWatch)) != 0)
  8027. {
  8028. DbgType* resultType = exprResult.mType->RemoveModifiers();
  8029. bool isMemoryWatch = (pendingExpr->mExpressionFlags & DwEvalExpressionFlag_MemoryWatch) != 0;
  8030. if (!resultType->IsPointerOrRef())
  8031. {
  8032. if (exprResult.mSrcAddress != 0)
  8033. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  8034. else
  8035. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  8036. }
  8037. else
  8038. {
  8039. auto innerType = resultType->mTypeParam;
  8040. int byteCount = innerType->GetByteCount();
  8041. if (pendingExpr->mFormatInfo.mArrayLength != -1)
  8042. byteCount *= pendingExpr->mFormatInfo.mArrayLength;
  8043. if (byteCount == 0)
  8044. {
  8045. 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());
  8046. }
  8047. #ifdef BF_DBG_32
  8048. else if ((isMemoryWatch) && (!IsMemoryBreakpointSizeValid(exprResult.mPtr, byteCount)))
  8049. {
  8050. if (innerType->mSize > 16)
  8051. 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);
  8052. else if (!IsMemoryBreakpointSizeValid(0, byteCount))
  8053. 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);
  8054. else
  8055. 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);
  8056. }
  8057. #else
  8058. else if ((isMemoryWatch) && (!IsMemoryBreakpointSizeValid(exprResult.mPtr, byteCount)))
  8059. {
  8060. if (innerType->mSize > 32)
  8061. 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);
  8062. else if (!IsMemoryBreakpointSizeValid(0, byteCount))
  8063. 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);
  8064. else
  8065. 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);
  8066. }
  8067. #endif
  8068. else
  8069. {
  8070. auto language = dbgExprEvaluator.GetLanguage();
  8071. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", byteCount) + "\n" + StrFormat("%d\t", language) + innerType->ToStringRaw(language);
  8072. }
  8073. }
  8074. }
  8075. else
  8076. {
  8077. if (pendingExpr->mFormatInfo.mNoEdit)
  8078. exprResult.mIsReadOnly = true;
  8079. if (!pendingExpr->mReferenceId.empty())
  8080. pendingExpr->mFormatInfo.mReferenceId = pendingExpr->mReferenceId;
  8081. val = DbgTypedValueToString(exprResult, pendingExpr->mExprNode->ToString(), pendingExpr->mFormatInfo, &dbgExprEvaluator, (pendingExpr->mExpressionFlags & DwEvalExpressionFlag_FullPrecision) != 0);
  8082. if ((!val.empty()) && (val[0] == '!'))
  8083. return val;
  8084. if (pendingExpr->mFormatInfo.mRawString)
  8085. return val;
  8086. if (exprResult.mIsLiteral)
  8087. val += "\n:literal";
  8088. if (bfPassInstance.HasMessages())
  8089. {
  8090. for (auto error : bfPassInstance.mErrors)
  8091. {
  8092. if (error->mIsWarning)
  8093. {
  8094. val += "\n:warn\t";
  8095. val += error->mError;
  8096. }
  8097. }
  8098. }
  8099. if (!pendingExpr->mFormatInfo.mReferenceId.empty())
  8100. val += "\n:referenceId\t" + pendingExpr->mFormatInfo.mReferenceId;
  8101. if ((exprResult.mSrcAddress != 0) && (HasMemoryBreakpoint(exprResult.mSrcAddress, exprResult.mType->GetByteCount())))
  8102. val += StrFormat("\n:break\t%@", exprResult.mSrcAddress);
  8103. auto checkType = exprResult.mType->RemoveModifiers();
  8104. if (checkType->IsBfObjectPtr())
  8105. val += "\n:type\tobject";
  8106. else if ((checkType->IsPointer()) || (checkType->mTypeCode == DbgType_Subroutine))
  8107. val += "\n:type\tpointer";
  8108. else if (checkType->IsInteger())
  8109. val += "\n:type\tint";
  8110. else if (checkType->IsFloat())
  8111. val += "\n:type\tfloat";
  8112. else if ((exprResult.mRegNum >= X64Reg_M128_XMM0) && (exprResult.mRegNum <= X64Reg_M128_XMM15))
  8113. val += "\n:type\tmm128";
  8114. else
  8115. val += "\n:type\tvaluetype";
  8116. if ((pendingExpr->mFormatInfo.mTypeKindFlags & DbgTypeKindFlag_Int) != 0)
  8117. val += "\n:type\tint";
  8118. if (dbgExprEvaluator.mHadSideEffects)
  8119. val += "\n:sideeffects";
  8120. auto underlyingType = exprResult.mType->RemoveModifiers();
  8121. bool canEdit = true;
  8122. if (pendingExpr->mFormatInfo.mLanguage == DbgLanguage_Beef)
  8123. {
  8124. if (exprResult.mType->IsConst())
  8125. canEdit = false;
  8126. }
  8127. if (pendingExpr->mFormatInfo.mNoEdit)
  8128. canEdit = false;
  8129. if (exprResult.mIsReadOnly)
  8130. canEdit = false;
  8131. if (val[0] == '!')
  8132. {
  8133. // Already has an error embedded, can't edit
  8134. }
  8135. else if ((exprResult.mSrcAddress != 0) && (underlyingType->mTypeCode >= DbgType_i8) && (underlyingType->mTypeCode <= DbgType_Ptr) &&
  8136. (underlyingType->mTypeCode != DbgType_Class) && (underlyingType->mTypeCode != DbgType_Struct))
  8137. {
  8138. if (canEdit)
  8139. val += "\n:canEdit";
  8140. if (exprResult.mType->mTypeCode == DbgType_Ptr)
  8141. {
  8142. val += "\n:editVal\t" + EncodeDataPtr(exprResult.mPtr, true);
  8143. }
  8144. }
  8145. else if ((underlyingType->IsStruct()) && (exprResult.mSrcAddress != 0) && (underlyingType->IsTypedPrimitive()))
  8146. {
  8147. auto primType = underlyingType->GetRootBaseType();
  8148. DbgTypedValue primVal = dbgExprEvaluator.ReadTypedValue(NULL, primType, exprResult.mSrcAddress, DbgAddrType_Target);
  8149. String primResult = DbgTypedValueToString(primVal, "", pendingExpr->mFormatInfo, NULL);
  8150. int crPos = (int)primResult.IndexOf('\n');
  8151. if (crPos != -1)
  8152. primResult.RemoveToEnd(crPos);
  8153. if (canEdit)
  8154. val += "\n:canEdit";
  8155. val += "\n:editVal\t" + primResult;
  8156. }
  8157. else if (exprResult.mRegNum >= 0)
  8158. {
  8159. bool isPseudoReg = ( ((exprResult.mRegNum >= X86Reg_M128_XMMREG_FIRST) && (exprResult.mRegNum <= X86Reg_M128_XMMREG_LAST))
  8160. || ((exprResult.mRegNum >= X86Reg_CAT_FIRST) && (exprResult.mRegNum <= X86Reg_CAT_LAST)) );
  8161. if (!isPseudoReg)
  8162. {
  8163. if (canEdit)
  8164. val += "\n:canEdit";
  8165. }
  8166. }
  8167. }
  8168. if (pendingExpr->mFormatInfo.mRawString)
  8169. return "";
  8170. if (pendingExpr->mCursorPos != -1)
  8171. val += GetAutocompleteOutput(autoComplete);
  8172. return val;
  8173. }
  8174. String WinDebugger::EvaluateContinue()
  8175. {
  8176. BP_ZONE("WinDebugger::EvaluateContinue");
  8177. AutoCrit autoCrit(mDebugManager->mCritSect);
  8178. if (mDebugPendingExpr == NULL)
  8179. return "!Evaluation canceled";
  8180. if (!IsPaused())
  8181. return "!Not paused";
  8182. if (mRunState == RunState_DebugEval_Done)
  8183. mRunState = RunState_Paused;
  8184. BfPassInstance bfPassInstance(mBfSystem);
  8185. String result = EvaluateContinue(mDebugPendingExpr, bfPassInstance);
  8186. if (result != "!pending")
  8187. {
  8188. BfLogDbg("EvaluateContinue finishing pending expr in thread %d\n", mDebugEvalThreadInfo.mThreadId);
  8189. CleanupDebugEval();
  8190. }
  8191. return result;
  8192. }
  8193. void WinDebugger::EvaluateContinueKeep()
  8194. {
  8195. if (mDebugPendingExpr != NULL)
  8196. mDebugPendingExpr->mIdleTicks = 0;
  8197. }
  8198. static void PdbTestFile(WinDebugger* debugger, const StringImpl& path)
  8199. {
  8200. if (!path.EndsWith(".PDB", StringImpl::CompareKind_OrdinalIgnoreCase))
  8201. return;
  8202. OutputDebugStrF("Testing %s\n", path.c_str());
  8203. COFF coffFile(debugger->mDebugTarget);
  8204. uint8 wantGuid[16] = { 0 };
  8205. if (!coffFile.TryLoadPDB(path, wantGuid, -1))
  8206. return;
  8207. if (!coffFile.mIs64Bit)
  8208. return;
  8209. coffFile.ParseTypeData();
  8210. coffFile.ParseSymbolData();
  8211. coffFile.ParseGlobalsData();
  8212. }
  8213. static void PdbTest(WinDebugger* debugger, const StringImpl& path)
  8214. {
  8215. for (auto& fileEntry : FileEnumerator(path, FileEnumerator::Flags_Files))
  8216. {
  8217. String filePath = fileEntry.GetFilePath();
  8218. PdbTestFile(debugger, filePath);
  8219. }
  8220. for (auto& fileEntry : FileEnumerator(path, FileEnumerator::Flags_Directories))
  8221. {
  8222. String childPath = fileEntry.GetFilePath();
  8223. String dirName;
  8224. dirName = GetFileName(childPath);
  8225. PdbTest(debugger, childPath);
  8226. }
  8227. }
  8228. String WinDebugger::Evaluate(const StringImpl& expr, DwFormatInfo formatInfo, int callStackIdx, int cursorPos, int language, DwEvalExpressionFlags expressionFlags)
  8229. {
  8230. BP_ZONE_F("WinDebugger::Evaluate %s", BP_DYN_STR(expr.c_str()));
  8231. AutoCrit autoCrit(mDebugManager->mCritSect);
  8232. if ((expressionFlags & DwEvalExpressionFlag_Symbol) != 0)
  8233. {
  8234. DwAutoComplete autoComplete;
  8235. String retVal;
  8236. retVal += GetAutocompleteOutput(autoComplete);
  8237. return retVal;
  8238. }
  8239. UpdateCallStackMethod(callStackIdx);
  8240. BfLogDbgExpr("Evaluate %s in thread %d\n", expr.c_str(), (mActiveThread != NULL) ? mActiveThread->mThreadId : 0);
  8241. if (language != -1)
  8242. formatInfo.mLanguage = (DbgLanguage)language;
  8243. auto activeThread = mActiveThread;
  8244. if ((!IsPaused()) && (mRunState != RunState_NotStarted) && (mRunState != RunState_DebugEval))
  8245. {
  8246. activeThread = NULL;
  8247. callStackIdx = -1;
  8248. }
  8249. if (mDebugPendingExpr != NULL)
  8250. {
  8251. // We already have a pending call
  8252. expressionFlags = (DwEvalExpressionFlags)(expressionFlags & ~DwEvalExpressionFlag_AllowCalls);
  8253. }
  8254. if ((expressionFlags & DwEvalExpressionFlag_RawStr) != 0)
  8255. {
  8256. formatInfo.mRawString = true;
  8257. }
  8258. auto dbgModule = GetCallStackDbgModule(callStackIdx);
  8259. auto dbgSubprogram = GetCallStackSubprogram(callStackIdx);
  8260. DbgCompileUnit* dbgCompileUnit = NULL;
  8261. if (dbgSubprogram != NULL)
  8262. dbgCompileUnit = dbgSubprogram->mCompileUnit;
  8263. auto terminatedExpr = expr + ";";
  8264. if ((expr.length() > 0) && (expr[0] == '!'))
  8265. {
  8266. if (expr.StartsWith("!step "))
  8267. {
  8268. expressionFlags = (DwEvalExpressionFlags)(expressionFlags | DwEvalExpressionFlag_StepIntoCalls);
  8269. for (int i = 0; i < 5; i++)
  8270. terminatedExpr[i] = ' ';
  8271. }
  8272. else
  8273. {
  8274. String cmd = expr;
  8275. int commaPos = (int)cmd.IndexOf(',');
  8276. if (commaPos != -1)
  8277. cmd.RemoveToEnd(commaPos);
  8278. if (cmd == "!info")
  8279. {
  8280. OutputMessage(StrFormat("Module: %s\n", dbgModule->mDisplayName.c_str()));
  8281. if (dbgSubprogram == NULL)
  8282. {
  8283. //
  8284. }
  8285. else if (dbgSubprogram->mLinkName != NULL)
  8286. {
  8287. OutputMessage(StrFormat("Link Name: %s\n", dbgSubprogram->mLinkName));
  8288. }
  8289. else
  8290. {
  8291. String outSymbol;
  8292. if (mDebugTarget->FindSymbolAt(dbgSubprogram->mBlock.mLowPC, &outSymbol))
  8293. {
  8294. OutputMessage(StrFormat("Link Name: %s\n", outSymbol.c_str()));
  8295. }
  8296. }
  8297. return "";
  8298. }
  8299. else if (cmd == "!dbg")
  8300. {
  8301. mDbgBreak = true;
  8302. return "";
  8303. }
  8304. else if (cmd == "!pdbtest")
  8305. {
  8306. PdbTest(this, "c:\\");
  8307. }
  8308. }
  8309. }
  8310. bool valIsAddr = false;
  8311. BfParser* parser = new BfParser(mBfSystem);
  8312. parser->mCompatMode = true;
  8313. BfPassInstance bfPassInstance(mBfSystem);
  8314. if ((terminatedExpr.length() > 2) && (terminatedExpr[0] == '@'))
  8315. {
  8316. if (terminatedExpr[1] == '!') // Return string as error
  8317. {
  8318. int errorEnd = (int)terminatedExpr.IndexOf("@!", 2);
  8319. if (errorEnd != -1)
  8320. return terminatedExpr.Substring(1, errorEnd - 1);
  8321. else
  8322. return terminatedExpr.Substring(1);
  8323. }
  8324. else if (terminatedExpr[1] == '>') // Return string as text
  8325. {
  8326. int errorEnd = (int)terminatedExpr.IndexOf("@>", 2);
  8327. if (errorEnd != -1)
  8328. return terminatedExpr.Substring(2, errorEnd - 1);
  8329. else
  8330. return terminatedExpr.Substring(2);
  8331. }
  8332. else // Look for "@:" or "@Beef:" style
  8333. {
  8334. int colonIdx = terminatedExpr.IndexOf(':');
  8335. if (colonIdx > 0)
  8336. {
  8337. bool isValid = true;
  8338. DbgLanguage language = DbgLanguage_Unknown;
  8339. String lang = terminatedExpr.Substring(1, colonIdx - 1);
  8340. lang = ToUpper(lang);
  8341. if ((lang == "") || (lang == "BEEF"))
  8342. {
  8343. language = DbgLanguage_Beef;
  8344. }
  8345. else if (lang == "C")
  8346. {
  8347. language = DbgLanguage_C;
  8348. }
  8349. if (language != DbgLanguage_Unknown)
  8350. {
  8351. for (int i = 0; i < colonIdx + 1; i++)
  8352. terminatedExpr[i] = ' ';
  8353. DbgLanguage curLanguage = DbgLanguage_Unknown;
  8354. if (dbgSubprogram != NULL)
  8355. curLanguage = dbgSubprogram->GetLanguage();
  8356. if (language != curLanguage)
  8357. {
  8358. dbgModule = mDebugTarget->mTargetBinary;
  8359. dbgSubprogram = NULL;
  8360. formatInfo.mLanguage = language;
  8361. callStackIdx = -1;
  8362. }
  8363. }
  8364. }
  8365. }
  8366. }
  8367. parser->SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  8368. parser->Parse(&bfPassInstance);
  8369. BfReducer bfReducer;
  8370. bfReducer.mAlloc = parser->mAlloc;
  8371. bfReducer.mSystem = mBfSystem;
  8372. bfReducer.mPassInstance = &bfPassInstance;
  8373. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser->mRootNode);
  8374. bfReducer.mVisitorPos.MoveNext();
  8375. bfReducer.mCompatMode = parser->mCompatMode;
  8376. bfReducer.mSource = parser;
  8377. auto exprNode = bfReducer.CreateExpression(parser->mRootNode->mChildArr.GetAs<BfAstNode*>(0));
  8378. parser->Close();
  8379. formatInfo.mCallStackIdx = callStackIdx;
  8380. if ((formatInfo.mLanguage == DbgLanguage_Unknown) && (dbgSubprogram != NULL))
  8381. formatInfo.mLanguage = dbgSubprogram->GetLanguage();
  8382. DbgPendingExpr* pendingExpr = new DbgPendingExpr();
  8383. if (activeThread != NULL)
  8384. pendingExpr->mThreadId = activeThread->mThreadId;
  8385. pendingExpr->mParser = parser;
  8386. pendingExpr->mCallStackIdx = callStackIdx;
  8387. pendingExpr->mCursorPos = cursorPos;
  8388. pendingExpr->mExpressionFlags = expressionFlags;
  8389. pendingExpr->mExprNode = exprNode;
  8390. DbgType* explicitType = NULL;
  8391. String formatFlags;
  8392. String assignExpr;
  8393. int assignExprOffset = -1;
  8394. if ((exprNode != NULL) && (exprNode->GetSrcEnd() < (int)expr.length()))
  8395. {
  8396. int formatOffset = exprNode->GetSrcEnd();
  8397. while (formatOffset < (int)expr.length())
  8398. {
  8399. char c = expr[formatOffset];
  8400. if (c == ' ')
  8401. formatOffset++;
  8402. else
  8403. break;
  8404. }
  8405. formatFlags = Trim(expr.Substring(formatOffset));
  8406. bool isComplexType = false;
  8407. for (char c : formatFlags)
  8408. if (c == '>')
  8409. isComplexType = true;
  8410. if (isComplexType)
  8411. {
  8412. explicitType = dbgModule->FindType(expr);
  8413. }
  8414. if ((explicitType == NULL) && (formatFlags.length() > 0))
  8415. {
  8416. String errorString = "Invalid expression";
  8417. if (!ParseFormatInfo(dbgModule, formatFlags, &formatInfo, &bfPassInstance, &assignExprOffset, &assignExpr, &errorString))
  8418. {
  8419. if (formatInfo.mRawString)
  8420. return "";
  8421. bfPassInstance.FailAt(errorString, parser->mSourceData, exprNode->GetSrcEnd(), (int) expr.length() - exprNode->GetSrcEnd());
  8422. formatFlags = "";
  8423. }
  8424. if (assignExprOffset != -1)
  8425. assignExprOffset += formatOffset;
  8426. }
  8427. }
  8428. if (assignExpr.length() > 0)
  8429. {
  8430. String newEvalStr = exprNode->ToString() + " = ";
  8431. int errorOffset = (int)newEvalStr.length();
  8432. newEvalStr += assignExpr;
  8433. String result = Evaluate(newEvalStr, formatInfo, callStackIdx, cursorPos, language, expressionFlags);
  8434. if (result[0] == '!')
  8435. {
  8436. int tabPos = (int)result.IndexOf('\t');
  8437. if (tabPos > 0)
  8438. {
  8439. int errorStart = atoi(result.Substring(1, tabPos - 1).c_str());
  8440. if (errorStart >= errorOffset)
  8441. {
  8442. result = StrFormat("!%d", errorStart - errorOffset + assignExprOffset) + result.Substring(tabPos);
  8443. }
  8444. }
  8445. }
  8446. return result;
  8447. }
  8448. pendingExpr->mExplitType = explicitType;
  8449. pendingExpr->mFormatInfo = formatInfo;
  8450. String result = EvaluateContinue(pendingExpr, bfPassInstance);
  8451. if (result == "!pending")
  8452. {
  8453. BF_ASSERT(mDebugPendingExpr == NULL);
  8454. if (mDebugPendingExpr != NULL)
  8455. {
  8456. return "!retry"; // We already have a pending
  8457. }
  8458. mDebugPendingExpr = pendingExpr;
  8459. mDebugEvalThreadInfo = *mActiveThread;
  8460. mActiveThread->mIsAtBreakpointAddress = 0;
  8461. mActiveThread->mStoppedAtAddress = 0;
  8462. mActiveThread->mBreakpointAddressContinuing = 0;
  8463. }
  8464. else
  8465. delete pendingExpr;
  8466. return result;
  8467. }
  8468. String WinDebugger::Evaluate(const StringImpl& expr, int callStackIdx, int cursorPos, int language, DwEvalExpressionFlags expressionFlags)
  8469. {
  8470. DwFormatInfo formatInfo;
  8471. return Evaluate(expr, formatInfo, callStackIdx, cursorPos, language, expressionFlags);
  8472. }
  8473. static void ConvertDoubleToFloat80(double d, byte fp80[10])
  8474. {
  8475. uint64 di = *reinterpret_cast<uint64*>(&d);
  8476. uint64 m = di & (((uint64)1 << 52) - 1);
  8477. uint64 e = (di >> 52) & 0x7ff;
  8478. memset(fp80, 0, 10);
  8479. // sign bit is directly transferred
  8480. if (di & ((uint64)1 << 63))
  8481. fp80[9] |= 0x80;
  8482. if (!e && !m)
  8483. return; // zero
  8484. fp80[7] |= 0x80; // leading integer bit in mantissa (always 1 in normalized numbers)
  8485. if (e == 0x7ff)
  8486. {
  8487. fp80[9] |= 0x7f;
  8488. fp80[8] = 0xff;
  8489. if (m == 0)
  8490. return; // inf
  8491. fp80[7] |= 0x3f; // any nonzero value will be a NaN (SNaN or QNaN)
  8492. if (m & ((uint64)1 << 51))
  8493. fp80[7] |= 0x40; // QNaN
  8494. return;
  8495. }
  8496. int useExponent = (int)e - 1023;
  8497. if (!e)
  8498. {
  8499. // denormal; can renormalize though since fp80 supports lower exponents
  8500. BF_ASSERT(m != 0); // we should have trapped zero above
  8501. while (!(m & ((uint64)1 << 51)))
  8502. {
  8503. m <<= 1;
  8504. --useExponent;
  8505. }
  8506. // finally we have our leading 1 bit; strip that off and we have a normalized number again
  8507. m <<= 1;
  8508. --useExponent;
  8509. m &= (((uint64)1 << 52) - 1);
  8510. }
  8511. useExponent += 16383;
  8512. BF_ASSERT((useExponent > 0) && (useExponent < 0x7fff));
  8513. *reinterpret_cast<uint16*>(&fp80[8]) |= (uint16)useExponent;
  8514. *reinterpret_cast<uint64*>(&fp80[0]) |= (m << 11);
  8515. }
  8516. bool WinDebugger::AssignToReg(int callStackIdx, DbgTypedValue regVal, DbgTypedValue value, String& outError)
  8517. {
  8518. BF_ASSERT(regVal.mRegNum >= 0);
  8519. if (mCallStack.size() == 0)
  8520. {
  8521. outError = "No call stack";
  8522. return false;
  8523. }
  8524. if (callStackIdx >= (int)mCallStack.size())
  8525. {
  8526. outError = "Invalid call stack index";
  8527. return false;
  8528. }
  8529. auto registers = &mCallStack[callStackIdx]->mRegisters;
  8530. void* regPtr = NULL;
  8531. #ifdef BF_DBG_32
  8532. if ((regVal.mRegNum >= X86Reg_INTREG_FIRST) && (regVal.mRegNum <= X86Reg_INTREG_LAST))
  8533. {
  8534. BF_ASSERT(regVal.mType->mSize == sizeof(int32));
  8535. registers->mIntRegsArray[regVal.mRegNum - X86Reg_INTREG_FIRST] = (uint64)value.mUInt32; // don't sign-extend
  8536. }
  8537. else if ((regVal.mRegNum >= X86Reg_FPSTREG_FIRST) && (regVal.mRegNum <= X86Reg_FPSTREG_LAST))
  8538. {
  8539. BF_ASSERT(regVal.mType->mSize == sizeof(float) || regVal.mType->mSize == sizeof(double));
  8540. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X86Reg_FPSTREG_FIRST];
  8541. double d;
  8542. if (regVal.mType->mSize == sizeof(float))
  8543. d = (double)value.mSingle;
  8544. else
  8545. d = value.mDouble;
  8546. ConvertDoubleToFloat80(d, reg->fp.fp80);
  8547. }
  8548. else if ((regVal.mRegNum >= X86Reg_MMREG_FIRST) && (regVal.mRegNum <= X86Reg_MMREG_LAST))
  8549. {
  8550. BF_ASSERT(regVal.mType->mSize == sizeof(int32) || regVal.mType->mSize == sizeof(int64));
  8551. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X86Reg_MMREG_FIRST];
  8552. if (regVal.mType->mSize == sizeof(int32))
  8553. reg->mm = (uint64)value.mUInt32; // don't sign-extend
  8554. else if (regVal.mType->mSize == sizeof(int64))
  8555. reg->mm = value.mInt64;
  8556. // 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
  8557. reg->fp.fp80[8] = reg->fp.fp80[9] = 0xFF;
  8558. }
  8559. else if ((regVal.mRegNum >= X86Reg_XMMREG_FIRST) && (regVal.mRegNum <= X86Reg_XMMREG_LAST))
  8560. {
  8561. int xmmMajor = (regVal.mRegNum - X86Reg_XMMREG_FIRST) >> 2;
  8562. int xmmMinor = (regVal.mRegNum - X86Reg_XMMREG_FIRST) & 3;
  8563. registers->mXmmRegsArray[xmmMajor].f[xmmMinor] = value.mSingle;
  8564. }
  8565. else if ((regVal.mRegNum >= X86Reg_M128_XMMREG_FIRST) && (regVal.mRegNum <= X86Reg_M128_XMMREG_LAST))
  8566. {
  8567. outError = "Cannot write directly to 128-bit XMM register, please use inner float components";
  8568. return false;
  8569. }
  8570. else if ((regVal.mRegNum >= X86Reg_FLAG_FIRST) && (regVal.mRegNum <= X86Reg_FLAG_LAST))
  8571. {
  8572. int flagBit = CPURegisters::GetFlagBitForRegister(regVal.mRegNum);
  8573. if (flagBit >= 0)
  8574. {
  8575. if (value.mBool)
  8576. registers->mIntRegs.efl |= ((uint64)1 << flagBit);
  8577. else
  8578. registers->mIntRegs.efl &= ~((uint64)1 << flagBit);
  8579. }
  8580. else
  8581. {
  8582. outError = "Unrecognized flag";
  8583. return false;
  8584. }
  8585. }
  8586. else if ((regVal.mRegNum >= X86Reg_CAT_FIRST) && (regVal.mRegNum <= X86Reg_CAT_LAST))
  8587. {
  8588. outError = "Cannot write directly to register categories, please use inner float components";
  8589. return false;
  8590. }
  8591. #else
  8592. if ((regVal.mRegNum >= X64Reg_INTREG_FIRST) && (regVal.mRegNum <= X64Reg_INTREG_LAST))
  8593. {
  8594. //BF_ASSERT(regVal.mType->mSize == sizeof(addr_target));
  8595. registers->mIntRegsArray[regVal.mRegNum - X64Reg_INTREG_FIRST] = value.GetInt64(); // don't sign-extend
  8596. regPtr = &registers->mIntRegsArray[regVal.mRegNum - X64Reg_INTREG_FIRST];
  8597. }
  8598. else if ((regVal.mRegNum >= X64Reg_FPSTREG_FIRST) && (regVal.mRegNum <= X64Reg_FPSTREG_LAST))
  8599. {
  8600. BF_ASSERT(regVal.mType->mSize == sizeof(float) || regVal.mType->mSize == sizeof(double));
  8601. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X64Reg_FPSTREG_FIRST];
  8602. double d;
  8603. if (regVal.mType->mSize == sizeof(float))
  8604. d = (double)value.mSingle;
  8605. else
  8606. d = value.mDouble;
  8607. ConvertDoubleToFloat80(d, reg->fp.fp80);
  8608. regPtr = reg;
  8609. }
  8610. else if ((regVal.mRegNum >= X64Reg_MMREG_FIRST) && (regVal.mRegNum <= X64Reg_MMREG_LAST))
  8611. {
  8612. BF_ASSERT(regVal.mType->mSize == sizeof(int32) || regVal.mType->mSize == sizeof(int64));
  8613. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X64Reg_MMREG_FIRST];
  8614. if (regVal.mType->mSize == sizeof(int32))
  8615. reg->mm = (uint64)value.mUInt32; // don't sign-extend
  8616. else if (regVal.mType->mSize == sizeof(int64))
  8617. reg->mm = value.mInt64;
  8618. // 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
  8619. reg->fp.fp80[8] = reg->fp.fp80[9] = 0xFF;
  8620. regPtr = reg;
  8621. }
  8622. else if ((regVal.mRegNum >= X64Reg_XMMREG_FIRST) && (regVal.mRegNum <= X64Reg_XMMREG_LAST))
  8623. {
  8624. int xmmMajor = (regVal.mRegNum - X64Reg_XMMREG_FIRST) >> 2;
  8625. int xmmMinor = (regVal.mRegNum - X64Reg_XMMREG_FIRST) & 3;
  8626. if (value.mType->GetByteCount() == 4)
  8627. registers->mXmmRegsArray[xmmMajor].f[xmmMinor] = value.mSingle;
  8628. else if (value.mType->GetByteCount() == 8)
  8629. registers->mXmmDRegsArray[xmmMajor].d[xmmMinor] = value.mDouble;
  8630. else
  8631. BF_FATAL("Invalid XMM set value type");
  8632. regPtr = &registers->mXmmRegsArray[xmmMajor];
  8633. }
  8634. else if ((regVal.mRegNum >= X64Reg_M128_XMMREG_FIRST) && (regVal.mRegNum <= X64Reg_M128_XMMREG_LAST))
  8635. {
  8636. outError = "Cannot write directly to 128-bit XMM register, please use inner float components";
  8637. return false;
  8638. }
  8639. else if ((regVal.mRegNum >= X64Reg_FLAG_FIRST) && (regVal.mRegNum <= X64Reg_FLAG_LAST))
  8640. {
  8641. int flagBit = CPURegisters::GetFlagBitForRegister(regVal.mRegNum);
  8642. if (flagBit >= 0)
  8643. {
  8644. if (value.mBool)
  8645. registers->mIntRegs.efl |= ((uint64)1 << flagBit);
  8646. else
  8647. registers->mIntRegs.efl &= ~((uint64)1 << flagBit);
  8648. regPtr = &registers->mIntRegs.efl;
  8649. }
  8650. else
  8651. {
  8652. outError = "Unrecognized flag";
  8653. return false;
  8654. }
  8655. }
  8656. else if ((regVal.mRegNum >= X64Reg_CAT_FIRST) && (regVal.mRegNum <= X64Reg_CAT_LAST))
  8657. {
  8658. outError = "Cannot write directly to register categories, please use inner float components";
  8659. return false;
  8660. }
  8661. else
  8662. BF_FATAL("Not implemented");
  8663. #endif
  8664. if (callStackIdx == 0)
  8665. {
  8666. SetRegisters(&mCallStack[0]->mRegisters);
  8667. return true;
  8668. }
  8669. else
  8670. {
  8671. bool wasSaved = false;
  8672. for (int calleeStackIdx = callStackIdx - 1; calleeStackIdx >= 0; calleeStackIdx--)
  8673. {
  8674. auto calleeRegisters = &mCallStack[calleeStackIdx]->mRegisters;
  8675. if (!mDebugTarget->PropogateRegisterUpCallStack(registers, calleeRegisters, regPtr, wasSaved))
  8676. {
  8677. outError = "Failed to set register";
  8678. return false;
  8679. }
  8680. if (wasSaved)
  8681. return true;
  8682. }
  8683. // This register wasn't saved, so commit it to the callstack top
  8684. return AssignToReg(0, regVal, value, outError);
  8685. }
  8686. }
  8687. String WinDebugger::GetAutocompleteOutput(DwAutoComplete& autoComplete)
  8688. {
  8689. String val = "\n:autocomplete\n";
  8690. if (autoComplete.mInsertStartIdx != -1)
  8691. {
  8692. val += StrFormat("insertRange\t%d %d\n", autoComplete.mInsertStartIdx, autoComplete.mInsertEndIdx);
  8693. }
  8694. Array<AutoCompleteEntry*> entries;
  8695. for (auto& entry : autoComplete.mEntriesSet)
  8696. {
  8697. entries.Add(&entry);
  8698. }
  8699. std::sort(entries.begin(), entries.end(), [](AutoCompleteEntry* lhs, AutoCompleteEntry* rhs)
  8700. {
  8701. return stricmp(lhs->mDisplay, rhs->mDisplay) < 0;
  8702. });
  8703. for (auto entry : entries)
  8704. {
  8705. val += String(entry->mEntryType);
  8706. val += "\t";
  8707. val += String(entry->mDisplay);
  8708. val += "\n";
  8709. }
  8710. /*if (autoComplete.mEntries.size() != 0)
  8711. {
  8712. for (auto& entry : autoComplete.mEntries)
  8713. {
  8714. val += String(entry.mEntryType) + "\t" + String(entry.mDisplay) + "\n";
  8715. }
  8716. }*/
  8717. return val;
  8718. }
  8719. String WinDebugger::EvaluateToAddress(const StringImpl& expr, int callStackIdx, int cursorPos)
  8720. {
  8721. AutoCrit autoCrit(mDebugManager->mCritSect);
  8722. if (IsInRunState())
  8723. return "!Target not paused";
  8724. auto dbgModule = GetCallStackDbgModule(callStackIdx);
  8725. auto dbgCompileUnit = GetCallStackCompileUnit(callStackIdx);
  8726. BfParser parser(mBfSystem);
  8727. parser.mCompatMode = true;
  8728. BfPassInstance bfPassInstance(mBfSystem);
  8729. auto terminatedExpr = expr + ";";
  8730. parser.SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  8731. parser.Parse(&bfPassInstance);
  8732. BfReducer bfReducer;
  8733. bfReducer.mAlloc = parser.mAlloc;
  8734. bfReducer.mSystem = mBfSystem;
  8735. bfReducer.mPassInstance = &bfPassInstance;
  8736. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser.mRootNode);
  8737. bfReducer.mVisitorPos.MoveNext();
  8738. bfReducer.mSource = &parser;
  8739. auto exprNode = bfReducer.CreateExpression(parser.mRootNode->GetFirst());
  8740. parser.Close();
  8741. DwAutoComplete autoComplete;
  8742. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, callStackIdx, cursorPos);
  8743. if (cursorPos != -1)
  8744. dbgExprEvaluator.mAutoComplete = &autoComplete;
  8745. dbgExprEvaluator.mDbgCompileUnit = dbgCompileUnit;
  8746. DwFormatInfo formatInfo;
  8747. formatInfo.mCallStackIdx = callStackIdx;
  8748. DbgTypedValue exprResult;
  8749. if (exprNode != NULL)
  8750. exprResult = dbgExprEvaluator.Resolve(exprNode);
  8751. DbgType* resultType = exprResult.mType->RemoveModifiers();
  8752. String val;
  8753. if (bfPassInstance.HasFailed())
  8754. {
  8755. val = StrFormat("!%d\t%d\t%s", bfPassInstance.mErrors[0]->mSrcStart, bfPassInstance.mErrors[0]->GetSrcLength(), bfPassInstance.mErrors[0]->mError.c_str());
  8756. }
  8757. else if (exprResult.mType == NULL)
  8758. {
  8759. val = "!Invalid expression";
  8760. }
  8761. else if (!resultType->IsPointerOrRef())
  8762. {
  8763. if (exprResult.mSrcAddress != 0)
  8764. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  8765. else
  8766. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  8767. }
  8768. else
  8769. {
  8770. auto innerType = resultType->mTypeParam;
  8771. int byteCount = innerType->GetByteCount();
  8772. if (byteCount == 0)
  8773. {
  8774. 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());
  8775. }
  8776. #ifdef BF_DBG_32
  8777. else if ((byteCount != 1) && (byteCount != 2) && (byteCount != 4))
  8778. {
  8779. 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);
  8780. }
  8781. #else
  8782. else if ((byteCount != 1) && (byteCount != 2) && (byteCount != 4) && (byteCount != 8))
  8783. {
  8784. 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);
  8785. }
  8786. #endif
  8787. else
  8788. {
  8789. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", byteCount);
  8790. }
  8791. }
  8792. if (cursorPos != -1)
  8793. val += GetAutocompleteOutput(autoComplete);
  8794. return val;
  8795. }
  8796. // This is currently only used for autocomplete during conditional breakpoint expression entry.
  8797. // If we want to use it for more than that then remove DwEvalExpressionFlags_ValidateOnly
  8798. String WinDebugger::EvaluateAtAddress(const StringImpl& expr, intptr atAddr, int cursorPos)
  8799. {
  8800. AutoCrit autoCrit(mDebugManager->mCritSect);
  8801. if (IsInRunState())
  8802. return "!Target not paused";
  8803. if (!IsPaused())
  8804. return "!Target not running";
  8805. WdStackFrame stackFrame;
  8806. memset(&stackFrame.mRegisters, 0, sizeof(stackFrame.mRegisters));
  8807. stackFrame.mHasGottenSubProgram = true;
  8808. *stackFrame.mRegisters.GetPCRegisterRef() = (intptr_target)atAddr;
  8809. stackFrame.mSubProgram = mDebugTarget->FindSubProgram((addr_target)atAddr);
  8810. if (stackFrame.mSubProgram == NULL)
  8811. return "!Invalid address";
  8812. mCallStack.push_back(&stackFrame);
  8813. int callStackIdx = (int)mCallStack.size() - 1;
  8814. String val = Evaluate(expr, callStackIdx, cursorPos, -1, DwEvalExpressionFlag_ValidateOnly);
  8815. mCallStack.pop_back();
  8816. return val;
  8817. }
  8818. String WinDebugger::GetAutoExpressions(int callStackIdx, uint64 memoryRangeStart, uint64 memoryRangeLen)
  8819. {
  8820. BP_ZONE("WinDebugger::GetAutoExpressions");
  8821. AutoCrit autoCrit(mDebugManager->mCritSect);
  8822. if (IsInRunState())
  8823. return "!Not paused";
  8824. if (!IsPaused())
  8825. return "!Not running";
  8826. if (!FixCallStackIdx(callStackIdx))
  8827. return "";
  8828. CPUStackFrame* stackFrame = (callStackIdx >= 0) ? mCallStack[callStackIdx] : mCallStack.front();
  8829. String result;
  8830. DbgAutoValueMapType dwarfAutos;
  8831. mDebugTarget->GetAutoValueNames(dwarfAutos, stackFrame, memoryRangeStart, memoryRangeLen);
  8832. for (auto const &a : dwarfAutos)
  8833. {
  8834. std::pair<uint64, uint64> varRange = a.mValue;
  8835. if (varRange.first != 0)
  8836. result += StrFormat("&%s\t%llu\t%llu\n", a.mKey.c_str(), varRange.second, varRange.first);
  8837. else
  8838. result += StrFormat("?%s\t%llu\n", a.mKey.c_str(), varRange.second);
  8839. }
  8840. #ifdef BF_DBG_64
  8841. // add int regs
  8842. const char* regStrs[] = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "rip", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", 0 };
  8843. #else
  8844. // add int regs
  8845. const char* regStrs[] = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "eip", 0 };
  8846. #endif
  8847. for (const char** p = regStrs; *p; ++p)
  8848. result += StrFormat("$%s\t%d\n", *p, sizeof(addr_target));
  8849. if (callStackIdx < (int)mCallStack.size() - 2)
  8850. {
  8851. WdStackFrame* prevStackFrame = mCallStack[callStackIdx + 1];
  8852. // Inlined methods have no stack frame
  8853. int stackSize = prevStackFrame->mRegisters.GetSP() - stackFrame->mRegisters.GetSP();
  8854. result += StrFormat("&$StackFrame\t%llu\t%llu\n", stackSize, stackFrame->mRegisters.GetSP());
  8855. }
  8856. return result;
  8857. }
  8858. String WinDebugger::GetAutoLocals(int stackFrameIdx, bool showRegs)
  8859. {
  8860. BP_ZONE("WinDebugger::GetAutoExpressions");
  8861. AutoCrit autoCrit(mDebugManager->mCritSect);
  8862. if (IsInRunState())
  8863. return "";
  8864. if (!IsPaused())
  8865. return "";
  8866. if (mCallStack.size() == 0)
  8867. UpdateCallStack();
  8868. String result;
  8869. Array<String> localList;
  8870. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  8871. UpdateCallStackMethod(actualStackFrameIdx);
  8872. if (actualStackFrameIdx >= mCallStack.size())
  8873. return "";
  8874. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  8875. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  8876. if (dwSubprogram == NULL)
  8877. return "";
  8878. auto langage = dwSubprogram->GetLanguage();
  8879. DbgLineData* dwLineData = FindLineDataInSubprogram(wdStackFrame->GetSourcePC(), dwSubprogram);
  8880. if (dwLineData == NULL)
  8881. return "";
  8882. dwSubprogram->PopulateSubprogram();
  8883. mDebugTarget->GetAutoLocalsInBlock(localList, dwSubprogram, &dwSubprogram->mBlock, wdStackFrame, dwLineData);
  8884. String lastLocal;
  8885. for (auto local : localList)
  8886. {
  8887. if (langage == DbgLanguage_C)
  8888. {
  8889. if ((local == "this") && (strncmp(dwSubprogram->mName, "<lambda_", 8) == 0))
  8890. {
  8891. // Use explicit "$this" so we can see the actual capture
  8892. result += "$this\n";
  8893. continue;
  8894. }
  8895. }
  8896. bool wasAlias = false;
  8897. for (int i = 0; i < (int)local.length() - 1; i++)
  8898. {
  8899. if ((local[i] == '$') && (local[i + 1] == 'a'))
  8900. {
  8901. // Alias
  8902. wasAlias = true;
  8903. String localName = local.Substring(0, i) + "\n";
  8904. if (localName != lastLocal)
  8905. {
  8906. result += localName;
  8907. lastLocal = localName;
  8908. }
  8909. break;
  8910. }
  8911. }
  8912. if (!wasAlias)
  8913. result += local + "\n";
  8914. }
  8915. if (showRegs)
  8916. {
  8917. result += "$FLAGS\n";
  8918. UpdateRegisterUsage(stackFrameIdx);
  8919. for (int regIdx = 0; regIdx < (int)wdStackFrame->mRegForms.size(); regIdx++)
  8920. {
  8921. if (wdStackFrame->mRegForms[regIdx] != RegForm_Invalid)
  8922. result += "$" + String(CPURegisters::GetRegisterName(regIdx)) + "\n";
  8923. }
  8924. }
  8925. return result;
  8926. }
  8927. String WinDebugger::CompactChildExpression(const StringImpl& expr, const StringImpl& parentExpr, int callStackIdx)
  8928. {
  8929. DbgCompileUnit* compileUnit = GetCallStackCompileUnit(callStackIdx);
  8930. DbgModule* dbgModule = GetCallStackDbgModule(callStackIdx);
  8931. if (dbgModule == NULL)
  8932. return "!failed";
  8933. DbgLanguage language = DbgLanguage_Unknown;
  8934. if (compileUnit != NULL)
  8935. language = compileUnit->mLanguage;
  8936. BfPassInstance bfPassInstance(mBfSystem);
  8937. BfParser parser(mBfSystem);
  8938. parser.mCompatMode = language != DbgLanguage_Beef;
  8939. auto terminatedExpr = expr + ";";
  8940. parser.SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  8941. parser.Parse(&bfPassInstance);
  8942. BfParser parentParser(mBfSystem);
  8943. auto terminatedParentExpr = parentExpr + ";";
  8944. parentParser.mCompatMode = language != DbgLanguage_Beef;
  8945. parentParser.SetSource(terminatedParentExpr.c_str(), terminatedParentExpr.length());
  8946. parentParser.Parse(&bfPassInstance);
  8947. BfReducer bfReducer;
  8948. bfReducer.mCompatMode = true;
  8949. bfReducer.mAlloc = parser.mAlloc;
  8950. bfReducer.mSystem = mBfSystem;
  8951. bfReducer.mPassInstance = &bfPassInstance;
  8952. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser.mRootNode);
  8953. bfReducer.mVisitorPos.MoveNext();
  8954. bfReducer.mSource = &parser;
  8955. auto exprNode = bfReducer.CreateExpression(parser.mRootNode->GetFirst());
  8956. bfReducer.mAlloc = parentParser.mAlloc;
  8957. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parentParser.mRootNode);
  8958. bfReducer.mVisitorPos.MoveNext();
  8959. auto parentExprNode = bfReducer.CreateExpression(parentParser.mRootNode->GetFirst());
  8960. parser.Close();
  8961. if ((exprNode == NULL) || (parentExprNode == NULL))
  8962. return "!failed";
  8963. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, callStackIdx, -1);
  8964. DwFormatInfo formatInfo;
  8965. formatInfo.mCallStackIdx = callStackIdx;
  8966. String formatFlags;
  8967. String assignExpr;
  8968. if ((exprNode != NULL) && (exprNode->GetSrcEnd() < (int) expr.length()))
  8969. {
  8970. formatFlags = Trim(expr.Substring(exprNode->GetSrcEnd()));
  8971. if (formatFlags.length() > 0)
  8972. {
  8973. String errorString = "Invalid expression";
  8974. if (!ParseFormatInfo(dbgModule, formatFlags, &formatInfo, &bfPassInstance, NULL, &assignExpr, &errorString))
  8975. {
  8976. bfPassInstance.FailAt(errorString, parser.mSourceData, exprNode->GetSrcEnd(), (int) expr.length() - exprNode->GetSrcEnd());
  8977. formatFlags = "";
  8978. }
  8979. }
  8980. }
  8981. dbgExprEvaluator.mExplicitThis = formatInfo.mExplicitThis;
  8982. dbgExprEvaluator.mExplicitThisExpr = parentExprNode;
  8983. DbgTypedValue exprResult = dbgExprEvaluator.Resolve(exprNode);
  8984. BfAstNode* headNode = dbgExprEvaluator.FinalizeExplicitThisReferences(exprNode);
  8985. BfPrinter printer(parser.mRootNode, NULL, NULL);
  8986. printer.mIgnoreTrivia = true;
  8987. printer.mReformatting = true;
  8988. printer.VisitChild(headNode);
  8989. auto result = printer.mOutString;
  8990. if (formatInfo.mNoVisualizers)
  8991. result += ", nv";
  8992. if (formatInfo.mNoMembers)
  8993. result += ", nm";
  8994. if (formatInfo.mNoEdit)
  8995. result += ", ne";
  8996. if (formatInfo.mIgnoreDerivedClassInfo)
  8997. result += ", nd";
  8998. if (formatInfo.mDisplayType == DwDisplayType_Ascii)
  8999. result += ", s";
  9000. if (formatInfo.mDisplayType == DwDisplayType_Utf8)
  9001. result += ", s8";
  9002. if (formatInfo.mDisplayType == DwDisplayType_Utf16)
  9003. result += ", s16";
  9004. if (formatInfo.mDisplayType == DwDisplayType_Utf32)
  9005. result += ", s32";
  9006. return result;
  9007. }
  9008. String WinDebugger::GetProcessInfo()
  9009. {
  9010. AutoCrit autoCrit(mDebugManager->mCritSect);
  9011. if ((mActiveThread == NULL) && (!mIsRunning))
  9012. return "";
  9013. SYSTEM_INFO sysinfo = { 0 };
  9014. GetSystemInfo(&sysinfo);
  9015. FILETIME creationTime = { 0 };
  9016. FILETIME exitTime = { 0 };
  9017. FILETIME kernelTime = { 0 };
  9018. FILETIME userTime = { 0 };
  9019. ::GetProcessTimes(mProcessInfo.hProcess, &creationTime, &exitTime, &kernelTime, &userTime);
  9020. String retStr;
  9021. PROCESS_MEMORY_COUNTERS memInfo = { 0 };
  9022. ::GetProcessMemoryInfo(mProcessInfo.hProcess, &memInfo, sizeof(PROCESS_MEMORY_COUNTERS));
  9023. FILETIME currentTime = { 0 };
  9024. ::GetSystemTimeAsFileTime(&currentTime);
  9025. retStr += StrFormat("VirtualMemory\t%d\n", memInfo.PagefileUsage);
  9026. retStr += StrFormat("WorkingMemory\t%d\n", memInfo.WorkingSetSize);
  9027. retStr += StrFormat("RunningTime\t%lld\n", *(int64*)&currentTime - *(int64*)&creationTime);
  9028. retStr += StrFormat("KernelTime\t%lld\n", *(int64*)&kernelTime / sysinfo.dwNumberOfProcessors);
  9029. retStr += StrFormat("UserTime\t%lld\n", *(int64*)&userTime / sysinfo.dwNumberOfProcessors);
  9030. return retStr;
  9031. }
  9032. String WinDebugger::GetThreadInfo()
  9033. {
  9034. AutoCrit autoCrit(mDebugManager->mCritSect);
  9035. String retStr;
  9036. if ((mActiveThread == NULL) && (!mIsRunning))
  9037. {
  9038. retStr = "";
  9039. }
  9040. else
  9041. {
  9042. if (mActiveThread != NULL)
  9043. retStr = StrFormat("%d", mActiveThread->mThreadId);
  9044. for (auto threadInfo : mThreadList)
  9045. {
  9046. SetAndRestoreValue<WdThreadInfo*> prevThread(mActiveThread, threadInfo);
  9047. retStr += "\n";
  9048. for (int pass = 0; pass < 2; pass++)
  9049. {
  9050. CPURegisters registers;
  9051. PopulateRegisters(&registers);
  9052. String locString = EncodeDataPtr((addr_target)registers.GetPC(), true);
  9053. TryGetThreadName(threadInfo);
  9054. bool hadThreadName = true;
  9055. String threadName = threadInfo->mName;
  9056. if (threadName.IsEmpty())
  9057. {
  9058. hadThreadName = false;
  9059. if (threadInfo->mThreadId == mProcessInfo.dwThreadId)
  9060. threadName = "Main Thread";
  9061. else
  9062. threadName = "Worker Thread";
  9063. }
  9064. bool isInvalid = false;
  9065. addr_target appendAddr = 0;
  9066. for (int stackIdx = 0; true; stackIdx++)
  9067. {
  9068. auto subProgram = mDebugTarget->FindSubProgram(registers.GetPC(), DbgOnDemandKind_LocalOnly);
  9069. if (subProgram != NULL)
  9070. {
  9071. if (subProgram->mLineInfo != NULL)
  9072. {
  9073. DbgModule* module = subProgram->mCompileUnit->mDbgModule;
  9074. DbgModule* linkedModule = module->GetLinkedModule();
  9075. if (linkedModule->mDisplayName.length() > 0)
  9076. {
  9077. locString = linkedModule->mDisplayName + "!" + subProgram->ToString();
  9078. if (!hadThreadName)
  9079. threadName = module->mDisplayName + " thread";
  9080. }
  9081. else
  9082. {
  9083. locString = subProgram->ToString();
  9084. }
  9085. appendAddr = 0;
  9086. break;
  9087. }
  9088. }
  9089. DbgModule* module = mDebugTarget->FindDbgModuleForAddress(registers.GetPC());
  9090. if (module == NULL)
  9091. {
  9092. isInvalid = true;
  9093. break;
  9094. }
  9095. DbgModule* linkedModule = module->GetLinkedModule();
  9096. appendAddr = (addr_target)registers.GetPC();
  9097. locString = linkedModule->mDisplayName + "!" + EncodeDataPtr((addr_target)registers.GetPC(), true);
  9098. if (!hadThreadName)
  9099. threadName = linkedModule->mDisplayName + " thread";
  9100. if ((mActiveThread == mExplicitStopThread) && (mActiveBreakpoint != NULL))
  9101. {
  9102. if ((subProgram == NULL) ||
  9103. (mActiveBreakpoint->mAddr < subProgram->mBlock.mLowPC) ||
  9104. (mActiveBreakpoint->mAddr >= subProgram->mBlock.mHighPC))
  9105. break;
  9106. }
  9107. if (pass == 1) // Just take the first item
  9108. break;
  9109. if (stackIdx == 128)
  9110. break; // Too many!
  9111. addr_target returnAddr;
  9112. if (!mDebugTarget->RollBackStackFrame(&registers, &returnAddr, true))
  9113. {
  9114. isInvalid = true;
  9115. break;
  9116. }
  9117. }
  9118. if ((isInvalid) && (pass == 0))
  9119. continue;
  9120. if (appendAddr != 0)
  9121. {
  9122. String symbolName;
  9123. addr_target offset;
  9124. DbgModule* dwarf;
  9125. if (mDebugTarget->FindSymbolAt(appendAddr, &symbolName, &offset, &dwarf))
  9126. {
  9127. DbgModule* linkedModule = dwarf->GetLinkedModule();
  9128. String demangledName = BfDemangler::Demangle(symbolName, DbgLanguage_Unknown);
  9129. if (!linkedModule->mDisplayName.empty())
  9130. {
  9131. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  9132. }
  9133. locString = demangledName + StrFormat("+0x%X", offset);
  9134. }
  9135. }
  9136. retStr += StrFormat("%d\t%s\t%s", threadInfo->mThreadId, threadName.c_str(), locString.c_str());
  9137. String attrs;
  9138. if (threadInfo->mFrozen)
  9139. {
  9140. attrs += "Fr";
  9141. }
  9142. if (!attrs.IsEmpty())
  9143. {
  9144. retStr += "\t";
  9145. retStr += attrs;
  9146. }
  9147. break;
  9148. }
  9149. }
  9150. }
  9151. return retStr;
  9152. }
  9153. void WinDebugger::SetActiveThread(int threadId)
  9154. {
  9155. AutoCrit autoCrit(mDebugManager->mCritSect);
  9156. if (mThreadMap.TryGetValue(threadId, &mActiveThread))
  9157. {
  9158. BfLogDbg("SetActiveThread %d\n", threadId);
  9159. ClearCallStack();
  9160. }
  9161. else
  9162. {
  9163. BfLogDbg("SetActiveThread %d FAILED\n", threadId);
  9164. }
  9165. }
  9166. int WinDebugger::GetActiveThread()
  9167. {
  9168. AutoCrit autoCrit(mDebugManager->mCritSect);
  9169. if (mActiveThread == NULL)
  9170. return -1;
  9171. return mActiveThread->mThreadId;
  9172. }
  9173. void WinDebugger::FreezeThread(int threadId)
  9174. {
  9175. AutoCrit autoCrit(mDebugManager->mCritSect);
  9176. BF_ASSERT(!IsInRunState());
  9177. auto thread = mThreadMap[threadId];
  9178. if (!thread->mFrozen)
  9179. {
  9180. thread->mFrozen = true;
  9181. ::SuspendThread(thread->mHThread);
  9182. BfLogDbg("SuspendThread %d from FreezeThread\n", thread->mThreadId);
  9183. }
  9184. }
  9185. void WinDebugger::ThawThread(int threadId)
  9186. {
  9187. AutoCrit autoCrit(mDebugManager->mCritSect);
  9188. BF_ASSERT(!IsInRunState());
  9189. auto thread = mThreadMap[threadId];
  9190. if (thread->mFrozen)
  9191. {
  9192. thread->mFrozen = false;
  9193. ::ResumeThread(thread->mHThread);
  9194. BfLogDbg("ResumeThread %d from ThawThread\n", thread->mThreadId);
  9195. }
  9196. }
  9197. bool WinDebugger::IsActiveThreadWaiting()
  9198. {
  9199. AutoCrit autoCrit(mDebugManager->mCritSect);
  9200. return mActiveThread == mDebuggerWaitingThread;
  9201. }
  9202. void WinDebugger::ClearCallStack()
  9203. {
  9204. AutoCrit autoCrit(mDebugManager->mCritSect);
  9205. BfLogDbg("ClearCallstack\n");
  9206. BF_ASSERT(mRunState != RunState_DebugEval);
  9207. for (auto wdStackFrame : mCallStack)
  9208. delete wdStackFrame;
  9209. mCallStack.Clear();
  9210. mIsPartialCallStack = true;
  9211. }
  9212. void WinDebugger::UpdateCallStack(bool slowEarlyOut)
  9213. {
  9214. AutoCrit autoCrit(mDebugManager->mCritSect);
  9215. if (!mIsPartialCallStack)
  9216. return;
  9217. BF_ASSERT(!IsInRunState());
  9218. uint32 tickStart = BFTickCount();
  9219. CPURegisters registers;
  9220. if (mCallStack.size() > 0)
  9221. {
  9222. WdStackFrame* wdStackFrame = mCallStack.back();
  9223. if (wdStackFrame->mIsEnd)
  9224. {
  9225. return;
  9226. }
  9227. memcpy(&registers, &wdStackFrame->mRegisters, sizeof(registers));
  9228. bool regsRolledBack = RollBackStackFrame(&registers, mCallStack.size() == 1);
  9229. // If we can't roll them back then mIsEnd should have been set for the previous frame
  9230. BF_ASSERT(regsRolledBack);
  9231. }
  9232. else
  9233. {
  9234. BF_ASSERT(mIsPartialCallStack);
  9235. mCallStack.Reserve(1024);
  9236. PopulateRegisters(&registers);
  9237. BfLogDbg("UpdateCallStack starting. Thread=%d PC=0x%p\n", mActiveThread->mThreadId, registers.GetPC());
  9238. }
  9239. bool isPartial = false;
  9240. // Incrementally fill callstack structure to avoid stepping slowdown during deep nesting
  9241. for (int fillIdx = 0; fillIdx < (slowEarlyOut ? 10000 : 100000); fillIdx++)
  9242. {
  9243. WdStackFrame* wdStackFrame = new WdStackFrame();
  9244. memcpy(&wdStackFrame->mRegisters, &registers, sizeof(registers));
  9245. wdStackFrame->mIsStart = mCallStack.size() == 0;
  9246. wdStackFrame->mIsEnd = false;
  9247. bool rollbackSuccess = false;
  9248. for (int tryCount = 0; tryCount < 16; tryCount++)
  9249. {
  9250. if (!RollBackStackFrame(&registers, wdStackFrame->mIsStart))
  9251. {
  9252. break;
  9253. }
  9254. if (registers.GetPC() > 0xFFFF)
  9255. {
  9256. rollbackSuccess = true;
  9257. break;
  9258. }
  9259. if (mCallStack.size() > 0)
  9260. break; // Only retry for the first frame
  9261. }
  9262. if (!rollbackSuccess)
  9263. wdStackFrame->mIsEnd = true;
  9264. if (registers.GetSP() <= wdStackFrame->mRegisters.GetSP())
  9265. {
  9266. // SP went the wrong direction, stop rolling back
  9267. wdStackFrame->mIsEnd = true;
  9268. }
  9269. mCallStack.push_back(wdStackFrame);
  9270. if (IsMiniDumpDebugger())
  9271. {
  9272. // Make sure to queue up any debug stuff we need
  9273. UpdateCallStackMethod((int)mCallStack.size() - 1);
  9274. }
  9275. if (wdStackFrame->mIsEnd)
  9276. break;
  9277. // Time-limit callstack generation. Most useful for debug mode.
  9278. if ((slowEarlyOut) && ((fillIdx % 100) == 0))
  9279. {
  9280. uint32 tickEnd = BFTickCount();
  9281. if (tickEnd - tickStart >= 10)
  9282. {
  9283. isPartial = true;
  9284. break;
  9285. }
  9286. }
  9287. }
  9288. if (!isPartial)
  9289. mIsPartialCallStack = false;
  9290. }
  9291. int WinDebugger::GetCallStackCount()
  9292. {
  9293. AutoCrit autoCrit(mDebugManager->mCritSect);
  9294. return (int)mCallStack.size();
  9295. }
  9296. int WinDebugger::GetRequestedStackFrameIdx()
  9297. {
  9298. AutoCrit autoCrit(mDebugManager->mCritSect);
  9299. if ((mActiveThread == mExplicitStopThread) && (mRequestedStackFrameIdx >= -1))
  9300. {
  9301. if (mActiveBreakpoint != NULL)
  9302. mRequestedStackFrameIdx = GetBreakStackFrameIdx();
  9303. if (mRequestedStackFrameIdx == -1)
  9304. mRequestedStackFrameIdx = 0;
  9305. return mRequestedStackFrameIdx;
  9306. }
  9307. int newCallStackIdx = 0;
  9308. while (true)
  9309. {
  9310. if (newCallStackIdx >= (int)mCallStack.size() - 1)
  9311. UpdateCallStack();
  9312. if (newCallStackIdx >= (int)mCallStack.size() - 1)
  9313. break;
  9314. intptr addr;
  9315. String file;
  9316. int hotIdx;
  9317. int defLineStart;
  9318. int defLineEnd;
  9319. int line;
  9320. int column;
  9321. int language;
  9322. int stackSize;
  9323. int8 flags;
  9324. GetStackFrameInfo(newCallStackIdx, &addr, &file, &hotIdx, &defLineStart, &defLineEnd, &line, &column, &language, &stackSize, &flags);
  9325. if (!file.empty())
  9326. return newCallStackIdx;
  9327. newCallStackIdx++;
  9328. }
  9329. return 0;
  9330. }
  9331. int WinDebugger::GetBreakStackFrameIdx()
  9332. {
  9333. AutoCrit autoCrit(mDebugManager->mCritSect);
  9334. if ((mActiveBreakpoint == NULL) || (mRunState != RunState_Breakpoint))
  9335. return -1;
  9336. if ((mBreakStackFrameIdx != -1) || (mActiveThread != mExplicitStopThread))
  9337. return mBreakStackFrameIdx;
  9338. mBreakStackFrameIdx = 0;
  9339. BF_ASSERT(mActiveBreakpoint != NULL);
  9340. if (mCallStack.IsEmpty())
  9341. UpdateCallStack();
  9342. if (!mCallStack.IsEmpty())
  9343. {
  9344. UpdateCallStackMethod(0);
  9345. for (int stackIdx = 0; stackIdx < (int)mCallStack.size(); stackIdx++)
  9346. {
  9347. auto callStackEntry = mCallStack[stackIdx];
  9348. if (callStackEntry->mSubProgram == NULL)
  9349. break;
  9350. if ((mActiveBreakpoint->mAddr < callStackEntry->mSubProgram->mBlock.mLowPC) ||
  9351. (mActiveBreakpoint->mAddr >= callStackEntry->mSubProgram->mBlock.mHighPC))
  9352. break;
  9353. DbgSubprogram* specificSubprogram = callStackEntry->mSubProgram;
  9354. auto dwLineData = callStackEntry->mSubProgram->FindClosestLine(mActiveBreakpoint->mAddr, &specificSubprogram);
  9355. if (dwLineData == NULL)
  9356. break;
  9357. if (mActiveBreakpoint->mLineData == dwLineData)
  9358. {
  9359. mBreakStackFrameIdx = stackIdx;
  9360. break;
  9361. }
  9362. }
  9363. }
  9364. return mBreakStackFrameIdx;
  9365. }
  9366. static const char* SafeString(const char* str)
  9367. {
  9368. if (str == NULL)
  9369. return "???";
  9370. return str;
  9371. }
  9372. void WinDebugger::UpdateRegisterUsage(int stackFrameIdx)
  9373. {
  9374. WdStackFrame* wdStackFrame = mCallStack[stackFrameIdx];
  9375. if (wdStackFrame->mRegForms.size() != 0)
  9376. return;
  9377. auto dwSubprogram = wdStackFrame->mSubProgram;
  9378. if (dwSubprogram == NULL)
  9379. return;
  9380. addr_target addr = dwSubprogram->mBlock.mLowPC;
  9381. const uint8* baseOp = nullptr;
  9382. while (addr < dwSubprogram->mBlock.mHighPC)
  9383. {
  9384. CPUInst inst;
  9385. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  9386. break;
  9387. bool overrideForm = inst.mAddress <= (addr_target)wdStackFrame->mRegisters.GetPC();
  9388. inst.MarkRegsUsed(wdStackFrame->mRegForms, overrideForm);
  9389. addr += inst.GetLength();
  9390. }
  9391. }
  9392. // It's safe to pass an invalid idx in here
  9393. void WinDebugger::UpdateCallStackMethod(int stackFrameIdx)
  9394. {
  9395. if (mCallStack.empty())
  9396. return;
  9397. int startIdx = std::min(stackFrameIdx, (int)mCallStack.size() - 1);
  9398. while (startIdx >= 0)
  9399. {
  9400. WdStackFrame* wdStackFrame = mCallStack[startIdx];
  9401. if (wdStackFrame->mHasGottenSubProgram)
  9402. break;
  9403. startIdx--;
  9404. }
  9405. startIdx++;
  9406. for (int checkFrameIdx = startIdx; checkFrameIdx <= stackFrameIdx; checkFrameIdx++)
  9407. {
  9408. //BF_ASSERT(checkFrameIdx < mCallStack.size());
  9409. if (checkFrameIdx >= mCallStack.size())
  9410. break;
  9411. WdStackFrame* wdStackFrame = mCallStack[checkFrameIdx];
  9412. wdStackFrame->mHasGottenSubProgram = true;
  9413. addr_target pcAddress = (addr_target)wdStackFrame->GetSourcePC();
  9414. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress, DbgOnDemandKind_LocalOnly);
  9415. wdStackFrame->mHasGottenSubProgram = true;
  9416. wdStackFrame->mSubProgram = dwSubprogram;
  9417. if ((dwSubprogram == NULL) && (IsMiniDumpDebugger()))
  9418. {
  9419. // FindSymbolAt will queue up debug info if necessary...
  9420. String symbolName;
  9421. addr_target offset;
  9422. DbgModule* dbgModule;
  9423. mDebugTarget->FindSymbolAt(pcAddress, &symbolName, &offset, &dbgModule);
  9424. }
  9425. // Insert inlines
  9426. int insertIdx = checkFrameIdx + 1;
  9427. while ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL))
  9428. {
  9429. WdStackFrame* inlineStackFrame = new WdStackFrame();
  9430. *inlineStackFrame = *wdStackFrame;
  9431. inlineStackFrame->mInInlineMethod = true;
  9432. wdStackFrame->mInInlineCall = true;
  9433. inlineStackFrame->mSubProgram = dwSubprogram->mInlineeInfo->mInlineParent;
  9434. mCallStack.Insert(insertIdx, inlineStackFrame);
  9435. dwSubprogram = dwSubprogram->mInlineeInfo->mInlineParent;
  9436. insertIdx++;
  9437. checkFrameIdx++;
  9438. }
  9439. }
  9440. }
  9441. void WinDebugger::GetCodeAddrInfo(intptr addr, String* outFile, int* outHotIdx, int* outDefLineStart, int* outDefLineEnd, int* outLine, int* outColumn)
  9442. {
  9443. AutoCrit autoCrit(mDebugManager->mCritSect);
  9444. DbgSubprogram* subProgram = NULL;
  9445. DbgLineData* callingLineData = FindLineDataAtAddress((addr_target)addr, &subProgram);
  9446. if (subProgram != NULL)
  9447. {
  9448. *outHotIdx = subProgram->mCompileUnit->mDbgModule->mHotIdx;
  9449. *outFile = subProgram->GetLineSrcFile(*callingLineData)->GetLocalPath();
  9450. *outLine = callingLineData->mLine;
  9451. *outColumn = callingLineData->mColumn;
  9452. FixupLineDataForSubprogram(subProgram);
  9453. DbgLineData* dwStartLineData = NULL;
  9454. DbgLineData* dwEndLineData = NULL;
  9455. if (subProgram->mLineInfo != NULL)
  9456. {
  9457. if (subProgram->mLineInfo->mLines.size() > 0)
  9458. {
  9459. dwStartLineData = &subProgram->mLineInfo->mLines[0];
  9460. dwEndLineData = &subProgram->mLineInfo->mLines.back();
  9461. }
  9462. }
  9463. else
  9464. {
  9465. if (subProgram->mInlineeInfo != NULL)
  9466. {
  9467. dwStartLineData = &subProgram->mInlineeInfo->mFirstLineData;
  9468. dwEndLineData = &subProgram->mInlineeInfo->mLastLineData;
  9469. }
  9470. }
  9471. if (dwEndLineData != NULL)
  9472. {
  9473. *outDefLineStart = dwStartLineData->mLine;
  9474. *outDefLineEnd = dwEndLineData->mLine;
  9475. }
  9476. }
  9477. }
  9478. void WinDebugger::GetStackAllocInfo(intptr addr, int* outThreadId, int* outStackIdx)
  9479. {
  9480. AutoCrit autoCrit(mDebugManager->mCritSect);
  9481. *outThreadId = 0;
  9482. if (outStackIdx != NULL)
  9483. *outStackIdx = -1;
  9484. if (!IsPaused())
  9485. return;
  9486. for (auto thread : mThreadList)
  9487. {
  9488. NT_TIB64 tib = { 0 };
  9489. if (!ReadMemory((intptr)thread->mThreadLocalBase, sizeof(tib), &tib))
  9490. continue;
  9491. MEMORY_BASIC_INFORMATION stackInfo = { 0 };
  9492. if (VirtualQueryEx(mProcessInfo.hProcess, (void*)(tib.StackBase - 1), &stackInfo, sizeof(MEMORY_BASIC_INFORMATION)) == 0)
  9493. continue;
  9494. if ((addr >= (intptr)stackInfo.AllocationBase) && (addr < (intptr)tib.StackBase))
  9495. {
  9496. *outThreadId = thread->mThreadId;
  9497. if (outStackIdx == NULL)
  9498. return;
  9499. if (mActiveThread == thread)
  9500. {
  9501. UpdateCallStack(false);
  9502. for (int callStackIdx = 0; callStackIdx < (int)mCallStack.size(); callStackIdx++)
  9503. {
  9504. UpdateCallStackMethod(callStackIdx);
  9505. auto stackFrame = mCallStack[callStackIdx];
  9506. if (addr >= (intptr)stackFrame->mRegisters.GetSP())
  9507. {
  9508. *outStackIdx = callStackIdx;
  9509. }
  9510. }
  9511. }
  9512. return;
  9513. }
  9514. }
  9515. }
  9516. String WinDebugger::GetStackFrameInfo(int stackFrameIdx, intptr* addr, String* outFile, int* outHotIdx, int* outDefLineStart, int* outDefLineEnd,
  9517. int* outLine, int* outColumn, int* outLanguage, int* outStackSize, int8* outFlags)
  9518. {
  9519. enum FrameFlags
  9520. {
  9521. FrameFlags_Optimized = 1,
  9522. FrameFlags_HasPendingDebugInfo = 2,
  9523. FrameFlags_CanGetOldSource = 4,
  9524. FrameFlags_WasHotReplaced = 8,
  9525. };
  9526. AutoCrit autoCrit(mDebugManager->mCritSect);
  9527. if (mCallStack.size() == 0)
  9528. UpdateCallStack();
  9529. *addr = 0;
  9530. *outFile = "";
  9531. *outHotIdx = 0;
  9532. *outDefLineStart = -1;
  9533. *outDefLineEnd = -1;
  9534. *outLine = -1;
  9535. *outColumn = 0;
  9536. *outLanguage = 0;
  9537. *outStackSize = 0;
  9538. *outFlags = 0;
  9539. UpdateCallStackMethod(stackFrameIdx);
  9540. if (stackFrameIdx >= mCallStack.size())
  9541. {
  9542. return "";
  9543. }
  9544. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9545. UpdateCallStackMethod(actualStackFrameIdx);
  9546. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9547. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  9548. if (stackFrameIdx == -1)
  9549. pcAddress = mShowPCOverride;
  9550. *addr = pcAddress;
  9551. if (actualStackFrameIdx < (int)mCallStack.size() - 2)
  9552. {
  9553. WdStackFrame* prevStackFrame = mCallStack[actualStackFrameIdx + 1];
  9554. // Inlined methods have no stack frame
  9555. *outStackSize = prevStackFrame->mRegisters.GetSP() - wdStackFrame->mRegisters.GetSP();
  9556. }
  9557. const auto& _CheckHashSrcFile = [&](String& outStr, DbgModule* dbgModule, DbgSrcFile* srcFile)
  9558. {
  9559. if (srcFile->mHashKind != DbgHashKind_None)
  9560. {
  9561. outStr += "#";
  9562. srcFile->GetHash(outStr);
  9563. }
  9564. };
  9565. auto _SetFlags = [&](DbgSubprogram* dwSubprogram)
  9566. {
  9567. DbgModule* dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  9568. if (dwSubprogram->mIsOptimized)
  9569. *outFlags |= FrameFlags_Optimized;
  9570. if (dbgModule->HasPendingDebugInfo())
  9571. *outFlags |= FrameFlags_HasPendingDebugInfo;
  9572. if (dbgModule->CanGetOldSource())
  9573. *outFlags |= FrameFlags_CanGetOldSource;
  9574. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) || (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid))
  9575. *outFlags |= FrameFlags_WasHotReplaced;
  9576. };
  9577. if (wdStackFrame->mInInlineMethod)
  9578. {
  9579. WdStackFrame* nextStackFrame = mCallStack[actualStackFrameIdx - 1];
  9580. auto subProgram = nextStackFrame->mSubProgram;
  9581. _SetFlags(subProgram);
  9582. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  9583. DbgSubprogram* parentSubprogram = subProgram->mInlineeInfo->mInlineParent; // Require it be in the inline parent
  9584. auto foundLine = parentSubprogram->FindClosestLine(subProgram->mBlock.mLowPC, &parentSubprogram);
  9585. if (foundLine != NULL)
  9586. {
  9587. auto srcFile = parentSubprogram->GetLineSrcFile(*foundLine);
  9588. *outFile = srcFile->GetLocalPath();
  9589. _CheckHashSrcFile(*outFile, subProgram->mCompileUnit->mDbgModule, srcFile);
  9590. *outLine = foundLine->mLine;
  9591. }
  9592. *outLanguage = subProgram->GetLanguage();
  9593. *outHotIdx = subProgram->mCompileUnit->mDbgModule->mHotIdx;
  9594. *outColumn = -1;
  9595. DbgSubprogram* callingSubProgram = NULL;
  9596. DbgLineData* callingLineData = FindLineDataAtAddress(nextStackFrame->mSubProgram->mBlock.mLowPC - 1, &callingSubProgram);
  9597. if ((callingLineData != NULL) && (callingSubProgram == wdStackFrame->mSubProgram))
  9598. {
  9599. auto callingSrcFile = callingSubProgram->GetLineSrcFile(*callingLineData);
  9600. *outLanguage = callingSubProgram->mCompileUnit->mLanguage;
  9601. auto srcFile = callingSrcFile;
  9602. *outFile = srcFile->GetLocalPath();
  9603. _CheckHashSrcFile(*outFile, subProgram->mCompileUnit->mDbgModule, srcFile);
  9604. if (*outLine == callingLineData->mLine)
  9605. *outColumn = callingLineData->mColumn;
  9606. }
  9607. String name = wdStackFrame->mSubProgram->ToString();
  9608. DbgModule* dbgModule = wdStackFrame->mSubProgram->mCompileUnit->mDbgModule;
  9609. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  9610. if (!linkedModule->mDisplayName.empty())
  9611. name = linkedModule->mDisplayName + "!" + name;
  9612. return name;
  9613. }
  9614. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  9615. if (dwSubprogram != NULL)
  9616. {
  9617. String demangledName;
  9618. if ((dwSubprogram->mName != NULL) && (strncmp(dwSubprogram->mName, ":Sep@", 5) == 0))
  9619. {
  9620. char* p;
  9621. auto addr = strtoll(dwSubprogram->mName + 5, &p, 16);
  9622. if (addr != 0)
  9623. {
  9624. auto parentSubprogram = mDebugTarget->FindSubProgram(addr);
  9625. if (parentSubprogram != NULL)
  9626. demangledName = parentSubprogram->ToString();
  9627. }
  9628. }
  9629. if (demangledName.IsEmpty())
  9630. {
  9631. dwSubprogram->ToString(demangledName, true);
  9632. }
  9633. DbgSrcFile* dwSrcFile = NULL;
  9634. DbgLineData* dwLineData = NULL;
  9635. FixupLineDataForSubprogram(dwSubprogram);
  9636. addr_target findAddress = wdStackFrame->GetSourcePC();
  9637. DbgSubprogram* specificSubprogram = dwSubprogram;
  9638. dwLineData = dwSubprogram->FindClosestLine(findAddress, &specificSubprogram);
  9639. if (dwLineData != NULL)
  9640. dwSrcFile = dwSubprogram->GetLineSrcFile(*dwLineData);
  9641. DbgLineData* dwStartLineData = NULL;
  9642. DbgLineData* dwEndLineData = NULL;
  9643. if (dwSubprogram->mLineInfo != NULL)
  9644. {
  9645. if (dwSubprogram->mLineInfo->mLines.size() > 0)
  9646. {
  9647. dwStartLineData = &dwSubprogram->mLineInfo->mLines[0];
  9648. dwEndLineData = &dwSubprogram->mLineInfo->mLines.back();
  9649. }
  9650. }
  9651. else
  9652. {
  9653. if (dwSubprogram->mInlineeInfo != NULL)
  9654. {
  9655. dwStartLineData = &dwSubprogram->mInlineeInfo->mFirstLineData;
  9656. dwEndLineData = &dwSubprogram->mInlineeInfo->mLastLineData;
  9657. }
  9658. }
  9659. DbgModule* dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  9660. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  9661. if (!linkedModule->mDisplayName.empty())
  9662. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  9663. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) || (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid))
  9664. demangledName = "#" + demangledName;
  9665. _SetFlags(dwSubprogram);
  9666. if ((dwLineData != NULL) && (dwSrcFile != NULL))
  9667. {
  9668. *outFile = dwSrcFile->GetLocalPath();
  9669. _CheckHashSrcFile(*outFile, dbgModule, dwSrcFile);
  9670. *outHotIdx = dbgModule->mHotIdx;
  9671. *outLine = dwLineData->mLine;
  9672. *outColumn = dwLineData->mColumn;
  9673. *outLanguage = (int)dwSubprogram->mCompileUnit->mLanguage;
  9674. if (dwEndLineData != NULL)
  9675. {
  9676. *outDefLineStart = dwStartLineData->mLine;
  9677. *outDefLineEnd = dwEndLineData->mLine;
  9678. }
  9679. return demangledName;
  9680. }
  9681. else
  9682. {
  9683. return demangledName + StrFormat("+0x%X", pcAddress - dwSubprogram->mBlock.mLowPC);
  9684. }
  9685. }
  9686. else
  9687. {
  9688. String symbolName;
  9689. addr_target offset;
  9690. DbgModule* dbgModule;
  9691. if (mDebugTarget->FindSymbolAt(pcAddress, &symbolName, &offset, &dbgModule))
  9692. {
  9693. if (dbgModule->HasPendingDebugInfo())
  9694. {
  9695. *outFlags |= FrameFlags_HasPendingDebugInfo;
  9696. if (mPendingDebugInfoLoad.ContainsKey(dbgModule))
  9697. {
  9698. String outName = EncodeDataPtr(pcAddress, true);
  9699. if ((dbgModule != NULL) && (!dbgModule->mDisplayName.empty()))
  9700. outName = dbgModule->mDisplayName + "!<Loading...>" + outName;
  9701. return outName;
  9702. }
  9703. }
  9704. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  9705. String demangledName = BfDemangler::Demangle(symbolName, DbgLanguage_Unknown);
  9706. if (!linkedModule->mDisplayName.empty())
  9707. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  9708. return demangledName + StrFormat("+0x%X", offset);
  9709. }
  9710. }
  9711. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress(pcAddress);
  9712. DbgModule* linkedModule = NULL;
  9713. if (dbgModule != NULL)
  9714. {
  9715. linkedModule = dbgModule->GetLinkedModule();
  9716. if (dbgModule->HasPendingDebugInfo())
  9717. *outFlags |= FrameFlags_HasPendingDebugInfo;
  9718. }
  9719. String outName = EncodeDataPtr(pcAddress, true);
  9720. if ((linkedModule != NULL) && (!linkedModule->mDisplayName.empty()))
  9721. outName = linkedModule->mDisplayName + "!" + outName;
  9722. return outName;
  9723. }
  9724. String WinDebugger::Callstack_GetStackFrameOldFileInfo(int stackFrameIdx)
  9725. {
  9726. AutoCrit autoCrit(mDebugManager->mCritSect);
  9727. if (!FixCallStackIdx(stackFrameIdx))
  9728. return "";
  9729. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9730. UpdateCallStackMethod(actualStackFrameIdx);
  9731. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9732. DbgModule* dbgModule = NULL;
  9733. DbgSrcFile* dbgSrcFile = NULL;
  9734. if (wdStackFrame->mInInlineMethod)
  9735. {
  9736. WdStackFrame* nextStackFrame = mCallStack[actualStackFrameIdx - 1];
  9737. auto subProgram = nextStackFrame->mSubProgram;
  9738. dbgModule = subProgram->mCompileUnit->mDbgModule;
  9739. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  9740. DbgSubprogram* parentSubprogram = subProgram->mInlineeInfo->mInlineParent; // Require it be in the inline parent
  9741. auto foundLine = parentSubprogram->FindClosestLine(subProgram->mBlock.mLowPC, &parentSubprogram);
  9742. if (foundLine != NULL)
  9743. dbgSrcFile = parentSubprogram->GetLineSrcFile(*foundLine);
  9744. DbgSubprogram* callingSubProgram = NULL;
  9745. DbgLineData* callingLineData = FindLineDataAtAddress(nextStackFrame->mSubProgram->mBlock.mLowPC - 1, &callingSubProgram);
  9746. if ((callingLineData != NULL) && (callingSubProgram == wdStackFrame->mSubProgram))
  9747. dbgSrcFile = callingSubProgram->GetLineSrcFile(*callingLineData);
  9748. }
  9749. else
  9750. {
  9751. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  9752. if (dwSubprogram != NULL)
  9753. {
  9754. FixupLineDataForSubprogram(dwSubprogram);
  9755. addr_target findAddress = wdStackFrame->GetSourcePC();
  9756. DbgSubprogram* dbgSubprogram = NULL;
  9757. DbgLineData* dwLineData = dwSubprogram->FindClosestLine(findAddress, &dbgSubprogram, &dbgSrcFile);
  9758. dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  9759. }
  9760. }
  9761. if (dbgSrcFile != NULL)
  9762. {
  9763. // Note: we must use mFilePath here, make sure we don't use GetLocalPath()
  9764. return dbgModule->GetOldSourceCommand(dbgSrcFile->mFilePath);
  9765. }
  9766. return "";
  9767. }
  9768. int WinDebugger::GetJmpState(int stackFrameIdx)
  9769. {
  9770. AutoCrit autoCrit(mDebugManager->mCritSect);
  9771. if (!FixCallStackIdx(stackFrameIdx))
  9772. return -1;
  9773. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9774. UpdateCallStackMethod(actualStackFrameIdx);
  9775. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9776. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  9777. CPUInst inst;
  9778. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  9779. return -1;
  9780. return inst.GetJmpState(wdStackFrame->mRegisters.mIntRegs.efl);
  9781. }
  9782. intptr WinDebugger::GetStackFrameCalleeAddr(int stackFrameIdx)
  9783. {
  9784. AutoCrit autoCrit(mDebugManager->mCritSect);
  9785. if (!FixCallStackIdx(stackFrameIdx))
  9786. return -1;
  9787. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9788. UpdateCallStackMethod(actualStackFrameIdx);
  9789. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9790. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  9791. if (stackFrameIdx == -1)
  9792. pcAddress = mShowPCOverride;
  9793. if (wdStackFrame->mInInlineMethod)
  9794. {
  9795. WdStackFrame* inlineStackFrame = mCallStack[actualStackFrameIdx - 1];
  9796. return inlineStackFrame->mSubProgram->mBlock.mLowPC - 1;
  9797. }
  9798. return pcAddress - 1;
  9799. }
  9800. String WinDebugger::GetStackMethodOwner(int stackFrameIdx, int& language)
  9801. {
  9802. AutoCrit autoCrit(mDebugManager->mCritSect);
  9803. if (!FixCallStackIdx(stackFrameIdx))
  9804. return "";
  9805. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9806. if (actualStackFrameIdx >= (int)mCallStack.size())
  9807. actualStackFrameIdx = 0;
  9808. UpdateCallStackMethod(actualStackFrameIdx);
  9809. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9810. if (wdStackFrame->mSubProgram == NULL)
  9811. return "";
  9812. auto parentType = wdStackFrame->mSubProgram->GetParent();
  9813. if (parentType == NULL)
  9814. return "";
  9815. parentType = parentType->GetPrimaryType();
  9816. language = (int)parentType->GetLanguage();
  9817. return parentType->ToString();
  9818. }
  9819. String WinDebugger::FindCodeAddresses(const StringImpl& fileName, int line, int column, bool allowAutoResolve)
  9820. {
  9821. String result;
  9822. if (mDebugTarget == NULL)
  9823. return "";
  9824. DbgSrcFile* srcFile = mDebugTarget->GetSrcFile(fileName);
  9825. if (srcFile == NULL)
  9826. return result;
  9827. bool foundInSequence = false;
  9828. WdBreakpoint* prevBreakpoint = NULL;
  9829. int bestLineOffset = 0x7FFFFFFF;
  9830. for (auto dbgSubprogram : srcFile->mLineDataRefs)
  9831. {
  9832. for (auto& lineData : dbgSubprogram->mLineInfo->mLines)
  9833. {
  9834. auto lineSrcFile = dbgSubprogram->GetLineSrcFile(lineData);
  9835. if (lineSrcFile != srcFile)
  9836. continue;
  9837. int lineOffset = lineData.mLine - line;
  9838. if ((lineOffset >= 0) && (lineOffset <= 12) && (lineOffset <= bestLineOffset))
  9839. {
  9840. if (lineOffset < bestLineOffset)
  9841. {
  9842. bestLineOffset = lineOffset;
  9843. result = "";
  9844. }
  9845. if (!foundInSequence)
  9846. {
  9847. auto addr = dbgSubprogram->GetLineAddr(lineData);
  9848. result += EncodeDataPtr(addr, false) + "\t" + dbgSubprogram->ToString() + "\n";
  9849. }
  9850. }
  9851. // New sequence?
  9852. if (!lineData.IsStackFrameSetup())
  9853. foundInSequence = false;
  9854. }
  9855. }
  9856. return result;
  9857. }
  9858. String WinDebugger::GetAddressSourceLocation(intptr address)
  9859. {
  9860. DbgSubprogram* subProgram = NULL;
  9861. DbgLineData* lineData = FindLineDataAtAddress(address, &subProgram);
  9862. if (lineData != NULL)
  9863. return StrFormat("%s:%d:%d", subProgram->GetLineSrcFile(*lineData)->GetLocalPath().c_str(), lineData->mLine + 1, lineData->mColumn + 1);
  9864. String outSymbol;
  9865. addr_target offset = 0;
  9866. DbgModule* dbgModule;
  9867. if (mDebugTarget->FindSymbolAt(address, &outSymbol, &offset, &dbgModule))
  9868. {
  9869. if (offset < 0x10000)
  9870. {
  9871. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9872. if (offset > 0)
  9873. outSymbol += StrFormat("+%x", offset);
  9874. return outSymbol;
  9875. }
  9876. }
  9877. return StrFormat("0x%@", address);
  9878. }
  9879. String WinDebugger::GetAddressSymbolName(intptr address, bool demangle)
  9880. {
  9881. String outSymbol;
  9882. addr_target offset = 0;
  9883. DbgModule* dbgModule;
  9884. if (mDebugTarget->FindSymbolAt(address, &outSymbol, &offset, &dbgModule))
  9885. {
  9886. if (offset < 0x10000)
  9887. {
  9888. if (demangle)
  9889. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9890. if (offset > 0)
  9891. outSymbol += StrFormat("+%x", offset);
  9892. return outSymbol;
  9893. }
  9894. }
  9895. return StrFormat("0x%@", address);
  9896. }
  9897. String WinDebugger::DisassembleAtRaw(intptr inAddress)
  9898. {
  9899. addr_target address = (addr_target)inAddress;
  9900. const int addrBorder = 1024;
  9901. for (int offset = 0; offset < 8; offset++)
  9902. {
  9903. String result;
  9904. bool addOffset = true;
  9905. bool hadAddr = false;
  9906. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress(address);
  9907. DbgModuleMemoryCache* memCache = NULL;
  9908. defer
  9909. (
  9910. if (dbgModule == NULL)
  9911. delete memCache;
  9912. );
  9913. if ((dbgModule != NULL) && (dbgModule->mOrigImageData == NULL))
  9914. dbgModule = NULL;
  9915. result += "R\n"; // Raw
  9916. addr_target addrStart = address;
  9917. if (dbgModule != NULL)
  9918. {
  9919. dbgModule->ParseSymbolData();
  9920. memCache = dbgModule->mOrigImageData;
  9921. addrStart = BF_MAX((addr_target)dbgModule->mImageBase, address - addrBorder - offset);
  9922. }
  9923. else
  9924. {
  9925. memCache = new DbgModuleMemoryCache(addrStart & (4096 - 1), 4096 * 2);
  9926. }
  9927. //addr_target imageBase = dbgModule->mImageBase;
  9928. //int imageSize = dbgModule->mImageSize;
  9929. addr_target dataAddr = addrStart;
  9930. addr_target addrEnd = addrStart + addrBorder * 2 + 16;
  9931. while (dataAddr < addrEnd)
  9932. {
  9933. if (dataAddr == address)
  9934. hadAddr = true;
  9935. if (dataAddr > address)
  9936. {
  9937. if (!hadAddr)
  9938. {
  9939. if (offset == 7)
  9940. {
  9941. dataAddr = address;
  9942. }
  9943. break;
  9944. }
  9945. }
  9946. String outSymbol;
  9947. addr_target symOffset = 0;
  9948. DbgModule* symDWARF;
  9949. if (mDebugTarget->FindSymbolAt(dataAddr, &outSymbol, &symOffset, &symDWARF))
  9950. {
  9951. if (symOffset == 0)
  9952. {
  9953. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9954. if ((symDWARF != NULL) && (!symDWARF->mDisplayName.empty()))
  9955. outSymbol = symDWARF->GetLinkedModule()->mDisplayName + "!" + outSymbol;
  9956. result += "T " + outSymbol + ":\n";
  9957. }
  9958. }
  9959. CPUInst inst;
  9960. if (!mCPU->Decode(dataAddr, memCache, &inst))
  9961. {
  9962. if ((offset == 7) && (!hadAddr))
  9963. {
  9964. uint8 instData[1];
  9965. memCache->Read(dataAddr, instData, 1);
  9966. int instLen = 1;
  9967. #ifdef BF_DBG_32
  9968. result += StrFormat("D %08X: ", dataAddr);
  9969. #else
  9970. result += StrFormat("D %@: ", dataAddr);
  9971. #endif
  9972. for (int i = 0; i < instLen; i++)
  9973. result += StrFormat("%02X ", instData[i]);
  9974. for (int i = instLen; i < 8; i++)
  9975. result += " ";
  9976. result += "\n";
  9977. dataAddr++;
  9978. continue;
  9979. }
  9980. break;
  9981. }
  9982. int instLen = inst.GetLength();
  9983. #ifdef BF_DBG_32
  9984. result += StrFormat("D %08X: ", dataAddr);
  9985. #else
  9986. result += StrFormat("D %@: ", dataAddr);
  9987. #endif
  9988. uint8 instData[32];
  9989. int showInstLen = BF_MIN(32, instLen);
  9990. memCache->Read(dataAddr, instData, showInstLen);
  9991. for (int i = 0; i < showInstLen; i++)
  9992. result += StrFormat("%02X ", instData[i]);
  9993. for (int i = instLen; i < 8; i++)
  9994. result += " ";
  9995. result += mCPU->InstructionToString(&inst, dataAddr);
  9996. if ((inst.IsCall()) || (inst.IsBranch()))
  9997. {
  9998. addr_target targetAddr = inst.GetTarget();
  9999. if (targetAddr != 0)
  10000. {
  10001. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &symOffset))
  10002. {
  10003. if (symOffset < 0x10000)
  10004. {
  10005. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  10006. result += " ; " + outSymbol;
  10007. if (symOffset > 0)
  10008. result += StrFormat("+%x", symOffset);
  10009. //result += ">";
  10010. }
  10011. }
  10012. }
  10013. }
  10014. result += "\n";
  10015. dataAddr += instLen;
  10016. }
  10017. if (!hadAddr)
  10018. continue;
  10019. return result;
  10020. }
  10021. return "";
  10022. }
  10023. String WinDebugger::DisassembleAt(intptr inAddress)
  10024. {
  10025. BP_ZONE("WinDebugger::DisassembleAt");
  10026. AutoCrit autoCrit(mDebugManager->mCritSect);
  10027. addr_target address = (addr_target)inAddress;
  10028. if (mDebugTarget == NULL)
  10029. return "";
  10030. String result;
  10031. auto dwSubProgram = mDebugTarget->FindSubProgram(address);
  10032. if (dwSubProgram == NULL)
  10033. return DisassembleAtRaw(address);
  10034. dwSubProgram = dwSubProgram->GetRootInlineParent();
  10035. DbgModule* dwarf = dwSubProgram->mCompileUnit->mDbgModule;
  10036. int frameBaseRegister = mDebugTarget->GetFrameBaseRegister(dwSubProgram);
  10037. addr_target addrStart = dwSubProgram->mBlock.mLowPC;
  10038. addr_target addrEnd = dwSubProgram->mBlock.mHighPC;
  10039. auto dwCompileUnit = dwSubProgram->mCompileUnit;
  10040. {
  10041. FixupLineData(dwCompileUnit);
  10042. }
  10043. DbgSrcFile* dwSrcFile = NULL;
  10044. FixupLineDataForSubprogram(dwSubProgram);
  10045. DbgLineData* dwLineData = NULL;
  10046. if (dwSubProgram->mLineInfo != NULL)
  10047. dwLineData = &dwSubProgram->mLineInfo->mLines[0];
  10048. int nextLineDataIdx = 1;
  10049. if (dwSubProgram->mIsOptimized)
  10050. result += "O\n";
  10051. DbgSrcFile* srcFile = NULL;
  10052. int firstLine = 0;
  10053. int curLine = 0;
  10054. if (dwLineData != NULL)
  10055. {
  10056. srcFile = dwSubProgram->GetLineSrcFile(*dwLineData);
  10057. result += "S " + srcFile->GetLocalPath() + "\n";
  10058. if (srcFile->mHashKind != DbgHashKind_None)
  10059. {
  10060. result += "H ";
  10061. srcFile->GetHash(result);
  10062. result += "\n";
  10063. }
  10064. curLine = BF_MAX(0, dwLineData->mLine - 5);
  10065. //for (; curLine <= dwLineData->mLine; curLine++)
  10066. result += StrFormat("L %d %d\n", curLine, dwLineData->mLine - curLine + 1);
  10067. curLine = dwLineData->mLine + 1;
  10068. firstLine = dwLineData->mLine;
  10069. }
  10070. Array<DbgSubprogram*> inlineStack;
  10071. Array<DbgBlock*> blockList;
  10072. blockList.push_back(&dwSubProgram->mBlock);
  10073. addr_target dataAddr = addrStart;
  10074. int decodeFailureCount = 0;
  10075. auto& _PopInlineStack = [&]()
  10076. {
  10077. int depth = inlineStack.size();
  10078. auto curStackEntry = inlineStack.back();
  10079. if (depth > 1)
  10080. result += StrFormat("T <<<%d Inline End ", depth);
  10081. else
  10082. result += "T <<< Inline End ";
  10083. result += curStackEntry->ToString();
  10084. result += "\n";
  10085. inlineStack.pop_back();
  10086. };
  10087. std::function<void(DbgSubprogram* subprogram, int depth)> _UpdateInlineStackHelper = [&](DbgSubprogram* subprogram, int depth)
  10088. {
  10089. int stackIdx = depth - 1;
  10090. if (stackIdx < inlineStack.size())
  10091. {
  10092. auto curStackEntry = inlineStack[stackIdx];
  10093. if (curStackEntry != subprogram)
  10094. _PopInlineStack();
  10095. }
  10096. if (depth > 1)
  10097. {
  10098. _UpdateInlineStackHelper(subprogram->mInlineeInfo->mInlineParent, depth - 1);
  10099. }
  10100. if (stackIdx >= inlineStack.size())
  10101. {
  10102. if (depth > 1)
  10103. result += StrFormat("T >>>%d Inline ", depth);
  10104. else
  10105. result += "T >>> Inline ";
  10106. result += subprogram->ToString();
  10107. result += "\n";
  10108. inlineStack.push_back(subprogram);
  10109. }
  10110. };
  10111. auto _UpdateInlineStack = [&](DbgSubprogram* subprogram)
  10112. {
  10113. if (subprogram == NULL)
  10114. {
  10115. while (!inlineStack.IsEmpty())
  10116. _PopInlineStack();
  10117. return;
  10118. }
  10119. int inlineDepth = subprogram->GetInlineDepth();
  10120. while (inlineDepth < inlineStack.size())
  10121. _PopInlineStack();
  10122. if (inlineDepth > 0)
  10123. _UpdateInlineStackHelper(subprogram, inlineDepth);
  10124. };
  10125. while (dataAddr < addrEnd)
  10126. {
  10127. // Pop off old scopes
  10128. while (blockList.size() > 0)
  10129. {
  10130. auto lastBlock = blockList.back();
  10131. if (dataAddr < lastBlock->mHighPC)
  10132. break;
  10133. blockList.pop_back();
  10134. }
  10135. // Check entry into new child scopes
  10136. auto lastBlock = blockList.back();
  10137. for (auto checkBlock : lastBlock->mSubBlocks)
  10138. {
  10139. if ((dataAddr >= checkBlock->mLowPC) && (dataAddr < checkBlock->mHighPC))
  10140. {
  10141. blockList.push_back(checkBlock);
  10142. break;
  10143. }
  10144. }
  10145. bool allowSourceJump = false;
  10146. if ((dwLineData != NULL) && (dwLineData->mContribSize != 0) && (dataAddr >= dwSubProgram->GetLineAddr(*dwLineData) + dwLineData->mContribSize))
  10147. {
  10148. DbgSubprogram* inlinedSubprogram = NULL;
  10149. auto inlinedLine = dwSubProgram->FindClosestLine(dataAddr, &inlinedSubprogram);
  10150. _UpdateInlineStack(dwSubProgram);
  10151. }
  10152. // Update line data
  10153. while ((dwLineData != NULL) && (dwSubProgram->GetLineAddr(*dwLineData) <= dataAddr))
  10154. {
  10155. _UpdateInlineStack(dwSubProgram->GetLineInlinee(*dwLineData));
  10156. const int lineLimit = 5; // 15
  10157. if (allowSourceJump)
  10158. curLine = dwLineData->mLine;
  10159. auto lineSrcFile = dwSubProgram->GetLineSrcFile(*dwLineData);
  10160. if (lineSrcFile != srcFile)
  10161. {
  10162. srcFile = lineSrcFile;
  10163. result += "S ";
  10164. result += srcFile->GetLocalPath();
  10165. result += "\n";
  10166. // Just show the one line from the new file
  10167. curLine = dwLineData->mLine;
  10168. }
  10169. if (dwLineData->mLine < curLine - 1)
  10170. {
  10171. // Jumping backwards - possibly into inlined method, or possibly in current method.
  10172. // Show previous 6 lines, for context
  10173. curLine = BF_MAX(0, dwLineData->mLine - lineLimit);
  10174. }
  10175. if ((curLine <= firstLine) && (dwLineData->mLine >= firstLine))
  10176. {
  10177. // Jumping from inlined method (declared above) back into main method
  10178. curLine = dwLineData->mLine;
  10179. }
  10180. if (curLine < dwLineData->mLine - lineLimit)
  10181. {
  10182. // Don't show huge span of source - only show the last 6 lines at maximum
  10183. curLine = dwLineData->mLine - lineLimit;
  10184. }
  10185. //for ( ; curLine <= dwLineData->mLine; curLine++)
  10186. result += StrFormat("L %d %d\n", curLine, dwLineData->mLine - curLine + 1);
  10187. curLine = dwLineData->mLine + 1;
  10188. DbgLineData* nextLineData = NULL;
  10189. while (nextLineDataIdx < dwSubProgram->mLineInfo->mLines.mSize)
  10190. {
  10191. nextLineData = &dwSubProgram->mLineInfo->mLines[nextLineDataIdx];
  10192. //TODO:
  10193. /*{
  10194. result += StrFormat("T LineIdx: %d (%@ to %@)", nextLineDataIdx, dwSubProgram->GetLineAddr(*nextLineData), dwSubProgram->GetLineAddr(*nextLineData) + nextLineData->mContribSize);
  10195. auto inlinee = dwSubProgram->GetLineInlinee(*nextLineData);
  10196. if (inlinee != NULL)
  10197. {
  10198. result += StrFormat(" Inlinee: %s Depth: %d", inlinee->mName, inlinee->GetInlineDepth());
  10199. }
  10200. result += "\n";
  10201. }*/
  10202. auto nextLineAddr = dwSubProgram->GetLineAddr(*nextLineData);
  10203. if (nextLineAddr > dataAddr)
  10204. {
  10205. if (nextLineDataIdx + 1 < dwSubProgram->mLineInfo->mLines.mSize)
  10206. {
  10207. auto peekLineData = &dwSubProgram->mLineInfo->mLines[nextLineDataIdx + 1];
  10208. if (peekLineData->mRelAddress == nextLineData->mRelAddress)
  10209. {
  10210. // Use the later entry
  10211. ++nextLineDataIdx;
  10212. continue;
  10213. }
  10214. }
  10215. break;
  10216. }
  10217. // If we go back to an older entry beacuse of a gap then we need to catch back up...
  10218. ++nextLineDataIdx;
  10219. nextLineData = NULL; // Keep searching...
  10220. }
  10221. dwLineData = nextLineData;
  10222. nextLineDataIdx++;
  10223. }
  10224. // Have we gone off the end of the inline function?
  10225. // We may not have an explicit non-inlined line data at the transition point...
  10226. while (!inlineStack.IsEmpty())
  10227. {
  10228. auto subProgram = inlineStack.back();
  10229. if (dataAddr < subProgram->mBlock.mHighPC)
  10230. break;
  10231. _PopInlineStack();
  10232. }
  10233. bool hadDecodeFailure = false;
  10234. CPUInst inst;
  10235. if (!mCPU->Decode(dataAddr, dwarf->mOrigImageData, &inst))
  10236. hadDecodeFailure = true;
  10237. if ((decodeFailureCount == 8) || ((decodeFailureCount > 0) && (!hadDecodeFailure)))
  10238. {
  10239. for (int i = decodeFailureCount; i < 4 + sizeof(addr_target); i++)
  10240. result += " ";
  10241. result += " ???\n";
  10242. decodeFailureCount = 0;
  10243. }
  10244. if (decodeFailureCount == 0)
  10245. {
  10246. #ifdef BF_DBG_32
  10247. result += StrFormat("D %08X: ", dataAddr);
  10248. #else
  10249. result += StrFormat("D %@: ", dataAddr);
  10250. #endif
  10251. }
  10252. if (hadDecodeFailure)
  10253. {
  10254. uint8 byte = 0;
  10255. dwarf->mOrigImageData->Read(dataAddr, &byte, 1);
  10256. result += StrFormat("%02X ", byte);
  10257. dataAddr++;
  10258. decodeFailureCount++;
  10259. continue;
  10260. }
  10261. int instLen = inst.GetLength();
  10262. uint8 instData[32];
  10263. int showInstLen = BF_MIN(32, instLen);
  10264. dwarf->mOrigImageData->Read(dataAddr, instData, showInstLen);
  10265. for (int i = 0; i < showInstLen; i++)
  10266. result += StrFormat("%02X ", instData[i]);
  10267. for (int i = instLen; i < 4 + sizeof(addr_target); i++)
  10268. result += " ";
  10269. result += " ";
  10270. result += mCPU->InstructionToString(&inst, dataAddr);
  10271. int reg;
  10272. int offset;
  10273. if (inst.GetIndexRegisterAndOffset(&reg, &offset))
  10274. {
  10275. for (int blockIdx = (int)blockList.size() - 1; blockIdx >= 0; blockIdx--)
  10276. {
  10277. auto dwBlock = blockList[blockIdx];
  10278. for (auto variable : dwBlock->mVariables)
  10279. {
  10280. int varRegister;
  10281. int varOffset;
  10282. if (mDebugTarget->GetVariableIndexRegisterAndOffset(variable, &varRegister, &varOffset))
  10283. {
  10284. if (varRegister == -1)
  10285. varRegister = frameBaseRegister;
  10286. if ((reg == varRegister) && (offset == varOffset))
  10287. {
  10288. result += " ; ";
  10289. result += variable->mName;
  10290. break;
  10291. }
  10292. }
  10293. }
  10294. }
  10295. }
  10296. else if ((inst.IsCall()) || (inst.IsBranch()) || (inst.IsLoadAddress()))
  10297. {
  10298. addr_target targetAddr = inst.GetTarget();
  10299. if (targetAddr != 0)
  10300. {
  10301. if ((targetAddr >= addrStart) && (targetAddr < addrEnd))
  10302. {
  10303. result += StrFormat("\nJ %s", EncodeDataPtr(targetAddr, false).c_str());
  10304. }
  10305. else
  10306. {
  10307. String outSymbol;
  10308. addr_target offset = 0;
  10309. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &offset))
  10310. {
  10311. if (offset < 0x10000)
  10312. {
  10313. outSymbol = BfDemangler::Demangle(outSymbol, dwSubProgram->GetLanguage());
  10314. result += " ; " + outSymbol;
  10315. if (offset > 0)
  10316. result += StrFormat("+%x", offset);
  10317. }
  10318. }
  10319. }
  10320. }
  10321. }
  10322. result += "\n";
  10323. dataAddr += instLen;
  10324. }
  10325. // Why did we want to "show lines at end"??
  10326. // Show lines at end
  10327. /*if (curLine > 0)
  10328. {
  10329. for (int i = 0; i < 6; i++, curLine++)
  10330. result += StrFormat("L %d\n", curLine);
  10331. }*/
  10332. return result;
  10333. }
  10334. String WinDebugger::FindLineCallAddresses(intptr inAddress)
  10335. {
  10336. String callAddresses;
  10337. addr_target address = (addr_target)inAddress;
  10338. DbgSubprogram* dwSubprogram = NULL;
  10339. DbgLineData* startLineData = FindLineDataAtAddress(address, &dwSubprogram, NULL);
  10340. if (dwSubprogram == NULL)
  10341. return "";
  10342. CPURegisters registers;
  10343. PopulateRegisters(&registers);
  10344. auto inlinerSubprogram = dwSubprogram->GetRootInlineParent();
  10345. FixupLineDataForSubprogram(inlinerSubprogram);
  10346. if (inlinerSubprogram->mLineInfo->mLines.mSize == 0)
  10347. return "";
  10348. auto lineData = &inlinerSubprogram->mLineInfo->mLines[0];
  10349. addr_target addr = dwSubprogram->mBlock.mLowPC;
  10350. addr_target endAddr = dwSubprogram->mBlock.mHighPC;
  10351. DbgSubprogram* checkSubprogram = dwSubprogram;
  10352. DbgLineData* checkLineData = lineData;
  10353. addr_target checkLineAddr = 0;
  10354. int lineIdx = 0;
  10355. while (checkLineData != NULL)
  10356. {
  10357. //auto nextLineData = dwSubprogram->mCompileUnit->mLineDataMap.GetNext(checkLineData);
  10358. ++lineIdx;
  10359. DbgLineData* nextLineData = NULL;
  10360. addr_target nextLineAddr;
  10361. if (lineIdx < inlinerSubprogram->mLineInfo->mLines.size())
  10362. {
  10363. nextLineData = &inlinerSubprogram->mLineInfo->mLines[lineIdx];
  10364. nextLineAddr = dwSubprogram->GetLineAddr(*nextLineData);
  10365. }
  10366. else
  10367. nextLineAddr = inlinerSubprogram->mBlock.mHighPC;
  10368. // This stuff doesn't make sense...
  10369. DbgSubprogram* nextSubProgram;
  10370. if (nextLineData != NULL)
  10371. {
  10372. if (nextLineAddr > dwSubprogram->mBlock.mHighPC)
  10373. break;
  10374. endAddr = nextLineAddr;
  10375. nextSubProgram = mDebugTarget->FindSubProgram(endAddr);
  10376. if (nextSubProgram != NULL)
  10377. {
  10378. auto dbgModule = nextSubProgram->mCompileUnit->mDbgModule;
  10379. dbgModule->ParseSymbolData();
  10380. }
  10381. }
  10382. else
  10383. {
  10384. nextSubProgram = dwSubprogram;
  10385. endAddr = dwSubprogram->mBlock.mHighPC;
  10386. }
  10387. auto _HandleSection = [&]()
  10388. {
  10389. while (addr < endAddr)
  10390. {
  10391. CPUInst inst;
  10392. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  10393. break;
  10394. *registers.GetPCRegisterRef() = addr;
  10395. if (inst.IsCall())
  10396. {
  10397. bool addSymbol = true;
  10398. if (addr < (addr_target)inAddress)
  10399. callAddresses += "-";
  10400. callAddresses += EncodeDataPtr(addr, false);
  10401. addr_target targetAddr = inst.GetTarget(this, &registers);
  10402. if (targetAddr != 0)
  10403. {
  10404. String outSymbol;
  10405. auto subprogram = mDebugTarget->FindSubProgram(targetAddr);
  10406. if (subprogram != NULL)
  10407. {
  10408. CreateFilterName(outSymbol, subprogram);
  10409. addSymbol = true;
  10410. }
  10411. else
  10412. {
  10413. addr_target offset = 0;
  10414. String fullSymbolName;
  10415. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &offset))
  10416. {
  10417. if (offset < 0x200)
  10418. {
  10419. //outSymbol = BfDemangler::Demangle(outSymbol, dwSubprogram->GetLanguage());
  10420. if (outSymbol == "___chkstk_ms")
  10421. addSymbol = false;
  10422. else
  10423. {
  10424. String demangledName = BfDemangler::Demangle(outSymbol, DbgLanguage_C);
  10425. outSymbol.clear();
  10426. CreateFilterName(outSymbol, demangledName.c_str(), DbgLanguage_C);
  10427. }
  10428. }
  10429. else
  10430. outSymbol.clear();
  10431. }
  10432. }
  10433. if (addSymbol)
  10434. {
  10435. if (outSymbol.empty())
  10436. callAddresses += "\tFunc@" + EncodeDataPtr(targetAddr, false);
  10437. else
  10438. callAddresses += "\t" + outSymbol;
  10439. String attrs;
  10440. bool isFiltered = false;
  10441. if (subprogram != NULL)
  10442. {
  10443. subprogram->PopulateSubprogram();
  10444. isFiltered = subprogram->mIsStepFilteredDefault;
  10445. if (isFiltered)
  10446. attrs += "d"; // 'd' for default filtered
  10447. }
  10448. StepFilter* stepFilterPtr = NULL;
  10449. if (mDebugManager->mStepFilters.TryGetValue(outSymbol, &stepFilterPtr))
  10450. isFiltered = stepFilterPtr->IsFiltered(isFiltered);
  10451. if (isFiltered)
  10452. attrs += "f"; // 'f' for filter
  10453. if (!attrs.IsEmpty())
  10454. callAddresses += "\t" + attrs;
  10455. }
  10456. }
  10457. if (addSymbol)
  10458. callAddresses += "\n";
  10459. }
  10460. inst.PartialSimulate(this, &registers);
  10461. addr += inst.GetLength();
  10462. }
  10463. };
  10464. // For inlining - only add calls that are found either directly in our main block (not an inlined block)
  10465. // But add inlined methods when their parent is our current block
  10466. if ((checkSubprogram == dwSubprogram) && (checkLineData->mLine == startLineData->mLine))
  10467. {
  10468. _HandleSection();
  10469. }
  10470. else if ((checkSubprogram->mInlineeInfo != NULL) && (checkSubprogram->mInlineeInfo->mInlineParent == dwSubprogram))
  10471. {
  10472. if (checkLineAddr == checkSubprogram->mBlock.mLowPC)
  10473. {
  10474. addr_target inlineStartAddr = checkSubprogram->mBlock.mLowPC;
  10475. // Find the calling line
  10476. DbgSubprogram* callingSubprogram = dwSubprogram;
  10477. auto checkLineData = dwSubprogram->FindClosestLine(inlineStartAddr, &callingSubprogram);
  10478. if ((checkLineData != NULL) && (checkLineData->mCtxIdx == startLineData->mCtxIdx) && (checkLineData->mLine == startLineData->mLine))
  10479. {
  10480. if (inlineStartAddr <= (addr_target)inAddress)
  10481. callAddresses += "-";
  10482. callAddresses += EncodeDataPtr(inlineStartAddr, false);
  10483. String outSymbol;
  10484. CreateFilterName(outSymbol, checkSubprogram);
  10485. callAddresses += "\t" + outSymbol;
  10486. bool isFiltered = dwSubprogram->mIsStepFilteredDefault;
  10487. StepFilter* stepFilterPtr;
  10488. if (mDebugManager->mStepFilters.TryGetValue(outSymbol, &stepFilterPtr))
  10489. isFiltered = stepFilterPtr->IsFiltered(isFiltered);
  10490. if (isFiltered)
  10491. callAddresses += "\tf"; // 'f' for filter
  10492. callAddresses += "\n";
  10493. }
  10494. // if (checkSubprogram->mBlock.mHighPC < endAddr)
  10495. // {
  10496. // addr = checkSubprogram->mBlock.mHighPC;
  10497. // _HandleSection();
  10498. // }
  10499. }
  10500. // If we have unattributed data after the end of an inlined method, add that
  10501. if ((endAddr > checkSubprogram->mBlock.mHighPC) && (nextSubProgram == dwSubprogram))
  10502. {
  10503. addr = checkSubprogram->mBlock.mHighPC;
  10504. _HandleSection();
  10505. }
  10506. }
  10507. checkLineData = nextLineData;
  10508. checkSubprogram = nextSubProgram;
  10509. checkLineAddr = nextLineAddr;
  10510. addr = endAddr;
  10511. }
  10512. return callAddresses;
  10513. }
  10514. String WinDebugger::GetCurrentException()
  10515. {
  10516. AutoCrit autoCrit(mDebugManager->mCritSect);
  10517. String result = StrFormat("%s\n%08X",
  10518. EncodeDataPtr((addr_target)(intptr)mCurException.ExceptionAddress, true).c_str(),
  10519. mCurException.ExceptionCode);
  10520. String exStr;
  10521. switch (mCurException.ExceptionCode)
  10522. {
  10523. case EXCEPTION_ACCESS_VIOLATION:
  10524. {
  10525. String accessType;
  10526. if (mCurException.ExceptionInformation[0] == 0)
  10527. accessType = "reading from";
  10528. else if (mCurException.ExceptionInformation[0] == 8)
  10529. accessType = "executing";
  10530. else
  10531. accessType = "writing to";
  10532. exStr = StrFormat("EXCEPTION_ACCESS_VIOLATION %s %s", accessType.c_str(), EncodeDataPtr((addr_target)mCurException.ExceptionInformation[1], true).c_str());
  10533. }
  10534. break;
  10535. case EXCEPTION_DATATYPE_MISALIGNMENT:
  10536. exStr = "EXCEPTION_DATATYPE_MISALIGNMENT";
  10537. case EXCEPTION_SINGLE_STEP:
  10538. exStr = "EXCEPTION_SINGLE_STEP";
  10539. break;
  10540. case EXCEPTION_BREAKPOINT:
  10541. exStr = "EXCEPTION_BREAKPOINT";
  10542. break;
  10543. case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
  10544. exStr = "EXCEPTION_ARRAY_BOUNDS_EXCEEDED";
  10545. break;
  10546. case EXCEPTION_FLT_DENORMAL_OPERAND:
  10547. exStr = "EXCEPTION_FLT_DENORMAL_OPERAND";
  10548. break;
  10549. case EXCEPTION_FLT_DIVIDE_BY_ZERO:
  10550. exStr = "EXCEPTION_FLT_DIVIDE_BY_ZERO";
  10551. break;
  10552. case EXCEPTION_FLT_INEXACT_RESULT:
  10553. exStr = "EXCEPTION_FLT_INEXACT_RESULT";
  10554. break;
  10555. case EXCEPTION_FLT_INVALID_OPERATION:
  10556. exStr = "EXCEPTION_FLT_INVALID_OPERATIO";
  10557. break;
  10558. case EXCEPTION_FLT_OVERFLOW:
  10559. exStr = "EXCEPTION_FLT_OVERFLOW";
  10560. break;
  10561. case EXCEPTION_FLT_STACK_CHECK:
  10562. exStr = "EXCEPTION_FLT_STACK_CHECK";
  10563. break;
  10564. case EXCEPTION_FLT_UNDERFLOW:
  10565. exStr = "EXCEPTION_FLT_UNDERFLOW";
  10566. break;
  10567. case EXCEPTION_INT_DIVIDE_BY_ZERO:
  10568. exStr = "EXCEPTION_INT_DIVIDE_BY_ZERO";
  10569. break;
  10570. case EXCEPTION_INT_OVERFLOW:
  10571. exStr = "EXCEPTION_INT_OVERFLOW";
  10572. break;
  10573. case EXCEPTION_PRIV_INSTRUCTION:
  10574. exStr = "EXCEPTION_PRIV_INSTRUCTION";
  10575. break;
  10576. case EXCEPTION_IN_PAGE_ERROR:
  10577. exStr = "EXCEPTION_IN_PAGE_ERROR";
  10578. break;
  10579. case EXCEPTION_ILLEGAL_INSTRUCTION:
  10580. exStr = "EXCEPTION_ILLEGAL_INSTRUCTION";
  10581. break;
  10582. case EXCEPTION_NONCONTINUABLE_EXCEPTION:
  10583. exStr = "EXCEPTION_NONCONTINUABLE_EXCEPTION";
  10584. break;
  10585. case EXCEPTION_STACK_OVERFLOW:
  10586. exStr = "EXCEPTION_STACK_OVERFLOW";
  10587. break;
  10588. case EXCEPTION_INVALID_DISPOSITION:
  10589. exStr = "EXCEPTION_INVALID_DISPOSITION";
  10590. break;
  10591. case EXCEPTION_GUARD_PAGE:
  10592. exStr = "EXCEPTION_GUARD_PAGE";
  10593. break;
  10594. case EXCEPTION_INVALID_HANDLE:
  10595. exStr = "EXCEPTION_INVALID_HANDLE";
  10596. break;
  10597. case CONTROL_C_EXIT:
  10598. exStr = "CONTROL_C_EXIT";
  10599. break;
  10600. default:
  10601. exStr += StrFormat("EXCEPTION %08X", mCurException.ExceptionCode);
  10602. }
  10603. if (mActiveThread != NULL)
  10604. exStr += StrFormat(" in thread %d", mActiveThread->mThreadId);
  10605. if (!exStr.empty())
  10606. result += "\n" + exStr;
  10607. // After we retrieve the exception then we can go back to just being normal 'paused'
  10608. // This allows us to evaluate stuff, Set Next Statement, etc.
  10609. mRunState = RunState_Paused;
  10610. return result.c_str();
  10611. }
  10612. void WinDebugger::SetAliasPath(const StringImpl& origPath, const StringImpl& localPath)
  10613. {
  10614. AutoCrit autoCrit(mDebugManager->mCritSect);
  10615. String fixedOrigPath = FixPathAndCase(origPath);
  10616. String fixedLocalPath = FixPathAndCase(localPath);
  10617. auto origFile = mDebugTarget->AddSrcFile(origPath);
  10618. origFile->mLocalPath = FixPath(localPath);
  10619. mDebugTarget->mLocalToOrigSrcMap[fixedLocalPath] = fixedOrigPath;
  10620. // We invalidate the step filters, because previously-failing 'CheckSourceFileExist' checks may now succeed
  10621. mDebugManager->mStepFilterVersion++;
  10622. }
  10623. String WinDebugger::GetModulesInfo()
  10624. {
  10625. AutoCrit autoCrit(mDebugManager->mCritSect);
  10626. String str;
  10627. for (auto module : mDebugTarget->mDbgModules)
  10628. {
  10629. COFF* coff = (COFF*)module;
  10630. if (module->mHotIdx > 0)
  10631. continue;
  10632. str += module->mDisplayName;
  10633. str += "\t";
  10634. if (module->mLoadState == DbgModuleLoadState_Loaded)
  10635. {
  10636. str += module->mFilePath;
  10637. }
  10638. else if (module->mLoadState == DbgModuleLoadState_NotLoaded)
  10639. {
  10640. str += module->mFilePath;
  10641. str += " (Loading...)";
  10642. }
  10643. else if (module->mLoadState == DbgModuleLoadState_Failed)
  10644. {
  10645. str += "!";
  10646. str += module->mFilePath;
  10647. }
  10648. if (module->mMappedImageFile != NULL)
  10649. {
  10650. str += " (";
  10651. str += module->mMappedImageFile->mFileName;
  10652. str += ")";
  10653. }
  10654. str += "\t";
  10655. str += coff->mPDBPath;
  10656. str += "\t";
  10657. str += module->mVersion;
  10658. str += StrFormat("\t%@-%@\t%dk\t", module->mImageBase, module->mImageBase + module->mImageSize, module->mImageSize / 1024);
  10659. time_t timestamp = coff->mTimeStamp;
  10660. if (timestamp == 0)
  10661. timestamp = GetFileTimeWrite(coff->mFilePath);
  10662. if (timestamp != 0)
  10663. {
  10664. char timeString[256];
  10665. auto time_info = localtime(&timestamp);
  10666. strftime(timeString, sizeof(timeString), "%D %T", time_info);
  10667. str += timeString;
  10668. }
  10669. str += "\n";
  10670. }
  10671. return str;
  10672. }
  10673. void WinDebugger::CancelSymSrv()
  10674. {
  10675. AutoCrit autoCrit(mDebugManager->mCritSect);
  10676. if (mActiveSymSrvRequest != NULL)
  10677. mActiveSymSrvRequest->Cancel();
  10678. }
  10679. bool WinDebugger::HasPendingDebugLoads()
  10680. {
  10681. AutoCrit autoCrit(mDebugManager->mCritSect);
  10682. return (!mPendingImageLoad.IsEmpty()) || (!mPendingDebugInfoLoad.IsEmpty());
  10683. }
  10684. int WinDebugger::LoadImageForModule(const StringImpl &modulePath, const StringImpl& imagePath)
  10685. {
  10686. AutoCrit autoCrit(mDebugManager->mCritSect);
  10687. for (auto dbgModule : mDebugTarget->mDbgModules)
  10688. {
  10689. if (modulePath.Equals(dbgModule->mFilePath, StringImpl::CompareKind_OrdinalIgnoreCase))
  10690. {
  10691. auto coff = (COFF*)dbgModule;
  10692. if (!coff->LoadModuleImage(imagePath))
  10693. {
  10694. mDebugManager->mOutMessages.push_back("error Failed to load image " + imagePath);
  10695. }
  10696. ModuleChanged(dbgModule);
  10697. return 0;
  10698. }
  10699. }
  10700. return 0;
  10701. }
  10702. int WinDebugger::LoadDebugInfoForModule(DbgModule* dbgModule)
  10703. {
  10704. if (!dbgModule->HasPendingDebugInfo())
  10705. return 0;
  10706. if (dbgModule->RequestDebugInfo())
  10707. {
  10708. ClearCallStack(); // Make this re-resolve with debug info
  10709. return 1;
  10710. }
  10711. DbgPendingDebugInfoLoad* dbgPendingDebugInfoLoad = NULL;
  10712. if (mPendingDebugInfoLoad.TryAdd(dbgModule, NULL, &dbgPendingDebugInfoLoad))
  10713. {
  10714. dbgPendingDebugInfoLoad->mModule = dbgModule;
  10715. dbgPendingDebugInfoLoad->mAllowRemote = true;
  10716. return 2;
  10717. }
  10718. dbgPendingDebugInfoLoad->mAllowRemote = true;
  10719. return 0;
  10720. }
  10721. int WinDebugger::LoadDebugInfoForModule(const StringImpl& moduleName)
  10722. {
  10723. AutoCrit autoCrit(mDebugManager->mCritSect);
  10724. for (auto dbgModule : mDebugTarget->mDbgModules)
  10725. {
  10726. String checkModuleName = GetFileName(dbgModule->mFilePath);
  10727. if (moduleName.Equals(checkModuleName, StringImpl::CompareKind_OrdinalIgnoreCase))
  10728. {
  10729. return LoadDebugInfoForModule(dbgModule);
  10730. }
  10731. }
  10732. return 0;
  10733. }
  10734. int WinDebugger::LoadDebugInfoForModule(const StringImpl& modulePath, const StringImpl& debugFileName)
  10735. {
  10736. AutoCrit autoCrit(mDebugManager->mCritSect);
  10737. for (auto dbgModule : mDebugTarget->mDbgModules)
  10738. {
  10739. if (modulePath.Equals(dbgModule->mFilePath, StringImpl::CompareKind_OrdinalIgnoreCase))
  10740. {
  10741. auto coff = (COFF*)dbgModule;
  10742. String err;
  10743. if (!coff->mPDBLoaded)
  10744. {
  10745. dbgModule->mFailMsgPtr = &err;
  10746. if (coff->TryLoadPDB(debugFileName, coff->mWantPDBGuid, coff->mWantAge))
  10747. {
  10748. ModuleChanged(dbgModule);
  10749. }
  10750. dbgModule->mFailMsgPtr = NULL;
  10751. }
  10752. else
  10753. {
  10754. err = StrFormat("Module '%s' already has debug information loaded", GetFileName(modulePath).c_str());
  10755. }
  10756. if (!err.IsEmpty())
  10757. {
  10758. mDebugManager->mOutMessages.push_back("error " + err);
  10759. }
  10760. return 0;
  10761. }
  10762. }
  10763. return 0;
  10764. }
  10765. void WinDebugger::FixupLineData(DbgCompileUnit* compileUnit)
  10766. {
  10767. if (!compileUnit || !compileUnit->mNeedsLineDataFixup)
  10768. return;
  10769. compileUnit->mNeedsLineDataFixup = false;
  10770. }
  10771. static int CompareLineData(const void* lineDataP1, const void* lineDataP2)
  10772. {
  10773. int cmpResult = (int)(((DbgLineData*)lineDataP1)->mRelAddress - ((DbgLineData*)lineDataP2)->mRelAddress);
  10774. if (cmpResult != 0)
  10775. return cmpResult;
  10776. // A larger contrib size means it's the 'outer' inlinee
  10777. cmpResult = -(((DbgLineData*)lineDataP1)->mContribSize - ((DbgLineData*)lineDataP2)->mContribSize);
  10778. if (cmpResult != 0)
  10779. return cmpResult;
  10780. return -(((DbgLineData*)lineDataP1)->mCtxIdx - ((DbgLineData*)lineDataP2)->mCtxIdx);
  10781. }
  10782. void WinDebugger::FixupLineDataForSubprogram(DbgSubprogram* subProgram)
  10783. {
  10784. if ((subProgram == NULL) || (!subProgram->mNeedLineDataFixup))
  10785. return;
  10786. BP_ZONE("FixupLineDataForSubprogram");
  10787. subProgram->mNeedLineDataFixup = false;
  10788. if (subProgram->mInlineeInfo != NULL)
  10789. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  10790. if ((subProgram->mLineInfo == NULL) || (subProgram->mLineInfo->mLines.mSize == 0))
  10791. return;
  10792. //TODO: I think this was covering up a bug in DWARF line encoding? Figure this out
  10793. // if (subProgram->mLineInfo->mLines.mSize >= 2)
  10794. // {
  10795. // DbgLineData* line0 = &subProgram->mLineInfo->mLines[0];
  10796. // DbgLineData* line1 = &subProgram->mLineInfo->mLines[1];
  10797. //
  10798. //
  10799. // if ((line0->mRelAddress == line1->mRelAddress) && (!line0->IsStackFrameSetup()) && (line1->IsStackFrameSetup()))
  10800. // {
  10801. // CPUInst inst;
  10802. // if (mCPU->Decode(line0->mAddress, subProgram->mCompileUnit->mDbgModule->mOrigImageData, &inst))
  10803. // line1->mAddress += inst.GetLength();
  10804. // }
  10805. // }
  10806. qsort(subProgram->mLineInfo->mLines.mVals, subProgram->mLineInfo->mLines.mSize, sizeof(DbgLineData), CompareLineData);
  10807. // If we have multiple lines with the same line/column/context, merge them
  10808. if (!subProgram->mLineInfo->mLines.IsEmpty())
  10809. {
  10810. auto prevLine = &subProgram->mLineInfo->mLines[0];
  10811. for (int i = 1; i < subProgram->mLineInfo->mLines.mSize; i++)
  10812. {
  10813. auto nextLine = &subProgram->mLineInfo->mLines[i];
  10814. if ((nextLine->mLine == prevLine->mLine) && (nextLine->mColumn == prevLine->mColumn) && (nextLine->mCtxIdx == prevLine->mCtxIdx) &&
  10815. (nextLine->mRelAddress == prevLine->mRelAddress + prevLine->mContribSize))
  10816. {
  10817. prevLine->mContribSize += nextLine->mContribSize;
  10818. // This messed up inline cases because mContribSize actually INCLUDES inlined lines so it caused the address to skip too far
  10819. //nextLine->mRelAddress += nextLine->mContribSize;
  10820. //nextLine->mContribSize = 0;
  10821. }
  10822. else
  10823. {
  10824. prevLine = nextLine;
  10825. }
  10826. }
  10827. }
  10828. }
  10829. void WinDebugger::ReserveHotTargetMemory(int size)
  10830. {
  10831. HotTargetMemory hotTargetMemory;
  10832. hotTargetMemory.mOffset = 0;
  10833. hotTargetMemory.mSize = 0;
  10834. hotTargetMemory.mPtr = NULL;
  10835. if (size > 0)
  10836. {
  10837. // In 64-bit mode we have a reserved region on program load that we commit here because the offsets
  10838. // must be within 32-bits of the original EXE image, but in 32-bit mode we don't reserve anything
  10839. // until here
  10840. #ifdef BF_DBG_32
  10841. //hotTargetMemory.mSize = std::max(1024 * 1024, size);
  10842. BF_ASSERT((size & (mPageSize - 1)) == 0);
  10843. hotTargetMemory.mSize = size;
  10844. hotTargetMemory.mPtr = (addr_target)(intptr)VirtualAllocEx(mProcessInfo.hProcess, NULL, hotTargetMemory.mSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
  10845. mDebugTarget->mHotHeap->AddTrackedRegion(hotTargetMemory.mPtr, hotTargetMemory.mSize);
  10846. #else
  10847. hotTargetMemory.mSize = size;
  10848. hotTargetMemory.mPtr = mDebugTarget->mHotHeap->Alloc(size);
  10849. BF_ASSERT(hotTargetMemory.mPtr != 0);
  10850. auto ptr = ::VirtualAllocEx(mProcessInfo.hProcess, (void*)(intptr)hotTargetMemory.mPtr, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  10851. BF_ASSERT(ptr == (void*)(intptr)hotTargetMemory.mPtr);
  10852. #endif
  10853. }
  10854. BfLogDbg("ReserveHotTargetMemory %p %d", hotTargetMemory.mPtr, hotTargetMemory.mSize);
  10855. int err = GetLastError();
  10856. mHotTargetMemory.push_back(hotTargetMemory);
  10857. }
  10858. addr_target WinDebugger::AllocHotTargetMemory(int size, bool canExecute, bool canWrite, int* outAllocSize)
  10859. {
  10860. int prot = PAGE_READWRITE;
  10861. if (canExecute && canWrite)
  10862. prot = PAGE_EXECUTE_READWRITE;
  10863. else if (canExecute)
  10864. prot = PAGE_EXECUTE_READ;
  10865. auto hotTargetMemory = (HotTargetMemory*)&mHotTargetMemory.back();
  10866. if (hotTargetMemory->mPtr == 0)
  10867. {
  10868. Fail("Failed to allocate memory for hot loading");
  10869. return 0;
  10870. }
  10871. size = (size + (mPageSize - 1)) & ~(mPageSize - 1);
  10872. *outAllocSize = size;
  10873. BF_ASSERT(hotTargetMemory->mOffset + size <= hotTargetMemory->mSize);
  10874. addr_target result = hotTargetMemory->mPtr + hotTargetMemory->mOffset;
  10875. ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)result, size, prot, NULL);
  10876. BfLogDbg("AllocHotTargetMemory: %p %d %d %d\n", result, size, canExecute, canWrite);
  10877. hotTargetMemory->mOffset += size;
  10878. return result;
  10879. }
  10880. void WinDebugger::ReleaseHotTargetMemory(addr_target addr, int size)
  10881. {
  10882. #ifdef BF_DBG_32
  10883. ::VirtualFreeEx(mProcessInfo.hProcess, (void*)(intptr)addr, 0, MEM_RELEASE);
  10884. #else
  10885. mDebugTarget->mHotHeap->Release(addr, size);
  10886. ::VirtualFreeEx(mProcessInfo.hProcess, (void*)(intptr)addr, size, MEM_DECOMMIT);
  10887. #endif
  10888. }
  10889. void WinDebugger::CleanupHotHeap()
  10890. {
  10891. mDebugTarget->mLastHotHeapCleanIdx = mDebugTarget->mHotHeap->mBlockAllocIdx;
  10892. // Our criteria for determining whether a hot loaded file is still being used:
  10893. // 1) If we are currently executing a method from that object file.
  10894. // 2) If the symbol map has a symbol with that address.
  10895. // 3) If the static variable map contains a reference - including a conservative scan of the data
  10896. // This handles vdata references
  10897. // This is a conservative check which won't purge hot reloads that contain deleted
  10898. // methods (for example), but it will purge hot reloads where all the changed
  10899. // data has been overwritten.
  10900. // For delegate bindings, the original module declaring the bind creates a "preserve"
  10901. // global such as "bf_hs_preserve@_ZN5TestO4TestEv", whose preserved symbol ensures it
  10902. // doesn't get unloaded. The current version of that method resides in "_ZN5TestO4TestEv",
  10903. // ensuring that the method pointed to by the global variable is valid
  10904. mDebugTarget->mHotHeap->ClearReferencedFlags();
  10905. addr_target lowAddr = mDebugTarget->mHotHeap->mHotAreaStart;
  10906. addr_target highAddr = lowAddr + mDebugTarget->mHotHeap->mHotAreaSize;
  10907. // Do conservative scan through all thread stacks. Stack traces aren't 100% reliable, so we
  10908. // need to do a full conservative scan of any addresses stored in the stack
  10909. // to ensure we don't miss any return addresses
  10910. for (int threadIdx = 0; threadIdx < (int)mThreadList.size(); threadIdx++)
  10911. {
  10912. WdThreadInfo* threadInfo = mThreadList[threadIdx];
  10913. BF_CONTEXT lcContext;
  10914. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  10915. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  10916. addr_target checkStackAddr = BF_CONTEXT_SP(lcContext);
  10917. checkStackAddr &= ~(sizeof(addr_target) - 1);
  10918. // Conservative check on registers
  10919. for (int regNum = 0; regNum < sizeof(BF_CONTEXT)/sizeof(addr_target); regNum++)
  10920. {
  10921. addr_target checkAddr = ((addr_target*)&lcContext)[regNum];
  10922. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  10923. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  10924. }
  10925. // Conservative check on all stack data
  10926. while (checkStackAddr < threadInfo->mStartSP)
  10927. {
  10928. addr_target checkAddrArr[1024];
  10929. int numAddrsChecking = BF_MIN(1024, (int)((threadInfo->mStartSP - checkStackAddr) / sizeof(addr_target)));
  10930. ReadMemory(checkStackAddr, numAddrsChecking * sizeof(addr_target), checkAddrArr);
  10931. checkStackAddr += numAddrsChecking * sizeof(addr_target);
  10932. for (int addrIdx = 0; addrIdx < numAddrsChecking; addrIdx++)
  10933. {
  10934. addr_target checkAddr = checkAddrArr[addrIdx];
  10935. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  10936. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  10937. }
  10938. }
  10939. }
  10940. auto mainModule = mDebugTarget->mTargetBinary;
  10941. for (auto entry : mainModule->mSymbolNameMap)
  10942. {
  10943. auto dwSymbol = entry->mValue;
  10944. addr_target checkAddr = dwSymbol->mAddress;
  10945. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  10946. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  10947. }
  10948. mDebugTarget->CleanupHotHeap();
  10949. BfLogDbg("Hot load memory used: %dk\n", (int)mDebugTarget->mHotHeap->GetUsedSize() / 1024);
  10950. }
  10951. int WinDebugger::EnableWriting(intptr address, int size)
  10952. {
  10953. DWORD oldProt;
  10954. bool success = ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)address, size, PAGE_READWRITE, &oldProt);
  10955. if (!success)
  10956. {
  10957. int err = GetLastError();
  10958. }
  10959. return (int)oldProt;
  10960. }
  10961. int WinDebugger::SetProtection(intptr address, int size, int prot)
  10962. {
  10963. DWORD oldProt;
  10964. ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)address, size, prot, &oldProt);
  10965. return (int)oldProt;
  10966. }
  10967. void WinDebugger::EnableMemCache()
  10968. {
  10969. mMemCacheAddr = 1;
  10970. }
  10971. void WinDebugger::DisableMemCache()
  10972. {
  10973. mMemCacheAddr = 0;
  10974. }
  10975. bool WinDebugger::ReadMemory(intptr address, uint64 length, void* dest, bool local)
  10976. {
  10977. if (local)
  10978. {
  10979. __try
  10980. {
  10981. memcpy(dest, (void*)address, length);
  10982. return true;
  10983. }
  10984. __except(EXCEPTION_EXECUTE_HANDLER)
  10985. {
  10986. return false;
  10987. }
  10988. }
  10989. if (mMemCacheAddr != 0)
  10990. {
  10991. addr_target targetAddr = (addr_target)address;
  10992. if ((targetAddr >= mMemCacheAddr) && (targetAddr + length <= mMemCacheAddr + WD_MEMCACHE_SIZE) && (mMemCacheAddr > 1))
  10993. {
  10994. memcpy(dest, mMemCacheData + (targetAddr - mMemCacheAddr), length);
  10995. return true;
  10996. }
  10997. // We need a new block
  10998. SIZE_T dwReadBytes;
  10999. if (::ReadProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, mMemCacheData, (SIZE_T)WD_MEMCACHE_SIZE, &dwReadBytes) != 0)
  11000. {
  11001. mMemCacheAddr = targetAddr;
  11002. memcpy(dest, mMemCacheData, length);
  11003. return true;
  11004. }
  11005. // Failed, turn off caching
  11006. mMemCacheAddr = 0;
  11007. }
  11008. SIZE_T dwReadBytes;
  11009. if (::ReadProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, dest, (SIZE_T)length, &dwReadBytes) != 0)
  11010. return true;
  11011. int lastErr = ::GetLastError();
  11012. memset(dest, 0, length);
  11013. return false;
  11014. }
  11015. bool WinDebugger::WriteMemory(intptr address, void* src, uint64 length)
  11016. {
  11017. SIZE_T dwBytesWritten = 0;
  11018. int result = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, src, (SIZE_T)length, &dwBytesWritten);
  11019. return result != 0;
  11020. }
  11021. addr_target WinDebugger::GetTLSOffset(int tlsIndex)
  11022. {
  11023. typedef LONG NTSTATUS;
  11024. typedef DWORD KPRIORITY;
  11025. typedef WORD UWORD;
  11026. enum THREADINFOCLASS
  11027. {
  11028. ThreadBasicInformation,
  11029. };
  11030. struct CLIENT_ID
  11031. {
  11032. HANDLE UniqueProcess;
  11033. HANDLE UniqueThread;
  11034. };
  11035. struct
  11036. {
  11037. NTSTATUS mExitStatus;
  11038. void* mTebBaseAddress;
  11039. CLIENT_ID mClientId;
  11040. KAFFINITY mAffinityMask;
  11041. KPRIORITY mPriority;
  11042. KPRIORITY mBasePriority;
  11043. } threadInfo = { 0 };
  11044. ULONG len = 0;
  11045. bool loadedManually = false;
  11046. static HMODULE module = NULL;
  11047. static NTSTATUS(__stdcall *NtQueryInformationThread)(HANDLE ThreadHandle, THREADINFOCLASS ThreadInformationClass, PVOID ThreadInformation, ULONG ThreadInformationLength, PULONG ReturnLength);
  11048. if (module == NULL)
  11049. {
  11050. module = GetModuleHandleA("ntdll.dll");
  11051. NtQueryInformationThread = reinterpret_cast<decltype(NtQueryInformationThread)>(GetProcAddress(module, "NtQueryInformationThread"));
  11052. }
  11053. if (NtQueryInformationThread == NULL)
  11054. return 0;
  11055. NTSTATUS status = NtQueryInformationThread(mActiveThread->mHThread, (THREADINFOCLASS)0, &threadInfo, sizeof(threadInfo), nullptr);
  11056. if (status < 0)
  11057. return 0;
  11058. #ifdef BF_DBG_32
  11059. addr_target tibAddr = ReadMemory<addr_target>((intptr)threadInfo.mTebBaseAddress + 0x0);
  11060. addr_target tlsTable = ReadMemory<addr_target>((intptr)tibAddr + 0x2C);
  11061. #else
  11062. addr_target tlsTable = ReadMemory<addr_target>((intptr)threadInfo.mTebBaseAddress + 0x58);
  11063. #endif
  11064. return ReadMemory<addr_target>(tlsTable + tlsIndex * sizeof(addr_target));
  11065. }
  11066. bool WinDebugger::WriteInstructions(intptr address, void* src, uint64 length)
  11067. {
  11068. SIZE_T dwBytesWritten = 0;
  11069. bool result = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, src, (SIZE_T)length, &dwBytesWritten) != 0;
  11070. result |= ::FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, (SIZE_T)length) != 0;
  11071. BF_ASSERT(result);
  11072. BfLogDbg("WriteInstructions: %p %d\n", address, length);
  11073. return result;
  11074. }
  11075. DbgMemoryFlags WinDebugger::GetMemoryFlags(intptr address)
  11076. {
  11077. MEMORY_BASIC_INFORMATION memBasicInfo;
  11078. if (::VirtualQueryEx(mProcessInfo.hProcess, (void*)address, &memBasicInfo, sizeof(MEMORY_BASIC_INFORMATION)) == 0)
  11079. {
  11080. //BfLogDbg("VirtualQueryEx failed with %d\n", GetLastError());
  11081. return DbgMemoryFlags_None;
  11082. }
  11083. DbgMemoryFlags flags = DbgMemoryFlags_None;
  11084. if (memBasicInfo.AllocationProtect & PAGE_READWRITE)
  11085. {
  11086. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11087. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11088. }
  11089. if (memBasicInfo.AllocationProtect & PAGE_READONLY)
  11090. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11091. if (memBasicInfo.AllocationProtect & PAGE_WRITECOPY)
  11092. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11093. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE)
  11094. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11095. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_READ)
  11096. {
  11097. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11098. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11099. }
  11100. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_READWRITE)
  11101. {
  11102. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11103. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11104. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11105. }
  11106. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_WRITECOPY)
  11107. {
  11108. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11109. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11110. }
  11111. return flags;
  11112. }
  11113. #ifdef BF_DBG_32
  11114. Debugger* Beefy::CreateDebugger32(DebugManager* debugManager, DbgMiniDump* miniDump)
  11115. #else
  11116. Debugger* Beefy::CreateDebugger64(DebugManager* debugManager, DbgMiniDump* miniDump)
  11117. #endif
  11118. {
  11119. if (miniDump != NULL)
  11120. {
  11121. auto debugger = new MiniDumpDebugger(debugManager, miniDump);
  11122. return debugger;
  11123. }
  11124. return new WinDebugger(debugManager);
  11125. }
  11126. #ifdef BF_DBG_32
  11127. void WdAllocTest()
  11128. {
  11129. Array<BeefyDbg32::WdStackFrame*> stackFrameList;
  11130. for (int i = 0; true; i++)
  11131. {
  11132. WdStackFrame* stackFrame = new WdStackFrame();
  11133. stackFrameList.push_back(stackFrame);
  11134. }
  11135. }
  11136. #endif
  11137. #endif //!defined BF32 || !defined BF_DBG_64