WinDebugger.cpp 361 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468
  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 <inttypes.h>
  20. #include <windows.h>
  21. #include "DbgExprEvaluator.h"
  22. #include "Compiler/BfSystem.h"
  23. #include "Compiler/BfParser.h"
  24. #include "Compiler/BfReducer.h"
  25. #include "Compiler/BfDemangler.h"
  26. #include "Compiler/BfPrinter.h"
  27. #include <Shlobj.h>
  28. #include "NetManager.h"
  29. #include "DebugManager.h"
  30. #include "X86Target.h"
  31. #include "HotHeap.h"
  32. #include "HotScanner.h"
  33. #include "Profiler.h"
  34. #include <float.h>
  35. #include <psapi.h>
  36. #if !defined BF32 || !defined BF_DBG_64
  37. #define STATUS_WX86_CONTINUE 0x4000001DL
  38. #define STATUS_WX86_SINGLE_STEP 0x4000001EL
  39. #define STATUS_WX86_BREAKPOINT 0x4000001FL
  40. #define STATUS_WX86_EXCEPTION_CONTINUE 0x40000020L
  41. #pragma pack(push, 1)
  42. struct HotJumpOp
  43. {
  44. uint8 mOpCode;
  45. int32 mRelTarget;
  46. };
  47. #pragma pack(pop)
  48. #include "BeefySysLib/util/AllocDebug.h"
  49. #include <limits>
  50. USING_NS_BF_DBG;
  51. static void FilterThreadName(String& name)
  52. {
  53. for (int i = 0; i < (int)name.length(); i++)
  54. {
  55. uint8 c = name[i];
  56. if (c == 0)
  57. {
  58. name.RemoveToEnd(i);
  59. return;
  60. }
  61. if (c < 32)
  62. {
  63. name.Remove(i);
  64. i--;
  65. continue;
  66. }
  67. }
  68. }
  69. //////////////////////////////////////////////////////////////////////////
  70. WdBreakpointCondition::~WdBreakpointCondition()
  71. {
  72. delete mDbgEvaluationContext;
  73. }
  74. //////////////////////////////////////////////////////////////////////////
  75. DbgEvaluationContext::DbgEvaluationContext(WinDebugger* winDebugger, DbgModule* dbgModule, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  76. {
  77. Init(winDebugger, dbgModule, expr, formatInfo, contextValue);
  78. }
  79. DbgEvaluationContext::DbgEvaluationContext(WinDebugger* winDebugger, DbgCompileUnit* dbgCompileUnit, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  80. {
  81. DbgModule* dbgModule = NULL;
  82. if (dbgCompileUnit != NULL)
  83. dbgModule = dbgCompileUnit->mDbgModule;
  84. Init(winDebugger, dbgModule, expr, formatInfo, contextValue);
  85. }
  86. void DbgEvaluationContext::Init(WinDebugger* winDebugger, DbgModule* dbgModule, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  87. {
  88. if (expr.empty())
  89. {
  90. mParser = NULL;
  91. mReducer = NULL;
  92. mPassInstance = NULL;
  93. mDbgExprEvaluator = NULL;
  94. mExprNode = NULL;
  95. return;
  96. }
  97. mParser = new BfParser(winDebugger->mBfSystem);
  98. mParser->mCompatMode = true;
  99. mPassInstance = new BfPassInstance(winDebugger->mBfSystem);
  100. auto terminatedExpr = expr + ";";
  101. mParser->SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  102. mParser->Parse(mPassInstance);
  103. mReducer = new BfReducer();
  104. mReducer->mAlloc = mParser->mAlloc;
  105. mReducer->mSystem = winDebugger->mBfSystem;
  106. mReducer->mPassInstance = mPassInstance;
  107. mReducer->mVisitorPos = BfReducer::BfVisitorPos(mParser->mRootNode);
  108. mReducer->mVisitorPos.MoveNext();
  109. mReducer->mCompatMode = mParser->mCompatMode;
  110. mReducer->mSource = mParser;
  111. mExprNode = mReducer->CreateExpression(mParser->mRootNode->GetFirst());
  112. mParser->Close();
  113. mDbgExprEvaluator = new DbgExprEvaluator(winDebugger, dbgModule, mPassInstance, -1, -1);
  114. if ((formatInfo != NULL) && (mExprNode != NULL) && (mExprNode->GetSrcEnd() < (int) expr.length()))
  115. {
  116. String formatFlags = expr.Substring(mExprNode->GetSrcEnd());
  117. String errorString = "Invalid expression";
  118. if (!winDebugger->ParseFormatInfo(dbgModule, formatFlags, formatInfo, mPassInstance, NULL, NULL, &errorString, contextValue))
  119. {
  120. mPassInstance->FailAt(errorString, mParser->mSourceData, mExprNode->GetSrcEnd(), (int)expr.length() - mExprNode->GetSrcEnd());
  121. formatFlags = "";
  122. }
  123. }
  124. if (formatInfo != NULL)
  125. {
  126. mDbgExprEvaluator->mExplicitThis = formatInfo->mExplicitThis;
  127. mDbgExprEvaluator->mCallStackIdx = formatInfo->mCallStackIdx;
  128. }
  129. }
  130. bool DbgEvaluationContext::HasExpression()
  131. {
  132. return mExprNode != NULL;
  133. }
  134. DbgEvaluationContext::~DbgEvaluationContext()
  135. {
  136. delete mParser;
  137. delete mReducer;
  138. delete mDbgExprEvaluator;
  139. delete mPassInstance;
  140. }
  141. DbgTypedValue DbgEvaluationContext::EvaluateInContext(DbgTypedValue contextTypedValue)
  142. {
  143. if (mExprNode == NULL)
  144. return DbgTypedValue();
  145. mPassInstance->ClearErrors();
  146. if (contextTypedValue)
  147. {
  148. mDbgExprEvaluator->mExplicitThis = contextTypedValue;
  149. if ((mDbgExprEvaluator->mExplicitThis.mType->IsPointer()) && (mDbgExprEvaluator->mExplicitThis.mType->mTypeParam->WantsRefThis()))
  150. {
  151. mDbgExprEvaluator->mExplicitThis.mType = mDbgExprEvaluator->mExplicitThis.mType->mTypeParam;
  152. mDbgExprEvaluator->mExplicitThis.mSrcAddress = mDbgExprEvaluator->mExplicitThis.mPtr;
  153. mDbgExprEvaluator->mExplicitThis.mPtr = 0;
  154. }
  155. if ((mDbgExprEvaluator->mExplicitThis.mType->IsCompositeType()) && (!mDbgExprEvaluator->mExplicitThis.mType->WantsRefThis()))
  156. {
  157. if (mDbgExprEvaluator->mExplicitThis.mSrcAddress != 0)
  158. {
  159. mDbgExprEvaluator->mExplicitThis.mType = mDbgExprEvaluator->mDbgModule->GetPointerType(mDbgExprEvaluator->mExplicitThis.mType);
  160. mDbgExprEvaluator->mExplicitThis.mPtr = mDbgExprEvaluator->mExplicitThis.mSrcAddress;
  161. mDbgExprEvaluator->mExplicitThis.mSrcAddress = 0;
  162. }
  163. }
  164. }
  165. if (contextTypedValue.mType != NULL)
  166. mDbgExprEvaluator->mDbgCompileUnit = contextTypedValue.mType->mCompileUnit;
  167. DbgTypedValue exprResult;
  168. auto result = mDbgExprEvaluator->Resolve(mExprNode);
  169. return result;
  170. }
  171. bool DbgEvaluationContext::HadError()
  172. {
  173. return mPassInstance->mFailedIdx != 0;
  174. }
  175. String DbgEvaluationContext::GetErrorStr()
  176. {
  177. String errorStr = mPassInstance->mErrors[0]->mError;
  178. if (mExprNode != NULL)
  179. {
  180. errorStr += ": ";
  181. errorStr += mExprNode->ToString();
  182. }
  183. return errorStr;
  184. }
  185. //////////////////////////////////////////////////////////////////////////
  186. typedef HRESULT(WINAPI* SetThreadDescription_t)(HANDLE hThread, PCWSTR lpThreadDescription);
  187. typedef HRESULT(WINAPI* GetThreadDescription_t)(HANDLE hThread, PWSTR* lpThreadDescription);
  188. static SetThreadDescription_t gSetThreadDescription = NULL;
  189. static GetThreadDescription_t gGetThreadDescription = NULL;
  190. static HMODULE gKernelDll = NULL;
  191. static void ImportKernel()
  192. {
  193. if (gKernelDll != NULL)
  194. return;
  195. WCHAR path[MAX_PATH];
  196. GetSystemDirectory(path, MAX_PATH);
  197. wcscat(path, L"\\kernel32.dll");
  198. gKernelDll = GetModuleHandle(path);
  199. if (gKernelDll == NULL)
  200. {
  201. return;
  202. }
  203. gSetThreadDescription = (SetThreadDescription_t)GetProcAddress(gKernelDll, "SetThreadDescription");
  204. gGetThreadDescription = (GetThreadDescription_t)GetProcAddress(gKernelDll, "GetThreadDescription");
  205. }
  206. void WinDebugger::TryGetThreadName(WdThreadInfo* threadInfo)
  207. {
  208. if (threadInfo->mHThread == NULL)
  209. return;
  210. ImportKernel();
  211. PWSTR wStr = NULL;
  212. if (gGetThreadDescription != NULL)
  213. {
  214. gGetThreadDescription(threadInfo->mHThread, &wStr);
  215. if (wStr == NULL)
  216. return;
  217. threadInfo->mName = UTF8Encode(wStr);
  218. FilterThreadName(threadInfo->mName);
  219. LocalFree(wStr);
  220. }
  221. }
  222. static void CreateFilterName(String& name, DbgType* type)
  223. {
  224. CreateFilterName(name, type->mParent);
  225. switch (type->mTypeCode)
  226. {
  227. case DbgType_Namespace:
  228. case DbgType_Struct:
  229. case DbgType_Class:
  230. name += type->mName;
  231. break;
  232. }
  233. }
  234. static void CreateFilterName(String& name, const char* srcStr, DbgLanguage language)
  235. {
  236. int chevronDepth = 0;
  237. const char* cPtr = srcStr;
  238. for (; true; cPtr++)
  239. {
  240. char c = *cPtr;
  241. if (c == 0)
  242. break;
  243. if (c == '>')
  244. chevronDepth--;
  245. bool inGeneric = chevronDepth > 0;
  246. if (c == '<')
  247. chevronDepth++;
  248. if (inGeneric) // Bundle all generic instances together
  249. continue;
  250. if (c == '[') // Bundle all arrays together
  251. name.clear();
  252. if (c == '(')
  253. return; // Start of params
  254. if ((c == ':') && (cPtr[1] == ':') && (language == DbgLanguage_Beef))
  255. {
  256. name.Append('.');
  257. cPtr++;
  258. }
  259. else
  260. name.Append(c);
  261. }
  262. }
  263. static void CreateFilterName(String& name, DbgSubprogram* subprogram)
  264. {
  265. auto language = subprogram->GetLanguage();
  266. if (subprogram->mName == NULL)
  267. {
  268. if (subprogram->mLinkName[0] == '<')
  269. {
  270. name += subprogram->mLinkName;
  271. return;
  272. }
  273. name = BfDemangler::Demangle(subprogram->mLinkName, language);
  274. // Strip off the params since we need to generate those ourselves
  275. int parenPos = (int)name.IndexOf('(');
  276. if (parenPos != -1)
  277. name.RemoveToEnd(parenPos);
  278. return;
  279. }
  280. else if (subprogram->mHasQualifiedName)
  281. {
  282. const char* cPtr = subprogram->mName;
  283. if (strncmp(cPtr, "_bf::", 5) == 0)
  284. {
  285. CreateFilterName(name, cPtr + 5, DbgLanguage_Beef);
  286. name.Replace(".__BfStaticCtor", ".this$static");
  287. name.Replace(".__BfCtorClear", ".this$clear");
  288. name.Replace(".__BfCtor", ".this");
  289. }
  290. else
  291. CreateFilterName(name, subprogram->mName, language);
  292. return;
  293. }
  294. else
  295. {
  296. if (subprogram->mParentType != NULL)
  297. {
  298. String parentName = subprogram->mParentType->ToString();
  299. CreateFilterName(name, parentName.c_str(), language);
  300. if (!name.empty())
  301. {
  302. if (language == DbgLanguage_Beef)
  303. name += ".";
  304. else
  305. name += "::";
  306. }
  307. }
  308. if ((language == DbgLanguage_Beef) && (subprogram->mParentType != NULL) && (subprogram->mParentType->mTypeName != NULL) &&
  309. (strcmp(subprogram->mName, subprogram->mParentType->mTypeName) == 0))
  310. name += "this";
  311. else if ((language == DbgLanguage_Beef) && (subprogram->mName[0] == '~'))
  312. name += "~this";
  313. else if (strncmp(subprogram->mName, "_bf::", 5) == 0)
  314. {
  315. CreateFilterName(name, subprogram->mName + 5, DbgLanguage_Beef);
  316. }
  317. else
  318. {
  319. CreateFilterName(name, subprogram->mName, language);
  320. }
  321. }
  322. if (name.empty())
  323. name += "`anon";
  324. if ((name[name.length() - 1] == '!') || (name[0] == '<'))
  325. {
  326. if (language == DbgLanguage_Beef)
  327. {
  328. // It's a mixin - assert that there's no params
  329. //BF_ASSERT(subprogram->mParams.Size() == 0);
  330. }
  331. return;
  332. }
  333. }
  334. //////////////////////////////////////////////////////////////////////////
  335. DbgPendingExpr::DbgPendingExpr()
  336. {
  337. mThreadId = -1;
  338. mCallStackIdx = -1;
  339. mParser = NULL;
  340. mCursorPos = -1;
  341. mExprNode = NULL;
  342. mIdleTicks = 0;
  343. mExplitType = NULL;
  344. mExpressionFlags = DwEvalExpressionFlag_None;
  345. }
  346. DbgPendingExpr::~DbgPendingExpr()
  347. {
  348. delete mParser;
  349. }
  350. // conversion logic based on table at http://en.wikipedia.org/wiki/Extended_precision
  351. //CDH TODO put this somewhere more general
  352. static double ConvertFloat80ToDouble(const byte fp80[10])
  353. {
  354. uint16 e = *((uint16*)&fp80[8]);
  355. uint64 m = *((uint64*)&fp80[0]);
  356. uint64 bit63 = (uint64)1 << 63;
  357. uint64 bit62 = (uint64)1 << 62;
  358. bool isNegative = (e & 0x8000) != 0;
  359. double s = isNegative ? -1.0 : 1.0;
  360. e &= 0x7fff;
  361. if (!e)
  362. {
  363. // the high bit and mantissa content will determine whether it's an actual zero, or a denormal or
  364. // pseudo-denormal number with an effective exponent of -16382. But since that exponent is so far
  365. // below anything we can handle in double-precision (even accounting for denormal bit shifts), we're
  366. // effectively still dealing with zero.
  367. return s * 0.0;
  368. }
  369. else if (e == 0x7fff)
  370. {
  371. if (m & bit63)
  372. {
  373. if (m & bit62)
  374. {
  375. return std::numeric_limits<double>::quiet_NaN();
  376. }
  377. else
  378. {
  379. if (m == bit63)
  380. return s * std::numeric_limits<double>::infinity();
  381. else
  382. return std::numeric_limits<double>::signaling_NaN();
  383. }
  384. }
  385. else
  386. {
  387. return std::numeric_limits<double>::quiet_NaN();
  388. }
  389. }
  390. else
  391. {
  392. if (!(m & bit63))
  393. return std::numeric_limits<double>::quiet_NaN(); // unnormal (we don't handle these since 80387 and later treat them as invalid operands anyway)
  394. // else is a normalized value
  395. }
  396. int useExponent = (int)e - 16383;
  397. if (useExponent < -1022)
  398. return s * 0.0; // we could technically support e from -1023 to -1074 as denormals, but don't bother with that for now.
  399. else if (useExponent > 1023)
  400. return s * HUGE_VAL;
  401. useExponent += 1023;
  402. BF_ASSERT((useExponent > 0) && (useExponent < 0x7ff)); // assume we've filtered for valid exponent range
  403. BF_ASSERT(m & bit63); // assume we've filtered out values that aren't normalized by now
  404. uint64 result = 0;
  405. if (isNegative)
  406. result |= bit63;
  407. result |= (uint64)useExponent << 52;
  408. result |= (m & ~bit63) >> 11;
  409. return *reinterpret_cast<double*>(&result);
  410. }
  411. addr_target NS_BF_DBG::DecodeTargetDataPtr(const char*& strRef)
  412. {
  413. addr_target val = (addr_target)stouln(strRef, sizeof(intptr) * 2);
  414. strRef += sizeof(intptr) * 2;
  415. return val;
  416. }
  417. WinDebugger::WinDebugger(DebugManager* debugManager) : mDbgSymSrv(this)
  418. {
  419. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  420. mActiveHotIdx = -1;
  421. mGotStartupEvent = false;
  422. mIsContinuingFromException = false;
  423. mDestroying = false;
  424. mDebugManager = debugManager;
  425. mNeedsRehupBreakpoints = false;
  426. mStepInAssembly = false;
  427. mStepSP = 0;
  428. mStepIsRecursing = false;
  429. mStepStopOnNextInstruction = false;
  430. mDebugTarget = NULL;
  431. mShuttingDown = false;
  432. mBfSystem = new BfSystem();
  433. mAtBreakThread = NULL;
  434. mActiveThread = NULL;
  435. mActiveBreakpoint = NULL;
  436. mSteppingThread = NULL;
  437. mExplicitStopThread = NULL;
  438. mStepSwitchedThreads = false;
  439. mIsDebuggerWaiting = false;
  440. mWantsDebugContinue = false;
  441. mContinueFromBreakpointFailed = false;
  442. mIsStepIntoSpecific = false;
  443. mDbgBreak = false;
  444. mDebuggerWaitingThread = NULL;
  445. mStepType = StepType_None;
  446. mOrigStepType = StepType_None;
  447. mLastValidStepIntoPC = 0;
  448. mActiveSymSrvRequest = NULL;
  449. mStoredReturnValueAddr = 0;
  450. #ifdef BF_DBG_32
  451. mCPU = gX86Target->mX86CPU;
  452. #else
  453. mCPU = gX86Target->mX64CPU;
  454. #endif
  455. mRunState = RunState_NotStarted;
  456. mIsRunning = false;
  457. mSavedAtBreakpointAddress = 0;
  458. mSavedBreakpointAddressContinuing = 0;
  459. mRequestedStackFrameIdx = 0;
  460. mShowPCOverride = 0;
  461. mCurNoInfoStepTries = 0;
  462. mDbgAttachFlags = BfDbgAttachFlag_None;
  463. mDbgProcessHandle = 0;
  464. mDbgThreadHandle = 0;
  465. mDbgProcessId = 0;
  466. mIsPartialCallStack = true;
  467. for (int i = 0; i < 4; i++)
  468. {
  469. mFreeMemoryBreakIndices.push_back(i);
  470. }
  471. SYSTEM_INFO systemInfo;
  472. GetSystemInfo(&systemInfo);
  473. mPageSize = systemInfo.dwPageSize;
  474. mEmptyDebugTarget = new DebugTarget(this);
  475. mEmptyDebugTarget->CreateEmptyTarget();
  476. mEmptyDebugTarget->mIsEmpty = true;
  477. mDebugTarget = mEmptyDebugTarget;
  478. mDebugPendingExpr = NULL;
  479. mDebugEvalThreadInfo = WdThreadInfo();
  480. mMemCacheAddr = 0;
  481. mDebuggerThreadId = 0;
  482. }
  483. WinDebugger::~WinDebugger()
  484. {
  485. mDestroying = true;
  486. delete gDbgPerfManager;
  487. gDbgPerfManager = NULL;
  488. if ((mDebugTarget != NULL) && (mDebugTarget != mEmptyDebugTarget))
  489. Detach();
  490. for (auto breakpoint : mBreakpoints)
  491. {
  492. auto checkBreakpoint = breakpoint->mLinkedSibling;
  493. while (checkBreakpoint != NULL)
  494. {
  495. auto nextBreakpoint = checkBreakpoint->mLinkedSibling;
  496. delete checkBreakpoint;
  497. checkBreakpoint = nextBreakpoint;
  498. }
  499. delete breakpoint;
  500. }
  501. delete mEmptyDebugTarget;
  502. delete mBfSystem;
  503. for (auto kv : mPendingProfilerMap)
  504. delete kv.mValue;
  505. for (auto profiler : mNewProfilerList)
  506. delete profiler;
  507. delete mDebugPendingExpr;
  508. }
  509. void WinDebugger::Fail(const StringImpl& error)
  510. {
  511. if (mIsRunning)
  512. mDebugManager->mOutMessages.push_back(StrFormat("error %s", error.c_str()));
  513. }
  514. // Leave active thread unpaused
  515. void WinDebugger::ThreadRestorePause(WdThreadInfo* onlyPauseThread, WdThreadInfo* dontPauseThread)
  516. {
  517. BfLogDbg("ThreadRestorePause %d %d\n", (onlyPauseThread != NULL) ? onlyPauseThread->mThreadId : 0, (dontPauseThread != NULL) ? dontPauseThread->mThreadId : 0);
  518. for (auto threadInfo : mThreadList)
  519. {
  520. if (((threadInfo != dontPauseThread) && (!threadInfo->mIsBreakRestorePaused)) &&
  521. ((onlyPauseThread == NULL) || (threadInfo == onlyPauseThread)))
  522. {
  523. BF_ASSERT(!threadInfo->mIsBreakRestorePaused);
  524. BfLogDbg("SuspendThread %d\n", threadInfo->mThreadId);
  525. ::SuspendThread(threadInfo->mHThread);
  526. threadInfo->mIsBreakRestorePaused = true;
  527. }
  528. }
  529. }
  530. void WinDebugger::ThreadRestoreUnpause()
  531. {
  532. BfLogDbg("ThreadRestoreUnpause\n");
  533. for (auto threadInfo : mThreadList)
  534. {
  535. if (threadInfo->mIsBreakRestorePaused)
  536. {
  537. BfLogDbg("ResumeThread %d\n", threadInfo->mThreadId);
  538. ::ResumeThread(threadInfo->mHThread);
  539. threadInfo->mIsBreakRestorePaused = false;
  540. }
  541. }
  542. }
  543. void WinDebugger::UpdateThreadDebugRegisters(WdThreadInfo* threadInfo)
  544. {
  545. auto threadId = threadInfo->mHThread;
  546. BF_CONTEXT lcContext;
  547. lcContext.ContextFlags = BF_CONTEXT_DEBUG_REGISTERS;
  548. BF_GetThreadContext(threadId, &lcContext);
  549. for (int memoryBreakIdx = 0; memoryBreakIdx < 4; memoryBreakIdx++)
  550. {
  551. WdMemoryBreakpointBind memoryBreakpointBind = mMemoryBreakpoints[memoryBreakIdx];
  552. WdBreakpoint* wdBreakpoint = memoryBreakpointBind.mBreakpoint;
  553. if (wdBreakpoint == NULL)
  554. {
  555. *(&lcContext.Dr0 + memoryBreakIdx) = 0;
  556. lcContext.Dr7 &= ~((1 << (memoryBreakIdx * 2)) | (1 << (16 + memoryBreakIdx * 4)) | (3 << (18 + memoryBreakIdx * 4)));
  557. }
  558. else
  559. {
  560. int sizeCode = 0;
  561. if (memoryBreakpointBind.mByteCount == 2)
  562. sizeCode = 1;
  563. else if (memoryBreakpointBind.mByteCount == 4)
  564. sizeCode = 3;
  565. else if (memoryBreakpointBind.mByteCount == 8)
  566. sizeCode = 2;
  567. addr_target calcAddr = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress + memoryBreakpointBind.mOfs;
  568. BF_ASSERT(calcAddr == memoryBreakpointBind.mAddress);
  569. *(&lcContext.Dr0 + memoryBreakIdx) = calcAddr;
  570. lcContext.Dr7 |= (1 << (memoryBreakIdx * 2)) | (1 << (16 + memoryBreakIdx * 4)) | (sizeCode << (18 + memoryBreakIdx * 4));
  571. }
  572. }
  573. bool worked = BF_SetThreadContext(threadId, &lcContext) != 0;
  574. BF_ASSERT(worked || (mRunState == RunState_Terminating) || (mRunState == RunState_Terminated));
  575. }
  576. void WinDebugger::UpdateThreadDebugRegisters()
  577. {
  578. for (auto threadInfo : mThreadList)
  579. {
  580. ::SuspendThread(threadInfo->mHThread);
  581. UpdateThreadDebugRegisters(threadInfo);
  582. ::ResumeThread(threadInfo->mHThread);
  583. }
  584. }
  585. void WinDebugger::PhysSetBreakpoint(addr_target address)
  586. {
  587. BfLogDbg("PhysSetBreakpoint %p\n", address);
  588. uint8 newData = 0xCC;
  589. // This ensure that we have the orig image data cached
  590. DbgMemoryFlags flags = mDebugTarget->ReadOrigImageData(address, NULL, 1);
  591. if ((flags & DbgMemoryFlags_Execute) == 0)
  592. {
  593. BfLogDbg("Breakpoint ignored - execute flag NOT set in breakpoint address\n", address);
  594. BfLogDbg("Memory Flags = %d\n", gDebugger->GetMemoryFlags(address));
  595. return;
  596. }
  597. // Replace it with Breakpoint
  598. SIZE_T dwReadBytes;
  599. BOOL worked = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, &newData, 1, &dwReadBytes);
  600. if (!worked)
  601. {
  602. int err = GetLastError();
  603. BfLogDbg("SetBreakpoint FAILED %p\n", address);
  604. }
  605. FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, 1);
  606. {
  607. uint8 mem = ReadMemory<uint8>(address);
  608. BfLogDbg("Breakpoint byte %X\n", mem);
  609. }
  610. }
  611. void WinDebugger::SetBreakpoint(addr_target address, bool fromRehup)
  612. {
  613. int* countPtr = NULL;
  614. if (mBreakpointAddrMap.TryAdd(address, NULL, &countPtr))
  615. {
  616. BfLogDbg("SetBreakpoint %p\n", address);
  617. *countPtr = 1;
  618. }
  619. else
  620. {
  621. if (fromRehup)
  622. {
  623. BfLogDbg("SetBreakpoint %p Count: %d. Rehup (ignored).\n", address, *countPtr);
  624. return;
  625. }
  626. (*countPtr)++;
  627. BfLogDbg("SetBreakpoint %p Count: %d\n", address, *countPtr);
  628. return;
  629. }
  630. PhysSetBreakpoint(address);
  631. }
  632. void WinDebugger::SetTempBreakpoint(addr_target address)
  633. {
  634. BfLogDbg("SetTempBreakpoint %p\n", address);
  635. mTempBreakpoint.push_back(address);
  636. SetBreakpoint(address);
  637. }
  638. void WinDebugger::PhysRemoveBreakpoint(addr_target address)
  639. {
  640. BfLogDbg("PhysRemoveBreakpoint %p\n", address);
  641. uint8 origData;
  642. DbgMemoryFlags flags = mDebugTarget->ReadOrigImageData(address, &origData, 1);
  643. if ((flags & DbgMemoryFlags_Execute) == 0)
  644. {
  645. //BF_ASSERT("Failed" == 0);
  646. return;
  647. }
  648. SIZE_T dwReadBytes;
  649. if (!WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, &origData, 1, &dwReadBytes))
  650. {
  651. int err = GetLastError();
  652. BfLogDbg("RemoveBreakpoint FAILED %p\n", address);
  653. }
  654. FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, 1);
  655. }
  656. void WinDebugger::RemoveBreakpoint(addr_target address)
  657. {
  658. int* countPtr = NULL;
  659. mBreakpointAddrMap.TryGetValue(address, &countPtr);
  660. // This can happen when we shutdown and we're continuing from a breakpoint
  661. //BF_ASSERT(*countPtr != NULL);
  662. if (countPtr == NULL)
  663. {
  664. BfLogDbg("RemoveBreakpoint %p FAILED\n", address);
  665. return;
  666. }
  667. BfLogDbg("RemoveBreakpoint %p count: %d\n", address, *countPtr);
  668. if (*countPtr > 1)
  669. {
  670. (*countPtr)--;
  671. return;
  672. }
  673. mBreakpointAddrMap.Remove(address);
  674. PhysRemoveBreakpoint(address);
  675. }
  676. void WinDebugger::SingleStepX86()
  677. {
  678. // In what cases did this catch bugs?
  679. // This caused other failures (caught in tests)
  680. // if (mActiveThread->mIsAtBreakpointAddress != 0)
  681. // {
  682. // ContinueFromBreakpoint();
  683. // return;
  684. // }
  685. BfLogDbg("Setup SingleStepX86 ActiveThread: %d\n", (mActiveThread != NULL) ? mActiveThread->mThreadId : -1);
  686. BF_CONTEXT lcContext;
  687. lcContext.ContextFlags = BF_CONTEXT_ALL;
  688. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  689. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  690. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  691. }
  692. bool WinDebugger::IsInRunState()
  693. {
  694. return (mRunState == RunState_Running) || (mRunState == RunState_Running_ToTempBreakpoint);
  695. }
  696. bool WinDebugger::ContinueFromBreakpoint()
  697. {
  698. if (mDebuggerWaitingThread->mFrozen)
  699. {
  700. BfLogDbg("ContinueFromBreakpoint bailout on frozen thread\n");
  701. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  702. mDebuggerWaitingThread->mIsAtBreakpointAddress = 0;
  703. return true;
  704. }
  705. mActiveThread = mDebuggerWaitingThread;
  706. mActiveBreakpoint = NULL;
  707. BfLogDbg("ContinueFromBreakpoint. ActiveThread: %d\n", (mActiveThread != NULL) ? mActiveThread->mThreadId : -1);
  708. BfLogDbg("ResumeThread %d\n", mActiveThread->mThreadId);
  709. BOOL success = ::ResumeThread(mActiveThread->mHThread);
  710. if (success)
  711. {
  712. // It's possible the active thread is suspended - possibly by the GC, so we would deadlock if we
  713. // attempted to pause the other threads
  714. BfLogDbg("SuspendThread %d\n", mActiveThread->mThreadId);
  715. BfLogDbg("Thread already paused!\n");
  716. ::SuspendThread(mActiveThread->mHThread);
  717. return false;
  718. }
  719. ThreadRestorePause(NULL, mActiveThread);
  720. PhysRemoveBreakpoint(mActiveThread->mIsAtBreakpointAddress);
  721. BF_CONTEXT lcContext;
  722. lcContext.ContextFlags = BF_CONTEXT_ALL;
  723. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  724. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  725. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  726. mActiveThread->mStoppedAtAddress = 0;
  727. mActiveThread->mBreakpointAddressContinuing = mActiveThread->mIsAtBreakpointAddress;
  728. mActiveThread->mIsAtBreakpointAddress = 0;
  729. BfLogDbg("ContinueFromBreakpoint set mIsAtBreakpointAddress = 0\n");
  730. return true;
  731. }
  732. Breakpoint* WinDebugger::FindBreakpointAt(intptr addressIn)
  733. {
  734. addr_target address = addressIn;
  735. WdBreakpoint* found = NULL;
  736. for (auto breakpoint : mBreakpoints)
  737. {
  738. if (breakpoint->mAddr == address)
  739. found = breakpoint;
  740. auto checkSibling = (WdBreakpoint*)breakpoint->mLinkedSibling;
  741. while (checkSibling != NULL)
  742. {
  743. if (checkSibling->mAddr == address)
  744. found = checkSibling;
  745. checkSibling = (WdBreakpoint*)checkSibling->mLinkedSibling;
  746. }
  747. }
  748. return found;
  749. }
  750. Breakpoint* WinDebugger::GetActiveBreakpoint()
  751. {
  752. if ((mActiveBreakpoint != NULL) && (mActiveBreakpoint->mHead != NULL))
  753. return mActiveBreakpoint->mHead;
  754. return mActiveBreakpoint;
  755. }
  756. void WinDebugger::DebugThreadProc()
  757. {
  758. BpSetThreadName("DebugThread");
  759. BfpThread_SetName(NULL, "DebugThread", NULL);
  760. mDebuggerThreadId = GetCurrentThreadId();
  761. if (!IsMiniDumpDebugger())
  762. {
  763. if (!DoOpenFile(mLaunchPath, mArgs, mWorkingDir, mEnvBlock))
  764. {
  765. if (mDbgProcessId != 0)
  766. OutputRawMessage("error Unable to attach to process");
  767. else
  768. OutputRawMessage(StrFormat("error Failed to launch: %s", mLaunchPath.c_str()));
  769. mShuttingDown = true;
  770. mRunState = RunState_Terminated;
  771. }
  772. }
  773. while (!mShuttingDown)
  774. {
  775. DoUpdate();
  776. }
  777. mIsRunning = false;
  778. for (int i = 0; i < (int) mBreakpoints.size(); i++)
  779. {
  780. WdBreakpoint* wdBreakpoint = mBreakpoints[i];
  781. wdBreakpoint->mAddr = 0;
  782. wdBreakpoint->mLineData = DbgLineDataEx();
  783. wdBreakpoint->mSrcFile = NULL;
  784. if (wdBreakpoint->mLinkedSibling != NULL)
  785. {
  786. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  787. wdBreakpoint->mLinkedSibling = NULL;
  788. }
  789. }
  790. if (!IsMiniDumpDebugger())
  791. {
  792. while (true)
  793. {
  794. if (!mIsDebuggerWaiting)
  795. {
  796. if (!WaitForDebugEvent(&mDebugEvent, 0))
  797. break;
  798. }
  799. if (mDebuggerWaitingThread != NULL)
  800. {
  801. BF_ASSERT_REL((mDebuggerWaitingThread->mIsAtBreakpointAddress == 0) || (mShuttingDown));
  802. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_CONTINUE);
  803. BfLogDbg("::ContinueDebugEvent startup ThreadId:%d\n", mDebuggerWaitingThread->mThreadId);
  804. }
  805. mIsDebuggerWaiting = false;
  806. mDebuggerWaitingThread = NULL;
  807. }
  808. }
  809. mDebuggerThreadId = 0;
  810. }
  811. static void DebugThreadProcThunk(void* winDebugger)
  812. {
  813. ((WinDebugger*) winDebugger)->DebugThreadProc();
  814. }
  815. int WinDebugger::GetAddrSize()
  816. {
  817. return sizeof(addr_target);
  818. }
  819. bool WinDebugger::CanOpen(const StringImpl& fileName, DebuggerResult* outResult)
  820. {
  821. FILE* fp = fopen(fileName.c_str(), "rb");
  822. if (fp == NULL)
  823. {
  824. *outResult = DebuggerResult_CannotOpen;
  825. return false;
  826. }
  827. FileStream fs;
  828. fs.mFP = fp;
  829. *outResult = DebuggerResult_Ok;
  830. bool canRead = DbgModule::CanRead(&fs, outResult);
  831. fclose(fp);
  832. return canRead;
  833. }
  834. void WinDebugger::OpenFile(const StringImpl& launchPath, const StringImpl& targetPath, const StringImpl& args, const StringImpl& workingDir, const Array<uint8>& envBlock)
  835. {
  836. BF_ASSERT(!mIsRunning);
  837. mLaunchPath = launchPath;
  838. mTargetPath = targetPath;
  839. mArgs = args;
  840. mWorkingDir = workingDir;
  841. mEnvBlock = envBlock;
  842. mDebugTarget = new DebugTarget(this);
  843. }
  844. bool WinDebugger::Attach(int processId, BfDbgAttachFlags attachFlags)
  845. {
  846. BF_ASSERT(!mIsRunning);
  847. mDbgAttachFlags = attachFlags;
  848. mDbgProcessHandle = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)processId);
  849. if (mDbgProcessHandle == 0)
  850. return false;
  851. BOOL is32Bit = false;
  852. if (!IsWow64Process(mDbgProcessHandle, &is32Bit))
  853. {
  854. mDbgProcessHandle = 0;
  855. ::CloseHandle(mDbgProcessHandle);
  856. return false;
  857. }
  858. bool want32Bit = sizeof(intptr_target) == 4;
  859. if (want32Bit != (is32Bit != 0))
  860. {
  861. mDbgProcessHandle = 0;
  862. ::CloseHandle(mDbgProcessHandle);
  863. return false;
  864. }
  865. HMODULE mainModule = 0;
  866. DWORD memNeeded = 0;
  867. ::EnumProcessModules(mDbgProcessHandle, &mainModule, sizeof(HMODULE), &memNeeded);
  868. WCHAR fileName[MAX_PATH] = {0};
  869. GetModuleFileNameExW(mDbgProcessHandle, mainModule, fileName, MAX_PATH);
  870. mLaunchPath = UTF8Encode(fileName);
  871. mTargetPath = mLaunchPath;
  872. mDbgProcessId = processId;
  873. mDbgProcessHandle = 0;
  874. ::CloseHandle(mDbgProcessHandle);
  875. mDebugTarget = new DebugTarget(this);
  876. return true;
  877. }
  878. void WinDebugger::Run()
  879. {
  880. mIsRunning = true;
  881. DWORD localThreadId;
  882. HANDLE hThread = ::CreateThread(NULL, 64 * 1024, (LPTHREAD_START_ROUTINE) &DebugThreadProcThunk, (void*)this, 0, &localThreadId);
  883. CloseHandle(hThread);
  884. }
  885. void WinDebugger::HotLoad(const Array<String>& objectFiles, int hotIdx)
  886. {
  887. AutoCrit autoCrit(mDebugManager->mCritSect);
  888. SetAndRestoreValue<int> prevHotIdx(mActiveHotIdx, hotIdx);
  889. BF_ASSERT(mHotThreadStates.empty());
  890. mHotThreadStates.Resize(mThreadList.size());
  891. for (int threadIdx = 0; threadIdx < (int)mThreadList.size(); threadIdx++)
  892. {
  893. WdThreadInfo* threadInfo = mThreadList[threadIdx];
  894. SetAndRestoreValue<WdThreadInfo*> prevActiveThread(mActiveThread, threadInfo);
  895. BfLogDbg("SuspendThread %d\n", threadInfo->mThreadId);
  896. ::SuspendThread(threadInfo->mHThread);
  897. PopulateRegisters(&mHotThreadStates[threadIdx]);
  898. }
  899. for (auto address : mTempBreakpoint)
  900. RemoveBreakpoint(address);
  901. mTempBreakpoint.Clear();
  902. mStepBreakpointAddrs.Clear();
  903. for (auto breakpoint : mBreakpoints)
  904. {
  905. DetachBreakpoint(breakpoint);
  906. }
  907. int startingModuleIdx = (int)mDebugTarget->mDbgModules.size();
  908. BfLogDbg("WinDebugger::HotLoad\n");
  909. bool failed = false;
  910. for (auto fileName : objectFiles)
  911. {
  912. BfLogDbg("WinDebugger::HotLoad: %s\n", fileName.c_str());
  913. DbgModule* newBinary = mDebugTarget->HotLoad(fileName, hotIdx);
  914. if ((newBinary != NULL) && (newBinary->mFailed))
  915. failed = true;
  916. }
  917. for (int moduleIdx = startingModuleIdx; moduleIdx < (int)mDebugTarget->mDbgModules.size(); moduleIdx++)
  918. {
  919. auto dbgModule = mDebugTarget->mDbgModules[moduleIdx];
  920. BF_ASSERT(dbgModule->mIsHotObjectFile);
  921. BF_ASSERT(dbgModule->mHotIdx == hotIdx);
  922. dbgModule->FinishHotSwap();
  923. }
  924. for (auto dwarf : mDebugTarget->mDbgModules)
  925. dwarf->RevertWritingEnable();
  926. mHotThreadStates.Clear();
  927. int blockAllocSinceClean = mDebugTarget->mHotHeap->mBlockAllocIdx - mDebugTarget->mLastHotHeapCleanIdx;
  928. // Clean up the hot heap every 64MB
  929. int blocksBetweenCleans = (64 * 1024 * 1024) / HotHeap::BLOCK_SIZE;
  930. #ifdef _DEBUG
  931. //TODO: This is just for testing
  932. blocksBetweenCleans = 1;
  933. #endif
  934. //TODO: Put this back after we fix the cleanup
  935. if (blockAllocSinceClean >= blocksBetweenCleans)
  936. CleanupHotHeap();
  937. mDebugTarget->RehupSrcFiles();
  938. for (int breakIdx = 0; breakIdx < (int)mBreakpoints.size(); breakIdx++)
  939. {
  940. auto breakpoint = mBreakpoints[breakIdx];
  941. CheckBreakpoint(breakpoint);
  942. }
  943. for (int threadIdx = 0; threadIdx < (int)mThreadList.size(); threadIdx++)
  944. {
  945. WdThreadInfo* threadInfo = mThreadList[threadIdx];
  946. BfLogDbg("ResumeThread %d\n", threadInfo->mThreadId);
  947. ::ResumeThread(threadInfo->mHThread);
  948. }
  949. if (IsPaused())
  950. {
  951. ClearCallStack();
  952. UpdateCallStack();
  953. }
  954. }
  955. void WinDebugger::InitiateHotResolve(DbgHotResolveFlags flags)
  956. {
  957. AutoCrit autoCrit(mDebugManager->mCritSect);
  958. delete mHotResolveData;
  959. mHotResolveData = NULL;
  960. mHotResolveData = new DbgHotResolveData();
  961. DbgHotScanner* hotScanner = new DbgHotScanner(this);
  962. hotScanner->Scan(flags);
  963. delete hotScanner;
  964. }
  965. bool WinDebugger::DoOpenFile(const StringImpl& fileName, const StringImpl& args, const StringImpl& workingDir, const Array<uint8>& envBlock)
  966. {
  967. BP_ZONE("WinDebugger::DoOpenFile");
  968. AutoCrit autoCrit(mDebugManager->mCritSect);
  969. //gDbgPerfManager->StartRecording();
  970. STARTUPINFOW si;
  971. ZeroMemory(&si, sizeof(si));
  972. si.cb = sizeof(si);
  973. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  974. if (mDbgProcessId != 0)
  975. {
  976. BOOL success = ::DebugActiveProcess(mDbgProcessId);
  977. if (!success)
  978. return false;
  979. mProcessInfo.dwProcessId = mDbgProcessId;
  980. }
  981. else
  982. {
  983. BP_ZONE("DoOpenFile_CreateProcessW");
  984. UTF16String envW;
  985. DWORD flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS | CREATE_DEFAULT_ERROR_MODE;
  986. void* envPtr = NULL;
  987. if (!envBlock.IsEmpty())
  988. {
  989. //UTF16?
  990. if (envBlock[1] == 0)
  991. {
  992. envPtr = (void*)&envBlock[0];
  993. flags |= CREATE_UNICODE_ENVIRONMENT;
  994. }
  995. else
  996. {
  997. String str8((char*)&envBlock[0], (int)envBlock.size());
  998. envW = UTF8Decode(str8);
  999. envPtr = (void*)envW.c_str();
  1000. flags |= CREATE_UNICODE_ENVIRONMENT;
  1001. }
  1002. }
  1003. String cmdLine = "\"";
  1004. cmdLine += fileName;
  1005. cmdLine += "\"";
  1006. if (!args.IsEmpty())
  1007. {
  1008. cmdLine += " ";
  1009. cmdLine += args;
  1010. }
  1011. BOOL worked = CreateProcessW(NULL, (WCHAR*)UTF8Decode(cmdLine).c_str(), NULL, NULL, FALSE,
  1012. flags, envPtr, (WCHAR*)UTF8Decode(workingDir).c_str(), &si, &mProcessInfo);
  1013. if (!worked)
  1014. {
  1015. auto lastError = ::GetLastError();
  1016. if (lastError == ERROR_DIRECTORY)
  1017. {
  1018. mDebugManager->mOutMessages.push_back(StrFormat("error Unable to locate specified working directory '%s'", SlashString(workingDir, false, false).c_str()));
  1019. }
  1020. return false;
  1021. }
  1022. WdThreadInfo* threadInfo = new WdThreadInfo();
  1023. threadInfo->mProcessId = mProcessInfo.dwProcessId;
  1024. threadInfo->mThreadId = mProcessInfo.dwThreadId;
  1025. threadInfo->mHThread = mProcessInfo.hThread;
  1026. threadInfo->mThreadLocalBase = NULL;
  1027. threadInfo->mStartAddress = NULL;
  1028. mThreadMap[mProcessInfo.dwThreadId] = threadInfo;
  1029. mThreadList.push_back(threadInfo);
  1030. }
  1031. mRunState = RunState_Running;
  1032. while (true)
  1033. {
  1034. BP_ZONE("DoOpenFile_WaitForImageBase");
  1035. autoCrit.mCritSect->Unlock();
  1036. DoUpdate();
  1037. autoCrit.mCritSect->Lock();
  1038. ContinueDebugEvent();
  1039. if ((mDebugTarget->mLaunchBinary != NULL) && (mDebugTarget->mLaunchBinary->mOrigImageData != NULL))
  1040. break;
  1041. }
  1042. RehupBreakpoints(true);
  1043. //gDbgPerfManager->StopRecording();
  1044. //gDbgPerfManager->DbgPrint();
  1045. return true;
  1046. }
  1047. void WinDebugger::StopDebugging()
  1048. {
  1049. AutoCrit autoCrit(mDebugManager->mCritSect);
  1050. BfLogDbg("WinDebugger::Terminate\n");
  1051. if (mActiveSymSrvRequest != NULL)
  1052. mActiveSymSrvRequest->Cancel();
  1053. if ((mRunState == RunState_NotStarted) || (mRunState == RunState_Terminated) || (mRunState == RunState_Terminating))
  1054. return;
  1055. if ((mDbgProcessId != 0) && ((mDbgAttachFlags & BfDbgAttachFlag_ShutdownOnExit) == 0))
  1056. {
  1057. BfLogDbg("StopDebugging\n");
  1058. ::DebugActiveProcessStop(mDbgProcessId);
  1059. mRunState = RunState_Terminated;
  1060. BfLogDbg("mRunState = RunState_Terminated\n");
  1061. }
  1062. else
  1063. {
  1064. TerminateProcess(mProcessInfo.hProcess, 0);
  1065. mRunState = RunState_Terminating;
  1066. BfLogDbg("mRunState = RunState_Terminating\n");
  1067. }
  1068. }
  1069. void WinDebugger::Terminate()
  1070. {
  1071. AutoCrit autoCrit(mDebugManager->mCritSect);
  1072. BfLogDbg("WinDebugger::Terminate\n");
  1073. if (mActiveSymSrvRequest != NULL)
  1074. mActiveSymSrvRequest->Cancel();
  1075. if ((mRunState == RunState_NotStarted) || (mRunState == RunState_Terminated) || (mRunState == RunState_Terminating))
  1076. return;
  1077. TerminateProcess(mProcessInfo.hProcess, 0);
  1078. mRunState = RunState_Terminating;
  1079. BfLogDbg("mRunState = RunState_Terminating\n");
  1080. }
  1081. static int gDebugUpdateCnt = 0;
  1082. void WinDebugger::Detach()
  1083. {
  1084. BfLogDbg("Debugger Detach\n");
  1085. mDebugManager->mNetManager->CancelAll();
  1086. while ((mIsRunning) || (mDebuggerThreadId != 0))
  1087. {
  1088. mShuttingDown = true;
  1089. Sleep(1);
  1090. }
  1091. mPendingProfilerMap.Clear();
  1092. for (auto profiler : mNewProfilerList)
  1093. delete profiler;
  1094. mNewProfilerList.Clear();
  1095. mPendingImageLoad.Clear();
  1096. mPendingDebugInfoLoad.Clear();
  1097. RemoveTempBreakpoints();
  1098. mContinueEvent.Reset();
  1099. if (mDebugTarget != mEmptyDebugTarget)
  1100. delete mDebugTarget;
  1101. mDebugTarget = mEmptyDebugTarget;
  1102. mShuttingDown = false;
  1103. mStepSP = 0;
  1104. ClearCallStack();
  1105. mRunState = RunState_NotStarted;
  1106. mStepType = StepType_None;
  1107. mHadImageFindError = false;
  1108. mIsPartialCallStack = true;
  1109. delete mDebugPendingExpr;
  1110. mDebugPendingExpr = NULL;
  1111. for (auto threadPair : mThreadMap)
  1112. {
  1113. auto threadInfo = threadPair.mValue;
  1114. delete threadInfo;
  1115. }
  1116. mThreadMap.Clear();
  1117. mThreadList.Clear();
  1118. mHotTargetMemory.Clear();
  1119. // We don't need to close the hThread when we have attached to a process
  1120. if (mDbgProcessId == 0)
  1121. {
  1122. CloseHandle(mProcessInfo.hThread);
  1123. CloseHandle(mProcessInfo.hProcess);
  1124. }
  1125. for (auto breakpoint : mBreakpoints)
  1126. {
  1127. if (!mDestroying)
  1128. {
  1129. BF_FATAL("Breakpoints should be deleted already");
  1130. }
  1131. if (breakpoint->mMemoryBreakpointInfo != NULL)
  1132. {
  1133. DetachBreakpoint(breakpoint);
  1134. }
  1135. }
  1136. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  1137. mStepBreakpointAddrs.Clear();
  1138. mIsRunning = false;
  1139. mDbgAttachFlags = BfDbgAttachFlag_None;
  1140. mDbgProcessId = 0;
  1141. mDbgProcessHandle = 0;
  1142. ClearCallStack();
  1143. mWantsDebugContinue = false;
  1144. mAtBreakThread = NULL;
  1145. mActiveThread = NULL;
  1146. mActiveBreakpoint = NULL;
  1147. mSteppingThread = NULL;
  1148. mExplicitStopThread = NULL;
  1149. mIsContinuingFromException = false;
  1150. mGotStartupEvent = false;
  1151. mIsDebuggerWaiting = false;
  1152. mBreakpointAddrMap.Clear();
  1153. gDebugUpdateCnt = 0;
  1154. }
  1155. Profiler* WinDebugger::StartProfiling()
  1156. {
  1157. return new DbgProfiler(this);
  1158. }
  1159. Profiler* WinDebugger::PopProfiler()
  1160. {
  1161. AutoCrit autoCrit(mDebugManager->mCritSect);
  1162. if (mNewProfilerList.IsEmpty())
  1163. return NULL;
  1164. auto profiler = (DbgProfiler*)mNewProfilerList[0];
  1165. mNewProfilerList.erase(mNewProfilerList.begin());
  1166. return profiler;
  1167. }
  1168. void WinDebugger::ReportMemory(MemReporter* memReporter)
  1169. {
  1170. mEmptyDebugTarget->ReportMemory(memReporter);
  1171. if (mDebugTarget != mEmptyDebugTarget)
  1172. mDebugTarget->ReportMemory(memReporter);
  1173. }
  1174. void WinDebugger::ModuleChanged(DbgModule* dbgModule)
  1175. {
  1176. mDebugManager->mOutMessages.push_back(String("dbgInfoLoaded ") + dbgModule->mFilePath);
  1177. }
  1178. bool WinDebugger::DoUpdate()
  1179. {
  1180. if ((mDbgProcessId != 0) && ((mDbgAttachFlags & BfDbgAttachFlag_ShutdownOnExit) == 0))
  1181. ::DebugSetProcessKillOnExit(FALSE);
  1182. else
  1183. ::DebugSetProcessKillOnExit(TRUE);
  1184. //
  1185. {
  1186. AutoCrit autoCrit(mDebugManager->mCritSect);
  1187. auto _ModuleChanged = [&](DbgModule* dbgModule)
  1188. {
  1189. ModuleChanged(dbgModule);
  1190. ClearCallStack(); // We may have actual dbgSubprograms and stuff now...
  1191. };
  1192. for (auto dbgModule : mPendingImageLoad)
  1193. {
  1194. dbgModule->PreCacheImage();
  1195. }
  1196. for (auto dbgModule : mPendingDebugInfoLoad)
  1197. {
  1198. dbgModule->PreCacheDebugInfo();
  1199. }
  1200. while (!mPendingImageLoad.IsEmpty())
  1201. {
  1202. auto dbgModule = mPendingImageLoad.back();
  1203. mPendingImageLoad.pop_back();
  1204. dbgModule->RequestImage();
  1205. _ModuleChanged(dbgModule);
  1206. }
  1207. while (!mPendingDebugInfoLoad.IsEmpty())
  1208. {
  1209. auto dbgModule = mPendingDebugInfoLoad.back();
  1210. mPendingDebugInfoLoad.pop_back();
  1211. dbgModule->RequestDebugInfo();
  1212. // We do a "_ModuleChanged" even if the load failed, so we rehup the callstack and stop
  1213. // saying "<Loading...>"
  1214. _ModuleChanged(dbgModule);
  1215. }
  1216. /*while (!mPendingDebugInfoRequests.IsEmpty())
  1217. {
  1218. if ((!mPendingImageLoad.IsEmpty()) || (!mPendingDebugInfoLoad.IsEmpty()))
  1219. break;
  1220. auto dbgModule = mPendingDebugInfoRequests.back();
  1221. mPendingDebugInfoRequests.pop_back();
  1222. if (LoadDebugInfoForModule(dbgModule) == 1)
  1223. _ModuleChanged(dbgModule);
  1224. }*/
  1225. }
  1226. if (IsMiniDumpDebugger())
  1227. {
  1228. Sleep(20);
  1229. return false;
  1230. }
  1231. if (mIsDebuggerWaiting)
  1232. {
  1233. if ((IsInRunState()) || (mRunState == RunState_Terminating) || (mRunState == RunState_DebugEval))
  1234. ContinueDebugEvent();
  1235. if (mContinueEvent.WaitFor(8))
  1236. {
  1237. BF_ASSERT(!mWantsDebugContinue); // mWantsDebugContinue should already been reset
  1238. BfLogDbg("::ContinueDebugEvent 1 ThreadId:%d\n", mDebuggerWaitingThread->mThreadId);
  1239. BF_ASSERT_REL(mDebuggerWaitingThread->mIsAtBreakpointAddress == 0);
  1240. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, mIsContinuingFromException ? DBG_EXCEPTION_NOT_HANDLED : DBG_CONTINUE);
  1241. mIsContinuingFromException = false;
  1242. mIsDebuggerWaiting = false;
  1243. mDebuggerWaitingThread = NULL;
  1244. }
  1245. else
  1246. return false;
  1247. }
  1248. if (!WaitForDebugEvent(&mDebugEvent, 8))
  1249. return false;
  1250. gDebugUpdateCnt++;
  1251. static const char* eventNames[] = { "DBG_EVENT ?",
  1252. "EXCEPTION_DEBUG_EVENT",
  1253. "CREATE_THREAD_DEBUG_EVENT",
  1254. "CREATE_PROCESS_DEBUG_EVENT",
  1255. "EXIT_THREAD_DEBUG_EVENT",
  1256. "EXIT_PROCESS_DEBUG_EVENT",
  1257. "LOAD_DLL_DEBUG_EVENT",
  1258. "UNLOAD_DLL_DEBUG_EVENT",
  1259. "OUTPUT_DEBUG_STRING_EVENT",
  1260. "RIP_EVENT"};
  1261. BfLogDbg("WaitForDebugEvent %s ThreadId:%d\n", eventNames[mDebugEvent.dwDebugEventCode], mDebugEvent.dwThreadId);
  1262. BP_ZONE(eventNames[mDebugEvent.dwDebugEventCode]);
  1263. AutoCrit autoCrit(mDebugManager->mCritSect);
  1264. mActiveBreakpoint = NULL;
  1265. mIsDebuggerWaiting = true;
  1266. mWantsDebugContinue = true;
  1267. mRequestedStackFrameIdx = 0;
  1268. mBreakStackFrameIdx = 0;
  1269. mShowPCOverride = 0;
  1270. WdThreadInfo* threadInfo = NULL;
  1271. mThreadMap.TryGetValue(mDebugEvent.dwThreadId, &threadInfo);
  1272. mDebuggerWaitingThread = threadInfo;
  1273. mExplicitStopThread = mDebuggerWaitingThread;
  1274. switch (mDebugEvent.dwDebugEventCode)
  1275. {
  1276. case CREATE_PROCESS_DEBUG_EVENT:
  1277. {
  1278. if (threadInfo == NULL)
  1279. {
  1280. BF_ASSERT(mThreadMap.size() == 0);
  1281. WdThreadInfo* newThreadInfo = new WdThreadInfo();
  1282. newThreadInfo->mProcessId = mDebugEvent.dwProcessId;
  1283. newThreadInfo->mThreadId = mDebugEvent.dwThreadId;
  1284. newThreadInfo->mHThread = mDebugEvent.u.CreateProcessInfo.hThread;
  1285. newThreadInfo->mThreadLocalBase = mDebugEvent.u.CreateProcessInfo.lpThreadLocalBase;
  1286. newThreadInfo->mStartAddress = (void*)mDebugEvent.u.CreateProcessInfo.lpStartAddress;
  1287. BF_CONTEXT lcContext;
  1288. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1289. BF_GetThreadContext(newThreadInfo->mHThread, &lcContext);
  1290. newThreadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1291. mThreadMap[mDebugEvent.dwThreadId] = newThreadInfo;
  1292. mDebuggerWaitingThread = newThreadInfo;
  1293. mThreadList.push_back(mDebuggerWaitingThread);
  1294. UpdateThreadDebugRegisters();
  1295. OutputMessage(StrFormat("Creating thread from CREATE_PROCESS_DEBUG_EVENT %d\n", mDebugEvent.dwThreadId));
  1296. threadInfo = mDebuggerWaitingThread;
  1297. mProcessInfo.dwThreadId = threadInfo->mThreadId;
  1298. mProcessInfo.hThread = threadInfo->mHThread;
  1299. mProcessInfo.hProcess = mDebugEvent.u.CreateProcessInfo.hProcess;
  1300. }
  1301. else
  1302. {
  1303. threadInfo->mThreadLocalBase = mDebugEvent.u.CreateProcessInfo.lpThreadLocalBase;
  1304. threadInfo->mStartAddress = (void*)mDebugEvent.u.CreateProcessInfo.lpStartAddress;
  1305. }
  1306. BF_CONTEXT lcContext;
  1307. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1308. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1309. threadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1310. DbgModule* launchBinary = mDebugTarget->Init(mLaunchPath, mTargetPath, (addr_target)(intptr)mDebugEvent.u.CreateProcessInfo.lpBaseOfImage);
  1311. addr_target gotImageBase = (addr_target)(intptr)mDebugEvent.u.CreateProcessInfo.lpBaseOfImage;
  1312. if (launchBinary->mImageBase != gotImageBase)
  1313. {
  1314. BF_FATAL("Image base didn't match");
  1315. }
  1316. launchBinary->mImageBase = gotImageBase;
  1317. launchBinary->mImageSize = (int)launchBinary->GetImageSize();
  1318. launchBinary->mOrigImageData = new DbgModuleMemoryCache(launchBinary->mImageBase, launchBinary->mImageSize);
  1319. if (launchBinary == mDebugTarget->mTargetBinary)
  1320. mDebugTarget->SetupTargetBinary();
  1321. if (mDebugEvent.u.CreateProcessInfo.hFile != NULL)
  1322. CloseHandle(mDebugEvent.u.CreateProcessInfo.hFile);
  1323. mDbgProcessHandle = mDebugEvent.u.CreateProcessInfo.hProcess;
  1324. mDbgThreadHandle = mDebugEvent.u.CreateProcessInfo.hThread;
  1325. mGotStartupEvent = true;
  1326. mDebugManager->mOutMessages.push_back("modulesChanged");
  1327. }
  1328. break;
  1329. case EXIT_PROCESS_DEBUG_EVENT:
  1330. {
  1331. BfLogDbg("EXIT_PROCESS_DEBUG_EVENT\n");
  1332. DWORD exitCode = mDebugEvent.u.ExitProcess.dwExitCode;
  1333. String exitMessage;
  1334. switch (exitCode)
  1335. {
  1336. case STATUS_DLL_NOT_FOUND:
  1337. exitMessage = "STATUS_DLL_NOT_FOUND";
  1338. break;
  1339. case STATUS_DLL_INIT_FAILED:
  1340. exitMessage = "STATUS_DLL_INIT_FAILED";
  1341. break;
  1342. case STATUS_ENTRYPOINT_NOT_FOUND:
  1343. exitMessage = "STATUS_ENTRYPOINT_NOT_FOUND";
  1344. break;
  1345. }
  1346. String exitCodeStr;
  1347. if ((exitCode >= 0x10000000) && (exitCode <= 0xF7000000))
  1348. exitCodeStr = StrFormat("0x%X", exitCode);
  1349. else
  1350. exitCodeStr = StrFormat("%d", exitCode);
  1351. if (!exitMessage.IsEmpty())
  1352. OutputMessage(StrFormat("Process terminated. ExitCode: %s (%s).\n", exitCodeStr.c_str(), exitMessage.c_str()));
  1353. else
  1354. OutputMessage(StrFormat("Process terminated. ExitCode: %s.\n", exitCodeStr.c_str()));
  1355. mRunState = RunState_Terminated;
  1356. mDebugManager->mOutMessages.push_back("modulesChanged");
  1357. }
  1358. break;
  1359. case LOAD_DLL_DEBUG_EVENT:
  1360. {
  1361. WCHAR moduleNameStr[MAX_PATH] = { 0 };
  1362. GetFinalPathNameByHandleW(mDebugEvent.u.LoadDll.hFile, moduleNameStr, MAX_PATH, FILE_NAME_NORMALIZED);
  1363. std::wstring wow64Dir;
  1364. std::wstring systemDir;
  1365. PWSTR wow64DirPtr = NULL;
  1366. SHGetKnownFolderPath(FOLDERID_SystemX86, KF_FLAG_NO_ALIAS, NULL, &wow64DirPtr);
  1367. if (wow64DirPtr != NULL)
  1368. {
  1369. wow64Dir = wow64DirPtr;
  1370. CoTaskMemFree(wow64DirPtr);
  1371. }
  1372. PWSTR systemDirPtr = NULL;
  1373. SHGetKnownFolderPath(FOLDERID_System, KF_FLAG_NO_ALIAS, NULL, &systemDirPtr);
  1374. if (systemDirPtr != NULL)
  1375. {
  1376. systemDir = systemDirPtr;
  1377. CoTaskMemFree(systemDirPtr);
  1378. }
  1379. if ((mDebugEvent.u.LoadDll.lpImageName != 0) && (mDebugEvent.u.LoadDll.fUnicode))
  1380. {
  1381. addr_target strAddr = ReadMemory<addr_target>((addr_target)(intptr)mDebugEvent.u.LoadDll.lpImageName);
  1382. for (int i = 0; i < MAX_PATH - 1; i++)
  1383. {
  1384. WCHAR c = ReadMemory<WCHAR>(strAddr + i*2);
  1385. moduleNameStr[i] = (WCHAR)c;
  1386. if (c == 0)
  1387. break;
  1388. }
  1389. }
  1390. String origModuleName = UTF8Encode(moduleNameStr);
  1391. String moduleName = origModuleName;
  1392. String loadMsg;
  1393. HANDLE altFileHandle = INVALID_HANDLE_VALUE;
  1394. if (moduleName != origModuleName)
  1395. {
  1396. loadMsg = StrFormat("Loading DLL: %s(%s) @ %s", origModuleName.c_str(), moduleName.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.LoadDll.lpBaseOfDll, true).c_str());
  1397. altFileHandle = ::CreateFileW(UTF8Decode(moduleName).c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  1398. }
  1399. else
  1400. {
  1401. loadMsg = StrFormat("Loading DLL: %s @ %s", moduleName.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.LoadDll.lpBaseOfDll, true).c_str());
  1402. }
  1403. BfLogDbg("LOAD_DLL_DEBUG_EVENT %s\n", moduleName.c_str());
  1404. bool skipLoad = false;
  1405. #ifdef BF_DBG_32
  1406. if (((uintptr)mDebugEvent.u.LoadDll.lpBaseOfDll & 0xFFFFFFFF00000000LL) != 0)
  1407. {
  1408. skipLoad = true;
  1409. loadMsg += " - Skipped";
  1410. }
  1411. #endif
  1412. if (!skipLoad)
  1413. {
  1414. FileHandleStream stream;
  1415. stream.mFileHandle = mDebugEvent.u.LoadDll.hFile;
  1416. if (altFileHandle != INVALID_HANDLE_VALUE)
  1417. stream.mFileHandle = altFileHandle;
  1418. if (mDebugTarget->SetupDyn(moduleName, &stream, (intptr)mDebugEvent.u.LoadDll.lpBaseOfDll) == NULL)
  1419. loadMsg += " - Failed to load";
  1420. stream.mFileHandle = 0;
  1421. }
  1422. OutputMessage(loadMsg + "\n");
  1423. if (altFileHandle != INVALID_HANDLE_VALUE)
  1424. ::CloseHandle(altFileHandle);
  1425. ::CloseHandle(mDebugEvent.u.LoadDll.hFile);
  1426. // Try to bind any breakpoints tied to this DLL
  1427. RehupBreakpoints(true);
  1428. mDebugManager->mOutMessages.push_back("modulesChanged");
  1429. }
  1430. break;
  1431. case UNLOAD_DLL_DEBUG_EVENT:
  1432. {
  1433. bool needsBreakpointRehup = false;
  1434. String name = "???";
  1435. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress((addr_target)(intptr)mDebugEvent.u.UnloadDll.lpBaseOfDll);
  1436. if (dbgModule != NULL)
  1437. {
  1438. name = dbgModule->mFilePath;
  1439. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  1440. {
  1441. auto breakpoint = mBreakpoints[i];
  1442. auto checkBreakpoint = breakpoint;
  1443. bool hasAddr = false;
  1444. while (checkBreakpoint != NULL)
  1445. {
  1446. if ((checkBreakpoint->mAddr >= dbgModule->mImageBase) && (checkBreakpoint->mAddr < dbgModule->mImageBase + dbgModule->mImageSize))
  1447. hasAddr = true;
  1448. checkBreakpoint = (WdBreakpoint*)checkBreakpoint->mLinkedSibling;
  1449. }
  1450. if (hasAddr)
  1451. {
  1452. DetachBreakpoint(breakpoint);
  1453. needsBreakpointRehup = true;
  1454. }
  1455. }
  1456. mDebugTarget->UnloadDyn(dbgModule->mImageBase);
  1457. if (needsBreakpointRehup)
  1458. RehupBreakpoints(true);
  1459. mPendingDebugInfoLoad.Remove(dbgModule);
  1460. mPendingDebugInfoRequests.Remove(dbgModule);
  1461. mDebugManager->mOutMessages.push_back("modulesChanged");
  1462. }
  1463. if (!name.empty())
  1464. OutputMessage(StrFormat("Unloading DLL: %s @ %0s\n", name.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.UnloadDll.lpBaseOfDll, true).c_str()));
  1465. BfLogDbg("UNLOAD_DLL_DEBUG_EVENT %s\n", name.c_str());
  1466. }
  1467. break;
  1468. case OUTPUT_DEBUG_STRING_EVENT:
  1469. {
  1470. const int maxChars = 1024 * 1024;
  1471. int len = BF_MIN(maxChars, (int)mDebugEvent.u.DebugString.nDebugStringLength); // 1MB max
  1472. char* message = new char[len + 1];
  1473. message[0] = 0;
  1474. message[len] = 0;
  1475. ReadMemory((addr_target)(intptr)mDebugEvent.u.DebugString.lpDebugStringData, len, message);
  1476. if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId == mDebugEvalThreadInfo.mThreadId))
  1477. mDebugManager->mOutMessages.push_back(String("dbgEvalMsg ") + message);
  1478. else
  1479. mDebugManager->mOutMessages.push_back(String("msg ") + message);
  1480. BfLogDbg("OUTPUT_DEBUG_STRING_EVENT (BreakAddr:%@): %s\n", threadInfo->mIsAtBreakpointAddress, message);
  1481. BF_ASSERT_REL(threadInfo->mIsAtBreakpointAddress == 0);
  1482. delete [] message;
  1483. }
  1484. break;
  1485. case CREATE_THREAD_DEBUG_EVENT:
  1486. {
  1487. WdThreadInfo* threadInfo = new WdThreadInfo();
  1488. threadInfo->mProcessId = mDebugEvent.dwProcessId;
  1489. threadInfo->mThreadId = mDebugEvent.dwThreadId;
  1490. threadInfo->mHThread = mDebugEvent.u.CreateThread.hThread;
  1491. threadInfo->mThreadLocalBase = mDebugEvent.u.CreateThread.lpThreadLocalBase;
  1492. threadInfo->mStartAddress = (void*)mDebugEvent.u.CreateThread.lpStartAddress;
  1493. BF_CONTEXT lcContext;
  1494. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1495. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1496. threadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1497. mThreadMap[mDebugEvent.dwThreadId] = threadInfo;
  1498. mDebuggerWaitingThread = threadInfo;
  1499. mThreadList.push_back(mDebuggerWaitingThread);
  1500. UpdateThreadDebugRegisters();
  1501. OutputMessage(StrFormat("Creating thread %d\n", mDebugEvent.dwThreadId));
  1502. }
  1503. break;
  1504. case EXIT_THREAD_DEBUG_EVENT:
  1505. {
  1506. OutputMessage(StrFormat("Exiting thread %d\n", mDebugEvent.dwThreadId));
  1507. if (mSteppingThread == threadInfo)
  1508. {
  1509. // We were attempting stepping on this thread, but not anymore!
  1510. ClearStep();
  1511. }
  1512. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_CONTINUE);
  1513. mIsDebuggerWaiting = false;
  1514. mWantsDebugContinue = false;
  1515. if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId == mDebugEvalThreadInfo.mThreadId))
  1516. {
  1517. // Thread terminated while evaluating! Is there a more graceful way of handling this?
  1518. CleanupDebugEval(false);
  1519. mRunState = RunState_Running;
  1520. }
  1521. mThreadList.Remove(mDebuggerWaitingThread);
  1522. delete mDebuggerWaitingThread;
  1523. mDebuggerWaitingThread = NULL;
  1524. mThreadMap.Remove(mDebugEvent.dwThreadId);
  1525. return true;
  1526. }
  1527. break;
  1528. case RIP_EVENT:
  1529. OutputMessage("RIP Event\n");
  1530. break;
  1531. case EXCEPTION_DEBUG_EVENT:
  1532. {
  1533. auto exceptionRecord = &mDebugEvent.u.Exception.ExceptionRecord;
  1534. switch (exceptionRecord->ExceptionCode)
  1535. {
  1536. case STATUS_WX86_BREAKPOINT:
  1537. case EXCEPTION_BREAKPOINT:
  1538. {
  1539. if (mRunState == RunState_Terminating)
  1540. {
  1541. BfLogDbg("Ignoring event because of RunState_Terminating\n");
  1542. break;
  1543. }
  1544. mAtBreakThread = threadInfo;
  1545. mActiveThread = mAtBreakThread;
  1546. bool isHighAddr = false;
  1547. #ifdef BF_DBG_32
  1548. if (((uintptr)exceptionRecord->ExceptionAddress & 0xFFFFFFFF00000000) != 0)
  1549. {
  1550. if (mActiveThread == mThreadList.front())
  1551. {
  1552. // Skip the initial Wow64 ntdll.dll!LdrpDoDebuggerBreak
  1553. mRunState = RunState_Running;
  1554. break;
  1555. }
  1556. isHighAddr = true;
  1557. }
  1558. #endif
  1559. addr_target pcAddress = (addr_target)(intptr)exceptionRecord->ExceptionAddress;
  1560. if (isHighAddr)
  1561. pcAddress = (addr_target)-1;
  1562. //mStoppedAtAddress = pcAddress;
  1563. bool isStepOut = false;
  1564. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto))
  1565. {
  1566. isStepOut = mStepBreakpointAddrs.Contains(pcAddress);
  1567. }
  1568. BF_CONTEXT lcContext;
  1569. lcContext.ContextFlags = BF_CONTEXT_ALL;
  1570. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1571. BfLogDbg("EXCEPTION_BREAKPOINT Thread:%d %p SP:%p\n", mActiveThread->mThreadId, pcAddress, BF_CONTEXT_SP(lcContext));
  1572. uint8 origImageData = 0xCC;
  1573. mDebugTarget->ReadOrigImageData(pcAddress, &origImageData, 1);
  1574. bool wasDebugBreakpoint = origImageData != 0xCC;
  1575. DbgSubprogram* dwSubprogram = NULL;
  1576. DbgLineData* dwLineData = NULL;
  1577. if (!isStepOut)
  1578. {
  1579. dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  1580. if (dwSubprogram == NULL)
  1581. dwSubprogram = mDebugTarget->FindSubProgram(pcAddress, DbgOnDemandKind_LocalOnly);
  1582. }
  1583. bool isLineStart = (dwLineData != NULL) && (dwSubprogram->GetLineAddr(*dwLineData) == pcAddress);
  1584. bool isNonDebuggerBreak = false;
  1585. if (wasDebugBreakpoint)
  1586. {
  1587. // Go ahead and set EIP back one instruction
  1588. BF_CONTEXT_IP(lcContext)--;
  1589. BF_SetThreadContext(threadInfo->mHThread, &lcContext);
  1590. }
  1591. else
  1592. {
  1593. // This was an actual "break" instruction
  1594. BfLogDbg("Non-debugger break\n");
  1595. isNonDebuggerBreak = true;
  1596. auto prevState = mRunState;
  1597. // Make it an "auto" stop, so for example when we have an assert/retry we won't stop inside assembly
  1598. mRequestedStackFrameIdx = -2;
  1599. mRunState = RunState_Paused;
  1600. CheckNonDebuggerBreak();
  1601. if (IsInRunState())
  1602. {
  1603. BF_ASSERT((prevState == RunState_Running) || (prevState == RunState_DebugEval));
  1604. mRunState = prevState;
  1605. break; // Continue as if nothing happened
  1606. }
  1607. if (prevState == RunState_DebugEval)
  1608. mRequestedStackFrameIdx = -1; // Don't show a rolled back stack idx if a debug eval fails
  1609. ClearStep();
  1610. }
  1611. if (threadInfo->mIsBreakRestorePaused)
  1612. {
  1613. // The thread is supposed to be paused, but the IP has been reset
  1614. // so just break here so we'll hit that breakpoint again once we're
  1615. // actually unpaused properly
  1616. BfLogDbg("Ignoring EXCEPTION_BREAKPOINT\n", threadInfo->mThreadId);
  1617. break;
  1618. }
  1619. if ((mRunState == RunState_DebugEval) || (mRunState == RunState_HotStep))
  1620. {
  1621. // If we hit a breakpoint while doing a debug eval, we just remove the breakpoint
  1622. // and expect to reinstate it during a rehup after the evaluation has completed
  1623. WdBreakpoint* breakpoint = (WdBreakpoint*)FindBreakpointAt((uintptr_t) exceptionRecord->ExceptionAddress);
  1624. if (breakpoint != NULL)
  1625. {
  1626. mNeedsRehupBreakpoints = true;
  1627. RemoveBreakpoint(breakpoint->mLineData.GetAddress());
  1628. }
  1629. break;
  1630. }
  1631. bool isDeeper = false;
  1632. int stepBreakAddrIdx = (int)mStepBreakpointAddrs.IndexOf(pcAddress);
  1633. WdBreakpoint* breakpoint = NULL;
  1634. bool ignoreBreakpoint = false;
  1635. if ((mStepType != StepType_None) && (mSteppingThread == mAtBreakThread))
  1636. {
  1637. if (mStepType == StepType_ToTempBreakpoint)
  1638. {
  1639. RemoveTempBreakpoints();
  1640. mRunState = RunState_Paused;
  1641. break;
  1642. }
  1643. if (mContinueFromBreakpointFailed)
  1644. {
  1645. BfLogDbg("Continuing from ContinueFromBreakpointFailed\n");
  1646. SetupStep(mStepType);
  1647. mRunState = RunState_Running;
  1648. break;
  1649. }
  1650. if (!isStepOut)
  1651. breakpoint = (WdBreakpoint*)FindBreakpointAt(pcAddress);
  1652. // Ignore breakpoint if it's on the line we're stepping off of
  1653. if ((breakpoint != NULL) && (breakpoint->mAddr == mStepPC) &&
  1654. (mStepSP == BF_CONTEXT_SP(lcContext)))
  1655. {
  1656. ignoreBreakpoint = true;
  1657. }
  1658. else if ((breakpoint != NULL) && (stepBreakAddrIdx == -1) && (!CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress)))
  1659. {
  1660. ignoreBreakpoint = true;
  1661. }
  1662. if ((stepBreakAddrIdx == -1) && (breakpoint == NULL) && (!isNonDebuggerBreak))
  1663. {
  1664. // If a breakpoint is removed in a prior thread
  1665. BfLogDbg("Ignoring step break (old breakpoint)\n");
  1666. if ((mSteppingThread == mAtBreakThread) && (mStepSwitchedThreads))
  1667. {
  1668. SetupStep(mStepType);
  1669. }
  1670. break;
  1671. }
  1672. if ((stepBreakAddrIdx != -1) && (breakpoint == NULL) && (mSteppingThread != mActiveThread))
  1673. {
  1674. BfLogDbg("Ignoring break (wrong thread)\n");
  1675. ThreadRestorePause(mSteppingThread, mActiveThread);
  1676. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1677. break;
  1678. }
  1679. isDeeper = mStepSP > BF_CONTEXT_SP(lcContext);
  1680. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto))
  1681. {
  1682. isDeeper = mStepSP >= BF_CONTEXT_SP(lcContext);
  1683. BfLogDbg("StepOut Iteration SP:%p StartSP:%p IsDeeper:%d\n", BF_CONTEXT_SP(lcContext), mStepSP, isDeeper);
  1684. }
  1685. if (((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto)) && (breakpoint == NULL) && (isDeeper))
  1686. {
  1687. // We're encountered recursion
  1688. // Make sure we don't already have one of these stored
  1689. BF_ASSERT(mStoredReturnValueAddr == 0);
  1690. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1691. break; // Don't fall through, we don't want to set mIsAtBreakpointAddress
  1692. }
  1693. if (isStepOut)
  1694. {
  1695. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1696. if (mStepType == StepType_StepOut_ThenInto)
  1697. {
  1698. dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  1699. if ((dwLineData != NULL) && (pcAddress == dwSubprogram->GetLineAddr(*dwLineData)))
  1700. {
  1701. // Our step out from a filtered function put us at the start of a new line. Stop here
  1702. // <do nothing>
  1703. }
  1704. else
  1705. {
  1706. // .. otherwise keep going until we get to the start of a new line
  1707. SetupStep(StepType_StepInto);
  1708. mRunState = RunState_Running;
  1709. break;
  1710. }
  1711. }
  1712. if (!mStepInAssembly)
  1713. {
  1714. // Keep stepping out until we find a frame that we have source for
  1715. DbgSubprogram* dwSubprogram = NULL;
  1716. DbgLineData* dwLineData = FindLineDataAtAddress(BF_CONTEXT_IP(lcContext), &dwSubprogram);
  1717. if (dwLineData == NULL)
  1718. {
  1719. SetupStep(StepType_StepOut);
  1720. break;
  1721. }
  1722. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  1723. {
  1724. // We've stepped out, but right into the start of an inlined method, so step out of this inlined method now...
  1725. SetupStep(StepType_StepOut);
  1726. break;
  1727. }
  1728. }
  1729. ClearStep();
  1730. mRunState = RunState_Paused;
  1731. threadInfo->mStoppedAtAddress = pcAddress;
  1732. break;
  1733. }
  1734. mRunState = RunState_Paused;
  1735. if (breakpoint != NULL)
  1736. {
  1737. // While stepping we hit a legit breakpoint
  1738. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  1739. // Ignore breakpoint on return statement if we're return-stepping
  1740. mRunState = RunState_Breakpoint;
  1741. }
  1742. if ((mStepType == StepType_StepInto) && (dwSubprogram != NULL))
  1743. {
  1744. // Don't filter out the current subprogram (would break cases where we explicitly stepped into or hit breakpoint in a filtered subprogram)
  1745. bool isInStartSubprogram = (mStepStartPC >= dwSubprogram->mBlock.mLowPC) && (mStepStartPC < dwSubprogram->mBlock.mHighPC);
  1746. if ((!isInStartSubprogram) && (IsStepFiltered(dwSubprogram, dwLineData)))
  1747. {
  1748. BfLogDbg("Hit step filter\n");
  1749. mRunState = RunState_Running;
  1750. SetupStep(StepType_StepOut_ThenInto);
  1751. break;
  1752. }
  1753. }
  1754. if ((mStepType == StepType_StepOver) && (stepBreakAddrIdx == 0) && (mStepBreakpointAddrs[0] != 0) && (mStepBreakpointAddrs.size() > 1))
  1755. {
  1756. // Break was on the 'call' instruction, not the instruction after it -- means recursion
  1757. BfLogDbg("StepOver detected recursing\n");
  1758. mStepIsRecursing = true;
  1759. if (mTempBreakpoint.Remove(mStepBreakpointAddrs[0]))
  1760. {
  1761. RemoveBreakpoint(mStepBreakpointAddrs[0]);
  1762. }
  1763. mStepBreakpointAddrs[0] = 0;
  1764. mRunState = RunState_Running;
  1765. break;
  1766. }
  1767. if ((mStepType == StepType_StepOver) && (stepBreakAddrIdx > 0) && (mStepBreakpointAddrs[0] != 0) && (isDeeper))
  1768. {
  1769. // This is the first time we've hit the target breakpoint.
  1770. if (HasSteppedIntoCall())
  1771. {
  1772. mStepIsRecursing = true;
  1773. RemoveBreakpoint(mStepBreakpointAddrs[0]);
  1774. mStepBreakpointAddrs[0] = 0;
  1775. //mStepBreakpointAddrs.erase(mStepBreakpointAddrs.begin());
  1776. }
  1777. }
  1778. if ((mStepType == StepType_StepOver) && (mStepIsRecursing) && (stepBreakAddrIdx != -1) && (isDeeper))
  1779. {
  1780. // Decrement so the equality test on "step out" marks us as not being deeper when we
  1781. // hit the expected SP
  1782. BfLogDbg("Converting StepOver to StepOut\n");
  1783. mStepSP--;
  1784. mStepType = StepType_StepOut_ThenInto;
  1785. //SetupStep(StepType_StepOut);
  1786. mRunState = RunState_Running;
  1787. break;
  1788. }
  1789. if ((mStepType == StepType_StepOver) && (!ignoreBreakpoint) && (breakpoint == NULL) && (!mStepInAssembly))
  1790. {
  1791. // Test for stepping over inline method
  1792. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  1793. // mTempBreakpoints will have 2 entries if we are on a 'call' line. If we have an inlined call immediately following a call, then we
  1794. // assume we're hitting a return break
  1795. /*if ((dwSubprogram != NULL) && (dwSubprogram->mInlineParent != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC) && (mTempBreakpoint.size() < 2))
  1796. {
  1797. BfLogDbg("Attempting StepOver of inlined method\n");
  1798. SetupStep(StepType_StepOut);
  1799. mRunState = RunState_Running;
  1800. break;
  1801. } */
  1802. //TODO: The previous logic with the "(mTempBreakpoint.size() < 2)" was causing Try!(Method()); stepovers to enter into Try!. What did we mean by
  1803. // "assume we're hitting a return break"?
  1804. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  1805. {
  1806. RemoveTempBreakpoints();
  1807. BfLogDbg("Attempting StepOver of inlined method\n");
  1808. SetupStep(StepType_StepOut);
  1809. mRunState = RunState_Running;
  1810. break;
  1811. }
  1812. }
  1813. if (mStepType == StepType_StepOut_Inline)
  1814. {
  1815. if (mOrigStepType == StepType_StepOver)
  1816. {
  1817. // For the step over, if we are still inside the source line after an inline then step over again...
  1818. DbgSubprogram* origSubprogram = NULL;
  1819. auto origLineData = FindLineDataAtAddress(mStepStartPC, &origSubprogram);
  1820. DbgSubprogram* curSubprogram = NULL;
  1821. auto curLineData = FindLineDataAtAddress(pcAddress, &curSubprogram);
  1822. if ((origLineData != NULL) &&
  1823. ((origLineData == curLineData) ||
  1824. ((origSubprogram == curSubprogram) && (origLineData->mLine == curLineData->mLine))))
  1825. {
  1826. mRunState = RunState_Running;
  1827. SetupStep(StepType_StepOver);
  1828. break;
  1829. }
  1830. }
  1831. ClearStep();
  1832. break;
  1833. }
  1834. if ((mStepType != StepType_None) && (ignoreBreakpoint) && (!mStepInAssembly) && (stepBreakAddrIdx == -1))
  1835. {
  1836. // Ignore breakpoint by just continuing...
  1837. mRunState = RunState_Running;
  1838. break;
  1839. }
  1840. RemoveTempBreakpoints();
  1841. if ((mStepType != StepType_None) && (!mStepInAssembly) && (!isLineStart) && (stepBreakAddrIdx != -1))
  1842. {
  1843. SetupStep(mStepType);
  1844. mRunState = RunState_Running;
  1845. }
  1846. else
  1847. {
  1848. //if (mStepType != StepType_Return)
  1849. if (stepBreakAddrIdx != -1)
  1850. {
  1851. // Even if we've detected we're at a breakpoint, we mark ourselves as just stepping if we also
  1852. // have a step breakpoint here
  1853. StepLineTryPause(pcAddress, true);
  1854. }
  1855. if (mRunState == RunState_Paused)
  1856. ClearStep();
  1857. }
  1858. if (ignoreBreakpoint)
  1859. {
  1860. SetupStep(mStepType);
  1861. mRunState = RunState_Running;
  1862. }
  1863. if ((mRunState == RunState_Paused) && (breakpoint != NULL))
  1864. {
  1865. // Just do the 'check' here so we can do the logging/condition stuff
  1866. CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress);
  1867. }
  1868. }
  1869. else
  1870. {
  1871. breakpoint = (WdBreakpoint*)FindBreakpointAt((uintptr_t)exceptionRecord->ExceptionAddress);
  1872. if ((breakpoint != NULL) && (!CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress)))
  1873. {
  1874. BfLogDbg("Skipping conditional breakpoint. Setting mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  1875. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  1876. mRunState = RunState_Running;
  1877. break;
  1878. }
  1879. if (breakpoint != NULL)
  1880. {
  1881. BfLogDbg("Breakpoint hit. mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  1882. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  1883. mRunState = RunState_Breakpoint;
  1884. }
  1885. else if ((stepBreakAddrIdx != -1) || (isNonDebuggerBreak))
  1886. {
  1887. if (mRunState != RunState_DebugEval)
  1888. {
  1889. // Was in mStepBreakpointAddrs list
  1890. if ((isNonDebuggerBreak) || (mStepType == StepType_None) || (mSteppingThread == mAtBreakThread))
  1891. {
  1892. BfLogDbg("Hit mStepBreakpointAddrs breakpoint\n");
  1893. mRunState = RunState_Paused;
  1894. }
  1895. else
  1896. {
  1897. BfLogDbg("Ignored mStepBreakpointAddrs breakpoint (wrong thread)\n");
  1898. mRunState = RunState_Running;
  1899. }
  1900. }
  1901. }
  1902. else
  1903. {
  1904. BfLogDbg("Ignoring break (old or ignored breakpoint)\n");
  1905. mRunState = RunState_Running;
  1906. }
  1907. }
  1908. if ((breakpoint != NULL) && (!ignoreBreakpoint))
  1909. {
  1910. mActiveBreakpoint = breakpoint;
  1911. mBreakStackFrameIdx = -1;
  1912. }
  1913. if ((mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint))
  1914. threadInfo->mStoppedAtAddress = pcAddress;
  1915. }
  1916. break;
  1917. case STATUS_WX86_SINGLE_STEP:
  1918. case EXCEPTION_SINGLE_STEP:
  1919. {
  1920. if (mRunState == RunState_Terminating)
  1921. {
  1922. BfLogDbg("Ignoring event because of RunState_Terminating\n");
  1923. break;
  1924. }
  1925. if ((mStepSwitchedThreads) && (mActiveThread == mSteppingThread) && (mActiveThread->mIsAtBreakpointAddress != NULL))
  1926. {
  1927. ContinueFromBreakpoint();
  1928. break;
  1929. }
  1930. if (mRunState == RunState_HotStep)
  1931. {
  1932. BF_ASSERT(mActiveThread == mDebuggerWaitingThread);
  1933. mRunState = RunState_Paused;
  1934. break;
  1935. }
  1936. mActiveThread = mDebuggerWaitingThread;
  1937. BF_CONTEXT lcContext;
  1938. lcContext.ContextFlags = BF_CONTEXT_ALL;
  1939. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  1940. addr_target pcAddress = BF_CONTEXT_IP(lcContext);
  1941. bool wasUnfilteredStep = mStepType == StepType_StepInto_Unfiltered;
  1942. if (mStepType == StepType_StepInto_UnfilteredSingle)
  1943. {
  1944. wasUnfilteredStep = true;
  1945. mStepType = StepType_StepInto;
  1946. mStepStartPC = pcAddress;
  1947. }
  1948. BfLogDbg("EXCEPTION_SINGLE_STEP Thread:%d PC:%p\n", mActiveThread->mThreadId, exceptionRecord->ExceptionAddress);
  1949. if (lcContext.Dr6 & 0x0F) // Memory breakpoint hit
  1950. {
  1951. WdBreakpoint* foundBreakpoint = NULL;
  1952. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  1953. {
  1954. if ((lcContext.Dr6 & ((intptr_target)1 << memoryWatchSlot)) != 0)
  1955. {
  1956. foundBreakpoint = mMemoryBreakpoints[memoryWatchSlot].mBreakpoint;
  1957. break;
  1958. }
  1959. }
  1960. BF_ASSERT(foundBreakpoint != NULL);
  1961. DbgSubprogram* subprogram = mDebugTarget->FindSubProgram(pcAddress);
  1962. if (CheckConditionalBreakpoint(foundBreakpoint, subprogram, pcAddress))
  1963. {
  1964. if (foundBreakpoint != NULL)
  1965. {
  1966. mDebugManager->mOutMessages.push_back(StrFormat("memoryBreak %s", EncodeDataPtr(foundBreakpoint->mMemoryBreakpointInfo->mMemoryAddress, false).c_str()));
  1967. mRunState = RunState_Paused;
  1968. }
  1969. mActiveBreakpoint = foundBreakpoint;
  1970. mBreakStackFrameIdx = -1;
  1971. RemoveTempBreakpoints();
  1972. BfLogDbg("Memory breakpoint hit: %p\n", foundBreakpoint);
  1973. }
  1974. break;
  1975. }
  1976. if ((mRunState == RunState_DebugEval) && (mDebugEvalThreadInfo.mThreadId == mDebuggerWaitingThread->mThreadId))
  1977. {
  1978. if ((addr_target)(intptr)exceptionRecord->ExceptionAddress == mDebugEvalSetRegisters.GetPC())
  1979. {
  1980. // This indicates we are returning from kernel mode and our registers are clobbered
  1981. SetRegisters(&mDebugEvalSetRegisters);
  1982. }
  1983. break;
  1984. }
  1985. bool hadBreakpointContinue = true;
  1986. if (threadInfo->mBreakpointAddressContinuing != 0)
  1987. {
  1988. bool wantsBreakpoint = WantsBreakpointAt(threadInfo->mBreakpointAddressContinuing);
  1989. BfLogDbg("Continuing breakpoint at %p WantsReset:%d\n", threadInfo->mBreakpointAddressContinuing, wantsBreakpoint);
  1990. if (wantsBreakpoint)
  1991. {
  1992. PhysSetBreakpoint(threadInfo->mBreakpointAddressContinuing);
  1993. }
  1994. threadInfo->mBreakpointAddressContinuing = NULL;
  1995. hadBreakpointContinue = true;
  1996. ThreadRestoreUnpause();
  1997. }
  1998. if ((mSteppingThread != NULL) && (mSteppingThread != mActiveThread))
  1999. {
  2000. // This SINGLE_STEP happened in the wrong thread - we need the stepping thread to do the stepping!
  2001. // Try again.
  2002. mActiveThread = mSteppingThread;
  2003. SingleStepX86();
  2004. break;
  2005. }
  2006. bool isDeeper = mStepSP > BF_CONTEXT_SP(lcContext);
  2007. if ((mStepSwitchedThreads) && (mStepType == StepType_StepOver) && (isDeeper))
  2008. {
  2009. if (HasSteppedIntoCall())
  2010. {
  2011. // Since we switched threads, we needed to do a hardware step which has placed us inside a
  2012. // call, so we need to step out of that now...
  2013. SetupStep(StepType_StepOut_NoFrame);
  2014. break;
  2015. }
  2016. }
  2017. // If we don't have a mStepBreakpointAddrs set, that means we're stepping through individual instructions --
  2018. // so process the new location here
  2019. if (((mStepType == StepType_StepInto) || (mStepType == StepType_StepInto_Unfiltered) || (mStepType == StepType_StepOver)) && (mStepBreakpointAddrs.size() == 0))
  2020. {
  2021. DbgSubprogram* dwSubprogram = NULL;
  2022. DbgLineData* dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  2023. if ((dwSubprogram != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC) && (dwSubprogram->mWasHotReplaced))
  2024. {
  2025. BfLogDbg("Stepping through hot thunk\n");
  2026. mRunState = RunState_Running;
  2027. SingleStepX86();
  2028. break;
  2029. }
  2030. if ((mStepType == StepType_StepOver) && (!mStepInAssembly))
  2031. {
  2032. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  2033. {
  2034. BfLogDbg("Attempting StepOver of inlined method - SingleStep\n");
  2035. SetupStep(StepType_StepOut);
  2036. mRunState = RunState_Running;
  2037. break;
  2038. }
  2039. }
  2040. // Column of -1 means "Illegal", keep stepping!
  2041. if ((mStepInAssembly) ||
  2042. ((dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dwLineData->mColumn >= 0) &&
  2043. ((dwSubprogram->GetLineAddr(*dwLineData) == pcAddress) || (mStepStopOnNextInstruction))))
  2044. {
  2045. // Hit a line while stepping, we're done!
  2046. mRunState = RunState_Paused;
  2047. StepLineTryPause(pcAddress, false);
  2048. if (mRunState == RunState_Paused)
  2049. {
  2050. if ((mStepType == StepType_StepInto) && (!wasUnfilteredStep) && (!mStepInAssembly) && (dwSubprogram != NULL))
  2051. {
  2052. // Don't filter out the current subprogram (would break cases where we explicitly stepped into or hit breakpoint in a filtered subprogram)
  2053. bool isInStartSubprogram = (mStepStartPC >= dwSubprogram->mBlock.mLowPC) && (mStepStartPC < dwSubprogram->mBlock.mHighPC);
  2054. if ((!isInStartSubprogram) && (IsStepFiltered(dwSubprogram, dwLineData)))
  2055. {
  2056. BfLogDbg("Hit step filter (2)\n");
  2057. mRunState = RunState_Running;
  2058. SetupStep(StepType_StepOut_ThenInto);
  2059. break;
  2060. }
  2061. }
  2062. ClearStep();
  2063. mCurNoInfoStepTries = 0; // Reset
  2064. }
  2065. else
  2066. SetupStep(mStepType);
  2067. }
  2068. else if (dwSubprogram != NULL)
  2069. {
  2070. if ((dwSubprogram->mWasHotReplaced) && ((mStepType == StepType_StepInto) || (mStepType == StepType_StepInto_Unfiltered)))
  2071. {
  2072. SingleStepX86();
  2073. }
  2074. else
  2075. {
  2076. // Inside a line's instruction, keep going
  2077. SetupStep(mStepType);
  2078. mCurNoInfoStepTries = 0; // Reset
  2079. }
  2080. }
  2081. else if (mStepType == StepType_StepInto_Unfiltered)
  2082. {
  2083. CPUInst inst;
  2084. if (mDebugTarget->DecodeInstruction(pcAddress, &inst))
  2085. {
  2086. if (inst.IsBranch())
  2087. {
  2088. auto target = inst.GetTarget();
  2089. if (target != 0)
  2090. {
  2091. DbgSubprogram* destSubprogram = mDebugTarget->FindSubProgram(target);
  2092. if ((destSubprogram != NULL) && (target == destSubprogram->mBlock.mLowPC))
  2093. {
  2094. // We're jumping to an actual subprogram, so continue stepping here
  2095. mStepType = StepType_StepInto_UnfilteredSingle;
  2096. SingleStepX86();
  2097. break;
  2098. }
  2099. }
  2100. }
  2101. }
  2102. // We requested to step into this method so stop here even if we don't have source
  2103. mRunState = RunState_Paused;
  2104. }
  2105. else
  2106. {
  2107. // No debug info!
  2108. bool doStepOut = false;
  2109. if (mCurNoInfoStepTries < 16)
  2110. {
  2111. mCurNoInfoStepTries++;
  2112. BfLogDbg("NoInfoStepTries: %d\n", mCurNoInfoStepTries);
  2113. if (!SetupStep(mStepType))
  2114. doStepOut = true;
  2115. }
  2116. else
  2117. doStepOut = true;
  2118. if (doStepOut)
  2119. {
  2120. // Step out of current call.
  2121. mStepSP = 0;
  2122. SetupStep(StepType_StepOut_NoFrame);
  2123. // Aggressive stepout - don't monitor BP
  2124. mStepSP = 0;
  2125. }
  2126. }
  2127. }
  2128. else if (!hadBreakpointContinue)
  2129. {
  2130. BF_DBG_FATAL("EXCEPTION_SINGLE_STEP bad debugger state");
  2131. }
  2132. if (mRunState == RunState_Paused)
  2133. threadInfo->mStoppedAtAddress = pcAddress;
  2134. }
  2135. break;
  2136. default:
  2137. {
  2138. bool isSystemException =
  2139. (exceptionRecord->ExceptionCode >= STATUS_ACCESS_VIOLATION) &&
  2140. (exceptionRecord->ExceptionCode <= STATUS_ASSERTION_FAILURE);
  2141. bool isFirstChance = mDebugEvent.u.Exception.dwFirstChance != 0;
  2142. bool handled = false;
  2143. //TODO: Use a user-defined filter here to determine whether to stop or continue
  2144. if ((!isSystemException) && (isFirstChance))
  2145. {
  2146. if (exceptionRecord->ExceptionCode == 0x406D1388) // Visual C
  2147. {
  2148. if ((int32)exceptionRecord->ExceptionInformation[0] == 0x1000)
  2149. {
  2150. struct THREADNAME_INFO
  2151. {
  2152. DWORD dwType; // Must be 0x1000.
  2153. LPCSTR szName; // Pointer to name (in user addr space).
  2154. DWORD dwThreadID; // Thread ID (-1=caller thread).
  2155. DWORD dwFlags; // Reserved for future use, must be zero.
  2156. };
  2157. THREADNAME_INFO* threadNameInfo = (THREADNAME_INFO*)exceptionRecord->ExceptionInformation;
  2158. DwFormatInfo formatInfo;
  2159. formatInfo.mRawString = true;
  2160. String nameStr = ReadString(DbgType_SChar, (intptr)threadNameInfo->szName, false, 1024, formatInfo);
  2161. WdThreadInfo* namingThreadInfo = threadInfo;
  2162. if (threadNameInfo->dwThreadID != (DWORD)-1)
  2163. {
  2164. namingThreadInfo = NULL;
  2165. mThreadMap.TryGetValue(threadNameInfo->dwThreadID, &namingThreadInfo);
  2166. }
  2167. if (namingThreadInfo != NULL)
  2168. {
  2169. namingThreadInfo->mName = nameStr;
  2170. FilterThreadName(namingThreadInfo->mName);
  2171. }
  2172. }
  2173. else if (((int32)exceptionRecord->ExceptionInformation[0] == 0x1001) && ((int32)exceptionRecord->ExceptionInformation[1] == 0x1002))
  2174. {
  2175. struct FailMessage
  2176. {
  2177. addr_target mPtr0; // Unknown
  2178. addr_target mPtr1; // 0
  2179. addr_target mPtr2; // 0
  2180. addr_target mPtr3; // Unknown
  2181. addr_target mErrorStr;
  2182. };
  2183. FailMessage failMessage = ReadMemory<FailMessage>(exceptionRecord->ExceptionInformation[2]);
  2184. DwFormatInfo formatInfo;
  2185. String failStr = ReadString(DbgType_SChar16, failMessage.mErrorStr, false, 8192, formatInfo);
  2186. mDebugManager->mOutMessages.push_back(StrFormat("error Run-Time Check Failure %d - %s", exceptionRecord->ExceptionInformation[6], failStr.c_str()));
  2187. mRunState = RunState_Paused;
  2188. mRequestedStackFrameIdx = -2; // -2 = "auto"
  2189. handled = true;
  2190. }
  2191. }
  2192. if (!handled)
  2193. {
  2194. OutputMessage(StrFormat("Skipping first chance exception %08Xd at address %@ in thread %d\n", exceptionRecord->ExceptionCode, exceptionRecord->ExceptionAddress, threadInfo->mThreadId));
  2195. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_EXCEPTION_NOT_HANDLED);
  2196. mIsDebuggerWaiting = false;
  2197. }
  2198. }
  2199. else
  2200. {
  2201. BfLogDbg("EXCEPTION in thread %d at %p\n", threadInfo->mThreadId, exceptionRecord->ExceptionAddress);
  2202. OutputDebugStrF("EXCEPTION\n");
  2203. mActiveThread = threadInfo;
  2204. memcpy(&mCurException, exceptionRecord, sizeof(EXCEPTION_RECORD));
  2205. if (mRunState == RunState_DebugEval)
  2206. {
  2207. if ((intptr)mCurException.ExceptionAddress == 42)
  2208. {
  2209. BfLogDbg("RunState_DebugEval_Done\n");
  2210. OutputDebugStrF(" RunState_DebugEval_Done\n");
  2211. }
  2212. else
  2213. {
  2214. BfLogDbg("Exception at 0x%@ in thread %d, exception code 0x%08X",
  2215. mCurException.ExceptionAddress, mActiveThread->mThreadId, mCurException.ExceptionCode);
  2216. mDebugPendingExpr->mException = StrFormat("Exception at 0x%@ in thread %d, exception code 0x%08X",
  2217. mCurException.ExceptionAddress, mActiveThread->mThreadId, mCurException.ExceptionCode);
  2218. }
  2219. mRunState = RunState_DebugEval_Done;
  2220. mExplicitStopThread = mActiveThread;
  2221. mRequestedStackFrameIdx = mDebugPendingExpr->mCallStackIdx;
  2222. }
  2223. else
  2224. {
  2225. mRunState = RunState_Exception;
  2226. }
  2227. }
  2228. }
  2229. break;
  2230. }
  2231. }
  2232. break;
  2233. }
  2234. if ((mDebugEvalThreadInfo.mThreadId != 0) && (mRunState != RunState_DebugEval) && (mRunState != RunState_DebugEval_Done))
  2235. {
  2236. CleanupDebugEval();
  2237. }
  2238. // Stepping done?
  2239. if (mStepType == StepType_None)
  2240. {
  2241. mLastValidStepIntoPC = 0;
  2242. }
  2243. BF_ASSERT(mDebuggerWaitingThread != NULL);
  2244. return true;
  2245. }
  2246. void WinDebugger::Update()
  2247. {
  2248. AutoCrit autoCrit(mDebugManager->mCritSect);
  2249. // if (mRunState == RunState_DebugEval)
  2250. // ContinueDebugEvent();
  2251. if (mRunState == RunState_DebugEval_Done)
  2252. {
  2253. if (mDebugPendingExpr != NULL)
  2254. {
  2255. mDebugPendingExpr->mIdleTicks++;
  2256. if (mDebugPendingExpr->mIdleTicks >= 2)
  2257. {
  2258. BfLogDbg("Finishing pending expr in thread %d\n", mDebugEvalThreadInfo.mThreadId);
  2259. mRunState = RunState_Paused;
  2260. CleanupDebugEval();
  2261. }
  2262. }
  2263. }
  2264. else if (mDebugPendingExpr != NULL)
  2265. {
  2266. mDebugPendingExpr->mIdleTicks = 0;
  2267. }
  2268. }
  2269. void WinDebugger::ContinueDebugEvent()
  2270. {
  2271. AutoCrit autoCrit(mDebugManager->mCritSect);
  2272. BF_ASSERT(mRunState != RunState_DebugEval_Done);
  2273. if (!mWantsDebugContinue)
  2274. return;
  2275. if (!TryRunContinue())
  2276. return;
  2277. // if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId != mDebugEvalThreadInfo.mThreadId))
  2278. // {
  2279. // // Don't process the 'mIsAtBreakpointAddress' stuff
  2280. // mWantsDebugContinue = false;
  2281. // mContinueEvent.Set();
  2282. // return;
  2283. // }
  2284. if ((mDebuggerWaitingThread->mIsAtBreakpointAddress == 0) && (mDebuggerWaitingThread->mStoppedAtAddress != 0))
  2285. {
  2286. auto breakpoint = FindBreakpointAt(mDebuggerWaitingThread->mStoppedAtAddress);
  2287. if (breakpoint != NULL)
  2288. {
  2289. mDebuggerWaitingThread->mIsAtBreakpointAddress = mDebuggerWaitingThread->mStoppedAtAddress;
  2290. }
  2291. }
  2292. if (mDebuggerWaitingThread->mIsAtBreakpointAddress != 0)
  2293. {
  2294. if (!ContinueFromBreakpoint())
  2295. {
  2296. BfLogDbg("ContinueFromBreakpoint failed\n");
  2297. ClearCallStack();
  2298. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  2299. mDebuggerWaitingThread->mIsAtBreakpointAddress = 0;
  2300. mWantsDebugContinue = false;
  2301. mContinueFromBreakpointFailed = true;
  2302. mContinueEvent.Set();
  2303. return;
  2304. }
  2305. }
  2306. if ((mRunState == RunState_Breakpoint) || (mRunState == RunState_Paused))
  2307. {
  2308. ClearCallStack();
  2309. mRunState = RunState_Running;
  2310. }
  2311. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  2312. mWantsDebugContinue = false;
  2313. BF_ASSERT_REL(mDebuggerWaitingThread->mIsAtBreakpointAddress == 0);
  2314. mContinueEvent.Set();
  2315. }
  2316. static BOOL CALLBACK WdEnumWindowsProc(HWND hwnd, LPARAM lParam)
  2317. {
  2318. HWND owner = GetWindow(hwnd, GW_OWNER);
  2319. if (!IsWindowVisible(hwnd))
  2320. return TRUE;
  2321. DWORD processId = 0;
  2322. DWORD threadId = GetWindowThreadProcessId(hwnd, &processId);
  2323. if (processId != ((WinDebugger*)gDebugger)->mProcessInfo.dwProcessId)
  2324. return TRUE;
  2325. SetForegroundWindow(hwnd);
  2326. return TRUE;
  2327. }
  2328. void WinDebugger::ForegroundTarget()
  2329. {
  2330. EnumWindows(WdEnumWindowsProc, 0);
  2331. }
  2332. static int gFindLineDataAt = 0;
  2333. DbgLineData* WinDebugger::FindLineDataAtAddress(addr_target address, DbgSubprogram** outSubProgram, DbgSrcFile** outSrcFile, int* outLineIdx, DbgOnDemandKind onDemandKind)
  2334. {
  2335. gFindLineDataAt++;
  2336. BP_ZONE("WinDebugger::FindLineDataAtAddress");
  2337. auto dwSubprogram = mDebugTarget->FindSubProgram((addr_target)address, onDemandKind);
  2338. if (dwSubprogram == NULL)
  2339. return NULL;
  2340. FixupLineDataForSubprogram(dwSubprogram);
  2341. auto lineData = dwSubprogram->FindClosestLine(address, outSubProgram, outSrcFile, outLineIdx);
  2342. return lineData;
  2343. }
  2344. DbgLineData* WinDebugger::FindLineDataInSubprogram(addr_target address, DbgSubprogram* dwSubprogram)
  2345. {
  2346. auto dwCompileUnit = dwSubprogram->mCompileUnit;
  2347. FixupLineDataForSubprogram(dwSubprogram);
  2348. auto lineData = dwSubprogram->FindClosestLine(address);
  2349. return lineData;
  2350. }
  2351. bool WinDebugger::IsStepFiltered(DbgSubprogram* dbgSubprogram, DbgLineData* dbgLineData)
  2352. {
  2353. if (mIsStepIntoSpecific)
  2354. return false;
  2355. if (dbgSubprogram->mStepFilterVersion != mDebugManager->mStepFilterVersion)
  2356. {
  2357. String filterName;
  2358. CreateFilterName(filterName, dbgSubprogram);
  2359. dbgSubprogram->PopulateSubprogram();
  2360. bool doDefault = false;
  2361. StepFilter* stepFilterPtr;
  2362. if (mDebugManager->mStepFilters.TryGetValue(filterName, &stepFilterPtr))
  2363. {
  2364. switch (stepFilterPtr->mFilterKind)
  2365. {
  2366. case BfStepFilterKind_Default:
  2367. doDefault = true;
  2368. break;
  2369. case BfStepFilterKind_Filtered:
  2370. dbgSubprogram->mIsStepFiltered = true;
  2371. break;
  2372. case BfStepFilterKind_NotFiltered:
  2373. dbgSubprogram->mIsStepFiltered = false;
  2374. break;
  2375. }
  2376. }
  2377. else
  2378. {
  2379. doDefault = true;
  2380. }
  2381. if (doDefault)
  2382. {
  2383. dbgSubprogram->mIsStepFiltered = dbgSubprogram->mIsStepFilteredDefault;
  2384. }
  2385. dbgSubprogram->mStepFilterVersion = mDebugManager->mStepFilterVersion;
  2386. }
  2387. if (!dbgSubprogram->mIsStepFiltered)
  2388. {
  2389. if (dbgLineData != NULL)
  2390. {
  2391. auto dbgSrcFile = dbgSubprogram->GetLineSrcFile(*dbgLineData);
  2392. if (dbgSrcFile->mStepFilterVersion != mDebugManager->mStepFilterVersion)
  2393. {
  2394. dbgSrcFile->mFileExistKind = dbgSubprogram->mCompileUnit->mDbgModule->CheckSourceFileExist(dbgSrcFile->GetLocalPath());
  2395. dbgSrcFile->mStepFilterVersion = mDebugManager->mStepFilterVersion;
  2396. }
  2397. switch (dbgSrcFile->mFileExistKind)
  2398. {
  2399. case DbgFileExistKind_NotFound:
  2400. return true;
  2401. case DbgFileExistKind_HasOldSourceCommand:
  2402. if (mDebugManager->mStepOverExternalFiles)
  2403. return true;
  2404. }
  2405. }
  2406. }
  2407. return dbgSubprogram->mIsStepFiltered;
  2408. }
  2409. void WinDebugger::RemoveTempBreakpoints()
  2410. {
  2411. BfLogDbg("RemoveTempBreakpoints\n");
  2412. for (auto address : mTempBreakpoint)
  2413. {
  2414. RemoveBreakpoint(address);
  2415. // if (FindBreakpointAt(address) == NULL)
  2416. // {
  2417. // RemoveBreakpoint(address);
  2418. // }
  2419. // else
  2420. // {
  2421. // BfLogDbg("Ignoring remove on temp breakpoint %p\n", address);
  2422. // }
  2423. }
  2424. mTempBreakpoint.Clear();
  2425. mStepBreakpointAddrs.Clear();
  2426. }
  2427. void WinDebugger::RehupBreakpoints(bool doFlush)
  2428. {
  2429. BfLogDbg("RehupBreakpoints\n");
  2430. // First pass- detach breakpoints that need to be rebound
  2431. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  2432. {
  2433. auto breakpoint = mBreakpoints[i];
  2434. while (breakpoint != NULL)
  2435. {
  2436. if (((breakpoint->mSrcFile != NULL) && (breakpoint->mSrcFile->mDeferredRefs.size() > 0)) ||
  2437. (!breakpoint->mSymbolName.IsEmpty()))
  2438. {
  2439. // This breakpoint was already bound, but we loaded a debug module that also had this file so rebind it
  2440. DetachBreakpoint(breakpoint);
  2441. }
  2442. breakpoint = (WdBreakpoint*)breakpoint->mLinkedSibling;
  2443. }
  2444. }
  2445. // Second pass- actually set breakpoints
  2446. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  2447. {
  2448. auto breakpoint = mBreakpoints[i];
  2449. while (breakpoint != NULL)
  2450. {
  2451. CheckBreakpoint(breakpoint);
  2452. if (breakpoint->mAddr != 0)
  2453. SetBreakpoint(breakpoint->mAddr, true);
  2454. breakpoint = (WdBreakpoint*)breakpoint->mLinkedSibling;
  2455. }
  2456. }
  2457. mNeedsRehupBreakpoints = false;
  2458. }
  2459. bool WinDebugger::WantsBreakpointAt(addr_target address)
  2460. {
  2461. if (mTempBreakpoint.Contains(address))
  2462. return true;
  2463. for (auto breakpoint : mBreakpoints)
  2464. {
  2465. WdBreakpoint* checkBreakpoint = breakpoint;
  2466. while (checkBreakpoint != NULL)
  2467. {
  2468. if (address == checkBreakpoint->mAddr)
  2469. return true;
  2470. checkBreakpoint = (WdBreakpoint*)checkBreakpoint->mLinkedSibling;
  2471. }
  2472. }
  2473. return false;
  2474. }
  2475. void WinDebugger::CheckBreakpoint(WdBreakpoint* wdBreakpoint, DbgSrcFile* srcFile, int lineNum, int hotIdx)
  2476. {
  2477. BP_ZONE("WinDebugger::CheckBreakpoint:atLoc");
  2478. if (hotIdx == -1)
  2479. {
  2480. BF_ASSERT(wdBreakpoint->mPendingHotBindIdx == -1);
  2481. }
  2482. WdBreakpoint* headBreakpoint = wdBreakpoint;
  2483. headBreakpoint->mPendingHotBindIdx = -1;
  2484. bool foundInSequence = false;
  2485. DbgSubprogram* lastFoundSubprogram = NULL;
  2486. int highestHotIdx = -1;
  2487. bool foundLine = false;
  2488. int bestLineNum = -1;
  2489. int bestLineOffset = 0x7FFFFFFF;
  2490. auto _CheckLineInfo = [&](DbgSubprogram* dbgSubprogram, DbgLineInfo* dbgLineInfo)
  2491. {
  2492. // Scan first so we can determine if we want to do fix up line data or not.
  2493. bool hasNear = false;
  2494. int maxLineDist = 6;
  2495. for (int lineIdx = 0; lineIdx < dbgLineInfo->mLines.mSize; lineIdx++)
  2496. {
  2497. auto lineData = &dbgLineInfo->mLines[lineIdx];
  2498. auto& ctx = dbgLineInfo->mContexts[lineData->mCtxIdx];
  2499. if (ctx.mSrcFile != srcFile)
  2500. continue;
  2501. int lineOffset = lineData->mLine - lineNum;
  2502. if ((lineOffset >= 0) && (lineOffset <= maxLineDist))
  2503. hasNear = true;
  2504. }
  2505. if (!hasNear)
  2506. return;
  2507. FixupLineDataForSubprogram(dbgSubprogram);
  2508. for (int lineIdx = 0; lineIdx < dbgLineInfo->mLines.mSize; lineIdx++)
  2509. {
  2510. //TODO: Do fixup lineData... ?
  2511. auto lineData = &dbgLineInfo->mLines[lineIdx];
  2512. auto& ctx = dbgLineInfo->mContexts[lineData->mCtxIdx];
  2513. if (ctx.mSrcFile != srcFile)
  2514. continue;
  2515. // if (ctx.mInlinee != NULL)
  2516. // {
  2517. // if (lineIdx + 1 < dbgLineInfo->mLines.mSize)
  2518. // {
  2519. // auto nextLineData = &dbgLineInfo->mLines[lineIdx + 1];
  2520. // if (nextLineData->mRelAddress == lineData->mRelAddress)
  2521. // {
  2522. // // Use the later entry (same logic from DisassembleAt)
  2523. // continue;
  2524. // }
  2525. // }
  2526. // }
  2527. if ((lineData->mColumn == -1) && (wdBreakpoint->mInstrOffset == -1))
  2528. continue;
  2529. int lineOffset = lineData->mLine - lineNum;
  2530. if (lineOffset == 0)
  2531. {
  2532. foundLine = true;
  2533. auto address = dbgSubprogram->GetLineAddr(*lineData);
  2534. auto subProgram = mDebugTarget->FindSubProgram(address);
  2535. if (subProgram->mNeedLineDataFixup)
  2536. FixupLineDataForSubprogram(subProgram);
  2537. if (subProgram != NULL)
  2538. highestHotIdx = BF_MAX(highestHotIdx, subProgram->mCompileUnit->mDbgModule->mHotIdx);
  2539. if ((foundInSequence) && (subProgram != lastFoundSubprogram))
  2540. foundInSequence = false;
  2541. if ((subProgram->mWasHotReplaced) && (address < subProgram->mBlock.mLowPC + sizeof(HotJumpOp)))
  2542. {
  2543. // If this breakpoint ends up on the hot jmp instruction
  2544. continue;
  2545. }
  2546. if (!foundInSequence)
  2547. {
  2548. lastFoundSubprogram = subProgram;
  2549. if ((subProgram != NULL) && (subProgram->mWasHotReplaced) && (address == subProgram->mBlock.mLowPC))
  2550. {
  2551. // This instruction is actually the hot jump, we don't need a breakpoint here
  2552. foundInSequence = true;
  2553. continue;
  2554. }
  2555. if (wdBreakpoint->mSrcFile != NULL)
  2556. {
  2557. wdBreakpoint = new WdBreakpoint();
  2558. // Insert at head
  2559. wdBreakpoint->mLinkedSibling = headBreakpoint->mLinkedSibling;
  2560. headBreakpoint->mLinkedSibling = wdBreakpoint;
  2561. wdBreakpoint->mRequestedLineNum = headBreakpoint->mRequestedLineNum;
  2562. wdBreakpoint->mLineNum = headBreakpoint->mLineNum;
  2563. wdBreakpoint->mColumn = headBreakpoint->mColumn;
  2564. wdBreakpoint->mInstrOffset = headBreakpoint->mInstrOffset;
  2565. wdBreakpoint->mIsLinkedSibling = true;
  2566. wdBreakpoint->mHead = headBreakpoint;
  2567. }
  2568. if (wdBreakpoint->mInstrOffset > 0)
  2569. {
  2570. for (int instIdx = 0; instIdx < wdBreakpoint->mInstrOffset; instIdx++)
  2571. {
  2572. CPUInst inst;
  2573. if (!mDebugTarget->DecodeInstruction(address, &inst))
  2574. break;
  2575. address += inst.mSize;
  2576. }
  2577. }
  2578. wdBreakpoint->mSrcFile = ctx.mSrcFile;
  2579. wdBreakpoint->mLineData = DbgLineDataEx(lineData, subProgram);
  2580. wdBreakpoint->mBreakpointType = BreakpointType_User;
  2581. wdBreakpoint->mAddr = address;
  2582. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mStoppedAtAddress == address))
  2583. {
  2584. BfLogDbg("CheckBreakpoint setting mIsAtBreakpointAddress = %p\n", address);
  2585. mDebuggerWaitingThread->mIsAtBreakpointAddress = address;
  2586. }
  2587. BfLogDbg("Breakpoint %p found at %s in %s\n", wdBreakpoint, subProgram->mName, GetFileName(subProgram->mCompileUnit->mDbgModule->mFilePath).c_str());
  2588. SetBreakpoint(address);
  2589. foundInSequence = true;
  2590. }
  2591. }
  2592. if ((lineOffset >= 0) && (lineOffset <= maxLineDist) && (lineOffset <= bestLineOffset))
  2593. {
  2594. if (lineOffset < bestLineOffset)
  2595. {
  2596. bestLineNum = lineData->mLine;
  2597. bestLineOffset = lineOffset;
  2598. }
  2599. }
  2600. }
  2601. };
  2602. for (int pass = 0; pass < 2; pass++)
  2603. {
  2604. if (lineNum == -1)
  2605. break;
  2606. bestLineNum = -1;
  2607. bestLineOffset = 0x7FFFFFFF;
  2608. if (hotIdx >= 0)
  2609. {
  2610. if (hotIdx >= srcFile->mHotReplacedDbgLineInfo.size())
  2611. return;
  2612. auto hotReplacedLineInfo = srcFile->mHotReplacedDbgLineInfo[hotIdx];
  2613. for (auto& hotReplacedEntry : hotReplacedLineInfo->mEntries)
  2614. {
  2615. _CheckLineInfo(hotReplacedEntry.mSubprogram, hotReplacedEntry.mLineInfo);
  2616. }
  2617. }
  2618. else
  2619. {
  2620. for (auto subprogram : srcFile->mLineDataRefs)
  2621. _CheckLineInfo(subprogram, subprogram->mLineInfo);
  2622. }
  2623. if (foundLine)
  2624. break;
  2625. // Don't allow the breakpoint to be inexactly bound -- only match on pass 0
  2626. if (hotIdx != -1)
  2627. break;
  2628. if (bestLineNum == -1)
  2629. break;
  2630. lineNum = bestLineNum;
  2631. wdBreakpoint->mLineNum = bestLineNum;
  2632. }
  2633. int highestCheckHotIdx = highestHotIdx - 1;
  2634. if (hotIdx != -1)
  2635. highestCheckHotIdx = hotIdx - 1;
  2636. for (int hotFileIdx = highestCheckHotIdx; hotFileIdx >= 0; hotFileIdx--)
  2637. {
  2638. auto& hotReplacedDbgLineData = wdBreakpoint->mSrcFile->mHotReplacedDbgLineInfo;
  2639. // Only try to bind to an old hot version if we haven't unloaded the hot module
  2640. if ((hotFileIdx < (int)hotReplacedDbgLineData.size()) && (hotReplacedDbgLineData[hotFileIdx]->mEntries.size() > 0))
  2641. {
  2642. headBreakpoint->mPendingHotBindIdx = hotFileIdx;
  2643. break;
  2644. }
  2645. }
  2646. }
  2647. void WinDebugger::HotBindBreakpoint(Breakpoint* breakpoint, int lineNum, int hotIdx)
  2648. {
  2649. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  2650. CheckBreakpoint(wdBreakpoint, wdBreakpoint->mSrcFile, lineNum, hotIdx);
  2651. }
  2652. void WinDebugger::CheckBreakpoint(WdBreakpoint* wdBreakpoint)
  2653. {
  2654. if (!mGotStartupEvent)
  2655. return;
  2656. if (wdBreakpoint->mThreadId == 0) // Not bound to threadId yet...
  2657. {
  2658. return;
  2659. }
  2660. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  2661. {
  2662. if (wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap != 0)
  2663. return;
  2664. if (mFreeMemoryBreakIndices.size() == 0)
  2665. return;
  2666. if ((IsInRunState()) || (mActiveThread == NULL))
  2667. return;
  2668. int wantBytes[4];
  2669. int wantBindCount = 0;
  2670. int bytesLeft = wdBreakpoint->mMemoryBreakpointInfo->mByteCount;
  2671. addr_target curAddr = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress;
  2672. while (bytesLeft > 0)
  2673. {
  2674. if (wantBindCount >= mFreeMemoryBreakIndices.size())
  2675. return;
  2676. int curByteCount = 1;
  2677. #ifdef BF_DBG_64
  2678. if ((bytesLeft >= 8) && ((curAddr & 7) == 0))
  2679. curByteCount = 8;
  2680. else
  2681. #endif
  2682. if ((bytesLeft >= 4) && ((curAddr & 3) == 0))
  2683. curByteCount = 4;
  2684. else if ((bytesLeft >= 2) && ((curAddr & 1) == 0))
  2685. curByteCount = 2;
  2686. wantBytes[wantBindCount++] = curByteCount;
  2687. bytesLeft -= curByteCount;
  2688. curAddr += curByteCount;
  2689. }
  2690. addr_target curOfs = 0;
  2691. for (int i = 0; i < wantBindCount; i++)
  2692. {
  2693. int memoryBreakIdx = mFreeMemoryBreakIndices.back();
  2694. mFreeMemoryBreakIndices.pop_back();
  2695. mMemoryBreakpoints[memoryBreakIdx].mBreakpoint = wdBreakpoint;
  2696. mMemoryBreakpoints[memoryBreakIdx].mAddress = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress + curOfs;
  2697. mMemoryBreakpoints[memoryBreakIdx].mByteCount = wantBytes[i];
  2698. mMemoryBreakpoints[memoryBreakIdx].mOfs = curOfs;
  2699. curOfs += wantBytes[i];
  2700. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap |= 1<<memoryBreakIdx;
  2701. }
  2702. UpdateThreadDebugRegisters();
  2703. }
  2704. if (wdBreakpoint->mAddr != 0)
  2705. return;
  2706. if (!wdBreakpoint->mSymbolName.IsEmpty())
  2707. {
  2708. auto headBreakpoint = wdBreakpoint->GetHeadBreakpoint();
  2709. String symbolName = wdBreakpoint->mSymbolName;
  2710. bool onlyBindFirst = false;
  2711. if (symbolName.StartsWith("-"))
  2712. {
  2713. symbolName.Remove(0);
  2714. onlyBindFirst = true;
  2715. }
  2716. for (auto dbgModule : mDebugTarget->mDbgModules)
  2717. {
  2718. dbgModule->ParseSymbolData();
  2719. addr_target targetAddr = -1;
  2720. auto entry = dbgModule->mSymbolNameMap.Find(symbolName.c_str());
  2721. if (entry != NULL)
  2722. {
  2723. DbgSymbol* dwSymbol = entry->mValue;
  2724. targetAddr = dwSymbol->mAddress;
  2725. }
  2726. if (targetAddr == -1)
  2727. {
  2728. if (symbolName == ".")
  2729. {
  2730. targetAddr = mDebugTarget->mLaunchBinary->mImageBase + mDebugTarget->mLaunchBinary->mEntryPoint;
  2731. onlyBindFirst = true;
  2732. }
  2733. }
  2734. if (targetAddr != -1)
  2735. {
  2736. if (wdBreakpoint->mAddr == 0)
  2737. {
  2738. wdBreakpoint->mAddr = targetAddr;
  2739. wdBreakpoint->mBreakpointType = BreakpointType_User;
  2740. SetBreakpoint(wdBreakpoint->mAddr);
  2741. }
  2742. else
  2743. {
  2744. wdBreakpoint = new WdBreakpoint();
  2745. // Insert at head
  2746. wdBreakpoint->mLinkedSibling = headBreakpoint->mLinkedSibling;
  2747. headBreakpoint->mLinkedSibling = wdBreakpoint;
  2748. wdBreakpoint->mSymbolName = headBreakpoint->mSymbolName;
  2749. wdBreakpoint->mIsLinkedSibling = true;
  2750. wdBreakpoint->mHead = headBreakpoint;
  2751. }
  2752. if (onlyBindFirst)
  2753. break;
  2754. }
  2755. }
  2756. return;
  2757. }
  2758. BP_ZONE("WinDebugger::CheckBreakpoint");
  2759. // Rehup if we load a DLL that also uses this file we bound to (thus the mDeferredRefs check)
  2760. if (wdBreakpoint->mSrcFile == NULL)
  2761. {
  2762. DbgSrcFile* srcFile = mDebugTarget->GetSrcFile(wdBreakpoint->mFilePath);
  2763. if (srcFile == NULL)
  2764. return;
  2765. for (auto& deferredSrcFileRef : srcFile->mDeferredRefs)
  2766. {
  2767. deferredSrcFileRef.mDbgModule->ParseCompileUnit(deferredSrcFileRef.mCompileUnitId);
  2768. }
  2769. srcFile->mDeferredRefs.Clear();
  2770. CheckBreakpoint(wdBreakpoint, srcFile, wdBreakpoint->mRequestedLineNum, -1);
  2771. }
  2772. }
  2773. bool WinDebugger::IsMemoryBreakpointSizeValid(addr_target addr, int size)
  2774. {
  2775. int wantBindCount = 0;
  2776. int bytesLeft = size;
  2777. addr_target curAddr = addr;
  2778. for (int i = 0; i < 4; i++)
  2779. {
  2780. int curByteCount = 1;
  2781. #ifdef BF_DBG_64
  2782. if ((bytesLeft >= 8) && ((curAddr & 7) == 0))
  2783. curByteCount = 8;
  2784. else
  2785. #endif
  2786. if ((bytesLeft >= 4) && ((curAddr & 3) == 0))
  2787. curByteCount = 4;
  2788. else if ((bytesLeft >= 2) && ((curAddr & 1) == 0))
  2789. curByteCount = 2;
  2790. bytesLeft -= curByteCount;
  2791. curAddr += curByteCount;
  2792. if (bytesLeft == 0)
  2793. return true;
  2794. }
  2795. return false;
  2796. }
  2797. bool WinDebugger::HasMemoryBreakpoint(addr_target addr, int size)
  2798. {
  2799. for (int i = 0; i < 4; i++)
  2800. {
  2801. if ((mMemoryBreakpoints[i].mAddress == addr) &&
  2802. (mMemoryBreakpoints[i].mOfs == 0) &&
  2803. (mMemoryBreakpoints[i].mBreakpoint->mMemoryBreakpointInfo->mByteCount == size))
  2804. return true;
  2805. }
  2806. return false;
  2807. }
  2808. Breakpoint* WinDebugger::CreateBreakpoint(const StringImpl& fileName, int lineNum, int wantColumn, int instrOffset)
  2809. {
  2810. AutoCrit autoCrit(mDebugManager->mCritSect);
  2811. BfLogDbg("CreateBreakpoint %s %d %d\n", fileName.c_str(), lineNum, wantColumn);
  2812. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  2813. wdBreakpoint->mFilePath = FixPathAndCase(fileName);
  2814. wdBreakpoint->mRequestedLineNum = lineNum;
  2815. wdBreakpoint->mLineNum = lineNum;
  2816. wdBreakpoint->mColumn = wantColumn;
  2817. wdBreakpoint->mInstrOffset = instrOffset;
  2818. mBreakpoints.push_back(wdBreakpoint);
  2819. BfLogDbg("CreateBreakpoint Created %p\n", wdBreakpoint);
  2820. return wdBreakpoint;
  2821. }
  2822. void WinDebugger::CheckBreakpoint(Breakpoint* checkBreakpoint)
  2823. {
  2824. AutoCrit autoCrit(mDebugManager->mCritSect);
  2825. CheckBreakpoint((WdBreakpoint*)checkBreakpoint);
  2826. }
  2827. Breakpoint* WinDebugger::CreateMemoryBreakpoint(intptr addr, int byteCount)
  2828. {
  2829. AutoCrit autoCrit(mDebugManager->mCritSect);
  2830. BfLogDbg("CreateMemoryBreakpoint %p %d\n", addr, byteCount);
  2831. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  2832. WdMemoryBreakpointInfo* memoryBreakInfo = new WdMemoryBreakpointInfo();
  2833. memoryBreakInfo->mMemoryAddress = addr;
  2834. memoryBreakInfo->mByteCount = byteCount;
  2835. wdBreakpoint->mMemoryBreakpointInfo = memoryBreakInfo;
  2836. mBreakpoints.push_back(wdBreakpoint);
  2837. CheckBreakpoint(wdBreakpoint);
  2838. return wdBreakpoint;
  2839. }
  2840. Breakpoint* WinDebugger::CreateSymbolBreakpoint(const StringImpl& symbolName)
  2841. {
  2842. AutoCrit autoCrit(mDebugManager->mCritSect);
  2843. BfLogDbg("CreateSymbolBreakpoint %s\n", symbolName.c_str());
  2844. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  2845. wdBreakpoint->mSymbolName = symbolName;
  2846. mBreakpoints.push_back(wdBreakpoint);
  2847. CheckBreakpoint(wdBreakpoint);
  2848. return wdBreakpoint;
  2849. }
  2850. Breakpoint* WinDebugger::CreateAddressBreakpoint(intptr inAddress)
  2851. {
  2852. AutoCrit autoCrit(mDebugManager->mCritSect);
  2853. BfLogDbg("CreateAddressBreakpoint %p\n", inAddress);
  2854. addr_target address = (addr_target)inAddress;
  2855. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  2856. wdBreakpoint->mAddr = address;
  2857. SetBreakpoint(address);
  2858. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mStoppedAtAddress == address))
  2859. {
  2860. BfLogDbg("CreateAddressBreakpoint setting mIsAtBreakpointAddress = %p\n", address);
  2861. mDebuggerWaitingThread->mIsAtBreakpointAddress = address;
  2862. }
  2863. mBreakpoints.push_back(wdBreakpoint);
  2864. return wdBreakpoint;
  2865. }
  2866. void WinDebugger::DeleteBreakpoint(Breakpoint* breakpoint)
  2867. {
  2868. AutoCrit autoCrit(mDebugManager->mCritSect);
  2869. if (breakpoint == mActiveBreakpoint)
  2870. mActiveBreakpoint = NULL;
  2871. BfLogDbg("WinDebugger::DeleteBreakpoint %p Count:%d\n", breakpoint, mBreakpoints.size());
  2872. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  2873. if (wdBreakpoint->mCondition != NULL)
  2874. {
  2875. if (!wdBreakpoint->mIsLinkedSibling)
  2876. delete wdBreakpoint->mCondition;
  2877. }
  2878. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  2879. {
  2880. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  2881. {
  2882. if (mMemoryBreakpoints[memoryWatchSlot].mBreakpoint == wdBreakpoint)
  2883. {
  2884. mFreeMemoryBreakIndices.push_back(memoryWatchSlot);
  2885. mMemoryBreakpoints[memoryWatchSlot] = WdMemoryBreakpointBind();
  2886. UpdateThreadDebugRegisters();
  2887. }
  2888. }
  2889. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap = 0;
  2890. }
  2891. if (wdBreakpoint->mAddr != 0)
  2892. {
  2893. RemoveBreakpoint(wdBreakpoint->mAddr);
  2894. for (auto thread : mThreadList)
  2895. {
  2896. if (thread->mIsAtBreakpointAddress == wdBreakpoint->mAddr)
  2897. thread->mIsAtBreakpointAddress = NULL;
  2898. if (thread->mBreakpointAddressContinuing == wdBreakpoint->mAddr)
  2899. thread->mBreakpointAddressContinuing = NULL;
  2900. }
  2901. }
  2902. if (!wdBreakpoint->mIsLinkedSibling)
  2903. {
  2904. mBreakpoints.Remove(wdBreakpoint);
  2905. }
  2906. if (wdBreakpoint->mLinkedSibling != NULL)
  2907. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  2908. delete wdBreakpoint;
  2909. }
  2910. void WinDebugger::DetachBreakpoint(Breakpoint* breakpoint)
  2911. {
  2912. AutoCrit autoCrit(mDebugManager->mCritSect);
  2913. BfLogDbg("WinDebugger::DetachBreakpoint %p\n", breakpoint);
  2914. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  2915. if (wdBreakpoint->mAddr != 0)
  2916. {
  2917. RemoveBreakpoint(wdBreakpoint->mAddr);
  2918. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mIsAtBreakpointAddress == wdBreakpoint->mAddr))
  2919. mDebuggerWaitingThread->mIsAtBreakpointAddress = NULL;
  2920. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mBreakpointAddressContinuing == wdBreakpoint->mAddr))
  2921. mDebuggerWaitingThread->mBreakpointAddressContinuing = NULL;
  2922. wdBreakpoint->mLineData = DbgLineDataEx();
  2923. wdBreakpoint->mAddr = 0;
  2924. }
  2925. if (wdBreakpoint->mCondition != NULL)
  2926. {
  2927. delete wdBreakpoint->mCondition->mDbgEvaluationContext;
  2928. wdBreakpoint->mCondition->mDbgEvaluationContext = NULL;
  2929. }
  2930. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  2931. {
  2932. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  2933. {
  2934. if (mMemoryBreakpoints[memoryWatchSlot].mBreakpoint == wdBreakpoint)
  2935. {
  2936. mFreeMemoryBreakIndices.push_back(memoryWatchSlot);
  2937. mMemoryBreakpoints[memoryWatchSlot] = WdMemoryBreakpointBind();
  2938. UpdateThreadDebugRegisters();
  2939. }
  2940. }
  2941. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap = 0;
  2942. }
  2943. if (wdBreakpoint->mLinkedSibling != NULL)
  2944. {
  2945. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  2946. wdBreakpoint->mLinkedSibling = NULL;
  2947. }
  2948. wdBreakpoint->mSrcFile = NULL;
  2949. wdBreakpoint->mPendingHotBindIdx = -1;
  2950. }
  2951. void WinDebugger::MoveBreakpoint(Breakpoint* breakpoint, int lineNum, int wantColumn, bool rebindNow)
  2952. {
  2953. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  2954. AutoCrit autoCrit(mDebugManager->mCritSect);
  2955. DetachBreakpoint(wdBreakpoint);
  2956. //TODO: This doesn't actually rebind correctly while the app is running
  2957. if ((lineNum != -1) && (wantColumn != -1))
  2958. {
  2959. wdBreakpoint->mRequestedLineNum = lineNum;
  2960. wdBreakpoint->mLineNum = lineNum;
  2961. wdBreakpoint->mColumn = wantColumn;
  2962. }
  2963. if (rebindNow)
  2964. CheckBreakpoint(wdBreakpoint);
  2965. }
  2966. void WinDebugger::MoveMemoryBreakpoint(Breakpoint* breakpoint, intptr addr, int byteCount)
  2967. {
  2968. AutoCrit autoCrit(mDebugManager->mCritSect);
  2969. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  2970. DetachBreakpoint(wdBreakpoint);
  2971. wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress = addr;
  2972. wdBreakpoint->mMemoryBreakpointInfo->mByteCount = byteCount;
  2973. CheckBreakpoint(wdBreakpoint);
  2974. }
  2975. void WinDebugger::DisableBreakpoint(Breakpoint* breakpoint)
  2976. {
  2977. AutoCrit autoCrit(mDebugManager->mCritSect);
  2978. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  2979. DetachBreakpoint(wdBreakpoint);
  2980. delete wdBreakpoint->mMemoryBreakpointInfo;
  2981. wdBreakpoint->mMemoryBreakpointInfo = NULL;
  2982. }
  2983. void WinDebugger::SetBreakpointCondition(Breakpoint* breakpoint, const StringImpl& conditionExpr)
  2984. {
  2985. AutoCrit autoCrit(mDebugManager->mCritSect);
  2986. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  2987. BF_ASSERT(!wdBreakpoint->mIsLinkedSibling);
  2988. if (conditionExpr.empty())
  2989. {
  2990. delete wdBreakpoint->mCondition;
  2991. WdBreakpoint* curBreakpoint = wdBreakpoint;
  2992. wdBreakpoint->mCondition = NULL;
  2993. }
  2994. else
  2995. {
  2996. delete wdBreakpoint->mCondition;
  2997. auto condition = new WdBreakpointCondition();
  2998. condition->mExpr = conditionExpr;
  2999. wdBreakpoint->mCondition = condition;
  3000. }
  3001. }
  3002. void WinDebugger::SetBreakpointLogging(Breakpoint* breakpoint, const StringImpl& logging, bool breakAfterLogging)
  3003. {
  3004. AutoCrit autoCrit(mDebugManager->mCritSect);
  3005. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3006. BF_ASSERT(!wdBreakpoint->mIsLinkedSibling);
  3007. wdBreakpoint->mLogging = logging;
  3008. wdBreakpoint->mBreakAfterLogging = breakAfterLogging;
  3009. }
  3010. bool WinDebugger::CheckConditionalBreakpoint(WdBreakpoint* breakpoint, DbgSubprogram* dbgSubprogram, addr_target pcAddress)
  3011. {
  3012. // What was this assertion for?
  3013. //BF_ASSERT(mCallStack.size() == 0);
  3014. auto headBreakpoint = breakpoint->GetHeadBreakpoint();
  3015. if (headBreakpoint->mThreadId != -1)
  3016. {
  3017. if ((mActiveThread != NULL) && (mActiveThread->mThreadId != headBreakpoint->mThreadId))
  3018. return false;
  3019. }
  3020. auto _SplitExpr = [&](const StringImpl& expr, String& outExpr, String& outSubject)
  3021. {
  3022. int crPos = expr.IndexOf('\n');
  3023. if (crPos != -1)
  3024. {
  3025. outExpr = expr.Substring(0, crPos);
  3026. outSubject = expr.Substring(crPos + 1);
  3027. }
  3028. else
  3029. {
  3030. outExpr = expr;
  3031. }
  3032. };
  3033. if (headBreakpoint->mCondition != NULL)
  3034. {
  3035. ClearCallStack();
  3036. auto conditional = headBreakpoint->mCondition;
  3037. if (conditional->mDbgEvaluationContext == NULL)
  3038. {
  3039. CPURegisters registers;
  3040. PopulateRegisters(&registers);
  3041. auto pcAddress = registers.GetPC();
  3042. DbgSubprogram* subprogram = mDebugTarget->FindSubProgram(pcAddress);
  3043. if (subprogram == NULL)
  3044. {
  3045. return false;
  3046. }
  3047. String expr;
  3048. String subjectExpr;
  3049. _SplitExpr(conditional->mExpr, expr, subjectExpr);
  3050. DbgLanguage language = DbgLanguage_Unknown;
  3051. if (expr.StartsWith("@Beef:"))
  3052. {
  3053. expr.Remove(0, 6);
  3054. language = DbgLanguage_Beef;
  3055. }
  3056. else if (expr.StartsWith("@C:"))
  3057. {
  3058. expr.Remove(0, 3);
  3059. language = DbgLanguage_C;
  3060. }
  3061. conditional->mDbgEvaluationContext = new DbgEvaluationContext(this, subprogram->mCompileUnit->mDbgModule, expr);
  3062. if (language != DbgLanguage_Unknown)
  3063. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mLanguage = language;
  3064. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mSubjectExpr = subjectExpr;
  3065. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mDbgCompileUnit = subprogram->mCompileUnit;
  3066. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mCallStackIdx = 0;
  3067. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mExpressionFlags = (DwEvalExpressionFlags)(DwEvalExpressionFlag_AllowSideEffects | DwEvalExpressionFlag_AllowCalls);
  3068. }
  3069. WdStackFrame* wdStackFrame = new WdStackFrame();
  3070. PopulateRegisters(&wdStackFrame->mRegisters);
  3071. mCallStack.Add(wdStackFrame);
  3072. DbgTypedValue result = conditional->mDbgEvaluationContext->EvaluateInContext(DbgTypedValue());
  3073. ClearCallStack();
  3074. if (conditional->mDbgEvaluationContext->mPassInstance->HasFailed())
  3075. {
  3076. String errorStr = "FAILED";
  3077. for (auto error : conditional->mDbgEvaluationContext->mPassInstance->mErrors)
  3078. {
  3079. if (!error->mIsWarning)
  3080. errorStr = error->mError;
  3081. }
  3082. String condError = StrFormat("error Conditional breakpoint expression '%s' failed: %s", conditional->mExpr.c_str(), errorStr.c_str());
  3083. mDebugManager->mOutMessages.push_back(condError);
  3084. return true;
  3085. }
  3086. else if ((!result) || (!result.mType->IsBoolean()))
  3087. {
  3088. mDebugManager->mOutMessages.push_back(StrFormat("error Conditional breakpoint expression '%s' must result in a boolean value", conditional->mExpr.c_str()));
  3089. return true;
  3090. }
  3091. else if (!result.mBool)
  3092. return false;
  3093. }
  3094. headBreakpoint->mHitCount++;
  3095. switch (headBreakpoint->mHitCountBreakKind)
  3096. {
  3097. case DbgHitCountBreakKind_Equals:
  3098. if (headBreakpoint->mHitCount != headBreakpoint->mTargetHitCount)
  3099. return false;
  3100. break;
  3101. case DbgHitCountBreakKind_GreaterEquals:
  3102. if (headBreakpoint->mHitCount < headBreakpoint->mTargetHitCount)
  3103. return false;
  3104. break;
  3105. case DbgHitCountBreakKind_Multiple:
  3106. if ((headBreakpoint->mHitCount % headBreakpoint->mTargetHitCount) != 0)
  3107. return false;
  3108. break;
  3109. }
  3110. mActiveBreakpoint = breakpoint;
  3111. mBreakStackFrameIdx = -1;
  3112. if (!headBreakpoint->mLogging.IsEmpty())
  3113. {
  3114. ClearCallStack();
  3115. DwFormatInfo formatInfo;
  3116. formatInfo.mCallStackIdx = 0;
  3117. DbgCompileUnit* dbgCompileUnit = NULL;
  3118. if (dbgSubprogram == NULL)
  3119. dbgSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3120. if (dbgSubprogram != NULL)
  3121. {
  3122. dbgCompileUnit = dbgSubprogram->mCompileUnit;
  3123. formatInfo.mLanguage = dbgSubprogram->GetLanguage();
  3124. }
  3125. auto prevRunState = mRunState;
  3126. mRunState = RunState_Paused; // We need to be paused to avoid certain errors in the eval
  3127. String displayString;
  3128. String expr;
  3129. _SplitExpr(headBreakpoint->mLogging, expr, formatInfo.mSubjectExpr);
  3130. if (expr.StartsWith("@Beef:"))
  3131. {
  3132. expr.Remove(0, 6);
  3133. formatInfo.mLanguage = DbgLanguage_Beef;
  3134. }
  3135. else if (expr.StartsWith("@C:"))
  3136. {
  3137. expr.Remove(0, 3);
  3138. formatInfo.mLanguage = DbgLanguage_C;
  3139. }
  3140. ProcessEvalString(dbgCompileUnit, DbgTypedValue(), expr, displayString, formatInfo, NULL, false);
  3141. mRunState = prevRunState;
  3142. displayString.Insert(0, "log ");
  3143. displayString.Append("\n");
  3144. mDebugManager->mOutMessages.push_back(displayString);
  3145. if (!headBreakpoint->mBreakAfterLogging)
  3146. return false;
  3147. }
  3148. return true;
  3149. }
  3150. void WinDebugger::CleanupDebugEval(bool restoreRegisters)
  3151. {
  3152. BfLogDbg("CleanupDebugEval ThreadId=%d\n", mDebugEvalThreadInfo.mThreadId);
  3153. WdThreadInfo* evalThreadInfo = NULL;
  3154. if (mThreadMap.TryGetValue(mDebugEvalThreadInfo.mThreadId, &evalThreadInfo))
  3155. {
  3156. if ((restoreRegisters) && (!mDbgBreak))
  3157. {
  3158. SetAndRestoreValue<WdThreadInfo*> activeThread(mActiveThread, evalThreadInfo);
  3159. RestoreAllRegisters();
  3160. // if (mRunState == RunState_Running_ToTempBreakpoint)
  3161. // mRunState = RunState_Paused;
  3162. }
  3163. evalThreadInfo->mStartSP = mDebugEvalThreadInfo.mStartSP;
  3164. evalThreadInfo->mStoppedAtAddress = mDebugEvalThreadInfo.mStoppedAtAddress;
  3165. evalThreadInfo->mIsAtBreakpointAddress = mDebugEvalThreadInfo.mIsAtBreakpointAddress;
  3166. evalThreadInfo->mBreakpointAddressContinuing = mDebugEvalThreadInfo.mBreakpointAddressContinuing;
  3167. }
  3168. delete mDebugPendingExpr;
  3169. mDebugPendingExpr = NULL;
  3170. mDebugEvalThreadInfo = WdThreadInfo();
  3171. OutputRawMessage("rehupLoc");
  3172. }
  3173. bool WinDebugger::FixCallStackIdx(int& callStackIdx)
  3174. {
  3175. callStackIdx = BF_MAX(callStackIdx, 0);
  3176. if (mCallStack.IsEmpty())
  3177. UpdateCallStack();
  3178. int stackSize = (int)mCallStack.size();
  3179. while (callStackIdx >= mCallStack.size())
  3180. {
  3181. UpdateCallStack();
  3182. if (stackSize == (int)mCallStack.size())
  3183. break; // Didn't change
  3184. stackSize = (int)mCallStack.size();
  3185. }
  3186. if (callStackIdx >= stackSize)
  3187. {
  3188. callStackIdx = 0;
  3189. return false;
  3190. }
  3191. return true;
  3192. }
  3193. bool WinDebugger::HasLineInfoAt(addr_target address)
  3194. {
  3195. BP_ZONE("WinDebugger::HasLineInfoAt");
  3196. DbgSubprogram* dbgSubprogram = NULL;
  3197. auto dwLineData = FindLineDataAtAddress(address, &dbgSubprogram);
  3198. return (dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dbgSubprogram->GetLineAddr(*dwLineData) == address);
  3199. }
  3200. void WinDebugger::StepLineTryPause(addr_target address, bool requireExactMatch)
  3201. {
  3202. if (mStepInAssembly)
  3203. return;
  3204. if (mStepLineData.mLineData != NULL)
  3205. {
  3206. DbgSubprogram* dbgSubprogram = NULL;
  3207. DbgSrcFile* dbgSrcFile = NULL;
  3208. auto dwLineData = FindLineDataAtAddress(address, &dbgSubprogram, &dbgSrcFile);
  3209. if ((dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && ((!requireExactMatch) || (dbgSubprogram->GetLineAddr(*dwLineData) == address)))
  3210. {
  3211. // "Invalid" line
  3212. if (dwLineData->mColumn == -1)
  3213. {
  3214. SetupStep(mStepType);
  3215. mRunState = RunState_Running;
  3216. return;
  3217. }
  3218. // If we're on the same line but a different column or a <= address then keep it keep looking
  3219. if ((dbgSrcFile == mStepLineData.GetSrcFile()) &&
  3220. ((!requireExactMatch) || (dwLineData != mStepLineData.mLineData) || (address <= mStepStartPC)) &&
  3221. (dwLineData->mLine == mStepLineData.mLineData->mLine))
  3222. {
  3223. SetupStep(mStepType);
  3224. mRunState = RunState_Running;
  3225. return;
  3226. }
  3227. }
  3228. }
  3229. mRunState = RunState_Paused;
  3230. }
  3231. void WinDebugger::BreakAll()
  3232. {
  3233. AutoCrit autoCrit(mDebugManager->mCritSect);
  3234. ::DebugBreakProcess(mProcessInfo.hProcess);
  3235. }
  3236. void WinDebugger::StepInto(bool inAssembly)
  3237. {
  3238. AutoCrit autoCrit(mDebugManager->mCritSect);
  3239. if (!TryRunContinue())
  3240. return;
  3241. BfLogDbg("StepInto\n");
  3242. mCurNoInfoStepTries = 0; // Reset
  3243. mStepInAssembly = inAssembly;
  3244. SetupStep(StepType_StepInto);
  3245. ContinueDebugEvent();
  3246. }
  3247. void WinDebugger::StepIntoSpecific(intptr inAddr)
  3248. {
  3249. addr_target addr = (addr_target)inAddr;
  3250. AutoCrit autoCrit(mDebugManager->mCritSect);
  3251. if (!TryRunContinue())
  3252. return;
  3253. BfLogDbg("StepIntoSpecific %p\n", addr);
  3254. mCurNoInfoStepTries = 0; // Reset
  3255. mStepInAssembly = false;
  3256. SetupStep(StepType_StepInto);
  3257. mIsStepIntoSpecific = true;
  3258. mStepType = StepType_StepInto_Unfiltered;
  3259. if (mStepStartPC != addr)
  3260. {
  3261. RemoveTempBreakpoints();
  3262. SetTempBreakpoint(addr);
  3263. mStepBreakpointAddrs.push_back(addr);
  3264. }
  3265. ContinueDebugEvent();
  3266. }
  3267. void WinDebugger::PushValue(CPURegisters* registers, int64 val)
  3268. {
  3269. addr_target* regSP = registers->GetSPRegisterRef();
  3270. *regSP -= sizeof(addr_target);
  3271. WriteMemory<addr_target>(*regSP, (addr_target)val);
  3272. }
  3273. void WinDebugger::PushValue(CPURegisters* registers, const DbgTypedValue& typedValue)
  3274. {
  3275. addr_target* regSP = registers->GetSPRegisterRef();
  3276. int byteCount = typedValue.mType->GetByteCount();
  3277. if ((byteCount == 8) || (sizeof(addr_target) == 8))
  3278. {
  3279. *regSP -= sizeof(int64);
  3280. addr_target val = typedValue.mInt64;
  3281. if (typedValue.mType->IsCompositeType())
  3282. val = typedValue.mSrcAddress;
  3283. WriteMemory<int64>(*regSP, val);
  3284. }
  3285. else
  3286. {
  3287. *regSP -= sizeof(int32);
  3288. addr_target val = typedValue.mInt32;
  3289. if (typedValue.mType->IsCompositeType())
  3290. val = typedValue.mSrcAddress;
  3291. WriteMemory<int32>(*regSP, val);
  3292. }
  3293. }
  3294. void WinDebugger::SetThisRegister(CPURegisters* registers, addr_target val)
  3295. {
  3296. #if BF_DBG_32
  3297. registers->mIntRegs.ecx = val;
  3298. #else
  3299. registers->mIntRegs.rcx = val;
  3300. #endif
  3301. }
  3302. void WinDebugger::AddParamValue(int paramIdx, bool hadThis, CPURegisters* registers, const DbgTypedValue& typedValue)
  3303. {
  3304. #if BF_DBG_32
  3305. PushValue(registers, typedValue);
  3306. #else
  3307. int regIdx = paramIdx + (hadThis ? 1 : 0);
  3308. if (typedValue.mType->IsFloat())
  3309. {
  3310. PushValue(registers, typedValue);
  3311. if (regIdx < 4)
  3312. {
  3313. if (typedValue.mType->mTypeCode == DbgType_Single)
  3314. {
  3315. registers->mXmmRegsArray[regIdx].f[0] = typedValue.mSingle;
  3316. }
  3317. else
  3318. {
  3319. registers->mXmmDRegsArray[regIdx].d[0] = typedValue.mDouble;
  3320. }
  3321. }
  3322. }
  3323. else
  3324. {
  3325. PushValue(registers, typedValue);
  3326. if (regIdx < 4)
  3327. {
  3328. int64 val;
  3329. if (typedValue.mType->IsCompositeType())
  3330. val = typedValue.mSrcAddress;
  3331. else
  3332. val = typedValue.mPtr;
  3333. if (regIdx == 0)
  3334. registers->mIntRegs.rcx = val;
  3335. else if (regIdx == 1)
  3336. registers->mIntRegs.rdx = val;
  3337. else if (regIdx == 2)
  3338. registers->mIntRegs.r8 = val;
  3339. else if (regIdx == 3)
  3340. registers->mIntRegs.r9 = val;
  3341. }
  3342. }
  3343. #endif
  3344. }
  3345. bool WinDebugger::CheckNeedsSRetArgument(DbgType* retType)
  3346. {
  3347. if (!retType->IsCompositeType())
  3348. return false;
  3349. //TODO: Change when we change the calling convention
  3350. if (retType->GetLanguage() == DbgLanguage_Beef)
  3351. return true;
  3352. int retSize = retType->GetByteCount();
  3353. //TODO: Check for 'POD' type?
  3354. if ((retSize == 1) || (retSize == 2) || (retSize == 4) || (retSize == sizeof(addr_target)))
  3355. return false;
  3356. return true;
  3357. }
  3358. DbgTypedValue WinDebugger::ReadReturnValue(CPURegisters* registers, DbgType* type)
  3359. {
  3360. DbgTypedValue retValue;
  3361. if (type->IsFloat())
  3362. {
  3363. retValue.mType = type;
  3364. #if BF_DBG_32
  3365. retValue.mDouble = ConvertFloat80ToDouble(registers->mFpMmRegsArray[0].fp.fp80);
  3366. if (type->mSize == 4)
  3367. retValue.mSingle = (float)retValue.mDouble;
  3368. #else
  3369. if (retValue.mType->mTypeCode == DbgType_Single)
  3370. retValue.mSingle = registers->mXmmRegsArray[0].f[0];
  3371. else
  3372. retValue.mDouble = registers->mXmmDRegsArray[0].d[0];
  3373. #endif
  3374. }
  3375. else if (type->IsCompositeType())
  3376. {
  3377. retValue.mType = type;
  3378. if (CheckNeedsSRetArgument(type))
  3379. {
  3380. #ifdef BF_DBG_32
  3381. retValue.mSrcAddress = mSavedContext.Esp - BF_ALIGN(type->GetByteCount(), 16);
  3382. #else
  3383. retValue.mSrcAddress = mSavedContext.Rsp - BF_ALIGN(type->GetByteCount(), 16);
  3384. #endif
  3385. }
  3386. else
  3387. {
  3388. #ifdef BF_DBG_32
  3389. retValue.mInt32 = mSavedContext.Eax;
  3390. #else
  3391. retValue.mInt64 = mSavedContext.Rax;
  3392. #endif
  3393. }
  3394. }
  3395. else
  3396. {
  3397. #ifdef BF_DBG_32
  3398. retValue.mType = type;
  3399. retValue.mInt32 = registers->mIntRegs.eax;
  3400. if (type->mSize == 8)
  3401. (&retValue.mInt32)[1] = registers->mIntRegs.edx;
  3402. #else
  3403. retValue.mType = type;
  3404. retValue.mInt64 = registers->mIntRegs.rax;
  3405. #endif
  3406. return retValue;
  3407. }
  3408. return retValue;
  3409. }
  3410. bool WinDebugger::SetRegisters(CPURegisters* registers)
  3411. {
  3412. BF_CONTEXT lcContext;
  3413. lcContext.ContextFlags = BF_CONTEXT_CONTROL | BF_CONTEXT_INTEGER | BF_CONTEXT_FLOATING_POINT | BF_CONTEXT_EXTENDED_REGISTERS | BF_CONTEXT_SEGMENTS;
  3414. lcContext.ContextFlags |= BF_CONTEXT_EXCEPTION_REQUEST;
  3415. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  3416. #ifdef BF_DBG_32
  3417. lcContext.Eax = registers->mIntRegs.eax;
  3418. lcContext.Ecx = registers->mIntRegs.ecx;
  3419. lcContext.Edx = registers->mIntRegs.edx;
  3420. lcContext.Ebx = registers->mIntRegs.ebx;
  3421. lcContext.Esp = registers->mIntRegs.esp;
  3422. lcContext.Ebp = registers->mIntRegs.ebp;
  3423. lcContext.Esi = registers->mIntRegs.esi;
  3424. lcContext.Edi = registers->mIntRegs.edi;
  3425. lcContext.Eip = registers->mIntRegs.eip;
  3426. lcContext.EFlags = registers->mIntRegs.efl;
  3427. BF_ASSERT(sizeof(lcContext.FloatSave.RegisterArea) == sizeof(registers->mFpMmRegsArray));
  3428. memcpy(lcContext.FloatSave.RegisterArea, registers->mFpMmRegsArray, sizeof(lcContext.FloatSave.RegisterArea));
  3429. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 32*sizeof(float));
  3430. memcpy(&lcContext.ExtendedRegisters[160], registers->mXmmRegsArray, sizeof(registers->mXmmRegsArray));
  3431. #else
  3432. lcContext.Rax = registers->mIntRegs.rax;
  3433. lcContext.Rcx = registers->mIntRegs.rcx;
  3434. lcContext.Rdx = registers->mIntRegs.rdx;
  3435. lcContext.Rbx = registers->mIntRegs.rbx;
  3436. lcContext.Rsp = registers->mIntRegs.rsp;
  3437. lcContext.Rbp = registers->mIntRegs.rbp;
  3438. lcContext.Rsi = registers->mIntRegs.rsi;
  3439. lcContext.Rdi = registers->mIntRegs.rdi;
  3440. lcContext.Rip = registers->mIntRegs.rip;
  3441. lcContext.EFlags = (DWORD)registers->mIntRegs.efl;
  3442. lcContext.R8 = registers->mIntRegs.r8;
  3443. lcContext.R9 = registers->mIntRegs.r9;
  3444. lcContext.R10 = registers->mIntRegs.r10;
  3445. lcContext.R11 = registers->mIntRegs.r11;
  3446. lcContext.R12 = registers->mIntRegs.r12;
  3447. lcContext.R13 = registers->mIntRegs.r13;
  3448. lcContext.R14 = registers->mIntRegs.r14;
  3449. lcContext.R15 = registers->mIntRegs.r15;
  3450. for (int i = 0; i < 8; i++)
  3451. {
  3452. memcpy(&lcContext.FltSave.FloatRegisters[i], &registers->mFpMmRegsArray[i], 10);
  3453. }
  3454. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 64 * sizeof(float));
  3455. memcpy(BF_CONTEXT_XMMDATA(lcContext), registers->mXmmRegsArray, sizeof(registers->mXmmRegsArray));
  3456. #endif
  3457. //lcContext.ContextFlags |= BF_CONTEXT_EXCEPTION_REQUEST;
  3458. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  3459. return (lcContext.ContextFlags & (BF_CONTEXT_EXCEPTION_ACTIVE | BF_CONTEXT_SERVICE_ACTIVE)) == 0;
  3460. }
  3461. void WinDebugger::SaveAllRegisters()
  3462. {
  3463. BfLogDbg("SaveAllRegisters setting mSavedAtBreakpointAddress = %p\n", mActiveThread->mIsAtBreakpointAddress);
  3464. mSavedAtBreakpointAddress = mActiveThread->mIsAtBreakpointAddress;
  3465. mSavedBreakpointAddressContinuing = mActiveThread->mBreakpointAddressContinuing;
  3466. mSavedContext.ContextFlags = BF_CONTEXT_ALL;
  3467. BF_GetThreadContext(mActiveThread->mHThread, &mSavedContext);
  3468. }
  3469. void WinDebugger::RestoreAllRegisters()
  3470. {
  3471. BfLogDbg("RestoreAllRegisters setting mIsAtBreakpointAddress = %p\n", mSavedAtBreakpointAddress);
  3472. mActiveThread->mIsAtBreakpointAddress = mSavedAtBreakpointAddress;
  3473. mActiveThread->mBreakpointAddressContinuing = mSavedBreakpointAddressContinuing;
  3474. BF_SetThreadContext(mActiveThread->mHThread, &mSavedContext);
  3475. #ifdef BF_DBG_32
  3476. //TODO: Find the test that this was required for...
  3477. // if (mActiveThread->mIsAtBreakpointAddress == mSavedContext.Eip)
  3478. // {
  3479. // if (mRunState == RunState_Running_ToTempBreakpoint)
  3480. // mRunState = RunState_Paused;
  3481. // }
  3482. // else
  3483. // {
  3484. // SetTempBreakpoint(mSavedContext.Eip);
  3485. // mRunState = RunState_Running_ToTempBreakpoint;
  3486. // mStepType = StepType_ToTempBreakpoint;
  3487. // mSteppingThread = mActiveThread;
  3488. // }
  3489. #endif
  3490. }
  3491. void WinDebugger::OutputMessage(const StringImpl& msg)
  3492. {
  3493. if (this == NULL)
  3494. return;
  3495. AutoCrit autoCrit(mDebugManager->mCritSect);
  3496. mDebugManager->mOutMessages.push_back("msg " + msg);
  3497. }
  3498. void WinDebugger::OutputRawMessage(const StringImpl& msg)
  3499. {
  3500. if (this == NULL)
  3501. return;
  3502. AutoCrit autoCrit(mDebugManager->mCritSect);
  3503. mDebugManager->mOutMessages.push_back(msg);
  3504. }
  3505. void WinDebugger::SetRunState(RunState runState)
  3506. {
  3507. mRunState = runState;
  3508. }
  3509. bool WinDebugger::TryRunContinue()
  3510. {
  3511. if (mRunState == RunState_Exception)
  3512. {
  3513. mIsContinuingFromException = true;
  3514. mRunState = RunState_Paused;
  3515. }
  3516. if (((mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint)) && (mNeedsRehupBreakpoints))
  3517. RehupBreakpoints(true);
  3518. return true;
  3519. }
  3520. void WinDebugger::ClearStep()
  3521. {
  3522. BfLogDbg("ClearStep\n");
  3523. RemoveTempBreakpoints();
  3524. mOrigStepType = StepType_None;
  3525. mStepType = StepType_None;
  3526. mStepStartPC = 0;
  3527. mStepSP = 0;
  3528. mStepPC = 0;
  3529. mIsStepIntoSpecific = false;
  3530. mStepIsRecursing = false;
  3531. mStepStopOnNextInstruction = false;
  3532. mStepLineData = DbgLineDataEx();
  3533. }
  3534. bool WinDebugger::SetupStep(StepType stepType)
  3535. {
  3536. BP_ZONE("SetupStep");
  3537. RemoveTempBreakpoints();
  3538. if (mNeedsRehupBreakpoints)
  3539. RehupBreakpoints(true);
  3540. if (mOrigStepType == StepType_None)
  3541. mOrigStepType = stepType;
  3542. mStepType = stepType;
  3543. mSteppingThread = mActiveThread;
  3544. mStepSwitchedThreads = false;
  3545. mContinueFromBreakpointFailed = false;
  3546. CPURegisters registers;
  3547. PopulateRegisters(&registers);
  3548. addr_target pcAddress = registers.GetPC();
  3549. if (mStepLineData.IsNull())
  3550. {
  3551. DbgSubprogram* dbgSubprogram = NULL;
  3552. auto dbgLineData = FindLineDataAtAddress(pcAddress, &dbgSubprogram);
  3553. mStepLineData = DbgLineDataEx(dbgLineData, dbgSubprogram);
  3554. mStepStartPC = registers.GetPC();
  3555. }
  3556. bool isDeeper = mStepSP > registers.GetSP();
  3557. 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);
  3558. mStepSP = registers.GetSP();
  3559. mStepPC = registers.GetPC();
  3560. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_NoFrame) || (mStepType == StepType_StepOut_ThenInto))
  3561. {
  3562. if (mStepType != StepType_StepOut_NoFrame)
  3563. {
  3564. // Test for stepping out of an inline method
  3565. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3566. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL))
  3567. {
  3568. DbgSubprogram* topSubprogram = dwSubprogram->GetRootInlineParent();
  3569. if ((mOrigStepType == StepType_StepInto) || (mOrigStepType == StepType_StepInto_Unfiltered))
  3570. {
  3571. mStepType = mOrigStepType;
  3572. }
  3573. else
  3574. {
  3575. mStepType = StepType_StepOut_Inline;
  3576. // Set up pcAddress to detect recursion
  3577. //TODO: We can't set a physical breakpoint here because we will immediately hit it when attempting to step over an inlined method.
  3578. // An inlined method can't recurse anyway, but store the pcAddress in mTempBreakpoints because we still check that for recursion
  3579. // SetTempBreakpoint(pcAddress);
  3580. //mTempBreakpoint.push_back(pcAddress);
  3581. mStepBreakpointAddrs.push_back(pcAddress);
  3582. }
  3583. addr_target endAddress = dwSubprogram->mBlock.mHighPC;
  3584. if (dwSubprogram->mHasLineAddrGaps)
  3585. {
  3586. // Keep bumping out the address as long as we can find lines that contain the nextPC
  3587. addr_target nextAddr = pcAddress;
  3588. for (auto& lineInfo : topSubprogram->mLineInfo->mLines)
  3589. {
  3590. auto lineAddr = topSubprogram->GetLineAddr(lineInfo);
  3591. if ((nextAddr >= lineAddr) && (nextAddr < lineAddr + lineInfo.mContribSize))
  3592. {
  3593. auto ctx = topSubprogram->mLineInfo->mContexts[lineInfo.mCtxIdx];
  3594. if (ctx.mInlinee == dwSubprogram)
  3595. {
  3596. nextAddr = lineAddr + lineInfo.mContribSize;
  3597. }
  3598. }
  3599. }
  3600. if (nextAddr != pcAddress)
  3601. endAddress = nextAddr;
  3602. }
  3603. BfLogDbg("Stepping out of inlined method, end address: %p\n", endAddress);
  3604. SetTempBreakpoint(endAddress);
  3605. mStepBreakpointAddrs.push_back(endAddress);
  3606. addr_target decodeAddress = dwSubprogram->mBlock.mLowPC;
  3607. while (decodeAddress < endAddress)
  3608. {
  3609. CPUInst inst;
  3610. if (!mDebugTarget->DecodeInstruction(decodeAddress, &inst))
  3611. break;
  3612. addr_target targetAddress = inst.GetTarget();
  3613. // We need to find a targetAddress
  3614. if ((targetAddress != 0) &&
  3615. !((targetAddress >= dwSubprogram->mBlock.mLowPC) && (targetAddress < dwSubprogram->mBlock.mHighPC)) &&
  3616. ((targetAddress >= topSubprogram->mBlock.mLowPC) && (targetAddress < topSubprogram->mBlock.mHighPC)))
  3617. {
  3618. BfLogDbg("Stepping out of inlined method, branch address: %p\n", targetAddress);
  3619. SetTempBreakpoint(targetAddress);
  3620. mStepBreakpointAddrs.push_back(targetAddress);
  3621. }
  3622. decodeAddress += inst.GetLength();
  3623. }
  3624. return true;
  3625. }
  3626. }
  3627. if ((mStepType != StepType_StepOut_NoFrame) && (RollBackStackFrame(&registers, true)))
  3628. {
  3629. pcAddress = registers.GetPC();
  3630. addr_target oldAddress = pcAddress;
  3631. CPUInst inst;
  3632. while (true)
  3633. {
  3634. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  3635. break;
  3636. if ((inst.IsBranch()) || (inst.IsCall()) || (inst.IsReturn()))
  3637. break;
  3638. DbgSubprogram* checkSubprogram = NULL;
  3639. auto checkLineData = FindLineDataAtAddress(pcAddress, &checkSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  3640. if (checkLineData == NULL)
  3641. break;
  3642. if (checkSubprogram->GetLineAddr(*checkLineData) == pcAddress)
  3643. break;
  3644. pcAddress += inst.GetLength();
  3645. }
  3646. if (pcAddress != oldAddress)
  3647. {
  3648. BfLogDbg("Adjusting stepout address from %p to %p\n", oldAddress, pcAddress);
  3649. }
  3650. #ifdef BF_DBG_32
  3651. // if (mDebugTarget->DecodeInstruction(pcAddress, &inst))
  3652. // {
  3653. // if (inst.IsStackAdjust())
  3654. // {
  3655. // auto oldAddress = pcAddress;
  3656. // pcAddress += inst.GetLength();
  3657. // BfLogDbg("Adjusting stepout address from %p to %p\n", oldAddress, pcAddress);
  3658. // }
  3659. // }
  3660. #endif
  3661. BfLogDbg("SetupStep Stepout SetTempBreakpoint %p\n", pcAddress);
  3662. SetTempBreakpoint(pcAddress);
  3663. mStepBreakpointAddrs.push_back(pcAddress);
  3664. if (mStepType != StepType_StepOut_ThenInto)
  3665. mStepType = StepType_StepOut;
  3666. }
  3667. else
  3668. {
  3669. // Try to handle the case where we just entered this call so the return address is the first entry on the stack
  3670. addr_target* regSP = registers.GetSPRegisterRef();
  3671. pcAddress = ReadMemory<addr_target>(*regSP);
  3672. *regSP += sizeof(addr_target);
  3673. if (mDebugTarget->FindSubProgram(pcAddress) != NULL)
  3674. {
  3675. BfLogDbg("SetupStep Stepout SetTempBreakpoint (2) %p\n", pcAddress);
  3676. SetTempBreakpoint(pcAddress);
  3677. mStepBreakpointAddrs.push_back(pcAddress);
  3678. if (mOrigStepType == StepType_StepInto)
  3679. mStepType = StepType_StepInto;
  3680. else
  3681. mStepType = StepType_StepOver;
  3682. return true;
  3683. }
  3684. else
  3685. {
  3686. // Just do stepovers until we eventually step out
  3687. //BF_DBG_FATAL("StepOut Failed");
  3688. BfLogDbg("StepOut Failed\n");
  3689. if (mLastValidStepIntoPC != 0)
  3690. {
  3691. BfLogDbg("Using mLastValidStepIntoPC: %p\n", mLastValidStepIntoPC);
  3692. if (mOrigStepType == StepType_StepInto)
  3693. mStepType = StepType_StepInto;
  3694. else
  3695. mStepType = StepType_StepOver;
  3696. SetTempBreakpoint(mLastValidStepIntoPC);
  3697. mStepBreakpointAddrs.push_back(0);
  3698. mStepBreakpointAddrs.push_back(mLastValidStepIntoPC);
  3699. mLastValidStepIntoPC = 0;
  3700. return true;
  3701. }
  3702. else
  3703. {
  3704. BfLogDbg("Stopping");
  3705. mStepType = StepType_None;
  3706. mRunState = RunState_Paused;
  3707. return true;
  3708. }
  3709. }
  3710. }
  3711. }
  3712. if ((mStepType != StepType_StepOut) && (mStepType != StepType_StepOut_ThenInto))
  3713. {
  3714. if (mDebuggerWaitingThread != mSteppingThread)
  3715. {
  3716. // We've switched threads, so there's a possible race condition:
  3717. // This new thread may already have an EXCEPTION_BREAKPOINT queued up so the PC is actually
  3718. // located one byte past the BREAK instruction, which is one byte into whatever instruction
  3719. // was previously there. We can't insert normal BREAK instructions because we don't know
  3720. // if the current PC is actually at an instruction start, so we do a single step with a
  3721. // slower stack call check to see if we need to step out after a "step over"
  3722. BfLogDbg("Step - switched threads mIsAtBreakpointAddress:%p\n", mSteppingThread->mIsAtBreakpointAddress);
  3723. mStepSwitchedThreads = true;
  3724. SingleStepX86();
  3725. return true;
  3726. }
  3727. bool breakOnNext = false;
  3728. int instIdx = 0;
  3729. for (instIdx = 0; true; instIdx++)
  3730. {
  3731. bool isAtLine = false;
  3732. DbgSubprogram* dwSubprogram = NULL;
  3733. auto dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  3734. isAtLine = (instIdx > 0) && (dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dwSubprogram->GetLineAddr(*dwLineData) == pcAddress);
  3735. // "Never step into" line
  3736. if ((dwLineData != NULL) && (dwLineData->mColumn == -2) && (stepType == StepType_StepInto))
  3737. stepType = StepType_StepOver;
  3738. CPUInst inst;
  3739. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  3740. {
  3741. BfLogDbg("Decode failed, set up SingleStepX86 %p\n", pcAddress);
  3742. SingleStepX86();
  3743. mStepStopOnNextInstruction = true;
  3744. return true;
  3745. }
  3746. if (instIdx > 256)
  3747. {
  3748. BfLogDbg("Too many SetupStep iterations");
  3749. breakOnNext = true;
  3750. }
  3751. if ((inst.IsReturn()) && (instIdx == 0) && (!mStepInAssembly))
  3752. {
  3753. // Do actual STEP OUT so we set up proper "stepping over unimportant post-return instructions"
  3754. return SetupStep(StepType_StepOut);
  3755. }
  3756. if ((breakOnNext) || (mStepInAssembly) || (isAtLine) || (inst.IsBranch()) || (inst.IsCall()) || (inst.IsReturn()))
  3757. {
  3758. if (((instIdx == 0) || (mStepInAssembly)) && (!breakOnNext))
  3759. {
  3760. if ((stepType == StepType_StepOver) && (inst.IsCall()))
  3761. {
  3762. // Continue - sets a breakpoint on the call line to detect recursion.
  3763. // The next loop through will set a breakpoint on the line after the return
  3764. BfLogDbg("StepHadCall\n");
  3765. breakOnNext = true;
  3766. BfLogDbg("StepHadCall setting mIsAtBreakpointAddress = %p\n", pcAddress);
  3767. mSteppingThread->mIsAtBreakpointAddress = pcAddress;
  3768. SetTempBreakpoint(pcAddress);
  3769. mStepBreakpointAddrs.push_back(pcAddress);
  3770. }
  3771. else
  3772. {
  3773. if (inst.IsCall())
  3774. {
  3775. if ((mLastValidStepIntoPC == 0) || (dwSubprogram != NULL))
  3776. mLastValidStepIntoPC = pcAddress + inst.mSize;
  3777. }
  3778. if ((dwLineData != NULL) && (inst.IsBranch()))
  3779. {
  3780. addr_target targetAddr = inst.GetTarget();
  3781. if (targetAddr < dwSubprogram->GetLineAddr(*dwLineData))
  3782. {
  3783. // Jumping backwards, stop at next instruction
  3784. mStepStopOnNextInstruction = true;
  3785. }
  3786. }
  3787. bool isPrefixOnly = false;
  3788. if ((mStepInAssembly) && (stepType == StepType_StepOver) && (inst.IsRep(isPrefixOnly)))
  3789. {
  3790. if (isPrefixOnly)
  3791. {
  3792. CPUInst nextInst;
  3793. if (mDebugTarget->DecodeInstruction(pcAddress + inst.GetLength(), &nextInst))
  3794. {
  3795. if (nextInst.IsBranch())
  3796. {
  3797. // repne jmp - this appears in __chkstk (for example)
  3798. // We don't have a good way to "step over" this one, so just do a single step
  3799. }
  3800. else
  3801. {
  3802. // Step over the rep + target instruction
  3803. auto doneAddr = pcAddress + inst.GetLength() + nextInst.GetLength();
  3804. BfLogDbg("SetupStep SetTempBreakpoint %p\n", doneAddr);
  3805. SetTempBreakpoint(doneAddr);
  3806. mStepBreakpointAddrs.push_back(doneAddr);
  3807. break;
  3808. }
  3809. }
  3810. }
  3811. else
  3812. {
  3813. // Step over the instruction
  3814. auto doneAddr = pcAddress + inst.GetLength();
  3815. BfLogDbg("SetupStep SetTempBreakpoint %p\n", doneAddr);
  3816. SetTempBreakpoint(doneAddr);
  3817. mStepBreakpointAddrs.push_back(doneAddr);
  3818. break;
  3819. }
  3820. }
  3821. // Just step a single instruction
  3822. BfLogDbg("SetupStep SingleStepX86 %p\n", pcAddress);
  3823. SingleStepX86();
  3824. if (inst.IsReturn())
  3825. mStepStopOnNextInstruction = true;
  3826. break;
  3827. }
  3828. }
  3829. else
  3830. {
  3831. // Move us to this instruction so we can hardware single-step into it
  3832. BfLogDbg("SetupStep SetTempBreakpoint %p\n", pcAddress);
  3833. SetTempBreakpoint(pcAddress);
  3834. mStepBreakpointAddrs.push_back(pcAddress);
  3835. break;
  3836. }
  3837. }
  3838. // Not an interesting instruction - move to next
  3839. pcAddress += inst.mSize;
  3840. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress >= dwSubprogram->mBlock.mHighPC))
  3841. {
  3842. auto endAddress = dwSubprogram->mBlock.mHighPC;
  3843. BfLogDbg("Stepping past end of inlined method, end address: %p\n", endAddress);
  3844. mStepType = StepType_StepOut_Inline;
  3845. SetTempBreakpoint(endAddress);
  3846. mStepBreakpointAddrs.push_back(endAddress);
  3847. return true;
  3848. }
  3849. }
  3850. if (instIdx > 1)
  3851. BfLogDbg("SetupStep instIdx: %d\n", instIdx);
  3852. }
  3853. return true;
  3854. }
  3855. void WinDebugger::CheckNonDebuggerBreak()
  3856. {
  3857. enum MessageType
  3858. {
  3859. MessageType_None = 0,
  3860. MessageType_Error = 1,
  3861. MessageType_ProfilerCmd = 2
  3862. };
  3863. CPURegisters registers;
  3864. PopulateRegisters(&registers);
  3865. addr_target pcAddress = registers.GetPC();
  3866. addr_target debugMessageDataAddr = (addr_target)-1;
  3867. if (mDebugTarget->mTargetBinary != NULL)
  3868. {
  3869. mDebugTarget->mTargetBinary->ParseSymbolData();
  3870. debugMessageDataAddr = mDebugTarget->FindSymbolAddr("gBfDebugMessageData");
  3871. }
  3872. if (debugMessageDataAddr != (addr_target)-1)
  3873. {
  3874. struct BfDebugMessageData
  3875. {
  3876. int mMessageType; // 0 = none, 1 = error
  3877. int mStackWindbackCount;
  3878. int mBufParamLen;
  3879. addr_target mBufParam;
  3880. addr_target mPCOverride;
  3881. };
  3882. BfDebugMessageData messageData = ReadMemory<BfDebugMessageData>(debugMessageDataAddr);
  3883. WriteMemory<int>(debugMessageDataAddr, 0); // Zero out type so we won't trigger again
  3884. if (messageData.mMessageType != 0)
  3885. {
  3886. llvm::SmallVector<char, 4096> strBuf;
  3887. int strLen = messageData.mBufParamLen;
  3888. strBuf.resize(strLen + 1);
  3889. char* str = &strBuf[0];
  3890. str[strLen] = 0;
  3891. if (ReadMemory(messageData.mBufParam, strLen, str))
  3892. {
  3893. if (messageData.mMessageType == MessageType_Error)
  3894. {
  3895. mRequestedStackFrameIdx = messageData.mStackWindbackCount;
  3896. if (messageData.mPCOverride != 0)
  3897. {
  3898. mShowPCOverride = messageData.mPCOverride;
  3899. mRequestedStackFrameIdx = -2;
  3900. }
  3901. mDebugManager->mOutMessages.push_back(StrFormat("error %s", str));
  3902. }
  3903. else if (messageData.mMessageType == MessageType_ProfilerCmd)
  3904. {
  3905. // It's important to set this here, because we unlock the critSect during StopSampling and we can't have the
  3906. // IDE thinking that we're actually paused when it checks the mRunState
  3907. mRunState = RunState_Running;
  3908. char* cmd = strtok(str, "\t");
  3909. if (strcmp(cmd, "StartSampling") == 0)
  3910. {
  3911. char* sessionIdStr = strtok(NULL, "\t");
  3912. char* threadIdStr = strtok(NULL, "\t");
  3913. char* sampleRateStr = strtok(NULL, "\t");
  3914. char* descStr = strtok(NULL, "\t");
  3915. if (threadIdStr != NULL)
  3916. {
  3917. int threadId = atoi(threadIdStr);
  3918. int sampleRate = atoi(sampleRateStr);
  3919. int sessionId = atoi(sessionIdStr);
  3920. Profiler** profilerPtr;
  3921. if (mPendingProfilerMap.TryAdd(sessionId, NULL, &profilerPtr))
  3922. {
  3923. DbgProfiler* profiler = new DbgProfiler(this);
  3924. if (descStr != NULL)
  3925. profiler->mDescription = descStr;
  3926. if (sampleRate > 0)
  3927. profiler->mSamplesPerSecond = sampleRate;
  3928. profiler->Start();
  3929. *profilerPtr = profiler;
  3930. mDebugManager->mOutMessages.push_back("newProfiler");
  3931. mNewProfilerList.push_back(profiler);
  3932. }
  3933. }
  3934. }
  3935. else if (strcmp(cmd, "StopSampling") == 0)
  3936. {
  3937. char* sessionIdStr = strtok(NULL, "\t");
  3938. if (sessionIdStr != NULL)
  3939. {
  3940. int sessionId = atoi(sessionIdStr);
  3941. Profiler* profiler;
  3942. if (mPendingProfilerMap.Remove(sessionId, &profiler))
  3943. {
  3944. if (profiler->IsSampling())
  3945. {
  3946. // Need to unlock so we don't deadlock
  3947. mDebugManager->mCritSect.Unlock();
  3948. profiler->Stop();
  3949. mDebugManager->mCritSect.Lock();
  3950. }
  3951. }
  3952. }
  3953. }
  3954. else if (strcmp(cmd, "ClearSampling") == 0)
  3955. {
  3956. for (auto& kv : mPendingProfilerMap)
  3957. {
  3958. auto profiler = kv.mValue;
  3959. profiler->Clear();
  3960. }
  3961. }
  3962. else if (strcmp(cmd, "ClearOutput") == 0)
  3963. {
  3964. mDebugManager->mOutMessages.push_back("clearOutput");
  3965. }
  3966. }
  3967. return;
  3968. }
  3969. }
  3970. }
  3971. intptr_target objAddr;
  3972. if (mDebugTarget->IsObjectAccessBreak(pcAddress, &registers, &objAddr))
  3973. {
  3974. String errorStr = "error Attempted to access deleted object";
  3975. String objectAddr = EncodeDataPtr((addr_target)objAddr, true);
  3976. errorStr += StrFormat("\x1LEAK\t(System.Object)%s\n (%s)%s\n", objectAddr.c_str(), "System.Object", objectAddr.c_str());
  3977. mDebugManager->mOutMessages.push_back(errorStr);
  3978. return;
  3979. }
  3980. bool showMainThread = false;
  3981. String symbol;
  3982. addr_target offset;
  3983. DbgModule* dbgModule;
  3984. if (mDebugTarget->FindSymbolAt(pcAddress, &symbol, &offset, &dbgModule))
  3985. {
  3986. if ((symbol == "DbgBreakPoint") || (symbol == "RtlUserThreadStart@8"))
  3987. {
  3988. showMainThread = true;
  3989. }
  3990. }
  3991. #ifdef BF_DBG_32
  3992. else if ((dbgModule != NULL) && (dbgModule->mDisplayName.Equals("kernel32.dll", StringImpl::CompareKind_OrdinalIgnoreCase)))
  3993. {
  3994. showMainThread = true;
  3995. }
  3996. #endif
  3997. if (showMainThread)
  3998. {
  3999. // This is a manual break, show the main thread
  4000. mActiveThread = mThreadList.front();
  4001. if (mDebugPendingExpr != NULL)
  4002. {
  4003. for (auto thread : mThreadList)
  4004. {
  4005. if (thread->mThreadId == mDebugEvalThreadInfo.mThreadId)
  4006. {
  4007. mActiveThread = thread;
  4008. break;
  4009. }
  4010. }
  4011. }
  4012. }
  4013. }
  4014. bool WinDebugger::HasSteppedIntoCall()
  4015. {
  4016. // Some calls (like __chkstk) actually push results to the stack, so we need to check
  4017. // if we're REALLY deeper or not, by rolling back the callstack once
  4018. CPURegisters registers;
  4019. PopulateRegisters(&registers);
  4020. if (RollBackStackFrame(&registers, true))
  4021. {
  4022. // If the previous frames SP is equal or deeper than our step start then we are indeed inside a call!
  4023. if (mStepSP >= registers.GetSP())
  4024. return true;
  4025. }
  4026. return false;
  4027. }
  4028. void WinDebugger::StepOver(bool inAssembly)
  4029. {
  4030. AutoCrit autoCrit(mDebugManager->mCritSect);
  4031. BfLogDbg("StepOver\n");
  4032. if (!TryRunContinue())
  4033. return;
  4034. mCurNoInfoStepTries = 0; // Reset
  4035. mStepInAssembly = inAssembly;
  4036. SetupStep(StepType_StepOver);
  4037. ContinueDebugEvent();
  4038. }
  4039. void WinDebugger::StepOut(bool inAssembly)
  4040. {
  4041. AutoCrit autoCrit(mDebugManager->mCritSect);
  4042. BfLogDbg("StepOut\n");
  4043. if (!TryRunContinue())
  4044. return;
  4045. mCurNoInfoStepTries = 0; // Reset
  4046. mStepInAssembly = inAssembly;
  4047. SetupStep(StepType_StepOut);
  4048. ContinueDebugEvent();
  4049. }
  4050. void WinDebugger::SetNextStatement(bool inAssembly, const StringImpl& fileName, int64 lineNumOrAsmAddr, int wantColumn)
  4051. {
  4052. AutoCrit autoCrit(mDebugManager->mCritSect);
  4053. DbgSubprogram* subProgram = NULL;
  4054. if (!inAssembly)
  4055. {
  4056. if (mCallStack.size() == 0)
  4057. UpdateCallStack();
  4058. if (mCallStack.size() > 0)
  4059. {
  4060. UpdateCallStackMethod(0);
  4061. subProgram = mCallStack[0]->mSubProgram;
  4062. }
  4063. if (subProgram == NULL)
  4064. return;
  4065. }
  4066. DbgSubprogram* rootInlineParent = NULL;
  4067. if (subProgram != NULL)
  4068. rootInlineParent = subProgram->GetRootInlineParent();
  4069. String result;
  4070. if (mDebugTarget == NULL)
  4071. return;
  4072. DbgSrcFile* srcFile = NULL;
  4073. if (!fileName.IsEmpty())
  4074. {
  4075. srcFile = mDebugTarget->GetSrcFile(fileName);
  4076. if (srcFile == NULL)
  4077. return;
  4078. }
  4079. addr_target pcAddress = 0;
  4080. if (inAssembly)
  4081. {
  4082. pcAddress = lineNumOrAsmAddr;
  4083. }
  4084. else
  4085. {
  4086. int lineNum = (int)lineNumOrAsmAddr;
  4087. addr_target bestAddr[2] = { 0, 0 };
  4088. int checkLineNum[2] = { lineNum - 1, lineNum };
  4089. auto _CheckLineInfo = [&](DbgSubprogram* dbgSubprogram, DbgLineInfo* dbgLineInfo)
  4090. {
  4091. for (int iPass = 0; iPass < 2; ++iPass)
  4092. {
  4093. int bestLineOffset = 0x7FFFFFFF;
  4094. for (auto& lineData : dbgLineInfo->mLines)
  4095. {
  4096. auto addr = dbgSubprogram->GetLineAddr(lineData);
  4097. if ((addr < subProgram->mBlock.mLowPC) || (addr >= subProgram->mBlock.mHighPC))
  4098. continue;
  4099. int lineOffset = lineData.mLine - checkLineNum[iPass];
  4100. if ((lineOffset >= 0) && (lineOffset <= 6) && (lineOffset <= bestLineOffset))
  4101. {
  4102. if (lineOffset < bestLineOffset)
  4103. {
  4104. bestLineOffset = lineOffset;
  4105. bestAddr[iPass] = addr;
  4106. }
  4107. }
  4108. }
  4109. }
  4110. };
  4111. for (int checkHotIdx = -1; checkHotIdx < (int)srcFile->mHotReplacedDbgLineInfo.size(); checkHotIdx++)
  4112. {
  4113. if (checkHotIdx >= 0)
  4114. {
  4115. auto hotReplacedLineInfo = srcFile->mHotReplacedDbgLineInfo[checkHotIdx];
  4116. for (auto& hotReplacedEntry : hotReplacedLineInfo->mEntries)
  4117. {
  4118. _CheckLineInfo(hotReplacedEntry.mSubprogram, hotReplacedEntry.mLineInfo);
  4119. }
  4120. }
  4121. else
  4122. {
  4123. for (auto subprogram : srcFile->mLineDataRefs)
  4124. _CheckLineInfo(subprogram, subprogram->mLineInfo);
  4125. }
  4126. if (bestAddr[1] != 0)
  4127. break;
  4128. }
  4129. if (bestAddr[1] != 0)
  4130. {
  4131. const int kMaxAddrDist = 64; // within reasonable range
  4132. if ((bestAddr[0] != 0) && (bestAddr[1] - bestAddr[0] <= kMaxAddrDist))
  4133. {
  4134. addr_target addrStart = bestAddr[0];
  4135. addr_target addrEnd = bestAddr[1];
  4136. addr_target addr = addrStart;
  4137. BF_ASSERT(addrEnd - addr <= kMaxAddrDist);
  4138. addr_target lastOp = 0;
  4139. while (addr < addrEnd)
  4140. {
  4141. CPUInst inst;
  4142. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  4143. break;
  4144. lastOp = addr;
  4145. addr += inst.GetLength();
  4146. }
  4147. }
  4148. pcAddress = (uint64)bestAddr[1];
  4149. }
  4150. }
  4151. if (pcAddress)
  4152. {
  4153. BF_ASSERT(mActiveThread->mBreakpointAddressContinuing == 0);
  4154. mActiveThread->mIsAtBreakpointAddress = 0;
  4155. mActiveThread->mStoppedAtAddress = pcAddress;
  4156. if (mCallStack.size() == 0)
  4157. UpdateCallStack();
  4158. CPURegisters* regs = &mCallStack.front()->mRegisters;
  4159. *regs->GetPCRegisterRef() = pcAddress;
  4160. SetRegisters(regs);
  4161. WdBreakpoint* breakpoint = (WdBreakpoint*)FindBreakpointAt(pcAddress);
  4162. if (breakpoint != NULL)
  4163. {
  4164. BfLogDbg("SetNextStatement setting mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  4165. mActiveThread->mIsAtBreakpointAddress = breakpoint->mAddr;
  4166. }
  4167. }
  4168. }
  4169. bool WinDebugger::PopulateRegisters(CPURegisters* registers, BF_CONTEXT& lcContext)
  4170. {
  4171. #ifdef BF_DBG_32
  4172. registers->mIntRegs.eax = lcContext.Eax;
  4173. registers->mIntRegs.ecx = lcContext.Ecx;
  4174. registers->mIntRegs.edx = lcContext.Edx;
  4175. registers->mIntRegs.ebx = lcContext.Ebx;
  4176. registers->mIntRegs.esp = lcContext.Esp;
  4177. registers->mIntRegs.ebp = lcContext.Ebp;
  4178. registers->mIntRegs.esi = lcContext.Esi;
  4179. registers->mIntRegs.edi = lcContext.Edi;
  4180. registers->mIntRegs.eip = lcContext.Eip;
  4181. registers->mIntRegs.efl = lcContext.EFlags;
  4182. BF_ASSERT(sizeof(lcContext.FloatSave.RegisterArea) == sizeof(registers->mFpMmRegsArray));
  4183. memcpy(registers->mFpMmRegsArray, lcContext.FloatSave.RegisterArea, sizeof(lcContext.FloatSave.RegisterArea));
  4184. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 32 * sizeof(float));
  4185. memcpy(registers->mXmmRegsArray, &lcContext.ExtendedRegisters[160], sizeof(registers->mXmmRegsArray));
  4186. #else
  4187. registers->mIntRegs.rax = lcContext.Rax;
  4188. registers->mIntRegs.rcx = lcContext.Rcx;
  4189. registers->mIntRegs.rdx = lcContext.Rdx;
  4190. registers->mIntRegs.rbx = lcContext.Rbx;
  4191. registers->mIntRegs.rsp = lcContext.Rsp;
  4192. registers->mIntRegs.rbp = lcContext.Rbp;
  4193. registers->mIntRegs.rsi = lcContext.Rsi;
  4194. registers->mIntRegs.rdi = lcContext.Rdi;
  4195. registers->mIntRegs.rip = lcContext.Rip;
  4196. registers->mIntRegs.efl = lcContext.EFlags;
  4197. registers->mIntRegs.r8 = lcContext.R8;
  4198. registers->mIntRegs.r9 = lcContext.R9;
  4199. registers->mIntRegs.r10 = lcContext.R10;
  4200. registers->mIntRegs.r11 = lcContext.R11;
  4201. registers->mIntRegs.r12 = lcContext.R12;
  4202. registers->mIntRegs.r13 = lcContext.R13;
  4203. registers->mIntRegs.r14 = lcContext.R14;
  4204. registers->mIntRegs.r15 = lcContext.R15;
  4205. registers->mIntRegs.gs = lcContext.SegGs;
  4206. for (int i = 0; i < 8; i++)
  4207. {
  4208. memcpy(&registers->mFpMmRegsArray[i], &lcContext.FltSave.FloatRegisters[i], 10);
  4209. }
  4210. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 64 * sizeof(float));
  4211. memcpy(registers->mXmmRegsArray, BF_CONTEXT_XMMDATA(lcContext), sizeof(registers->mXmmRegsArray));
  4212. #endif
  4213. return (lcContext.ContextFlags & (BF_CONTEXT_EXCEPTION_ACTIVE | BF_CONTEXT_SERVICE_ACTIVE)) == 0;
  4214. }
  4215. bool WinDebugger::PopulateRegisters(CPURegisters* registers)
  4216. {
  4217. /*static bool sCheckedProcessorFeatures = false;
  4218. static bool sMmxAvailable = false;
  4219. static bool sXmmAvailable = false;
  4220. if (!sCheckedProcessorFeatures)
  4221. {
  4222. //CDH we don't do anything with these yet since we grab BF_CONTEXT_ALL anyway, but could be useful
  4223. sMmxAvailable = ::IsProcessorFeaturePresent(PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  4224. sXmmAvailable = ::IsProcessorFeaturePresent(PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  4225. sCheckedProcessorFeatures = true;
  4226. }*/
  4227. BF_ASSERT(registers != nullptr);
  4228. BF_CONTEXT lcContext;
  4229. lcContext.ContextFlags = BF_CONTEXT_ALL | BF_CONTEXT_EXCEPTION_REQUEST;
  4230. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4231. return PopulateRegisters(registers, lcContext);
  4232. }
  4233. bool WinDebugger::RollBackStackFrame(CPURegisters* registers, bool isStackStart)
  4234. {
  4235. BF_ASSERT(registers != nullptr);
  4236. return mDebugTarget->RollBackStackFrame(registers, NULL, isStackStart);
  4237. }
  4238. bool WinDebugger::SetHotJump(DbgSubprogram* oldSubprogram, DbgSubprogram* newSubprogram)
  4239. {
  4240. //AutoCrit autoCrit(mDebugManager->mCritSect);
  4241. BF_ASSERT(mDebugManager->mCritSect.mLockCount == 1);
  4242. addr_target jmpInstStart = oldSubprogram->mBlock.mLowPC;
  4243. addr_target jmpInstEnd = jmpInstStart + sizeof(HotJumpOp);
  4244. if (jmpInstEnd > oldSubprogram->mBlock.mHighPC)
  4245. {
  4246. if ((oldSubprogram->mBlock.mHighPC - oldSubprogram->mBlock.mLowPC == 1) &&
  4247. (newSubprogram->mBlock.mHighPC - newSubprogram->mBlock.mLowPC == 1))
  4248. return true; // Special case for just stub 'ret' methods
  4249. String err = StrFormat("Failed to hot replace method, method '%s' too small to insert hot thunk", newSubprogram->ToString().c_str());
  4250. Fail(err);
  4251. return false;
  4252. }
  4253. if (!oldSubprogram->mWasHotReplaced)
  4254. {
  4255. for (int threadIdx = 0; threadIdx < (int)mThreadList.size(); threadIdx++)
  4256. {
  4257. CPURegisters* cpuRegisters = &mHotThreadStates[threadIdx];
  4258. int tryStart = GetTickCount();
  4259. while ((cpuRegisters->GetPC() >= jmpInstStart) && (cpuRegisters->GetPC() < jmpInstEnd))
  4260. {
  4261. if (GetTickCount() - tryStart >= 8000)
  4262. {
  4263. Fail("Failed to hot replace method, can't move past prelude");
  4264. return false;
  4265. }
  4266. BfLogDbg("SetHotJump skipping through %p\n", cpuRegisters->GetPC());
  4267. bool removedBreakpoint = false;
  4268. mActiveThread = mThreadList[threadIdx];
  4269. if ((mActiveThread->mStoppedAtAddress >= jmpInstStart) && (mActiveThread->mStoppedAtAddress < jmpInstEnd))
  4270. {
  4271. for (addr_target addr = jmpInstStart; addr < jmpInstEnd; addr++)
  4272. {
  4273. if (mBreakpointAddrMap.ContainsKey(addr))
  4274. {
  4275. removedBreakpoint = true;
  4276. RemoveBreakpoint(addr);
  4277. }
  4278. }
  4279. }
  4280. RunState oldRunState = mRunState;
  4281. mRunState = RunState_HotStep;
  4282. if (mWantsDebugContinue)
  4283. {
  4284. mWantsDebugContinue = false;
  4285. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4286. mContinueEvent.Set();
  4287. }
  4288. BF_CONTEXT lcContext;
  4289. lcContext.ContextFlags = BF_CONTEXT_ALL;
  4290. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4291. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  4292. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  4293. ::ResumeThread(mActiveThread->mHThread);
  4294. BfLogDbg("ResumeThread %d\n", mActiveThread->mThreadId);
  4295. while (mRunState != RunState_Terminated)
  4296. {
  4297. mDebugManager->mCritSect.Unlock();
  4298. Sleep(0);
  4299. mDebugManager->mCritSect.Lock();
  4300. if (IsPaused())
  4301. break;
  4302. if (mWantsDebugContinue)
  4303. {
  4304. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4305. mWantsDebugContinue = false;
  4306. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4307. mContinueEvent.Set();
  4308. }
  4309. }
  4310. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4311. ::SuspendThread(mActiveThread->mHThread);
  4312. BfLogDbg("SuspendThread %d\n", mActiveThread->mThreadId);
  4313. mRunState = oldRunState;
  4314. if ((mRunState != RunState_Terminated) && (mRunState != RunState_Terminating))
  4315. {
  4316. if (!IsPaused())
  4317. {
  4318. BF_ASSERT(mWantsDebugContinue);
  4319. mWantsDebugContinue = false;
  4320. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4321. mContinueEvent.Set();
  4322. }
  4323. }
  4324. PopulateRegisters(cpuRegisters);
  4325. }
  4326. }
  4327. }
  4328. HotJumpOp jumpOp;
  4329. jumpOp.mOpCode = 0xE9;
  4330. jumpOp.mRelTarget = newSubprogram->mBlock.mLowPC - oldSubprogram->mBlock.mLowPC - sizeof(HotJumpOp);
  4331. WriteMemory(oldSubprogram->mBlock.mLowPC, jumpOp);
  4332. ::FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)oldSubprogram->mBlock.mLowPC, sizeof(HotJumpOp));
  4333. return true;
  4334. }
  4335. DbgSubprogram* WinDebugger::TryFollowHotJump(DbgSubprogram* subprogram, addr_target addr)
  4336. {
  4337. if (!subprogram->mWasHotReplaced)
  4338. return subprogram;
  4339. if (addr != subprogram->mBlock.mLowPC)
  4340. return subprogram;
  4341. auto dbgModule = subprogram->mCompileUnit->mDbgModule;
  4342. HotJumpOp jumpOp = ReadMemory<HotJumpOp>(addr);
  4343. if (jumpOp.mOpCode != 0xE9)
  4344. return subprogram;
  4345. addr_target jumpAddr = addr + jumpOp.mRelTarget + sizeof(HotJumpOp);
  4346. auto jumpSubprogram = mDebugTarget->FindSubProgram(jumpAddr);
  4347. if (jumpSubprogram == NULL)
  4348. return subprogram;
  4349. return jumpSubprogram;
  4350. }
  4351. bool WinDebugger::ShouldShowStaticMember(DbgType* dbgType, DbgVariable* member)
  4352. {
  4353. // If locationData is non-null, that means it was added in addition to the static declaration in the CV type info,
  4354. // so only add the names from the type definition
  4355. auto flavor = dbgType->mCompileUnit->mDbgModule->mDbgFlavor;
  4356. return ((((dbgType->IsNamespace()) || (flavor != DbgFlavor_MS)) && ((member->mLocationData != NULL) || member->mIsConst)) ||
  4357. ((flavor == DbgFlavor_MS) && (member->mLocationData == NULL)));
  4358. }
  4359. String WinDebugger::GetMemberList(DbgType* dbgType, const StringImpl& expr, bool isPtr, bool isStatic, bool forceCast, bool isSplat, bool isReadOnly)
  4360. {
  4361. auto dbgModule = dbgType->GetDbgModule();
  4362. dbgType->PopulateType();
  4363. auto language = dbgType->GetLanguage();
  4364. if (!isStatic)
  4365. {
  4366. String retVal;
  4367. bool needsNewline = false;
  4368. bool isBfObject = false;
  4369. if (dbgType->IsBfObjectPtr())
  4370. {
  4371. isBfObject = true;
  4372. dbgType = dbgType->mTypeParam;
  4373. }
  4374. int baseIdx = 0;
  4375. for (auto baseTypeEntry : dbgType->mBaseTypes)
  4376. {
  4377. auto baseType = baseTypeEntry->mBaseType;
  4378. if ((baseType->mSize > 0) || (baseType->mTypeCode != DbgType_Struct) || (strcmp(baseType->mTypeName, "ValueType") != 0))
  4379. {
  4380. String baseTypeStr = baseType->ToStringRaw(language);
  4381. if (baseIdx > 0)
  4382. retVal += "\n";
  4383. if (isSplat)
  4384. retVal += "[base]\t((" + baseTypeStr + ")" + expr + "), nv";
  4385. else if (dbgType->WantsRefThis())
  4386. retVal += "[base]\t((" + baseTypeStr + ")this), nd, na, nv, this=" + expr;
  4387. else
  4388. retVal += "[base]\t((" + baseTypeStr + "*)this), nd, na, nv, this=" + expr;
  4389. if (isReadOnly)
  4390. retVal += ", ne";
  4391. }
  4392. needsNewline = true;
  4393. baseIdx++;
  4394. }
  4395. String thisExpr = expr;
  4396. String castString;
  4397. if (dbgType->IsBfObject())
  4398. {
  4399. auto ptrType = dbgType->GetDbgModule()->GetPointerType(dbgType);
  4400. castString = ptrType->ToStringRaw(language);
  4401. }
  4402. else
  4403. castString = dbgType->ToStringRaw(language);
  4404. bool hadStatics = false;
  4405. for (auto member : dbgType->mMemberList)
  4406. {
  4407. if (member->mMemberOffset < 0)
  4408. continue;
  4409. if (member->mIsStatic)
  4410. {
  4411. if (ShouldShowStaticMember(dbgType, member))
  4412. hadStatics = true;
  4413. }
  4414. else
  4415. {
  4416. bool ignoreMember = false;
  4417. if (member->mName != NULL)
  4418. {
  4419. if ((member->mName[0] == '?') ||
  4420. (strncmp(member->mName, "_vptr$", 6) == 0))
  4421. ignoreMember = true;
  4422. }
  4423. if (!ignoreMember)
  4424. {
  4425. if (needsNewline)
  4426. retVal += "\n";
  4427. if (member->mName == NULL)
  4428. {
  4429. retVal += GetMemberList(member->mType, expr, isPtr, isStatic, forceCast, isSplat, isReadOnly);
  4430. }
  4431. else
  4432. {
  4433. retVal += String(member->mName);
  4434. if (isSplat)
  4435. {
  4436. retVal += "\t(" + thisExpr + ")." + String(member->mName);
  4437. // We don't want to rely on this being enforced here. For one, ref types shouldn't get ", ne" added,
  4438. // and this doesn't solve the issue of attempting to assign via the Immediate window
  4439. /*if (isReadOnly)
  4440. retVal += ", ne";*/
  4441. }
  4442. else
  4443. {
  4444. if (forceCast)
  4445. retVal += "\t((" + castString + ")this)." + String(member->mName);
  4446. else if ((member->mName[0] >= '0') && (member->mName[0] <= '9')) // Numbered tuple member?
  4447. retVal += "\tthis." + String(member->mName);
  4448. else
  4449. retVal += "\t" + String(member->mName);
  4450. retVal += ", this=" + thisExpr;
  4451. // if (isReadOnly)
  4452. // retVal += ", ne";
  4453. }
  4454. }
  4455. needsNewline = true;
  4456. }
  4457. }
  4458. }
  4459. if (hadStatics)
  4460. {
  4461. if (needsNewline)
  4462. retVal += "\n";
  4463. retVal += "Static values\t" + castString;
  4464. }
  4465. return retVal;
  4466. }
  4467. else
  4468. {
  4469. if (dbgType->IsBfObjectPtr())
  4470. dbgType = dbgType->mTypeParam;
  4471. String retVal;
  4472. String memberPrefix = expr;
  4473. bool needsNewline = false;
  4474. bool hadStatics = false;
  4475. for (auto member : dbgType->mMemberList)
  4476. {
  4477. if (member->mIsStatic)
  4478. {
  4479. if (ShouldShowStaticMember(dbgType, member))
  4480. {
  4481. if (needsNewline)
  4482. retVal += "\n";
  4483. retVal += String(member->mName) + "\t" + memberPrefix + "." + String(member->mName);
  4484. needsNewline = true;
  4485. }
  4486. }
  4487. }
  4488. return retVal;
  4489. }
  4490. return "";
  4491. }
  4492. bool WinDebugger::ParseFormatInfo(DbgModule* dbgModule, const StringImpl& formatInfoStr, DwFormatInfo* formatInfo, BfPassInstance* bfPassInstance, int* assignExprOffset, String* assignExprString, String* errorString, DbgTypedValue contextTypedValue)
  4493. {
  4494. String formatFlags = formatInfoStr;
  4495. if (assignExprOffset != NULL)
  4496. *assignExprOffset = -1;
  4497. while (formatFlags.length() > 0)
  4498. {
  4499. formatFlags = Trim(formatFlags);
  4500. if (formatFlags[0] != ',')
  4501. {
  4502. return false;
  4503. }
  4504. else
  4505. {
  4506. int nextComma = formatFlags.IndexOf(',', 1);
  4507. int quotePos = formatFlags.IndexOf('"', 1);
  4508. if ((quotePos != -1) && (quotePos < nextComma))
  4509. {
  4510. int nextQuotePos = formatFlags.IndexOf('"', quotePos + 1);
  4511. if (nextQuotePos != -1)
  4512. nextComma = formatFlags.IndexOf(',', nextQuotePos + 1);
  4513. }
  4514. if (nextComma == -1)
  4515. nextComma = formatFlags.length();
  4516. String formatCmd = formatFlags.Substring(1, nextComma - 1);
  4517. formatCmd = Trim(formatCmd);
  4518. bool hadError = false;
  4519. if (strncmp(formatCmd.c_str(), "this=", 5) == 0)
  4520. {
  4521. formatCmd = formatFlags.Substring(1);
  4522. formatCmd = Trim(formatCmd);
  4523. String thisExpr = formatCmd.Substring(5);
  4524. if (thisExpr.empty())
  4525. break;
  4526. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, thisExpr, formatInfo);
  4527. formatInfo->mExplicitThis = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4528. if (dbgEvaluationContext.HadError())
  4529. {
  4530. if (errorString != NULL)
  4531. *errorString = dbgEvaluationContext.GetErrorStr();
  4532. return false;
  4533. }
  4534. formatFlags = thisExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4535. continue;
  4536. }
  4537. else if (strncmp(formatCmd.c_str(), "count=", 6) == 0)
  4538. {
  4539. formatCmd = formatFlags.Substring(1);
  4540. formatCmd = Trim(formatCmd);
  4541. String countExpr = formatCmd.Substring(6);
  4542. if (countExpr.empty())
  4543. break;
  4544. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4545. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4546. if ((countValue) && (countValue.mType->IsInteger()))
  4547. formatInfo->mOverrideCount = (int)countValue.GetInt64();
  4548. if (dbgEvaluationContext.HadError())
  4549. {
  4550. if (errorString != NULL)
  4551. *errorString = dbgEvaluationContext.GetErrorStr();
  4552. return false;
  4553. }
  4554. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4555. continue;
  4556. }
  4557. else if (strncmp(formatCmd.c_str(), "maxcount=", 9) == 0)
  4558. {
  4559. formatCmd = formatFlags.Substring(1);
  4560. formatCmd = Trim(formatCmd);
  4561. String countExpr = formatCmd.Substring(9);
  4562. if (countExpr.empty())
  4563. break;
  4564. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4565. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4566. if ((countValue) && (countValue.mType->IsInteger()))
  4567. formatInfo->mOverrideCount = (int)countValue.GetInt64();
  4568. if (dbgEvaluationContext.HadError())
  4569. {
  4570. if (errorString != NULL)
  4571. *errorString = dbgEvaluationContext.GetErrorStr();
  4572. return false;
  4573. }
  4574. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4575. continue;
  4576. }
  4577. else if (strncmp(formatCmd.c_str(), "arraysize=", 10) == 0)
  4578. {
  4579. formatCmd = formatFlags.Substring(1);
  4580. formatCmd = Trim(formatCmd);
  4581. String countExpr = formatCmd.Substring(10);
  4582. if (countExpr.empty())
  4583. break;
  4584. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4585. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4586. if ((countValue) && (countValue.mType->IsInteger()))
  4587. formatInfo->mArrayLength = (int)countValue.GetInt64();
  4588. if (dbgEvaluationContext.HadError())
  4589. {
  4590. if (errorString != NULL)
  4591. *errorString = dbgEvaluationContext.GetErrorStr();
  4592. return false;
  4593. }
  4594. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4595. continue;
  4596. }
  4597. else if (strncmp(formatCmd.c_str(), "assign=", 7) == 0)
  4598. {
  4599. formatCmd = formatFlags.Substring(1);
  4600. formatCmd = Trim(formatCmd);
  4601. String assignExpr = formatCmd.Substring(7);
  4602. if (assignExpr.empty())
  4603. break;
  4604. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, assignExpr, formatInfo);
  4605. if (dbgEvaluationContext.HadError())
  4606. {
  4607. if (errorString != NULL)
  4608. *errorString = dbgEvaluationContext.GetErrorStr();
  4609. return false;
  4610. }
  4611. if (assignExprOffset != NULL)
  4612. {
  4613. //TODO: Keep track of the offset directly, this is a hack
  4614. *assignExprOffset = (int)formatInfoStr.IndexOf("assign=") + 7;
  4615. }
  4616. if (assignExprString != NULL)
  4617. *assignExprString = dbgEvaluationContext.mExprNode->ToString();
  4618. formatFlags = assignExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4619. continue;
  4620. }
  4621. else if (strncmp(formatCmd.c_str(), "refid=", 6) == 0)
  4622. {
  4623. formatInfo->mReferenceId = formatCmd.Substring(6);
  4624. if (formatInfo->mReferenceId[0] == '\"')
  4625. formatInfo->mReferenceId = formatInfo->mReferenceId.Substring(1, formatInfo->mReferenceId.length() - 2);
  4626. }
  4627. else if (strncmp(formatCmd.c_str(), "_=", 2) == 0)
  4628. {
  4629. formatInfo->mSubjectExpr = formatCmd.Substring(2);
  4630. if (formatInfo->mSubjectExpr[0] == '\"')
  4631. formatInfo->mSubjectExpr = formatInfo->mSubjectExpr.Substring(1, formatInfo->mSubjectExpr.length() - 2);
  4632. }
  4633. else if (strncmp(formatCmd.c_str(), "expectedType=", 13) == 0)
  4634. {
  4635. formatInfo->mExpectedType = formatCmd.Substring(13);
  4636. if (formatInfo->mExpectedType[0] == '\"')
  4637. formatInfo->mExpectedType = formatInfo->mExpectedType.Substring(1, formatInfo->mExpectedType.length() - 2);
  4638. }
  4639. else if (strncmp(formatCmd.c_str(), "namespaceSearch=", 16) == 0)
  4640. {
  4641. formatInfo->mNamespaceSearch = formatCmd.Substring(16);
  4642. if (formatInfo->mNamespaceSearch[0] == '\"')
  4643. formatInfo->mNamespaceSearch = formatInfo->mNamespaceSearch.Substring(1, formatInfo->mNamespaceSearch.length() - 2);
  4644. }
  4645. else if (formatCmd == "d")
  4646. {
  4647. formatInfo->mDisplayType = DwDisplayType_Decimal;
  4648. }
  4649. else if (formatCmd == "x")
  4650. {
  4651. formatInfo->mDisplayType = DwDisplayType_HexLower;
  4652. }
  4653. else if (formatCmd == "X")
  4654. {
  4655. formatInfo->mDisplayType = DwDisplayType_HexUpper;
  4656. }
  4657. else if (formatCmd == "s")
  4658. {
  4659. formatInfo->mHidePointers = true;
  4660. formatInfo->mDisplayType = DwDisplayType_Ascii;
  4661. }
  4662. else if (formatCmd == "s8")
  4663. {
  4664. formatInfo->mHidePointers = true;
  4665. formatInfo->mDisplayType = DwDisplayType_Utf8;
  4666. }
  4667. else if (formatCmd == "s16")
  4668. {
  4669. formatInfo->mHidePointers = true;
  4670. formatInfo->mDisplayType = DwDisplayType_Utf16;
  4671. }
  4672. else if (formatCmd == "s32")
  4673. {
  4674. formatInfo->mHidePointers = true;
  4675. formatInfo->mDisplayType = DwDisplayType_Utf32;
  4676. }
  4677. else if (formatCmd == "nd")
  4678. {
  4679. formatInfo->mIgnoreDerivedClassInfo = true;
  4680. }
  4681. else if (formatCmd == "na")
  4682. {
  4683. formatInfo->mHidePointers = true;
  4684. }
  4685. else if (formatCmd == "nm")
  4686. {
  4687. formatInfo->mNoMembers = true;
  4688. }
  4689. else if (formatCmd == "ne")
  4690. {
  4691. formatInfo->mNoEdit = true;
  4692. }
  4693. else if (formatCmd == "nv")
  4694. {
  4695. formatInfo->mNoVisualizers = true;
  4696. }
  4697. else if (formatCmd == "rawStr")
  4698. {
  4699. formatInfo->mRawString = true;
  4700. }
  4701. else if (((!formatCmd.IsEmpty()) && ((formatCmd[0] >= '0') && (formatCmd[0] <= '9'))) ||
  4702. (formatCmd.StartsWith("(")))
  4703. {
  4704. String countExpr = formatCmd;
  4705. if (countExpr.empty())
  4706. break;
  4707. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4708. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4709. if ((countValue) && (countValue.mType->IsInteger()))
  4710. formatInfo->mArrayLength = (int)countValue.GetInt64();
  4711. if (dbgEvaluationContext.HadError())
  4712. {
  4713. if (errorString != NULL)
  4714. *errorString = dbgEvaluationContext.GetErrorStr();
  4715. return false;
  4716. }
  4717. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4718. continue;
  4719. }
  4720. else
  4721. hadError = true;
  4722. if (hadError)
  4723. {
  4724. if (errorString != NULL)
  4725. *errorString = "Invalid format flags";
  4726. return false;
  4727. }
  4728. formatFlags = formatFlags.Substring(nextComma);
  4729. }
  4730. }
  4731. return true;
  4732. }
  4733. String WinDebugger::MaybeQuoteFormatInfoParam(const StringImpl& str)
  4734. {
  4735. bool needsQuote = false;
  4736. for (int i = 0; i < (int)str.length(); i++)
  4737. {
  4738. char c = str[i];
  4739. if (c == ',')
  4740. needsQuote = true;
  4741. }
  4742. if (!needsQuote)
  4743. return str;
  4744. String qStr = "\"";
  4745. qStr += str;
  4746. qStr += "\"";
  4747. return qStr;
  4748. }
  4749. DbgTypedValue WinDebugger::EvaluateInContext(DbgCompileUnit* dbgCompileUnit, const DbgTypedValue& contextTypedValue, const StringImpl& subExpr, DwFormatInfo* formatInfo, String* outReferenceId, String* outErrors)
  4750. {
  4751. DbgEvaluationContext dbgEvaluationContext(this, dbgCompileUnit->mDbgModule, subExpr, formatInfo, contextTypedValue);
  4752. dbgEvaluationContext.mDbgExprEvaluator->mDbgCompileUnit = dbgCompileUnit;
  4753. if (formatInfo != NULL)
  4754. {
  4755. dbgEvaluationContext.mDbgExprEvaluator->mLanguage = formatInfo->mLanguage;
  4756. dbgEvaluationContext.mDbgExprEvaluator->mSubjectExpr = formatInfo->mSubjectExpr;
  4757. }
  4758. dbgEvaluationContext.mDbgExprEvaluator->mReferenceId = outReferenceId;
  4759. auto result = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4760. if ((formatInfo != NULL) && (dbgEvaluationContext.mDbgExprEvaluator->mCountResultOverride != -1))
  4761. formatInfo->mOverrideCount = dbgEvaluationContext.mDbgExprEvaluator->mCountResultOverride;
  4762. if (dbgEvaluationContext.mPassInstance->HasFailed())
  4763. {
  4764. if (outErrors != NULL)
  4765. {
  4766. int errIdx = 0;
  4767. for (auto err : dbgEvaluationContext.mPassInstance->mErrors)
  4768. {
  4769. if (errIdx > 0)
  4770. (*outErrors) += "\n";
  4771. (*outErrors) += err->mError;
  4772. errIdx++;
  4773. }
  4774. }
  4775. return DbgTypedValue();
  4776. }
  4777. return result;
  4778. }
  4779. void WinDebugger::DbgVisFailed(DebugVisualizerEntry* debugVis, const StringImpl& evalString, const StringImpl& errors)
  4780. {
  4781. bool onlyMemError = errors.StartsWith("Failed to read") && !errors.Contains('\n');
  4782. if ((!debugVis->mShowedError) && (!onlyMemError))
  4783. {
  4784. debugVis->mShowedError = true;
  4785. String errStr = StrFormat("DbgVis '%s' failed while evaluating condition '%s'\n", debugVis->mName.c_str(), evalString.c_str());
  4786. String spacedErrors = errors;
  4787. spacedErrors.Insert(0, " ");
  4788. spacedErrors.Replace("\n", "\n ");
  4789. errStr += spacedErrors;
  4790. OutputMessage(errStr);
  4791. }
  4792. }
  4793. bool WinDebugger::EvalCondition(DebugVisualizerEntry* debugVis, DbgCompileUnit* dbgCompileUnit, DbgTypedValue typedVal, DwFormatInfo& formatInfo, const StringImpl& condition, const Array<String>& dbgVisWildcardCaptures, String& errorStr)
  4794. {
  4795. DwFormatInfo displayStrFormatInfo = formatInfo;
  4796. displayStrFormatInfo.mHidePointers = false;
  4797. displayStrFormatInfo.mRawString = false;
  4798. String errors;
  4799. const String conditionStr = mDebugManager->mDebugVisualizers->DoStringReplace(condition, dbgVisWildcardCaptures);
  4800. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, typedVal, conditionStr, &displayStrFormatInfo, NULL, &errors);
  4801. if ((!evalResult) || (!evalResult.mType->IsBoolean()))
  4802. {
  4803. if (formatInfo.mRawString)
  4804. return false;
  4805. errorStr += "<DbgVis Failed>";
  4806. DbgVisFailed(debugVis, conditionStr, errors);
  4807. return false;
  4808. }
  4809. return evalResult.mBool;
  4810. }
  4811. String WinDebugger::GetArrayItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgType* valueType, DbgTypedValue& curNode, int& count, String* outContinuationData)
  4812. {
  4813. DbgEvaluationContext conditionEvaluationContext(this, dbgCompileUnit, debugVis->mCondition);
  4814. String addrs;
  4815. bool checkLeft = true;
  4816. int usedCount = 0;
  4817. while (usedCount < count)
  4818. {
  4819. DbgTypedValue condVal = conditionEvaluationContext.EvaluateInContext(curNode);
  4820. if (!condVal)
  4821. break;
  4822. if (condVal.mBool)
  4823. {
  4824. auto val = curNode;
  4825. if (valueType == NULL)
  4826. {
  4827. String typeAddr = val.mType->ToStringRaw();
  4828. // RPad
  4829. typeAddr.Append(' ', sizeof(addr_target) * 2 - typeAddr.length());
  4830. addrs += typeAddr;
  4831. }
  4832. String addr = EncodeDataPtr(val.mPtr, false);
  4833. addrs += addr;
  4834. usedCount++;
  4835. }
  4836. curNode.mPtr += curNode.mType->mTypeParam->GetStride();
  4837. }
  4838. count = usedCount;
  4839. if (outContinuationData != NULL)
  4840. {
  4841. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(valueType, false) +
  4842. EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  4843. }
  4844. return addrs;
  4845. }
  4846. String WinDebugger::GetLinkedListItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, addr_target endNodePtr, DbgType* valueType, DbgTypedValue& curNode, int& count, String* outContinuationData)
  4847. {
  4848. DbgEvaluationContext nextEvaluationContext(this, dbgCompileUnit, debugVis->mNextPointer);
  4849. DbgEvaluationContext valueEvaluationContext(this, dbgCompileUnit, debugVis->mValuePointer);
  4850. String addrs;
  4851. bool checkLeft = true;
  4852. int mapIdx;
  4853. for (mapIdx = 0; mapIdx < count; mapIdx++)
  4854. {
  4855. if (curNode.mPtr == endNodePtr)
  4856. break;
  4857. DbgTypedValue val = valueEvaluationContext.EvaluateInContext(curNode);
  4858. if (!val)
  4859. break;
  4860. if (val.mPtr == 0)
  4861. break;
  4862. if (valueType == NULL)
  4863. {
  4864. String typeAddr = val.mType->ToStringRaw();
  4865. // RPad
  4866. typeAddr.Append(' ', sizeof(addr_target)*2 - typeAddr.length());
  4867. addrs += typeAddr;
  4868. }
  4869. String addr = EncodeDataPtr(val.mPtr, false);
  4870. addrs += addr;
  4871. curNode = nextEvaluationContext.EvaluateInContext(curNode);
  4872. }
  4873. count = mapIdx;
  4874. if (outContinuationData != NULL)
  4875. {
  4876. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(endNodePtr, false) + EncodeDataPtr(valueType, false) +
  4877. EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  4878. }
  4879. return addrs;
  4880. }
  4881. String WinDebugger::GetDictionaryItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgTypedValue dictValue, int bucketIdx, int nodeIdx, int& count, String* outContinuationData)
  4882. {
  4883. //DbgEvaluationContext bucketsEvaluationContext(this, dbgModule, debugVis->mBuckets);
  4884. DbgEvaluationContext nextEvaluationContext(this, dbgCompileUnit->mDbgModule, debugVis->mNextPointer);
  4885. DbgTypedValue bucketsPtr = EvaluateInContext(dbgCompileUnit, dictValue, debugVis->mBuckets);
  4886. DbgTypedValue entriesPtr = EvaluateInContext(dbgCompileUnit, dictValue, debugVis->mEntries);
  4887. if ((!bucketsPtr) || (!entriesPtr))
  4888. {
  4889. count = -1;
  4890. return "";
  4891. }
  4892. int entrySize = entriesPtr.mType->mTypeParam->GetByteCount();
  4893. String addrs;
  4894. bool checkLeft = true;
  4895. int encodeCount = 0;
  4896. while (encodeCount < count)
  4897. {
  4898. if (nodeIdx != -1)
  4899. {
  4900. DbgTypedValue entryValue;
  4901. entryValue.mSrcAddress = entriesPtr.mPtr + (nodeIdx * entrySize);
  4902. entryValue.mType = entriesPtr.mType->mTypeParam;
  4903. addrs += EncodeDataPtr(entryValue.mSrcAddress, false);
  4904. DbgTypedValue nextValue = nextEvaluationContext.EvaluateInContext(entryValue);
  4905. if ((!nextValue) || (!nextValue.mType->IsInteger()))
  4906. {
  4907. break;
  4908. }
  4909. nodeIdx = (int)nextValue.GetInt64();
  4910. encodeCount++;
  4911. }
  4912. else
  4913. {
  4914. nodeIdx = ReadMemory<int>(bucketsPtr.mPtr + bucketIdx * sizeof(int32));
  4915. bucketIdx++;
  4916. }
  4917. }
  4918. count = encodeCount;
  4919. //count = mapIdx;
  4920. if (outContinuationData != NULL)
  4921. {
  4922. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(dictValue.mType, false) + EncodeDataPtr(dictValue.mSrcAddress, false) +
  4923. EncodeDataPtr((addr_target)bucketIdx, false) + EncodeDataPtr((addr_target)nodeIdx, false);
  4924. }
  4925. return addrs;
  4926. }
  4927. String WinDebugger::GetTreeItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, Array<addr_target>& parentList, DbgType*& valueType, DbgTypedValue& curNode, int count, String* outContinuationData)
  4928. {
  4929. DbgEvaluationContext leftEvaluationContext(this, dbgCompileUnit, debugVis->mLeftPointer);
  4930. DbgEvaluationContext rightEvaluationContext(this, dbgCompileUnit, debugVis->mRightPointer);
  4931. DbgEvaluationContext valueEvaluationContext(this, dbgCompileUnit, debugVis->mValuePointer);
  4932. DbgEvaluationContext conditionEvaluationContext(this, dbgCompileUnit, debugVis->mCondition);
  4933. String addrs;
  4934. bool checkLeft = true;
  4935. if ((curNode.mPtr & 2) != 0) // Flag from continuation
  4936. {
  4937. checkLeft = false;
  4938. curNode.mPtr &= (addr_target)~2;
  4939. }
  4940. HashSet<intptr> seenAddrs;
  4941. for (int mapIdx = 0; mapIdx < count; mapIdx++)
  4942. {
  4943. DbgTypedValue readNode;
  4944. while (true)
  4945. {
  4946. bool checkNode = (curNode.mPtr & 1) == 0;
  4947. readNode = curNode;
  4948. readNode.mPtr &= (addr_target)~1;
  4949. if (checkLeft)
  4950. {
  4951. DbgTypedValue leftValue = leftEvaluationContext.EvaluateInContext(readNode);
  4952. bool isEmpty = leftValue.mPtr == NULL;
  4953. if ((leftValue) && (conditionEvaluationContext.HasExpression()))
  4954. {
  4955. auto condValue = conditionEvaluationContext.EvaluateInContext(leftValue);
  4956. if (condValue)
  4957. isEmpty = !condValue.mBool;
  4958. }
  4959. if (isEmpty)
  4960. {
  4961. checkLeft = false;
  4962. break; // Handle node
  4963. }
  4964. parentList.push_back(curNode.mPtr);
  4965. curNode = leftValue;
  4966. }
  4967. else if (checkNode)
  4968. {
  4969. break; // Handle node
  4970. }
  4971. else
  4972. {
  4973. DbgTypedValue rightValue = rightEvaluationContext.EvaluateInContext(readNode);
  4974. bool isEmpty = rightValue.mPtr == NULL;
  4975. if ((rightValue) && (conditionEvaluationContext.HasExpression()))
  4976. {
  4977. auto condValue = conditionEvaluationContext.EvaluateInContext(rightValue);
  4978. if (condValue)
  4979. isEmpty = !condValue.mBool;
  4980. }
  4981. if (!isEmpty)
  4982. {
  4983. curNode = rightValue;
  4984. checkLeft = true;
  4985. }
  4986. else
  4987. {
  4988. if (parentList.size() == 0)
  4989. {
  4990. // Failed
  4991. break;
  4992. }
  4993. curNode.mPtr = parentList.back();
  4994. parentList.pop_back();
  4995. continue; // Don't check against seenAddrs
  4996. }
  4997. }
  4998. if (!seenAddrs.Add(curNode.mPtr))
  4999. {
  5000. // Failed!
  5001. return "";
  5002. }
  5003. }
  5004. DbgTypedValue val = valueEvaluationContext.EvaluateInContext(readNode);
  5005. if (valueType == NULL)
  5006. valueType = val.mType;
  5007. String addr = EncodeDataPtr(val.mPtr, false);
  5008. addrs += addr;
  5009. curNode.mPtr |= 1; // Node handled
  5010. }
  5011. if (!checkLeft)
  5012. curNode.mPtr |= 2;
  5013. if (outContinuationData != NULL)
  5014. {
  5015. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(valueType, false) + EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  5016. for (auto parent : parentList)
  5017. *outContinuationData += EncodeDataPtr(parent, false);
  5018. }
  5019. return addrs;
  5020. }
  5021. String WinDebugger::GetCollectionContinuation(const StringImpl& continuationData, int callStackIdx, int count)
  5022. {
  5023. DbgCompileUnit* dbgCompileUnit = GetCallStackCompileUnit(callStackIdx);;
  5024. if (!IsPaused())
  5025. return "";
  5026. const char* dataPtr = continuationData.c_str();
  5027. DebugVisualizerEntry* debugVis = (DebugVisualizerEntry*)DecodeLocalDataPtr(dataPtr);
  5028. if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_TreeItems)
  5029. {
  5030. DbgType* valueType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5031. DbgTypedValue curNode;
  5032. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5033. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5034. Array<addr_target> parentList;
  5035. String newContinuationData;
  5036. while (*dataPtr != 0)
  5037. parentList.push_back(DecodeTargetDataPtr(dataPtr));
  5038. String retVal = GetTreeItems(dbgCompileUnit, debugVis, parentList, valueType, curNode, count, &newContinuationData);
  5039. retVal += "\n" + newContinuationData;
  5040. return retVal;
  5041. }
  5042. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_LinkedList)
  5043. {
  5044. addr_target endNodePtr = DecodeTargetDataPtr(dataPtr);
  5045. DbgType* valueType = (DbgType*) DecodeLocalDataPtr(dataPtr);
  5046. DbgTypedValue curNode;
  5047. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5048. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5049. String newContinuationData;
  5050. if (count < 0)
  5051. count = 3;
  5052. String retVal = GetLinkedListItems(dbgCompileUnit, debugVis, endNodePtr, valueType, curNode, count, &newContinuationData);
  5053. retVal += "\n" + newContinuationData;
  5054. return retVal;
  5055. }
  5056. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Array)
  5057. {
  5058. DbgType* valueType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5059. DbgTypedValue curNode;
  5060. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5061. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5062. String newContinuationData;
  5063. if (count < 0)
  5064. count = 3;
  5065. String retVal = GetArrayItems(dbgCompileUnit, debugVis, valueType, curNode, count, &newContinuationData);
  5066. retVal += "\n" + newContinuationData;
  5067. return retVal;
  5068. }
  5069. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Dictionary)
  5070. {
  5071. DbgTypedValue dictValue;
  5072. dictValue.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5073. dictValue.mSrcAddress = DecodeTargetDataPtr(dataPtr);
  5074. int bucketIdx = (int)DecodeTargetDataPtr(dataPtr);
  5075. int nodeIdx = (int)DecodeTargetDataPtr(dataPtr);
  5076. String newContinuationData;
  5077. String retVal = GetDictionaryItems(dbgCompileUnit, debugVis, dictValue, bucketIdx, nodeIdx, count, &newContinuationData);
  5078. retVal += "\n" + newContinuationData;
  5079. return retVal;
  5080. }
  5081. return "";
  5082. }
  5083. template <typename T>
  5084. static String IntTypeToString(T val, const StringImpl& name, DwDisplayInfo* displayInfo, DwFormatInfo& formatInfo)
  5085. {
  5086. auto intDisplayType = displayInfo->mIntDisplayType;
  5087. if (formatInfo.mDisplayType == DwDisplayType_Decimal)
  5088. intDisplayType = DwIntDisplayType_Decimal;
  5089. else if (formatInfo.mDisplayType == DwDisplayType_HexUpper)
  5090. intDisplayType = DwIntDisplayType_HexadecimalUpper;
  5091. else if (formatInfo.mDisplayType == DwDisplayType_HexLower)
  5092. intDisplayType = DwIntDisplayType_HexadecimalLower;
  5093. if (intDisplayType == DwIntDisplayType_Binary)
  5094. {
  5095. String binary;
  5096. for (int i = 0; i < sizeof(T) * 8; i++)
  5097. {
  5098. if ((i != 0) && (i % 4 == 0))
  5099. binary = "'" + binary;
  5100. if ((i != 0) && (i % 16 == 0))
  5101. binary = "'" + binary;
  5102. binary = ((val & ((T)1 << i)) ? "1" : "0") + binary;
  5103. }
  5104. return StrFormat("0b'%s\n%s", binary.c_str(), name.c_str());
  5105. }
  5106. if (intDisplayType == DwIntDisplayType_Octal)
  5107. {
  5108. String format;
  5109. if (sizeof(T) == 8)
  5110. {
  5111. format = StrFormat("0o%%lo\n%s", name.c_str());
  5112. }
  5113. else
  5114. format = StrFormat("0o%%0%do\n%s", sizeof(val) * 2, name.c_str());
  5115. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5116. }
  5117. if (intDisplayType == DwIntDisplayType_HexadecimalUpper)
  5118. {
  5119. String format;
  5120. if (sizeof(T) == 8)
  5121. {
  5122. format = StrFormat("0x%%l@\n%s", name.c_str());
  5123. }
  5124. else
  5125. format = StrFormat("0x%%0%dX\n%s", sizeof(val) * 2, name.c_str());
  5126. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5127. }
  5128. //TODO: Implement HexadecimalLower
  5129. if (intDisplayType == DwIntDisplayType_HexadecimalLower)
  5130. {
  5131. String format;
  5132. if (sizeof(T) == 8)
  5133. {
  5134. format = StrFormat("0x%%l@\n%s", name.c_str());
  5135. }
  5136. else
  5137. format = StrFormat("0x%%0%dX\n%s", sizeof(val) * 2, name.c_str());
  5138. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5139. }
  5140. if (std::is_unsigned<T>::value)
  5141. {
  5142. if (sizeof(T) == 8)
  5143. {
  5144. if (val > 0x7FFFFFFFF)
  5145. return StrFormat("%llu\n%s\n:editVal\t%lluUL", val, name.c_str(), val);
  5146. else
  5147. return StrFormat("%llu\n%s", val, name.c_str());
  5148. }
  5149. else
  5150. return StrFormat("%u\n%s", val, name.c_str());
  5151. }
  5152. else
  5153. {
  5154. if (sizeof(T) == 8)
  5155. {
  5156. if ((val > 0x7FFFFFFFF) || (val < -0x80000000LL))
  5157. return StrFormat("%lld\n%s\n:editVal\t%lldL", val, name.c_str(), val);
  5158. else
  5159. return StrFormat("%lld\n%s", val, name.c_str(), val);
  5160. }
  5161. else
  5162. return StrFormat("%d\n%s", val, name.c_str());
  5163. }
  5164. }
  5165. DwDisplayInfo* WinDebugger::GetDisplayInfo(const StringImpl& referenceId)
  5166. {
  5167. DwDisplayInfo* displayInfo = &mDebugManager->mDefaultDisplayInfo;
  5168. if (!referenceId.empty())
  5169. {
  5170. mDebugManager->mDisplayInfos.TryGetValue(referenceId, &displayInfo);
  5171. }
  5172. return displayInfo;
  5173. }
  5174. static String WrapWithModifiers(const StringImpl& origName, DbgType* dbgType, DbgLanguage language)
  5175. {
  5176. if (language == DbgLanguage_Unknown)
  5177. language = dbgType->GetLanguage();
  5178. String name = origName;
  5179. while (true)
  5180. {
  5181. if (dbgType->mTypeCode == DbgType_Const)
  5182. {
  5183. if (language == DbgLanguage_Beef)
  5184. name = "readonly " + name;
  5185. else
  5186. name = "const " + name;
  5187. dbgType = dbgType->mTypeParam;
  5188. }
  5189. else if (dbgType->mTypeCode == DbgType_Volatile)
  5190. {
  5191. name = "volatile " + name;
  5192. dbgType = dbgType->mTypeParam;
  5193. }
  5194. else if (dbgType->mTypeCode == DbgType_TypeDef)
  5195. {
  5196. dbgType = dbgType->mTypeParam;
  5197. }
  5198. else if (dbgType->mTypeCode == DbgType_Ref)
  5199. {
  5200. if (language == DbgLanguage_Beef)
  5201. name = "ref " + name;
  5202. else
  5203. name = name + "&";
  5204. dbgType = dbgType->mTypeParam;
  5205. }
  5206. else if (dbgType->mTypeCode == DbgType_Bitfield)
  5207. {
  5208. return dbgType->ToString(language);
  5209. }
  5210. else
  5211. return name;
  5212. }
  5213. }
  5214. DebugVisualizerEntry* WinDebugger::FindVisualizerForType(DbgType* dbgType, Array<String>* wildcardCaptures)
  5215. {
  5216. auto entry = mDebugManager->mDebugVisualizers->FindEntryForType(dbgType->ToString(DbgLanguage_Unknown, true), dbgType->mCompileUnit->mDbgModule->mDbgFlavor, wildcardCaptures);
  5217. if (entry == NULL)
  5218. {
  5219. dbgType = dbgType->GetPrimaryType();
  5220. dbgType->PopulateType();
  5221. for (auto baseTypeEntry : dbgType->mBaseTypes)
  5222. {
  5223. entry = FindVisualizerForType(baseTypeEntry->mBaseType, wildcardCaptures);
  5224. if (entry != NULL)
  5225. break;
  5226. }
  5227. }
  5228. return entry;
  5229. }
  5230. #define GET_FROM(ptr, T) *((T*)(ptr += sizeof(T)) - 1)
  5231. String WinDebugger::ReadString(DbgTypeCode charType, intptr addr, bool isLocalAddr, int maxLength, DwFormatInfo& formatInfo)
  5232. {
  5233. int origMaxLength = maxLength;
  5234. if (addr == 0)
  5235. return "";
  5236. BP_ZONE("WinDebugger::ReadString");
  5237. String retVal = "\"";
  5238. bool wasTerminated = false;
  5239. String valString;
  5240. int maxShowSize = 255;
  5241. if (maxLength == -1)
  5242. maxLength = formatInfo.mOverrideCount;
  5243. else if (formatInfo.mOverrideCount != -1)
  5244. maxLength = BF_MIN(formatInfo.mOverrideCount, maxLength);
  5245. if (formatInfo.mMaxCount != -1)
  5246. maxLength = BF_MIN(formatInfo.mMaxCount, maxLength);
  5247. if (maxLength == -1)
  5248. maxLength = 8 * 1024 * 1024; // Is 8MB crazy?
  5249. if (!formatInfo.mRawString)
  5250. maxLength = BF_MIN(maxLength, maxShowSize);
  5251. //EnableMemCache();
  5252. bool readFailed = false;
  5253. intptr strPtr = addr;
  5254. int charLen = 1;
  5255. if ((charType == DbgType_SChar16) || (charType == DbgType_UChar16))
  5256. charLen = 2;
  5257. else if ((charType == DbgType_SChar32) || (charType == DbgType_UChar32))
  5258. charLen = 4;
  5259. bool isUTF8 = formatInfo.mDisplayType == DwDisplayType_Utf8;
  5260. int readSize = BF_MIN(1024, maxLength * charLen);
  5261. uint8 buf[1024];
  5262. uint8* bufPtr = NULL;
  5263. uint8* bufEnd = NULL;
  5264. bool hasHighAscii = false;
  5265. int i;
  5266. for (i = 0; i < maxLength; i++)
  5267. {
  5268. if (bufPtr >= bufEnd)
  5269. {
  5270. while (true)
  5271. {
  5272. if (readSize < charLen)
  5273. {
  5274. readFailed = true;
  5275. break;
  5276. }
  5277. if (ReadMemory(strPtr, readSize, buf, isLocalAddr))
  5278. break;
  5279. readSize /= 2;
  5280. }
  5281. if (readFailed)
  5282. break;
  5283. bufPtr = buf;
  5284. bufEnd = buf + readSize;
  5285. }
  5286. switch (charLen)
  5287. {
  5288. case 1:
  5289. {
  5290. char c = GET_FROM(bufPtr, char);
  5291. if (c != 0)
  5292. {
  5293. if ((uint8)c >= 0x80)
  5294. hasHighAscii = true;
  5295. valString.Append(c);
  5296. }
  5297. else
  5298. wasTerminated = true;
  5299. }
  5300. break;
  5301. case 2:
  5302. {
  5303. uint16 c16 = GET_FROM(bufPtr, uint16);
  5304. if (c16 != 0)
  5305. {
  5306. char str[8];
  5307. u8_toutf8(str, 8, c16);
  5308. valString += str;
  5309. }
  5310. else
  5311. wasTerminated = true;
  5312. }
  5313. break;
  5314. case 4:
  5315. {
  5316. uint32 c32 = GET_FROM(bufPtr, uint32);
  5317. if (c32 != 0)
  5318. {
  5319. char str[8];
  5320. u8_toutf8(str, 8, c32);
  5321. valString += str;
  5322. }
  5323. else
  5324. wasTerminated = true;
  5325. }
  5326. break;
  5327. }
  5328. if ((wasTerminated) && (formatInfo.mOverrideCount != -1))
  5329. {
  5330. valString += '\x00';
  5331. wasTerminated = false;
  5332. }
  5333. if ((wasTerminated) || (readFailed))
  5334. {
  5335. break;
  5336. }
  5337. strPtr += charLen;
  5338. }
  5339. //DisableMemCache();
  5340. if (formatInfo.mOverrideCount != -1)
  5341. {
  5342. if (i == formatInfo.mOverrideCount)
  5343. wasTerminated = true;
  5344. }
  5345. if (strPtr == addr + origMaxLength)
  5346. wasTerminated = true;
  5347. if (valString.length() == formatInfo.mOverrideCount)
  5348. wasTerminated = true;
  5349. // if (formatInfo.mDisplayType == DwDisplayType_Ascii)
  5350. // {
  5351. // // Our encoding for retVal is already assumed to be UTF8, so the special case here actually Ascii
  5352. // valString = UTF8Encode(ToWString(valString));
  5353. // }
  5354. if (formatInfo.mRawString)
  5355. {
  5356. if ((formatInfo.mDisplayType == DwDisplayType_Utf8) || (!hasHighAscii))
  5357. return valString;
  5358. String utf8Str;
  5359. for (int i = 0; i < (int)valString.length(); i++)
  5360. {
  5361. char c = valString[i];
  5362. if ((uint8)c >= 0x80)
  5363. {
  5364. utf8Str += (char)(0xC0 | (((uint8)c & 0xFF) >> 6));
  5365. utf8Str += (char)(0x80 | ((uint8)c & 0x3F));
  5366. }
  5367. else
  5368. utf8Str += c;
  5369. }
  5370. return utf8Str;
  5371. }
  5372. if ((readFailed) && (valString.IsEmpty()))
  5373. return "< Failed to read string >";
  5374. retVal += SlashString(valString, true, true, formatInfo.mLanguage == DbgLanguage_Beef);
  5375. // We could go over 'maxShowSize' if we have a lot of slashed chars. An uninitialized string can be filled with '\xcc' chars
  5376. if ((!formatInfo.mRawString) && ((int)retVal.length() > maxShowSize))
  5377. {
  5378. retVal = retVal.Substring(0, maxShowSize);
  5379. wasTerminated = false;
  5380. }
  5381. if (wasTerminated)
  5382. retVal += "\"";
  5383. else
  5384. retVal += "...";
  5385. return retVal;
  5386. }
  5387. void WinDebugger::ProcessEvalString(DbgCompileUnit* dbgCompileUnit, DbgTypedValue useTypedValue, String& evalStr, String& displayString, DwFormatInfo& formatInfo, DebugVisualizerEntry* debugVis, bool limitLength)
  5388. {
  5389. for (int i = 0; i < (int)evalStr.length(); i++)
  5390. {
  5391. char c = evalStr[i];
  5392. char nextC = 0;
  5393. if (i < (int)evalStr.length() - 1)
  5394. nextC = evalStr[i + 1];
  5395. if ((c == '{') && (nextC != '{'))
  5396. {
  5397. // Evaluate
  5398. int endIdx = i;
  5399. for (; endIdx < (int)evalStr.length(); endIdx++)
  5400. {
  5401. //TODO: Do better parsing - this paren could be inside a string, for example
  5402. if (evalStr[endIdx] == '}')
  5403. break;
  5404. }
  5405. DwFormatInfo displayStrFormatInfo = formatInfo;
  5406. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + (int)displayString.length();
  5407. displayStrFormatInfo.mHidePointers = false;
  5408. if ((limitLength) && (displayStrFormatInfo.mTotalSummaryLength > 255))
  5409. {
  5410. displayString += "...";
  5411. }
  5412. else
  5413. {
  5414. String evalString = evalStr.Substring(i + 1, endIdx - i - 1);
  5415. String errors;
  5416. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, useTypedValue, evalString, &displayStrFormatInfo, NULL, &errors);
  5417. if (evalResult)
  5418. {
  5419. if (displayStrFormatInfo.mNoEdit)
  5420. formatInfo.mNoEdit = true;
  5421. String result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  5422. if ((formatInfo.mRawString) && (limitLength))
  5423. {
  5424. displayString = result;
  5425. return;
  5426. }
  5427. int crPos = result.IndexOf('\n');
  5428. if (crPos != -1)
  5429. displayString += result.Substring(0, crPos);
  5430. else
  5431. displayString += result;
  5432. }
  5433. else if (debugVis != NULL)
  5434. {
  5435. displayString += "<DbgVis Failed>";
  5436. DbgVisFailed(debugVis, evalString, errors);
  5437. }
  5438. else
  5439. {
  5440. displayString += "<Eval Failed>";
  5441. }
  5442. }
  5443. i = endIdx;
  5444. continue;
  5445. }
  5446. else if ((c == '{') && (nextC == '{'))
  5447. {
  5448. // Skip next paren
  5449. i++;
  5450. }
  5451. else if ((c == '}') && (nextC == '}'))
  5452. {
  5453. // Skip next paren
  5454. i++;
  5455. }
  5456. displayString += c;
  5457. }
  5458. }
  5459. static bool IsNormalChar(uint32 c)
  5460. {
  5461. return (c < 0x80);
  5462. }
  5463. String WinDebugger::DbgTypedValueToString(const DbgTypedValue& origTypedValue, const StringImpl& expr, DwFormatInfo& formatInfo, DbgExprEvaluator* optEvaluator, bool fullPrecision)
  5464. {
  5465. BP_ZONE("WinDebugger::DbgTypedValueToString");
  5466. DbgTypedValue typedValue = origTypedValue;
  5467. auto dbgCompileUnit = typedValue.mType->mCompileUnit;
  5468. auto dbgModule = typedValue.mType->GetDbgModule();
  5469. auto language = origTypedValue.mType->GetLanguage();
  5470. if (language == DbgLanguage_Unknown)
  5471. language = formatInfo.mLanguage;
  5472. formatInfo.mLanguage = language;
  5473. bool isBeef = language == DbgLanguage_Beef;
  5474. char str[32];
  5475. bool readFailed = false;
  5476. bool isCompositeType = false;
  5477. bool isSizedArray = false;
  5478. bool isEnum = false;
  5479. int64 enumVal = 0;
  5480. String result;
  5481. DwDisplayInfo* displayInfo = GetDisplayInfo(formatInfo.mReferenceId);
  5482. DbgType* origValueType = typedValue.mType;
  5483. bool origHadRef = false;
  5484. DbgType* dwValueType = typedValue.mType->RemoveModifiers(&origHadRef);
  5485. // if (origValueType->mTypeCode == DbgType_Bitfield)
  5486. // {
  5487. // auto dbgBitfieldType = (DbgBitfieldType*)origValueType;
  5488. //
  5489. // typedValue.mUInt64 = typedValue.mUInt64 >> dbgBitfieldType->mPosition;
  5490. //
  5491. // uint64 mask = ((uint64)1<<dbgBitfieldType->mLength) - 1;
  5492. // typedValue.mUInt64 &= mask;
  5493. //
  5494. // if ((dwValueType->IsSigned()) && ((typedValue.mUInt64 & (1LL << (dbgBitfieldType->mLength - 1))) != 0))
  5495. // {
  5496. // // Sign extend
  5497. // typedValue.mUInt64 |= ~mask;
  5498. // }
  5499. // }
  5500. if (dwValueType == NULL)
  5501. dwValueType = dbgModule->GetPrimitiveType(DbgType_Void, language);
  5502. if (dwValueType->mTypeCode == DbgType_TypeDef)
  5503. {
  5504. DbgTypedValue realTypedVal = typedValue;
  5505. realTypedVal.mType = dwValueType->mTypeParam;
  5506. return DbgTypedValueToString(realTypedVal, expr, formatInfo, optEvaluator);
  5507. }
  5508. if (formatInfo.mRawString)
  5509. {
  5510. if ((dwValueType->mTypeCode != DbgType_Struct) && (dwValueType->mTypeCode != DbgType_Class) && (dwValueType->mTypeCode != DbgType_Ptr) && (dwValueType->mTypeCode != DbgType_SizedArray))
  5511. return "";
  5512. }
  5513. auto _ShowArraySummary = [&](String& retVal, addr_target ptrVal, int arraySize, DbgType* innerType)
  5514. {
  5515. String displayString;
  5516. displayString += "{";
  5517. for (int idx = 0; idx < arraySize; idx++)
  5518. {
  5519. if (formatInfo.mTotalSummaryLength + retVal.length() + displayString.length() > 255)
  5520. {
  5521. displayString += "...";
  5522. break;
  5523. }
  5524. if ((idx != 0) && (!displayString.EndsWith('{')))
  5525. displayString += ", ";
  5526. DwFormatInfo displayStrFormatInfo = formatInfo;
  5527. displayStrFormatInfo.mExpandItemDepth = 1;
  5528. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + retVal.length() + displayString.length();
  5529. displayStrFormatInfo.mHidePointers = false;
  5530. displayStrFormatInfo.mArrayLength = -1;
  5531. // Why did we have this "na" on here? It made "void*[3]" type things show up as "{,,}"
  5532. //String evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + StrFormat(")[%d], na", idx);
  5533. String evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + StrFormat(")[%d]", idx);
  5534. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, typedValue, evalStr, &displayStrFormatInfo);
  5535. String result;
  5536. if (evalResult)
  5537. {
  5538. result = DbgTypedValueToString(evalResult, evalStr, displayStrFormatInfo, NULL);
  5539. int crPos = result.IndexOf('\n');
  5540. if (crPos != -1)
  5541. result.RemoveToEnd(crPos);
  5542. }
  5543. else
  5544. result = "???";
  5545. displayString += result;
  5546. }
  5547. displayString += "}";
  5548. retVal += displayString;
  5549. };
  5550. if (formatInfo.mArrayLength != -1)
  5551. {
  5552. if (formatInfo.mRawString)
  5553. return "";
  5554. if (dwValueType->IsPointer())
  5555. {
  5556. String retVal;
  5557. addr_target ptrVal = (addr_target)typedValue.mPtr;
  5558. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  5559. {
  5560. retVal = EncodeDataPtr(ptrVal, true) + " ";
  5561. retVal += dwValueType->mTypeParam->ToString(language);
  5562. retVal += StrFormat("[%d] ", formatInfo.mArrayLength);
  5563. }
  5564. else
  5565. {
  5566. // Show first item
  5567. // String evalString = "*((" + typedValue.mType->ToStringRaw(language) + ")" + EncodeDataPtr(ptrVal, true) + "), nm";
  5568. // DwFormatInfo emptyFormatInfo;
  5569. // DbgTypedValue evalResult = EvaluateInContext(dbgModule, typedValue, evalString, &emptyFormatInfo);
  5570. // if (evalResult)
  5571. // {
  5572. // retVal += DbgTypedValueToString(evalResult, evalString, emptyFormatInfo, NULL);
  5573. // }
  5574. }
  5575. _ShowArraySummary(retVal, ptrVal, formatInfo.mArrayLength, dwValueType->mTypeParam);
  5576. String idxStr = "[{0}]";
  5577. DbgType* innerType = dwValueType->mTypeParam;
  5578. retVal += "\n" + dwValueType->ToString(language);
  5579. String evalStr = "*((" + typedValue.mType->ToStringRaw(language) + ")" + EncodeDataPtr(ptrVal, true) + " + {0})";
  5580. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)BF_MAX(formatInfo.mArrayLength, 0), 10000) +
  5581. "\t" + idxStr + "\t" + evalStr;
  5582. return retVal;
  5583. }
  5584. else
  5585. {
  5586. DwFormatInfo newFormatInfo = formatInfo;
  5587. newFormatInfo.mArrayLength = -1;
  5588. String retVal = DbgTypedValueToString(typedValue, expr, newFormatInfo, optEvaluator);
  5589. int crPos = (int)retVal.IndexOf('\n');
  5590. if (crPos != -1)
  5591. retVal = "!Array length flag not valid with this type" + retVal.Substring(crPos);
  5592. return retVal;
  5593. }
  5594. }
  5595. switch (dwValueType->mTypeCode)
  5596. {
  5597. case DbgType_Void:
  5598. return "\nvoid";
  5599. case DbgType_Bool:
  5600. {
  5601. if (typedValue.mUInt8 == 0)
  5602. return "false\n" + WrapWithModifiers("bool", origValueType, language);
  5603. else if (typedValue.mUInt8 == 1)
  5604. return "true\n" + WrapWithModifiers("bool", origValueType, language);
  5605. else
  5606. return StrFormat("true (%d)\n", typedValue.mUInt8) + WrapWithModifiers("bool", origValueType, language);
  5607. }
  5608. break;
  5609. case DbgType_UChar:
  5610. if (language != DbgLanguage_Beef)
  5611. return IntTypeToString<int8>(typedValue.mUInt8, WrapWithModifiers("uint8_t", origValueType, language), displayInfo, formatInfo);
  5612. case DbgType_SChar:
  5613. {
  5614. if (typedValue.mInt8 != 0)
  5615. {
  5616. char str[2] = {(char)typedValue.mInt8};
  5617. result = SlashString(str, formatInfo.mDisplayType == DwDisplayType_Utf8, true);
  5618. if (!IsNormalChar(typedValue.mUInt8))
  5619. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt8);
  5620. else
  5621. result = StrFormat("'%s'\n", result.c_str());
  5622. }
  5623. else
  5624. result = "'\\0'\n";
  5625. return result + WrapWithModifiers("char", origValueType, language);
  5626. }
  5627. break;
  5628. case DbgType_UChar16:
  5629. if (language != DbgLanguage_Beef)
  5630. return IntTypeToString<int16>(typedValue.mUInt8, WrapWithModifiers("uint16_t", origValueType, language), displayInfo, formatInfo);
  5631. case DbgType_SChar16:
  5632. {
  5633. if (typedValue.mInt16 != 0)
  5634. {
  5635. u8_toutf8(str, 8, typedValue.mUInt32);
  5636. result = SlashString(str, true, true);
  5637. if (!IsNormalChar(typedValue.mUInt32))
  5638. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt16);
  5639. else
  5640. result = StrFormat("'%s'\n", result.c_str());
  5641. }
  5642. else
  5643. result = "'\\0'";
  5644. return result + WrapWithModifiers(isBeef ? "char16" : "int16_t", origValueType, language);
  5645. }
  5646. break;
  5647. case DbgType_UChar32:
  5648. case DbgType_SChar32:
  5649. {
  5650. if (typedValue.mInt32 != 0)
  5651. {
  5652. u8_toutf8(str, 8, typedValue.mUInt32);
  5653. result = SlashString(str, true, true);
  5654. if (!IsNormalChar(typedValue.mUInt32))
  5655. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt32);
  5656. else
  5657. result = StrFormat("'%s'\n", result.c_str());
  5658. }
  5659. else
  5660. result = "'\\0'";
  5661. return result + WrapWithModifiers(isBeef ? "char32" : "int32_t", origValueType, language);
  5662. }
  5663. break;
  5664. case DbgType_i8:
  5665. return IntTypeToString<int8>(typedValue.mInt8, WrapWithModifiers(isBeef ? "int8" : "int8_t", origValueType, language), displayInfo, formatInfo);
  5666. case DbgType_u8:
  5667. return IntTypeToString<uint8>(typedValue.mUInt8, WrapWithModifiers(isBeef ? "uint8" : "uint8_t", origValueType, language), displayInfo, formatInfo);
  5668. case DbgType_i16:
  5669. return IntTypeToString<int16>(typedValue.mInt16, WrapWithModifiers(isBeef ? "int16" : "int16_t", origValueType, language), displayInfo, formatInfo);
  5670. case DbgType_u16:
  5671. return IntTypeToString<uint16>(typedValue.mUInt16, WrapWithModifiers(isBeef ? "uint16" : "uint16_t", origValueType, language), displayInfo, formatInfo);
  5672. case DbgType_i32:
  5673. return IntTypeToString<int32>(typedValue.mInt32, WrapWithModifiers(isBeef ? "int32" : "int32_t", origValueType, language), displayInfo, formatInfo);
  5674. case DbgType_u32:
  5675. return IntTypeToString<uint32>(typedValue.mUInt32, WrapWithModifiers(isBeef ? "uint32" : "uint32_t", origValueType, language), displayInfo, formatInfo);
  5676. case DbgType_i64:
  5677. return IntTypeToString<int64>(typedValue.mInt64, WrapWithModifiers(isBeef ? "int64" : "int64_t", origValueType, language), displayInfo, formatInfo);
  5678. case DbgType_u64:
  5679. return IntTypeToString<uint64>(typedValue.mUInt64, WrapWithModifiers(isBeef ? "uint64" : "uint64_t", origValueType, language), displayInfo, formatInfo);
  5680. case DbgType_RegGroup:
  5681. {
  5682. if ((typedValue.mRegNum >= CPUReg_M128_XMMREG_FIRST) && (typedValue.mRegNum <= CPUReg_M128_XMMREG_LAST))
  5683. {
  5684. int callStackIdx = formatInfo.mCallStackIdx;
  5685. FixCallStackIdx(callStackIdx);
  5686. UpdateRegisterUsage(callStackIdx);
  5687. WdStackFrame* wdStackFrame = mCallStack[callStackIdx];
  5688. RegForm regForm = RegForm_Unknown;
  5689. if (typedValue.mRegNum < (int)wdStackFrame->mRegForms.size())
  5690. regForm = wdStackFrame->mRegForms[typedValue.mRegNum];
  5691. int xmmMajor = typedValue.mRegNum - CPUReg_M128_XMMREG_FIRST;
  5692. String headerStr;
  5693. String xmmType = "__m128";
  5694. int xmmCount = 4;
  5695. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2) ||
  5696. (regForm == RegForm_Long) || (regForm == RegForm_Long2) ||
  5697. (regForm == RegForm_ULong) || (regForm == RegForm_ULong2))
  5698. xmmCount = 2;
  5699. //TODO: add byte, short, int, etc...
  5700. if (optEvaluator)
  5701. {
  5702. DwMmDisplayType mmDwMmDisplayType = displayInfo->mMmDisplayType;
  5703. if (mmDwMmDisplayType == DwMmDisplayType_Default)
  5704. {
  5705. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2))
  5706. mmDwMmDisplayType = DwMmDisplayType_Double;
  5707. else if (regForm == RegForm_Int4)
  5708. mmDwMmDisplayType = DwMmDisplayType_Int;
  5709. }
  5710. //TODO: Add support for int types
  5711. if (mmDwMmDisplayType == DwMmDisplayType_Double)
  5712. {
  5713. xmmType = "__m128d";
  5714. xmmCount = 2;
  5715. double xmmRegVals[2];
  5716. CPURegisters* regs = optEvaluator->GetRegisters();
  5717. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5718. {
  5719. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5720. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_Double);
  5721. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5722. xmmRegVals[xmmMinor] = xmmReg.mDouble;
  5723. }
  5724. headerStr = StrFormat("(%f, %f)", xmmRegVals[0], xmmRegVals[1]);
  5725. }
  5726. else if (mmDwMmDisplayType == DwMmDisplayType_Int)
  5727. {
  5728. int xmmRegVals[4];
  5729. xmmCount = 4;
  5730. CPURegisters* regs = optEvaluator->GetRegisters();
  5731. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5732. {
  5733. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5734. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i32);
  5735. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5736. xmmRegVals[xmmMinor] = xmmReg.mInt32;
  5737. }
  5738. headerStr = StrFormat("(%d, %d, %d, %d)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  5739. }
  5740. else // Float
  5741. {
  5742. float xmmRegVals[4];
  5743. xmmCount = 4;
  5744. CPURegisters* regs = optEvaluator->GetRegisters();
  5745. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5746. {
  5747. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5748. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_Single);
  5749. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5750. xmmRegVals[xmmMinor] = xmmReg.mSingle;
  5751. }
  5752. headerStr = StrFormat("(%f, %f, %f, %f)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  5753. }
  5754. }
  5755. else
  5756. {
  5757. headerStr = StrFormat("XMM%d", xmmMajor);
  5758. }
  5759. result = headerStr + "\n" + xmmType;
  5760. for (int i = 0; i < xmmCount; i++)
  5761. result += WrapWithModifiers(StrFormat("\n[%d]\t$xmm%d_%d", i, xmmMajor, i, language), origValueType, language);
  5762. return result;
  5763. }
  5764. else
  5765. {
  5766. switch (typedValue.mRegNum)
  5767. {
  5768. case CPUReg_CAT_ALLREGS:
  5769. {
  5770. return "ALLREGS\n__allregs\niregs\t$iregs\nflags\t$flags\nfpregs\t$fpregs\nmmregs\t$mmregs\nxmmregs\t$xmmregs";
  5771. }
  5772. break;
  5773. case CPUReg_CAT_IREGS:
  5774. {
  5775. #ifdef BF_DBG_32
  5776. String headerStr;
  5777. if (optEvaluator)
  5778. {
  5779. CPURegisters* regs = optEvaluator->GetRegisters();
  5780. 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)",
  5781. (uint32)regs->mIntRegs.eax, (uint32)regs->mIntRegs.ebx, (uint32)regs->mIntRegs.ecx, (uint32)regs->mIntRegs.edx,
  5782. (uint32)regs->mIntRegs.esi, (uint32)regs->mIntRegs.edi, (uint32)regs->mIntRegs.esp, (uint32)regs->mIntRegs.ebp,
  5783. (uint32)regs->mIntRegs.eip, (uint32)regs->mIntRegs.efl);
  5784. }
  5785. else
  5786. {
  5787. headerStr = "IREGS";
  5788. }
  5789. 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());
  5790. #else
  5791. String headerStr;
  5792. if (optEvaluator)
  5793. {
  5794. CPURegisters* regs = optEvaluator->GetRegisters();
  5795. 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)",
  5796. (uint64)regs->mIntRegs.rax, (uint64)regs->mIntRegs.rbx, (uint64)regs->mIntRegs.rcx, (uint64)regs->mIntRegs.rdx,
  5797. (uint64)regs->mIntRegs.rsi, (uint64)regs->mIntRegs.rdi, (uint64)regs->mIntRegs.rsp, (uint64)regs->mIntRegs.rbp,
  5798. (uint64)regs->mIntRegs.rip,
  5799. (uint64)regs->mIntRegs.r8, (uint64)regs->mIntRegs.r9, (uint64)regs->mIntRegs.r10, (uint64)regs->mIntRegs.r11,
  5800. (uint64)regs->mIntRegs.r12, (uint64)regs->mIntRegs.r13, (uint64)regs->mIntRegs.r14, (uint64)regs->mIntRegs.r15,
  5801. (uint32)regs->mIntRegs.efl);
  5802. }
  5803. else
  5804. {
  5805. headerStr = "IREGS";
  5806. }
  5807. 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());
  5808. #endif
  5809. }
  5810. break;
  5811. case CPUReg_CAT_FPREGS:
  5812. {
  5813. String headerStr;
  5814. if (optEvaluator)
  5815. {
  5816. CPURegisters* regs = optEvaluator->GetRegisters();
  5817. headerStr = "(";
  5818. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  5819. {
  5820. if (i)
  5821. headerStr += ", ";
  5822. double val = ConvertFloat80ToDouble(regs->mFpMmRegsArray[i].fp.fp80);
  5823. headerStr += StrFormat("%f", val);
  5824. }
  5825. headerStr += ")";
  5826. }
  5827. else
  5828. {
  5829. headerStr = "FPREGS";
  5830. }
  5831. result = StrFormat("%s\n__fpregs", headerStr.c_str());
  5832. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  5833. result += StrFormat("\n[%d]\t$st%d", i, i);
  5834. return result;
  5835. }
  5836. break;
  5837. case CPUReg_CAT_MMREGS:
  5838. {
  5839. String headerStr;
  5840. if (optEvaluator)
  5841. {
  5842. CPURegisters* regs = optEvaluator->GetRegisters();
  5843. headerStr = "(";
  5844. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  5845. {
  5846. if (i)
  5847. headerStr += ", ";
  5848. uint64 val = regs->mFpMmRegsArray[i].mm;
  5849. headerStr += StrFormat("0x%016llx", val);
  5850. }
  5851. headerStr += ")";
  5852. }
  5853. else
  5854. {
  5855. headerStr = "MMREGS";
  5856. }
  5857. result = StrFormat("%s\n__mmregs", headerStr.c_str());
  5858. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  5859. result += StrFormat("\n[%d]\t$mm%d", i, i);
  5860. return result;
  5861. }
  5862. break;
  5863. case CPUReg_CAT_XMMREGS:
  5864. {
  5865. String headerStr = StrFormat("XMMREGS[%d]", CPURegisters::kNumXmmRegs); // these are too big to put a useful header for the entire category
  5866. result = StrFormat("%s\n__xmmregs", headerStr.c_str());
  5867. for (int i = 0; i < CPURegisters::kNumXmmRegs; ++i)
  5868. result += StrFormat("\n[%d]\t$xmm%d", i, i);
  5869. return result;
  5870. }
  5871. break;
  5872. case CPUReg_CAT_FLAGS:
  5873. {
  5874. String headerStr;
  5875. if (optEvaluator)
  5876. {
  5877. CPURegisters* regs = optEvaluator->GetRegisters();
  5878. #ifdef BF_DBG_32
  5879. #define FLAGVAR(abbr, name) int flag##abbr = ((regs->mIntRegs.efl & ((uint64)1 << CPURegisters::GetFlagBitForRegister(X86Reg_FLAG_##abbr##_##name))) != 0) ? 1 : 0
  5880. FLAGVAR(CF, CARRY);
  5881. FLAGVAR(PF, PARITY);
  5882. FLAGVAR(AF, ADJUST);
  5883. FLAGVAR(ZF, ZERO);
  5884. FLAGVAR(SF, SIGN);
  5885. FLAGVAR(IF, INTERRUPT);
  5886. FLAGVAR(DF, DIRECTION);
  5887. FLAGVAR(OF, OVERFLOW);
  5888. #undef FLAGVAR
  5889. #else
  5890. #define FLAGVAR(abbr, name) int flag##abbr = ((regs->mIntRegs.efl & ((uint64)1 << CPURegisters::GetFlagBitForRegister(X64Reg_FLAG_##abbr##_##name))) != 0) ? 1 : 0
  5891. FLAGVAR(CF, CARRY);
  5892. FLAGVAR(PF, PARITY);
  5893. FLAGVAR(AF, ADJUST);
  5894. FLAGVAR(ZF, ZERO);
  5895. FLAGVAR(SF, SIGN);
  5896. FLAGVAR(IF, INTERRUPT);
  5897. FLAGVAR(DF, DIRECTION);
  5898. FLAGVAR(OF, OVERFLOW);
  5899. #undef FLAGVAR
  5900. #endif
  5901. headerStr = StrFormat("(CF=%d, PF=%d, AF=%d, ZF=%d, SF=%d, IF=%d, DF=%d, OF=%d)",
  5902. flagCF, flagPF, flagAF, flagZF, flagSF, flagIF, flagDF, flagOF);
  5903. }
  5904. else
  5905. {
  5906. headerStr = "FLAGS";
  5907. }
  5908. 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",
  5909. headerStr.c_str());
  5910. }
  5911. break;
  5912. default:
  5913. BF_ASSERT(false && "unknown category register");
  5914. return "UNKNOWNCATEGORY\n__unknown\n";
  5915. }
  5916. }
  5917. }
  5918. break;
  5919. case DbgType_Single:
  5920. {
  5921. ExactMinimalFloatToStr(typedValue.mSingle, str);
  5922. return StrFormat("%s\n%s", str, WrapWithModifiers("float", origValueType, language).c_str());
  5923. }
  5924. case DbgType_Double:
  5925. ExactMinimalDoubleToStr(typedValue.mDouble, str);
  5926. return StrFormat("%s\n%s", str, WrapWithModifiers("double", origValueType, language).c_str());
  5927. case DbgType_Subroutine:
  5928. if (typedValue.mCharPtr != NULL)
  5929. return StrFormat("%s\nfunc", typedValue.mCharPtr);
  5930. else
  5931. return "\nfunc";
  5932. case DbgType_RawText:
  5933. return StrFormat("%s\nrawtext", typedValue.mCharPtr);
  5934. case DbgType_Ptr:
  5935. {
  5936. addr_target ptrVal = (addr_target)typedValue.mPtr;
  5937. String retVal;
  5938. DbgType* innerType = dwValueType->mTypeParam;
  5939. if (innerType == NULL)
  5940. return EncodeDataPtr(ptrVal, true) + "\nvoid*";
  5941. bool isChar = false;
  5942. DbgType* unmodInnerType = innerType->RemoveModifiers();
  5943. if (unmodInnerType != NULL)
  5944. {
  5945. if (language == DbgLanguage_Beef)
  5946. {
  5947. if ((unmodInnerType->mTypeCode == DbgType_UChar) ||
  5948. (unmodInnerType->mTypeCode == DbgType_UChar16) ||
  5949. (unmodInnerType->mTypeCode == DbgType_UChar32))
  5950. isChar = true;
  5951. }
  5952. else
  5953. {
  5954. if ((unmodInnerType->mTypeCode == DbgType_SChar) ||
  5955. (unmodInnerType->mTypeCode == DbgType_SChar16) ||
  5956. (unmodInnerType->mTypeCode == DbgType_SChar32))
  5957. isChar = true;
  5958. }
  5959. }
  5960. if ((isChar) && (formatInfo.mArrayLength == -1))
  5961. {
  5962. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  5963. retVal = EncodeDataPtr(ptrVal, true);
  5964. String strResult = ReadString(unmodInnerType->mTypeCode, typedValue.mLocalIntPtr, typedValue.mIsLiteral, typedValue.mIsLiteral ? strlen(typedValue.mCharPtr) : -1, formatInfo);
  5965. if (formatInfo.mRawString)
  5966. return strResult;
  5967. if (!strResult.IsEmpty())
  5968. {
  5969. if (!retVal.IsEmpty())
  5970. retVal += " ";
  5971. retVal += strResult;
  5972. }
  5973. retVal += "\n" + origValueType->ToString(language);
  5974. return retVal;
  5975. }
  5976. else if ((unmodInnerType != NULL) &&
  5977. ((unmodInnerType->mTypeCode == DbgType_Class) || (unmodInnerType->mTypeCode == DbgType_Struct) || (unmodInnerType->mTypeCode == DbgType_Union)))
  5978. {
  5979. isCompositeType = true;
  5980. }
  5981. else if ((unmodInnerType != NULL) && (unmodInnerType->mTypeCode == DbgType_SizedArray))
  5982. {
  5983. isSizedArray = true;
  5984. }
  5985. else if (unmodInnerType->mTypeCode == DbgType_Subroutine)
  5986. {
  5987. if (formatInfo.mRawString)
  5988. return "";
  5989. addr_target funcPtr = (addr_target)typedValue.mPtr;
  5990. String retVal;
  5991. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  5992. retVal = EncodeDataPtr(funcPtr, true);
  5993. String symbolName;
  5994. addr_target offset;
  5995. DbgModule* dwarf;
  5996. static String demangledName;
  5997. auto subProgram = mDebugTarget->FindSubProgram(funcPtr);
  5998. if (subProgram != NULL)
  5999. {
  6000. demangledName = subProgram->ToString();
  6001. }
  6002. else if (mDebugTarget->FindSymbolAt(funcPtr, &symbolName, &offset, &dwarf))
  6003. {
  6004. demangledName = BfDemangler::Demangle(symbolName, language);
  6005. if (offset != 0)
  6006. demangledName += StrFormat("+%d", offset);
  6007. }
  6008. else
  6009. {
  6010. auto dbgModule = mDebugTarget->FindDbgModuleForAddress(funcPtr);
  6011. if (dbgModule != NULL)
  6012. demangledName += dbgModule->mDisplayName + "!";
  6013. demangledName += StrFormat("0x%@", funcPtr);
  6014. }
  6015. retVal += " {";
  6016. retVal += demangledName;
  6017. retVal += "}";
  6018. retVal += "\n" + origValueType->ToString(language);
  6019. return retVal;
  6020. }
  6021. else if (unmodInnerType->mTypeCode == DbgType_Void)
  6022. {
  6023. if (formatInfo.mRawString)
  6024. return "";
  6025. addr_target ptr = (addr_target)typedValue.mPtr;
  6026. String symbolName;
  6027. addr_target offset;
  6028. DbgModule* dwarf;
  6029. String demangledName;
  6030. retVal += demangledName = StrFormat("0x%@", ptr);
  6031. if (mDebugTarget->FindSymbolAt(ptr, &symbolName, &offset, &dwarf))
  6032. {
  6033. if (offset == 0)
  6034. {
  6035. retVal += " {";
  6036. retVal += BfDemangler::Demangle(symbolName, language);
  6037. retVal += "}";
  6038. }
  6039. }
  6040. retVal += "\n" + origValueType->ToString(language);
  6041. return retVal;
  6042. }
  6043. else
  6044. {
  6045. if (formatInfo.mRawString)
  6046. return "";
  6047. addr_target ptrVal = (addr_target)typedValue.mPtr;
  6048. String retVal;
  6049. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6050. retVal = EncodeDataPtr(ptrVal, true);
  6051. if (ptrVal != 0)
  6052. {
  6053. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, NULL, -1, -1);
  6054. DbgTypedValue innerTypedVal = dbgExprEvaluator.ReadTypedValue(innerType, typedValue.mPtr, DbgAddrType_Target);
  6055. if (innerTypedVal)
  6056. {
  6057. DwFormatInfo defaultFormatInfo;
  6058. defaultFormatInfo.mLanguage = formatInfo.mLanguage;
  6059. defaultFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + 2; // Take into accout the necessary {}'s
  6060. defaultFormatInfo.mExpandItemDepth++;
  6061. String innerStr = DbgTypedValueToString(innerTypedVal, "", defaultFormatInfo, &dbgExprEvaluator);
  6062. int crIdx = innerStr.IndexOf('\n');
  6063. if (crIdx != -1)
  6064. {
  6065. String innerDataStr = innerStr.Substring(0, crIdx);
  6066. if (!innerDataStr.empty())
  6067. {
  6068. if (!retVal.empty())
  6069. retVal += " ";
  6070. retVal += "{" + innerDataStr + "}";
  6071. }
  6072. }
  6073. else
  6074. {
  6075. retVal += "{ ??? }";
  6076. }
  6077. }
  6078. }
  6079. retVal += "\n" + origValueType->ToString(language);
  6080. innerType->PopulateType();
  6081. if ((ptrVal != 0) &&
  6082. ((!innerType->mMemberList.IsEmpty()) || (innerType->mSize > 0) || (innerType->mTypeParam != NULL)))
  6083. {
  6084. String ptrDataStr = StrFormat("(%s)", dwValueType->ToStringRaw(language).c_str()) + EncodeDataPtr(typedValue.mPtr, true);
  6085. retVal += "\n*\t";
  6086. // Why did we have this? It messed up a pointer to sized array
  6087. /*if (language == DbgLanguage_Beef)
  6088. retVal += "this";
  6089. else*/
  6090. retVal += "*this";
  6091. if (!formatInfo.mReferenceId.empty())
  6092. retVal += ", refid=" + MaybeQuoteFormatInfoParam(formatInfo.mReferenceId);
  6093. retVal += ", this=" + ptrDataStr;
  6094. }
  6095. return retVal;
  6096. }
  6097. break;
  6098. }
  6099. case DbgType_Union:
  6100. case DbgType_Class:
  6101. case DbgType_Struct:
  6102. isCompositeType = true;
  6103. break;
  6104. case DbgType_Enum:
  6105. enumVal = typedValue.GetInt64();
  6106. isEnum = true;
  6107. break;
  6108. case DbgType_SizedArray:
  6109. {
  6110. isSizedArray = true;
  6111. }
  6112. break;
  6113. default:
  6114. break;
  6115. }
  6116. if (isSizedArray)
  6117. {
  6118. String retVal;
  6119. addr_target ptrVal = 0;
  6120. DbgType* arrayType = dwValueType;
  6121. DbgType* innerType = dwValueType->mTypeParam;
  6122. if (dwValueType->mTypeCode == DbgType_SizedArray)
  6123. {
  6124. ptrVal = (addr_target)typedValue.mSrcAddress;
  6125. }
  6126. else
  6127. {
  6128. BF_ASSERT(dwValueType->mTypeCode == DbgType_Ptr);
  6129. arrayType = innerType;
  6130. innerType = arrayType->mTypeParam;
  6131. ptrVal = typedValue.mPtr;
  6132. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6133. retVal = EncodeDataPtr(ptrVal, true) + " ";
  6134. }
  6135. if (ptrVal == 0)
  6136. ptrVal = typedValue.mPtr;
  6137. int arraySize = 0;
  6138. int innerSize = innerType->GetStride();
  6139. if (innerSize > 0)
  6140. arraySize = arrayType->GetStride() / innerSize;
  6141. else
  6142. {
  6143. // Failure!
  6144. }
  6145. String idxStr = "[{0}]";
  6146. if (innerType->IsChar(language))
  6147. {
  6148. String strVal = ReadString(innerType->mTypeCode, typedValue.mSrcAddress, false, arraySize, formatInfo);
  6149. if (formatInfo.mRawString)
  6150. return strVal;
  6151. retVal += strVal;
  6152. }
  6153. else
  6154. {
  6155. if (formatInfo.mRawString)
  6156. return "";
  6157. _ShowArraySummary(retVal, ptrVal, arraySize, innerType);
  6158. }
  6159. retVal += "\n" + origValueType->ToString(language);
  6160. String referenceId = dwValueType->ToString(language);
  6161. String evalStr;
  6162. // Why did we have the "na"? Do we not want to show addresses for all members?
  6163. //evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + ")[{0}], na, refid=" + referenceId + ".[]";
  6164. evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + ")[{0}], refid=" + MaybeQuoteFormatInfoParam(referenceId + ".[]");
  6165. if (typedValue.mIsReadOnly)
  6166. evalStr += ", ne";
  6167. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)BF_MAX(arraySize, 0), 10000) +
  6168. "\t" + idxStr + "\t" + evalStr;
  6169. return retVal;
  6170. }
  6171. dwValueType->PopulateType();
  6172. if (isEnum)
  6173. {
  6174. String retVal;
  6175. int64 bitsLeft = enumVal;
  6176. int valueCount = 0;
  6177. String editVal;
  6178. dwValueType = dwValueType->GetPrimaryType();
  6179. dwValueType->PopulateType();
  6180. while ((bitsLeft != 0) || (valueCount == 0))
  6181. {
  6182. DbgVariable* bestMatch = NULL;
  6183. for (auto member : dwValueType->mMemberList)
  6184. {
  6185. if (member->mConstValue == bitsLeft)
  6186. {
  6187. bestMatch = member;
  6188. break;
  6189. }
  6190. }
  6191. if (bestMatch == NULL)
  6192. {
  6193. for (auto member : dwValueType->mMemberList)
  6194. {
  6195. if ((member->mConstValue != 0) &&
  6196. ((member->mConstValue & bitsLeft) == member->mConstValue))
  6197. {
  6198. bestMatch = member;
  6199. break;
  6200. }
  6201. }
  6202. }
  6203. if (bestMatch == NULL)
  6204. break;
  6205. if (valueCount > 0)
  6206. {
  6207. retVal += " | ";
  6208. if (language == DbgLanguage_C)
  6209. editVal += " | ";
  6210. }
  6211. if (language == DbgLanguage_Beef)
  6212. retVal += ".";
  6213. retVal += bestMatch->mName;
  6214. if (language == DbgLanguage_C)
  6215. {
  6216. if (dwValueType->mParent != NULL)
  6217. {
  6218. editVal += dwValueType->mParent->ToString(language);
  6219. editVal += "::";
  6220. }
  6221. editVal += bestMatch->mName;
  6222. }
  6223. valueCount++;
  6224. bitsLeft &= ~bestMatch->mConstValue;
  6225. }
  6226. if ((valueCount == 0) || (bitsLeft != 0))
  6227. {
  6228. if (valueCount > 0)
  6229. retVal += " | ";
  6230. retVal += StrFormat("%d", bitsLeft);
  6231. if (language == DbgLanguage_C)
  6232. {
  6233. if (valueCount > 0)
  6234. editVal += " | ";
  6235. editVal += StrFormat("%d", bitsLeft);
  6236. }
  6237. }
  6238. retVal += "\n" + origValueType->ToString();
  6239. if (language == DbgLanguage_C)
  6240. {
  6241. retVal += "\n:editVal\t";
  6242. retVal += editVal;
  6243. }
  6244. retVal += "\n:canEdit";
  6245. return retVal;
  6246. }
  6247. else if (isCompositeType)
  6248. {
  6249. addr_target ptrVal;
  6250. if (dwValueType->IsPointer())
  6251. ptrVal = (addr_target)typedValue.mPtr;
  6252. else
  6253. ptrVal = (addr_target)typedValue.mSrcAddress;
  6254. String retVal;
  6255. if ((!typedValue.mIsLiteral) && (dwValueType->IsPointer()) &&
  6256. ((!formatInfo.mHidePointers) || (ptrVal == 0)))
  6257. retVal = EncodeDataPtr(ptrVal, true);
  6258. DbgType* innerType = dwValueType;
  6259. bool wasPtr = false;
  6260. if (innerType->mTypeCode == DbgType_Ptr)
  6261. {
  6262. wasPtr = true;
  6263. innerType = dwValueType->mTypeParam;
  6264. innerType = innerType->RemoveModifiers();
  6265. }
  6266. innerType = innerType->GetPrimaryType();
  6267. addr_target dataPtr = wasPtr ? typedValue.mPtr : typedValue.mSrcAddress;
  6268. DbgType* actualType = NULL;
  6269. bool useActualRawType = false;
  6270. bool isBfObject = innerType->IsBfObject();
  6271. bool hasCPPVTable = false;
  6272. if (!isBfObject)
  6273. hasCPPVTable = innerType->HasCPPVTable();
  6274. int bfObjectFlags = 0;
  6275. addr_target classVDataPtr = 0;
  6276. bool isAppendBfObject = false;
  6277. bool isStackBfObject = false;
  6278. bool isDeletedBfObject = false;
  6279. bool isCompositeWithoutAddress = false;
  6280. if (innerType->IsBfPayloadEnum())
  6281. {
  6282. if (formatInfo.mRawString)
  6283. return "";
  6284. auto tagMember = innerType->mMemberList.mTail;
  6285. int tagIdx = 0;
  6286. if (dataPtr == -1)
  6287. {
  6288. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, "(int)" + expr, &formatInfo);
  6289. auto dscValue = dbgEvaluationContext.EvaluateInContext(DbgTypedValue());
  6290. tagIdx = dscValue.mInt32;
  6291. }
  6292. else if (!ReadMemory((intptr)ptrVal + tagMember->mMemberOffset, tagMember->mType->mSize, (void*)&tagIdx))
  6293. {
  6294. return StrFormat("!Failed to read from 0x%@", ptrVal);
  6295. }
  6296. char findStr[16];
  6297. findStr[0] = '_';
  6298. itoa(tagIdx, findStr + 1, 10);
  6299. int len = strlen(findStr);
  6300. findStr[len] = '_';
  6301. len++;
  6302. if (!retVal.empty())
  6303. retVal += " ";
  6304. int startIdx = 0;
  6305. for (auto member : innerType->mMemberList)
  6306. {
  6307. if (strncmp(member->mName, findStr, len) == 0)
  6308. {
  6309. retVal += ".";
  6310. retVal += member->mName + len;
  6311. String tupleExpr;
  6312. DbgTypedValue tupleVal;
  6313. if (dataPtr == -1)
  6314. {
  6315. tupleVal.mSrcAddress = -1;
  6316. tupleVal.mType = member->mType;
  6317. //tupleExpr = "$" + expr + "$u";
  6318. tupleVal.mVariable = typedValue.mVariable;
  6319. tupleExpr = "(" + member->mType->ToStringRaw() + ")(" + expr + ")";
  6320. }
  6321. else
  6322. {
  6323. tupleVal.mType = member->mType;
  6324. tupleVal.mSrcAddress = ptrVal;
  6325. }
  6326. DwFormatInfo displayStrFormatInfo = formatInfo;
  6327. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + (int)retVal.length();
  6328. displayStrFormatInfo.mExpandItemDepth++;
  6329. displayStrFormatInfo.mHidePointers = false;
  6330. retVal += DbgTypedValueToString(tupleVal, tupleExpr, displayStrFormatInfo, NULL);
  6331. int idx = (int)retVal.IndexOf('\n');
  6332. if (idx != -1)
  6333. {
  6334. String typeName = innerType->ToString(DbgLanguage_Unknown, true);
  6335. typeName += " ";
  6336. retVal.Insert(idx + 1, typeName);
  6337. }
  6338. return retVal;
  6339. }
  6340. }
  6341. }
  6342. if (isBfObject)
  6343. {
  6344. classVDataPtr = ReadMemory<addr_target>(ptrVal);
  6345. mDebugTarget->GetCompilerSettings();
  6346. if (mDebugTarget->mBfObjectHasFlags)
  6347. {
  6348. bfObjectFlags = ((int)classVDataPtr) & 0xFF;
  6349. //TODO: Only do this in debug?
  6350. if (bfObjectFlags & BfObjectFlag_Deleted)
  6351. isDeletedBfObject = true;
  6352. if (bfObjectFlags & BfObjectFlag_AppendAlloc)
  6353. isAppendBfObject = true;
  6354. if (bfObjectFlags & BfObjectFlag_StackAlloc)
  6355. isStackBfObject = true;
  6356. classVDataPtr &= ~0xFF;
  6357. }
  6358. }
  6359. if (!formatInfo.mIgnoreDerivedClassInfo)
  6360. {
  6361. if (isBfObject)
  6362. {
  6363. dbgModule->ParseSymbolData();
  6364. String symbolName;
  6365. addr_target symOffset;
  6366. if ((mDebugTarget->FindSymbolAt(classVDataPtr, &symbolName, &symOffset)) && (symOffset < 0x100))
  6367. {
  6368. String mangledClassName;
  6369. const char* symEnd = "sBfClassVData";
  6370. int symEndLen = strlen(symEnd);
  6371. if (((int)symbolName.length() > symEndLen) && (strstr(symbolName.c_str(), symEnd) != NULL))
  6372. mangledClassName = symbolName;
  6373. // If we have flags then we may be pointing past the _typeData, actually. We could fix this by masking out
  6374. // the flags area, but we need to be sure we are running a build that supports flags
  6375. symEnd = "sBfTypeData";
  6376. symEndLen = strlen(symEnd);
  6377. if (((int) symbolName.length() > symEndLen) && (strstr(symbolName.c_str(), symEnd) != NULL))
  6378. mangledClassName = symbolName;
  6379. if (mangledClassName.length() > 0)
  6380. {
  6381. String className = BfDemangler::Demangle(mangledClassName, innerType->GetLanguage(), BfDemangler::Flag_RawDemangle);
  6382. for (int i = 0; i < className.length() - 3; i++)
  6383. {
  6384. if ((className[i] == 'b') &&
  6385. (className[i + 1] == 'f') &&
  6386. (className[i + 2] == '.'))
  6387. {
  6388. bool matches;
  6389. if (i == 0)
  6390. matches = true;
  6391. else
  6392. {
  6393. char prevC = className[i - 1];
  6394. if ((prevC == ' ') ||
  6395. (prevC == ',') ||
  6396. (prevC == '<'))
  6397. {
  6398. matches = true;
  6399. }
  6400. }
  6401. if (matches)
  6402. className.Remove(i, 3);
  6403. }
  6404. }
  6405. // if (className.StartsWith("bf."))
  6406. // className.Remove(0, 3);
  6407. // else if (className.StartsWith("Box<bf."))
  6408. // className.Remove(4, 3);
  6409. int lastDot = (int)className.LastIndexOf('.');
  6410. if (lastDot > 0)
  6411. className = className.Substring(0, lastDot);
  6412. const char* arrPrefix = "System.Array1<";
  6413. if (strncmp(className.c_str(), arrPrefix, strlen(arrPrefix)) == 0)
  6414. {
  6415. className = className.Substring(strlen(arrPrefix), className.length() - strlen(arrPrefix) - 1);
  6416. className += "[]";
  6417. }
  6418. auto typeEntry = dbgModule->GetLinkedModule()->mTypeMap.Find(className.c_str(), DbgLanguage_BeefUnfixed);
  6419. if (typeEntry != NULL)
  6420. {
  6421. actualType = typeEntry->mValue;
  6422. if (!actualType->IsBfObject())
  6423. {
  6424. if (actualType->mTypeCode == DbgType_Ptr)
  6425. {
  6426. actualType = actualType->mTypeParam;
  6427. }
  6428. }
  6429. }
  6430. }
  6431. }
  6432. }
  6433. else if (hasCPPVTable)
  6434. {
  6435. dbgModule->ParseSymbolData();
  6436. addr_target classVDataPtr = ReadMemory<addr_target>(ptrVal);
  6437. String symbolName;
  6438. addr_target offset = 0;
  6439. if (mDebugTarget->FindSymbolAt(classVDataPtr, &symbolName, &offset, NULL))
  6440. {
  6441. // On GNU, vtable indices can "go negative" for things like RTTI and virtual inheritance, so
  6442. // we can't rely on an exact vtable address lookup
  6443. if (offset < 0x200)
  6444. {
  6445. DbgLanguage lang = innerType->GetLanguage();
  6446. const char* symStart = (innerType->mCompileUnit->mDbgModule->mDbgFlavor == DbgFlavor_GNU) ? "_ZTV" : "??_7";
  6447. if (strncmp(symbolName.c_str(), symStart, strlen(symStart)) == 0)
  6448. {
  6449. //String mangledClassName = symbolName.Substring(1);
  6450. String className = BfDemangler::Demangle(symbolName, lang);
  6451. int vtableNameIdx = (int)className.IndexOf("::`vftable'");
  6452. if (vtableNameIdx != -1)
  6453. className = className.Substring(0, vtableNameIdx);
  6454. auto typeEntry = dbgModule->mTypeMap.Find(className.c_str(), DbgLanguage_C);
  6455. if (typeEntry != NULL)
  6456. {
  6457. actualType = typeEntry->mValue;
  6458. if ((int)className.IndexOf('<') != -1)
  6459. useActualRawType = true;
  6460. int thisOffset = 0;
  6461. if (!DbgExprEvaluator::TypeIsSubTypeOf(actualType, innerType, &thisOffset))
  6462. {
  6463. // This catches virtual inheritance cases where we can't downcast
  6464. actualType = NULL;
  6465. }
  6466. }
  6467. }
  6468. }
  6469. }
  6470. }
  6471. }
  6472. DbgType* displayType = origValueType;
  6473. String displayString;
  6474. bool wantsCustomExpandedItems = false;
  6475. DebugVisualizerEntry* debugVis = NULL;
  6476. Array<String> dbgVisWildcardCaptures;
  6477. DbgType* dwUseType = (actualType != NULL) ? actualType : innerType;
  6478. //auto ptrDataType = dwValueType;
  6479. //TODO: Changed this from the above to account for COFF types where 'this' is always a fwd reference, does this cause any issues?
  6480. auto ptrDataType = innerType;
  6481. String ptrDataStr;
  6482. if (/*(!innerType->IsBfObject()) &&*/ (!ptrDataType->IsPointer()))
  6483. {
  6484. if ((dataPtr != 0) || (ptrDataType->GetByteCount() > sizeof(addr_target)))
  6485. {
  6486. bool wantsRefThis = ptrDataType->WantsRefThis();
  6487. ptrDataType = ptrDataType->GetDbgModule()->GetPointerType(ptrDataType);
  6488. if (wantsRefThis)
  6489. ptrDataStr += "*";
  6490. }
  6491. else
  6492. {
  6493. // Data is inline - must be int-sized or less
  6494. isCompositeWithoutAddress = true;
  6495. dataPtr = typedValue.mPtr;
  6496. }
  6497. }
  6498. String ptrDataTypeStr = ptrDataType->ToStringRaw();
  6499. ptrDataStr += StrFormat("(%s)", ptrDataTypeStr.c_str()) + EncodeDataPtr(dataPtr, true);
  6500. DbgType* dwUsePtrType = dwUseType;
  6501. String ptrUseDataStr;
  6502. if (!dwUsePtrType->IsPointer())
  6503. {
  6504. bool wantsRefThis = dwUsePtrType->WantsRefThis();
  6505. dwUsePtrType = dwUsePtrType->GetDbgModule()->GetPointerType(dwUsePtrType);
  6506. if (wantsRefThis)
  6507. ptrUseDataStr += "*";
  6508. }
  6509. String ptrUseDataTypeStr = dwUsePtrType->ToStringRaw();
  6510. ptrUseDataStr += StrFormat("(%s)", ptrUseDataTypeStr.c_str()) + EncodeDataPtr(dataPtr, true);
  6511. if ((origTypedValue.mSrcAddress == -1) && (origTypedValue.mVariable != NULL))
  6512. {
  6513. ptrDataStr = origTypedValue.mVariable->mName;
  6514. if (!origTypedValue.mType->RemoveModifiers()->Equals(origTypedValue.mVariable->mType->RemoveModifiers()))
  6515. {
  6516. //ptrDataStr = StrFormat("(%s)%s", origTypedValue.mType->ToString().c_str(), origTypedValue.mVariable->mName);
  6517. ptrDataStr = expr;
  6518. }
  6519. ptrUseDataStr = ptrDataStr;
  6520. }
  6521. if ((ptrVal == 0) && (dwValueType->IsTypedPrimitive()))
  6522. {
  6523. DbgTypedValue rawVal;
  6524. rawVal.mInt64 = origTypedValue.mInt64;
  6525. rawVal.mType = dwValueType->GetRootBaseType();
  6526. ptrDataStr = "(" + dwUseType->ToStringRaw() + ")";
  6527. ptrDataStr += DbgTypedValueToString(rawVal, expr, formatInfo, optEvaluator, fullPrecision);
  6528. int editValIdx = ptrDataStr.IndexOf(":editVal");
  6529. if (editValIdx != -1)
  6530. ptrDataStr.Remove(0, editValIdx + 9);
  6531. int crPos = (int)ptrDataStr.IndexOf('\n');
  6532. if (crPos != -1)
  6533. ptrDataStr.RemoveToEnd(crPos);
  6534. ptrUseDataStr = ptrDataStr;
  6535. if ((origTypedValue.mRegNum != -1) && (!expr.IsEmpty()) && (!formatInfo.mExplicitThis))
  6536. {
  6537. // There's no address, use direct local identifier
  6538. ptrDataStr = expr;
  6539. ptrUseDataStr = expr;
  6540. }
  6541. }
  6542. else if ((ptrVal == 0) && (dwValueType->IsCompositeType()))
  6543. {
  6544. }
  6545. bool isNull = wasPtr && (dataPtr == 0);
  6546. bool isBadSrc = !wasPtr && (dataPtr == 0);
  6547. DbgTypedValue useTypedValue = typedValue;
  6548. if ((origHadRef) || ((typedValue.mType->HasPointer()) && (!dwUseType->HasPointer())))
  6549. {
  6550. useTypedValue.mSrcAddress = useTypedValue.mPtr;
  6551. useTypedValue.mPtr = 0;
  6552. if (dwUseType->IsTypedPrimitive())
  6553. {
  6554. int byteCount = dwUseType->GetByteCount();
  6555. if (byteCount <= sizeof(intptr))
  6556. {
  6557. ReadMemory(useTypedValue.mSrcAddress, byteCount, &useTypedValue.mPtr);
  6558. }
  6559. }
  6560. }
  6561. useTypedValue.mType = dwUseType;
  6562. if ((!formatInfo.mNoVisualizers) && (!isNull) && (!isBadSrc))
  6563. {
  6564. if (language == DbgLanguage_Beef)
  6565. dwUseType->FixName();
  6566. debugVis = FindVisualizerForType(dwUseType, &dbgVisWildcardCaptures);
  6567. // for (auto& wildcardCapture : dbgVisWildcardCaptures)
  6568. // {
  6569. // if (wildcardCapture.StartsWith("`"))
  6570. // {
  6571. // dwUseType->PopulateType();
  6572. // auto entry = dbgModule->mTypeMap.Find(wildcardCapture.c_str(), language);
  6573. // if (entry != NULL)
  6574. // {
  6575. // //wildcardCapture = entry->mValue->ToStringRaw(language);
  6576. // }
  6577. // }
  6578. // }
  6579. }
  6580. bool hadCustomDisplayString = false;
  6581. if (debugVis != NULL)
  6582. {
  6583. auto& displayStringList = formatInfo.mRawString ? debugVis->mStringViews : debugVis->mDisplayStrings;
  6584. for (auto displayEntry : displayStringList)
  6585. {
  6586. if (!displayEntry->mCondition.empty())
  6587. {
  6588. if (!EvalCondition(debugVis, dbgCompileUnit, useTypedValue, formatInfo, displayEntry->mCondition, dbgVisWildcardCaptures, displayString))
  6589. continue;
  6590. }
  6591. hadCustomDisplayString = true;
  6592. String displayStr = mDebugManager->mDebugVisualizers->DoStringReplace(displayEntry->mString, dbgVisWildcardCaptures);
  6593. if (displayString.length() > 0)
  6594. displayString += " ";
  6595. ProcessEvalString(dbgCompileUnit, useTypedValue, displayStr, displayString, formatInfo, debugVis, true);
  6596. if (formatInfo.mRawString)
  6597. return displayString;
  6598. break;
  6599. }
  6600. if ((!debugVis->mExpandItems.empty()) || (debugVis->mCollectionType != DebugVisualizerEntry::CollectionType_None))
  6601. {
  6602. wantsCustomExpandedItems = true;
  6603. }
  6604. }
  6605. if (formatInfo.mRawString)
  6606. return "";
  6607. bool isTuple = (dwUseType->mName != NULL) && (dwUseType->mName[0] == '(') && (language == DbgLanguage_Beef);
  6608. if (isBadSrc)
  6609. {
  6610. displayString += "<null parent>";
  6611. }
  6612. else if ((!isNull) && (!formatInfo.mNoVisualizers) && (!hadCustomDisplayString))
  6613. {
  6614. // Create our own custom display
  6615. String firstRet;
  6616. String bigRet = isTuple ? "(" : "{ ";
  6617. int memberIdx = 0;
  6618. DbgType* summaryType = dwUseType;
  6619. bool summaryDone = false;
  6620. bool truncatedMemberList = false;
  6621. DbgTypedValue summaryTypedValue = useTypedValue;
  6622. String summaryDataStr = ptrDataStr;
  6623. String splatStr;
  6624. if (dataPtr == -1)
  6625. splatStr = expr;
  6626. while (summaryType != NULL)
  6627. {
  6628. summaryType->PopulateType();
  6629. if (summaryType->IsPrimitiveType())
  6630. {
  6631. if (formatInfo.mTotalSummaryLength + (int)displayString.length() > 255)
  6632. {
  6633. truncatedMemberList = true;
  6634. summaryDone = true;
  6635. bigRet += "...";
  6636. }
  6637. else
  6638. {
  6639. DwFormatInfo displayStrFormatInfo = formatInfo;
  6640. displayStrFormatInfo.mExpandItemDepth = 1;
  6641. displayStrFormatInfo.mTotalSummaryLength += (int)displayString.length();
  6642. displayStrFormatInfo.mHidePointers = false;
  6643. auto primType = dwUseType->GetDbgModule()->GetPrimitiveType(summaryType->mTypeCode, dwUseType->GetLanguage());
  6644. String result;
  6645. if ((dataPtr != 0) && (dataPtr != -1))
  6646. {
  6647. String evalString = "(" + primType->ToString() + ")" + ptrDataStr;
  6648. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, origTypedValue, evalString, &displayStrFormatInfo);
  6649. if (evalResult)
  6650. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  6651. }
  6652. else
  6653. {
  6654. DbgTypedValue evalResult = origTypedValue;
  6655. evalResult.mType = primType;
  6656. String evalString = "(" + primType->ToString() + ")" + expr;
  6657. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  6658. }
  6659. if (formatInfo.mRawString)
  6660. return result;
  6661. int crPos = result.IndexOf('\n');
  6662. if (crPos != -1)
  6663. result.RemoveToEnd(crPos);
  6664. if (memberIdx == 0)
  6665. firstRet = result;
  6666. bigRet += result;
  6667. memberIdx++;
  6668. }
  6669. }
  6670. for (auto member : summaryType->mMemberList)
  6671. {
  6672. if (!member->mIsStatic)
  6673. {
  6674. if (formatInfo.mTotalSummaryLength + retVal.length() + bigRet.length() > 255)
  6675. {
  6676. truncatedMemberList = true;
  6677. summaryDone = true;
  6678. bigRet += "...";
  6679. break;
  6680. }
  6681. if (member->mName != NULL)
  6682. {
  6683. if (!isdigit(*member->mName))
  6684. {
  6685. if (memberIdx != 0)
  6686. bigRet += isTuple ? ", " : " ";
  6687. if ((!isTuple) || (member->mName[0] != '_'))
  6688. {
  6689. bigRet += String(member->mName);
  6690. bigRet += isTuple ? ":" : "=";
  6691. }
  6692. }
  6693. else
  6694. {
  6695. if (memberIdx != 0)
  6696. bigRet += ", ";
  6697. }
  6698. DwFormatInfo displayStrFormatInfo = formatInfo;
  6699. displayStrFormatInfo.mExpandItemDepth = 1;
  6700. displayStrFormatInfo.mHidePointers = false;
  6701. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + retVal.length() + bigRet.length();
  6702. String evalString;
  6703. if (dataPtr != -1)
  6704. {
  6705. if ((member->mName[0] >= '0') && (member->mName[0] <= '9'))
  6706. evalString += "this.";
  6707. evalString += String(member->mName); // +", this=" + summaryDataStr;
  6708. }
  6709. else
  6710. {
  6711. evalString = "(";
  6712. evalString += splatStr;
  6713. evalString += ").";
  6714. evalString += member->mName;
  6715. }
  6716. String referenceId;
  6717. String result;
  6718. if (!member->mType->IsValuelessType())
  6719. {
  6720. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, summaryTypedValue, evalString, &displayStrFormatInfo, &referenceId);
  6721. if (evalResult)
  6722. {
  6723. displayStrFormatInfo.mReferenceId = referenceId;
  6724. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  6725. int crPos = result.IndexOf('\n');
  6726. if (crPos != -1)
  6727. result.RemoveToEnd(crPos);
  6728. }
  6729. else
  6730. result = "???";
  6731. }
  6732. if (formatInfo.mRawString)
  6733. return result;
  6734. if (memberIdx == 0)
  6735. firstRet = result;
  6736. bigRet += result;
  6737. //formatInfo.mEmbeddedDisplayCount = displayStrFormatInfo.mEmbeddedDisplayCount;
  6738. memberIdx++;
  6739. }
  6740. else
  6741. {
  6742. //TODO: Handle C++ unions?
  6743. }
  6744. }
  6745. }
  6746. if (truncatedMemberList)
  6747. break;
  6748. // Find first base class with members
  6749. DbgType* nextSummaryType = NULL;
  6750. for (auto checkBase : summaryType->mBaseTypes)
  6751. {
  6752. auto checkBaseType = checkBase->mBaseType;
  6753. checkBaseType = checkBaseType->GetPrimaryType();
  6754. checkBaseType->PopulateType();
  6755. if ((checkBaseType->GetByteCount() > 0) || (checkBaseType->IsPrimitiveType()))
  6756. {
  6757. if (!splatStr.empty())
  6758. {
  6759. splatStr = "(" + checkBaseType->ToString() + ")" + splatStr;
  6760. }
  6761. else
  6762. {
  6763. summaryTypedValue.mType = checkBaseType;
  6764. }
  6765. nextSummaryType = checkBaseType;
  6766. break;
  6767. }
  6768. }
  6769. summaryType = nextSummaryType;
  6770. if (summaryType == NULL)
  6771. break;
  6772. // Don't add the Object members
  6773. if ((summaryType->GetBaseType() == NULL) && (summaryType->IsBfObject()))
  6774. break;
  6775. // If we don't have many members then find a base class with some members to show
  6776. if ((memberIdx != 0) && (displayString.length() >= 255))
  6777. {
  6778. truncatedMemberList = true;
  6779. bigRet += "...";
  6780. break;
  6781. }
  6782. }
  6783. bigRet += isTuple ? ")" : " }";
  6784. if (displayString.length() > 0)
  6785. displayString += " ";
  6786. if ((memberIdx == 1) && (!truncatedMemberList) && (firstRet.IndexOf('{') == -1) && (!isTuple))
  6787. displayString += "{ " + firstRet + " }";
  6788. else
  6789. displayString += bigRet;
  6790. }
  6791. DbgType* memberListType = actualType;
  6792. bool memberListForceCast = false;
  6793. if (actualType != NULL)
  6794. {
  6795. String valTypeName = displayType->ToString();
  6796. String actualTypeName = actualType->ToString(DbgLanguage_Unknown, true);
  6797. String actualUseTypeName = actualTypeName;
  6798. if ((int)actualTypeName.IndexOf('^') != -1)
  6799. useActualRawType = true;
  6800. if (useActualRawType)
  6801. actualUseTypeName = actualType->ToStringRaw();
  6802. if (displayString.empty())
  6803. {
  6804. // Nothing to display
  6805. }
  6806. else
  6807. {
  6808. if (!retVal.empty())
  6809. retVal += " ";
  6810. retVal += displayString;
  6811. }
  6812. retVal += "\n" + valTypeName;
  6813. if ((innerType->IsBaseBfObject()) || (innerType->IsInterface()))
  6814. {
  6815. if (actualType != innerType)
  6816. {
  6817. retVal += " {" + actualTypeName + "}";
  6818. memberListForceCast = true;
  6819. }
  6820. }
  6821. else
  6822. {
  6823. if (actualType != innerType)
  6824. {
  6825. retVal += " {" + actualTypeName + "}";
  6826. retVal += "\n";
  6827. if (!wantsCustomExpandedItems)
  6828. {
  6829. retVal += "[" + actualTypeName + "]\t((" + actualUseTypeName;
  6830. if (!actualType->IsBfObject())
  6831. retVal += "*";
  6832. retVal += ")this), nd, na, nv, this=" + ptrDataStr;
  6833. memberListType = innerType;
  6834. }
  6835. }
  6836. }
  6837. }
  6838. else
  6839. {
  6840. if ((formatInfo.mHidePointers) && (formatInfo.mIgnoreDerivedClassInfo))
  6841. {
  6842. displayType = innerType;
  6843. if (displayString.empty())
  6844. retVal += displayType->ToString(DbgLanguage_Unknown, true);
  6845. }
  6846. if (!displayString.empty())
  6847. {
  6848. if (!retVal.empty())
  6849. retVal += " ";
  6850. retVal += displayString;
  6851. }
  6852. else
  6853. {
  6854. if (formatInfo.mRawString)
  6855. return "";
  6856. }
  6857. retVal += "\n" + displayType->ToString(DbgLanguage_Unknown, true);
  6858. memberListType = innerType;
  6859. }
  6860. if ((isBfObject) && (mDebugTarget->mBfObjectHasFlags) && (!formatInfo.mNoVisualizers) && (!formatInfo.mRawString))
  6861. {
  6862. int stackTraceLen = 1;
  6863. addr_target stackTraceAddr = ptrVal + sizeof(addr_target);
  6864. if ((bfObjectFlags & BfObjectFlag_AllocInfo) != 0)
  6865. {
  6866. addr_target objectSize = ReadMemory<addr_target>(ptrVal + sizeof(addr_target));
  6867. addr_target largeAllocInfo = ReadMemory<addr_target>(ptrVal + objectSize);
  6868. stackTraceLen = largeAllocInfo & 0xFFFF;
  6869. stackTraceAddr = ptrVal + objectSize + sizeof(addr_target);
  6870. }
  6871. else if ((bfObjectFlags & BfObjectFlag_AllocInfo_Short) != 0)
  6872. {
  6873. addr_target dbgAllocInfo = ReadMemory<addr_target>(ptrVal + sizeof(addr_target));
  6874. stackTraceLen = dbgAllocInfo & 0xFF;
  6875. stackTraceAddr = ptrVal + (dbgAllocInfo >> 16);
  6876. }
  6877. if (stackTraceLen == 1)
  6878. {
  6879. retVal += StrFormat("\n[AllocStackTrace]\t*(System.CallStackAddr*)%s, nm", EncodeDataPtr(stackTraceAddr, true).c_str());
  6880. }
  6881. else if (stackTraceLen > 0)
  6882. {
  6883. retVal += StrFormat("\n[AllocStackTrace]\t(System.CallStackAddr*)%s, %d, na", EncodeDataPtr(stackTraceAddr, true).c_str(), stackTraceLen);
  6884. }
  6885. }
  6886. retVal += StrFormat("\n:language\t%d", language);
  6887. if (formatInfo.mNoMembers)
  6888. {
  6889. //
  6890. }
  6891. else if (wantsCustomExpandedItems)
  6892. {
  6893. HandleCustomExpandedItems(retVal, dbgCompileUnit, debugVis, dwUseType, dwValueType, ptrUseDataStr, ptrDataStr, useTypedValue, dbgVisWildcardCaptures, formatInfo);
  6894. }
  6895. else if ((!isNull) && (!isBadSrc))
  6896. {
  6897. if (dataPtr == -1)
  6898. {
  6899. //String splatName = ((origTypedValue.mSrcAddress == -1) && (origTypedValue.mVariable != NULL)) ? origTypedValue.mVariable->mName : expr;
  6900. String splatName = expr;
  6901. retVal += "\n" + GetMemberList(memberListType, splatName, wasPtr, false, false, true, origTypedValue.mIsReadOnly);
  6902. }
  6903. else
  6904. {
  6905. retVal += "\n" + GetMemberList(memberListType, ptrDataStr, wasPtr, false, memberListForceCast, isCompositeWithoutAddress, origTypedValue.mIsReadOnly);
  6906. }
  6907. }
  6908. if (formatInfo.mExpandItemDepth > 0)
  6909. return retVal;
  6910. if (isAppendBfObject)
  6911. retVal += "\n:appendAlloc";
  6912. if (isStackBfObject)
  6913. retVal += "\n:stack";
  6914. if (isDeletedBfObject)
  6915. retVal += "\n:deleted";
  6916. if ((debugVis != NULL) && (!debugVis->mAction.empty()))
  6917. {
  6918. String rawActionStr = mDebugManager->mDebugVisualizers->DoStringReplace(debugVis->mAction, dbgVisWildcardCaptures);
  6919. String actionStr;
  6920. ProcessEvalString(dbgCompileUnit, useTypedValue, rawActionStr, actionStr, formatInfo, debugVis, true);
  6921. retVal += "\n:action\t" + actionStr;
  6922. }
  6923. if ((!typedValue.mIsLiteral) && (dwValueType->IsPointer()))
  6924. {
  6925. retVal += "\n:editVal\t" + EncodeDataPtr(ptrVal, true);
  6926. }
  6927. return retVal;
  6928. }
  6929. return "Unknown Type\n" + origValueType->ToString();
  6930. }
  6931. void WinDebugger::HandleCustomExpandedItems(String& retVal, DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgType* dwUseType, DbgType* dwValueType, String& ptrUseDataStr, String& ptrDataStr, DbgTypedValue useTypedValue, Array<String>& dbgVisWildcardCaptures, DwFormatInfo& formatInfo)
  6932. {
  6933. auto debugVisualizers = mDebugManager->mDebugVisualizers;
  6934. auto dbgModule = dbgCompileUnit->mDbgModule;
  6935. if (formatInfo.mExpandItemDepth > 10) // Avoid crashing on circular ExpandItems
  6936. return;
  6937. auto language = formatInfo.mLanguage;
  6938. bool isReadOnly = false;
  6939. if (useTypedValue.mIsReadOnly)
  6940. isReadOnly = true;
  6941. for (auto entry : debugVis->mExpandItems)
  6942. {
  6943. if (!entry->mCondition.empty())
  6944. {
  6945. String error;
  6946. if (!EvalCondition(debugVis, dbgCompileUnit, useTypedValue, formatInfo, entry->mCondition, dbgVisWildcardCaptures, error))
  6947. {
  6948. if (!error.empty())
  6949. retVal += "\n" + entry->mName + "\t@!<DbgVis Failed>@!";
  6950. continue;
  6951. }
  6952. }
  6953. String replacedStr = debugVisualizers->DoStringReplace(entry->mValue, dbgVisWildcardCaptures);
  6954. retVal += "\n" + entry->mName + "\t" + replacedStr + ", this=(" + ptrUseDataStr + ")";
  6955. }
  6956. String referenceId = dwUseType->ToString();
  6957. if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_ExpandedItem)
  6958. {
  6959. DbgTypedValue itemValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  6960. if (itemValue)
  6961. {
  6962. DwFormatInfo itemFormatInfo = formatInfo;
  6963. itemFormatInfo.mExpandItemDepth++;
  6964. String itemRetVal = DbgTypedValueToString(itemValue, "", itemFormatInfo, NULL);
  6965. int crIdx = (int)itemRetVal.IndexOf('\n');
  6966. if (crIdx != -1)
  6967. {
  6968. crIdx = (int)itemRetVal.IndexOf('\n', crIdx + 1);
  6969. if (crIdx != -1)
  6970. retVal += itemRetVal.Substring(crIdx);
  6971. }
  6972. }
  6973. }
  6974. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Array)
  6975. {
  6976. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  6977. Array<int> lowerDimSizes;
  6978. for (auto lowerDim : debugVis->mLowerDimSizes)
  6979. {
  6980. DbgTypedValue lowerDimValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(lowerDim, dbgVisWildcardCaptures), &formatInfo);
  6981. int dimSize = 0;
  6982. if ((lowerDimValue) && (lowerDimValue.mType->IsInteger()))
  6983. dimSize = (int)lowerDimValue.GetInt64();
  6984. dimSize = BF_MAX(dimSize, 1);
  6985. lowerDimSizes.push_back(dimSize);
  6986. }
  6987. if ((sizeValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  6988. {
  6989. if (!debugVis->mCondition.IsEmpty())
  6990. {
  6991. int size = (int)sizeValue.GetInt64();
  6992. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  6993. DbgTypedValue curNode = headPointer;
  6994. Array<addr_target> parentList;
  6995. String continuationData;
  6996. int totalSize = 2;
  6997. auto valueType = headPointer.mType;
  6998. String addrs = GetArrayItems(dbgCompileUnit, debugVis, valueType, headPointer, totalSize, &continuationData);
  6999. String firstAddr;
  7000. String secondAddr;
  7001. bool hasSecondAddr = valueType == NULL;
  7002. if (addrs.length() > 0)
  7003. {
  7004. const char* addrsPtr = addrs.c_str();
  7005. firstAddr = addrs.Substring(0, sizeof(addr_target) * 2);
  7006. if (hasSecondAddr)
  7007. secondAddr = addrs.Substring(sizeof(addr_target) * 2, sizeof(addr_target) * 2);
  7008. }
  7009. String evalStr;
  7010. if (valueType != NULL)
  7011. {
  7012. evalStr = "(" + valueType->ToStringRaw();
  7013. if (!valueType->IsPointer())
  7014. evalStr += "*";
  7015. evalStr += ")0x{1}";
  7016. }
  7017. else
  7018. {
  7019. evalStr += "({1})0x{2}";
  7020. }
  7021. if (!debugVis->mShowElementAddrs)
  7022. evalStr.Insert(0, "*");
  7023. if (addrs.length() > 0)
  7024. {
  7025. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7026. if (isReadOnly)
  7027. evalStr += ", ne";
  7028. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, BF_MAX(size, 0), 10000) +
  7029. "\t[{0}]\t" + evalStr + "\t" + firstAddr;
  7030. if (hasSecondAddr)
  7031. retVal += "\t" + secondAddr;
  7032. if (size != 0)
  7033. {
  7034. retVal += "\n:addrs\t" + addrs;
  7035. if (valueType == NULL)
  7036. retVal += "\n:addrsEntrySize\t2";
  7037. if (continuationData.length() > 0)
  7038. retVal += "\n:continuation\t" + continuationData;
  7039. }
  7040. }
  7041. }
  7042. else if (lowerDimSizes.size() == 1)
  7043. {
  7044. int dimSize1 = lowerDimSizes[0];
  7045. String evalStr = "(" + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7046. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7047. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7048. if (isReadOnly)
  7049. evalStr += ", ne";
  7050. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64() / dimSize1, 50000) +
  7051. "\t[{0}]\t" + evalStr;
  7052. }
  7053. else if (lowerDimSizes.size() == 2)
  7054. {
  7055. int dimSize1 = lowerDimSizes[0];
  7056. int dimSize2 = lowerDimSizes[1];
  7057. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7058. if ((headPointer.mType != NULL) && (headPointer.mType->IsPointer()))
  7059. {
  7060. String evalStr = StrFormat("((%s[%d]*)", headPointer.mType->mTypeParam->ToStringRaw(language).c_str(), dimSize2) + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7061. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7062. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7063. if (isReadOnly)
  7064. evalStr += ", ne";
  7065. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64() / dimSize1 / dimSize2, 50000) +
  7066. "\t[{0}]\t" + evalStr;
  7067. }
  7068. }
  7069. else if (lowerDimSizes.size() == 3)
  7070. {
  7071. int dimSize1 = lowerDimSizes[0];
  7072. int dimSize2 = lowerDimSizes[1];
  7073. int dimSize3 = lowerDimSizes[2];
  7074. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7075. if ((headPointer.mType != NULL) && (headPointer.mType->IsPointer()))
  7076. {
  7077. String evalStr = StrFormat("((%s[%d][%d]*)", headPointer.mType->mTypeParam->ToStringRaw(language).c_str(), dimSize2, dimSize3) + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7078. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7079. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7080. if (isReadOnly)
  7081. evalStr += ", ne";
  7082. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64() / dimSize1 / dimSize2 / dimSize3, 50000) +
  7083. "\t[{0}]\t" + evalStr;
  7084. }
  7085. }
  7086. else
  7087. {
  7088. String evalStr = "*(" + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) + " + {0}), this=" + ptrUseDataStr;
  7089. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7090. if (isReadOnly)
  7091. evalStr += ", ne";
  7092. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64(), 50000) +
  7093. "\t[{0}]\t" + evalStr;
  7094. }
  7095. }
  7096. }
  7097. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_IndexItems)
  7098. {
  7099. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7100. if ((sizeValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7101. {
  7102. String evalStr = debugVis->mValuePointer + ", this=" + ptrUseDataStr;
  7103. evalStr.Replace("$i", "{0}");
  7104. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7105. if (isReadOnly)
  7106. evalStr += ", ne";
  7107. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64(), 50000) +
  7108. "\t[{0}]\t" + evalStr;
  7109. }
  7110. }
  7111. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_LinkedList)
  7112. {
  7113. DbgType* valueType = NULL;
  7114. if (!debugVis->mValueType.empty())
  7115. {
  7116. valueType = dbgModule->FindType(debugVisualizers->DoStringReplace(debugVis->mValueType, dbgVisWildcardCaptures), dwValueType);
  7117. if (valueType != NULL)
  7118. valueType = valueType->ResolveTypeDef();
  7119. }
  7120. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mHeadPointer, dbgVisWildcardCaptures), &formatInfo);
  7121. if (headPointer)
  7122. {
  7123. DbgTypedValue endPointer;
  7124. if (!debugVis->mEndPointer.empty())
  7125. endPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mEndPointer, dbgVisWildcardCaptures), &formatInfo);
  7126. DbgTypedValue nextPointer = EvaluateInContext(dbgCompileUnit, headPointer, debugVisualizers->DoStringReplace(debugVis->mNextPointer, dbgVisWildcardCaptures), &formatInfo);
  7127. int size = -1;
  7128. if (!debugVis->mSize.empty())
  7129. {
  7130. auto sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7131. if (sizeValue)
  7132. size = (int)sizeValue.GetInt64();
  7133. }
  7134. DbgTypedValue curNode = headPointer;
  7135. Array<addr_target> parentList;
  7136. String continuationData;
  7137. int totalSize = 2;
  7138. String addrs = GetLinkedListItems(dbgCompileUnit, debugVis, endPointer.mPtr, valueType, curNode, totalSize, &continuationData);
  7139. String firstAddr;
  7140. String secondAddr;
  7141. bool hasSecondAddr = valueType == NULL;
  7142. if (addrs.length() > 0)
  7143. {
  7144. const char* addrsPtr = addrs.c_str();
  7145. firstAddr = addrs.Substring(0, sizeof(addr_target)*2);
  7146. if (hasSecondAddr)
  7147. secondAddr = addrs.Substring(sizeof(addr_target)*2, sizeof(addr_target)*2);
  7148. }
  7149. String evalStr;
  7150. if (valueType != NULL)
  7151. {
  7152. evalStr = "(" + valueType->ToStringRaw();
  7153. if (!valueType->IsPointer())
  7154. evalStr += "*";
  7155. evalStr += ")0x{1}";
  7156. }
  7157. else
  7158. {
  7159. evalStr += "({1})0x{2}";
  7160. }
  7161. if (!debugVis->mShowElementAddrs)
  7162. evalStr.Insert(0, "*");
  7163. if (addrs.length() > 0)
  7164. {
  7165. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7166. if (isReadOnly)
  7167. evalStr += ", ne";
  7168. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, size, 10000) +
  7169. "\t[{0}]\t" + evalStr + "\t" + firstAddr;
  7170. if (hasSecondAddr)
  7171. retVal += "\t" + secondAddr;
  7172. if (size != 0)
  7173. {
  7174. retVal += "\n:addrs\t" + addrs;
  7175. if (valueType == NULL)
  7176. retVal += "\n:addrsEntrySize\t2";
  7177. if (continuationData.length() > 0)
  7178. retVal += "\n:continuation\t" + continuationData;
  7179. }
  7180. }
  7181. }
  7182. }
  7183. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_TreeItems)
  7184. {
  7185. DbgType* valueType = NULL;
  7186. if (!debugVis->mValueType.empty())
  7187. {
  7188. valueType = dbgModule->FindType(debugVisualizers->DoStringReplace(debugVis->mValueType, dbgVisWildcardCaptures), dwValueType);
  7189. if (valueType != NULL)
  7190. valueType = valueType->ResolveTypeDef();
  7191. }
  7192. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7193. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mHeadPointer, dbgVisWildcardCaptures), &formatInfo);
  7194. if (sizeValue)
  7195. sizeValue.mType = sizeValue.mType->RemoveModifiers();
  7196. if ((sizeValue) && (headPointer) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7197. {
  7198. DbgTypedValue curNode = headPointer;
  7199. Array<addr_target> parentList;
  7200. String continuationData;
  7201. int getItemCount = (int)BF_MIN(sizeValue.GetInt64(), 32LL);
  7202. String addrs = GetTreeItems(dbgCompileUnit, debugVis, parentList, valueType, curNode, getItemCount, &continuationData);
  7203. addr_target firstAddr = 0;
  7204. addr_target secondAddr = 0;
  7205. bool hasSecondAddr = valueType == NULL;
  7206. if (addrs.length() > 0)
  7207. {
  7208. const char* addrsPtr = addrs.c_str();
  7209. firstAddr = DecodeTargetDataPtr(addrsPtr);
  7210. if (hasSecondAddr)
  7211. secondAddr = DecodeTargetDataPtr(addrsPtr);
  7212. }
  7213. String evalStr;
  7214. if (valueType != NULL)
  7215. {
  7216. evalStr = "*(" + valueType->ToStringRaw();
  7217. if (!valueType->IsPointer())
  7218. evalStr += "*";
  7219. evalStr += ")0x{1}";
  7220. }
  7221. else
  7222. {
  7223. evalStr += "*(_T_{1}*)0x{2}";
  7224. }
  7225. int size = (int)sizeValue.GetInt64();
  7226. if (addrs.length() == 0)
  7227. {
  7228. evalStr = ""; // Failed
  7229. }
  7230. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7231. if (isReadOnly)
  7232. evalStr += ", ne";
  7233. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, size, 10000) +
  7234. "\t[{0}]\t" + evalStr + "\t" + EncodeDataPtr(firstAddr, false);
  7235. if (hasSecondAddr)
  7236. retVal += "\t" + EncodeDataPtr(secondAddr, false);
  7237. if (addrs.length() > 0)
  7238. {
  7239. retVal += "\n:addrs\t" + addrs;
  7240. if (continuationData.length() > 0)
  7241. retVal += "\n:continuation\t" + continuationData;
  7242. }
  7243. }
  7244. }
  7245. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Dictionary)
  7246. {
  7247. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7248. DbgTypedValue entriesPtrValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mEntries, dbgVisWildcardCaptures), &formatInfo);
  7249. if (sizeValue)
  7250. sizeValue.mType = sizeValue.mType->RemoveModifiers();
  7251. if ((sizeValue) && (entriesPtrValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7252. {
  7253. String continuationData;
  7254. DbgType* valueType = entriesPtrValue.mType;
  7255. int getItemCount = (int)std::min(sizeValue.GetInt64(), 2LL);
  7256. DbgType* useTypedValType = useTypedValue.mType;
  7257. addr_target useTypedValPtr = useTypedValue.mPtr;
  7258. addr_target useTypedValAddr = useTypedValue.mSrcAddress;
  7259. String addrs = GetDictionaryItems(dbgCompileUnit, debugVis, useTypedValue, 0, -1, getItemCount, &continuationData);
  7260. addr_target firstAddr = 0;
  7261. if (addrs.length() > 0)
  7262. {
  7263. const char* addrsPtr = addrs.c_str();
  7264. firstAddr = DecodeTargetDataPtr(addrsPtr);
  7265. }
  7266. String evalStr = "((" + valueType->ToStringRaw() + ")0x{1}), na";
  7267. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7268. if (isReadOnly)
  7269. evalStr += ", ne";
  7270. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64(), 10000) +
  7271. "\t[{0}]\t" + evalStr + "\t" + EncodeDataPtr(firstAddr, false);
  7272. if (addrs.length() > 0)
  7273. {
  7274. retVal += "\n:addrs\t" + addrs;
  7275. if (continuationData.length() > 0)
  7276. retVal += "\n:continuation\t" + continuationData;
  7277. }
  7278. }
  7279. }
  7280. if (formatInfo.mExpandItemDepth == 0)
  7281. {
  7282. //retVal += "\n[Raw View]\tthis, this=" + ptrDataStr + ", nv";
  7283. retVal += "\n[Raw View]\t" + ptrDataStr + ", nv";
  7284. }
  7285. }
  7286. bool WinDebugger::IsPaused()
  7287. {
  7288. return (mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint) || (mRunState == RunState_Exception) || (mRunState == RunState_DebugEval_Done);
  7289. }
  7290. DbgTypedValue WinDebugger::GetRegister(const StringImpl& regName, DbgLanguage language, CPURegisters* registers, Array<RegForm>* regForms)
  7291. {
  7292. int regNum = -1;
  7293. String lwrRegName(regName);
  7294. _strlwr((char*)lwrRegName.c_str());
  7295. // int regs
  7296. #ifdef BF_DBG_32
  7297. DbgTypeCode regType = DbgType_i32;
  7298. if (lwrRegName == "eax")
  7299. regNum = X86Reg_EAX;
  7300. else if (lwrRegName == "ecx")
  7301. regNum = X86Reg_ECX;
  7302. else if (lwrRegName == "edx")
  7303. regNum = X86Reg_EDX;
  7304. else if (lwrRegName == "ebx")
  7305. regNum = X86Reg_EBX;
  7306. else if (lwrRegName == "esp")
  7307. regNum = X86Reg_ESP;
  7308. else if (lwrRegName == "ebp")
  7309. regNum = X86Reg_EBP;
  7310. else if (lwrRegName == "esi")
  7311. regNum = X86Reg_ESI;
  7312. else if (lwrRegName == "edi")
  7313. regNum = X86Reg_EDI;
  7314. else if (lwrRegName == "eip")
  7315. regNum = X86Reg_EIP;
  7316. else if (lwrRegName == "efl")
  7317. regNum = X86Reg_EFL;
  7318. #else
  7319. DbgTypeCode regType = DbgType_i64;
  7320. if (lwrRegName == "rax")
  7321. regNum = X64Reg_RAX;
  7322. else if (lwrRegName == "rcx")
  7323. regNum = X64Reg_RCX;
  7324. else if (lwrRegName == "rdx")
  7325. regNum = X64Reg_RDX;
  7326. else if (lwrRegName == "rbx")
  7327. regNum = X64Reg_RBX;
  7328. else if (lwrRegName == "rsp")
  7329. regNum = X64Reg_RSP;
  7330. else if (lwrRegName == "rbp")
  7331. regNum = X64Reg_RBP;
  7332. else if (lwrRegName == "rsi")
  7333. regNum = X64Reg_RSI;
  7334. else if (lwrRegName == "rdi")
  7335. regNum = X64Reg_RDI;
  7336. else if (lwrRegName == "rip")
  7337. regNum = X64Reg_RIP;
  7338. else if (lwrRegName == "r8")
  7339. regNum = X64Reg_R8;
  7340. else if (lwrRegName == "r9")
  7341. regNum = X64Reg_R9;
  7342. else if (lwrRegName == "r10")
  7343. regNum = X64Reg_R10;
  7344. else if (lwrRegName == "r11")
  7345. regNum = X64Reg_R11;
  7346. else if (lwrRegName == "r12")
  7347. regNum = X64Reg_R12;
  7348. else if (lwrRegName == "r13")
  7349. regNum = X64Reg_R13;
  7350. else if (lwrRegName == "r14")
  7351. regNum = X64Reg_R14;
  7352. else if (lwrRegName == "r15")
  7353. regNum = X64Reg_R15;
  7354. else
  7355. {
  7356. regType = DbgType_i32;
  7357. if (lwrRegName == "eax")
  7358. regNum = X64Reg_RAX;
  7359. else if (lwrRegName == "ecx")
  7360. regNum = X64Reg_RCX;
  7361. else if (lwrRegName == "edx")
  7362. regNum = X64Reg_RDX;
  7363. else if (lwrRegName == "ebx")
  7364. regNum = X64Reg_RBX;
  7365. else if (lwrRegName == "efl")
  7366. regNum = X64Reg_EFL;
  7367. else if (lwrRegName == "esi")
  7368. regNum = X64Reg_RSI;
  7369. else if (lwrRegName == "edi")
  7370. regNum = X64Reg_RDI;
  7371. else if (lwrRegName == "r8d")
  7372. regNum = X64Reg_R8;
  7373. else if (lwrRegName == "r9d")
  7374. regNum = X64Reg_R9;
  7375. else if (lwrRegName == "r10d")
  7376. regNum = X64Reg_R10;
  7377. else if (lwrRegName == "r11d")
  7378. regNum = X64Reg_R11;
  7379. else if (lwrRegName == "r12d")
  7380. regNum = X64Reg_R12;
  7381. else if (lwrRegName == "r13d")
  7382. regNum = X64Reg_R13;
  7383. else if (lwrRegName == "r14d")
  7384. regNum = X64Reg_R14;
  7385. else if (lwrRegName == "r15d")
  7386. regNum = X64Reg_R15;
  7387. else
  7388. {
  7389. regType = DbgType_i16;
  7390. if (lwrRegName == "ax")
  7391. regNum = X64Reg_RAX;
  7392. else if (lwrRegName == "cx")
  7393. regNum = X64Reg_RCX;
  7394. else if (lwrRegName == "dx")
  7395. regNum = X64Reg_RDX;
  7396. else if (lwrRegName == "bx")
  7397. regNum = X64Reg_RBX;
  7398. else if (lwrRegName == "si")
  7399. regNum = X64Reg_RSI;
  7400. else if (lwrRegName == "di")
  7401. regNum = X64Reg_RDI;
  7402. else if (lwrRegName == "r8w")
  7403. regNum = X64Reg_R8;
  7404. else if (lwrRegName == "r9w")
  7405. regNum = X64Reg_R9;
  7406. else if (lwrRegName == "r10w")
  7407. regNum = X64Reg_R10;
  7408. else if (lwrRegName == "r11w")
  7409. regNum = X64Reg_R11;
  7410. else if (lwrRegName == "r12w")
  7411. regNum = X64Reg_R12;
  7412. else if (lwrRegName == "r13w")
  7413. regNum = X64Reg_R13;
  7414. else if (lwrRegName == "r14w")
  7415. regNum = X64Reg_R14;
  7416. else if (lwrRegName == "r15w")
  7417. regNum = X64Reg_R15;
  7418. else
  7419. {
  7420. regType = DbgType_i8;
  7421. if (lwrRegName == "al")
  7422. regNum = X64Reg_RAX;
  7423. else if (lwrRegName == "cl")
  7424. regNum = X64Reg_RCX;
  7425. else if (lwrRegName == "dl")
  7426. regNum = X64Reg_RDX;
  7427. else if (lwrRegName == "bl")
  7428. regNum = X64Reg_RBX;
  7429. else if (lwrRegName == "sil")
  7430. regNum = X64Reg_RSI;
  7431. else if (lwrRegName == "dil")
  7432. regNum = X64Reg_RDI;
  7433. else if (lwrRegName == "r8b")
  7434. regNum = X64Reg_R8;
  7435. else if (lwrRegName == "r9b")
  7436. regNum = X64Reg_R9;
  7437. else if (lwrRegName == "r10b")
  7438. regNum = X64Reg_R10;
  7439. else if (lwrRegName == "r11b")
  7440. regNum = X64Reg_R11;
  7441. else if (lwrRegName == "r12b")
  7442. regNum = X64Reg_R12;
  7443. else if (lwrRegName == "r13b")
  7444. regNum = X64Reg_R13;
  7445. else if (lwrRegName == "r14b")
  7446. regNum = X64Reg_R14;
  7447. else if (lwrRegName == "r15b")
  7448. regNum = X64Reg_R15;
  7449. }
  7450. }
  7451. }
  7452. #endif
  7453. auto dbgModule = mDebugTarget->GetMainDbgModule();
  7454. if (regNum != -1)
  7455. {
  7456. DbgTypedValue typedVal;
  7457. typedVal.mType = dbgModule->GetPrimitiveType(regType, language);
  7458. typedVal.mInt64 = registers->mIntRegsArray[regNum];
  7459. typedVal.mRegNum = regNum;
  7460. return typedVal;
  7461. }
  7462. // st regs
  7463. if ((lwrRegName.length() == 3) && (lwrRegName[0] == 's') && (lwrRegName[1] == 't') && (lwrRegName[2] >= '0') && (lwrRegName[2] <= '7'))
  7464. {
  7465. regNum = CPUReg_FPSTREG_FIRST + (lwrRegName[2] - '0');
  7466. }
  7467. if (regNum != -1)
  7468. {
  7469. DbgTypedValue typedVal;
  7470. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Double, language);
  7471. typedVal.mDouble = ConvertFloat80ToDouble(registers->mFpMmRegsArray[regNum - CPUReg_FPSTREG_FIRST].fp.fp80);
  7472. typedVal.mRegNum = regNum;
  7473. return typedVal;
  7474. }
  7475. // mm regs
  7476. if ((lwrRegName.length() == 3) && (lwrRegName[0] == 'm') && (lwrRegName[1] == 'm') && (lwrRegName[2] >= '0') && (lwrRegName[2] <= '7'))
  7477. {
  7478. regNum = CPUReg_MMREG_FIRST + (lwrRegName[2] - '0');
  7479. }
  7480. if (regNum != -1)
  7481. {
  7482. DbgTypedValue typedVal;
  7483. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_i64, language);
  7484. typedVal.mInt64 = registers->mFpMmRegsArray[regNum - CPUReg_MMREG_FIRST].mm;
  7485. typedVal.mRegNum = regNum;
  7486. return typedVal;
  7487. }
  7488. // xmm regs
  7489. #ifdef BF_DBG_32
  7490. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '7') &&
  7491. (lwrRegName[4] == '_') && (lwrRegName[5] >= '0') && (lwrRegName[5] <= '3'))
  7492. {
  7493. regNum = CPUReg_XMMREG_FIRST + ((lwrRegName[3] - '0') * 4) + (lwrRegName[5] - '0');
  7494. }
  7495. #else
  7496. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '9') &&
  7497. (lwrRegName[4] == '_') && (lwrRegName[5] >= '0') && (lwrRegName[5] <= '3'))
  7498. {
  7499. regNum = CPUReg_XMMREG_FIRST + ((lwrRegName[3] - '0') * 4) + (lwrRegName[5] - '0');
  7500. }
  7501. if ((lwrRegName.length() == 7) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] == '1') && (lwrRegName[4] >= '0') && (lwrRegName[4] <= '9') &&
  7502. (lwrRegName[5] == '_') && (lwrRegName[6] >= '0') && (lwrRegName[6] <= '3'))
  7503. {
  7504. regNum = CPUReg_XMMREG_FIRST + ((10 + (lwrRegName[4] - '0')) * 4) + (lwrRegName[6] - '0');
  7505. }
  7506. #endif
  7507. if (regNum != -1)
  7508. {
  7509. int xmmMajor = (regNum - CPUReg_XMMREG_FIRST) >> 2;
  7510. int xmmMinor = (regNum - CPUReg_XMMREG_FIRST) & 3;
  7511. DwMmDisplayType mmDisplayType = GetDisplayInfo(StrFormat("$XMM%d", xmmMajor))->mMmDisplayType;
  7512. RegForm regForm = RegForm_Unknown;
  7513. if (regForms != NULL)
  7514. {
  7515. int regFormIdx = CPUReg_M128_XMMREG_FIRST + xmmMajor;
  7516. if (regFormIdx < (int)regForms->size())
  7517. regForm = (*regForms)[regFormIdx];
  7518. }
  7519. if (mmDisplayType == DwMmDisplayType_Default)
  7520. {
  7521. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2))
  7522. mmDisplayType = DwMmDisplayType_Double;
  7523. else if (regForm == RegForm_Int4)
  7524. mmDisplayType = DwMmDisplayType_Int;
  7525. }
  7526. //TODO: Add int types
  7527. if (mmDisplayType == DwMmDisplayType_Double)
  7528. {
  7529. DbgTypedValue typedVal;
  7530. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Double, language);
  7531. typedVal.mDouble = registers->mXmmDRegsArray[xmmMajor].d[xmmMinor];
  7532. typedVal.mRegNum = regNum;
  7533. return typedVal;
  7534. }
  7535. if (mmDisplayType == DwMmDisplayType_Int)
  7536. {
  7537. DbgTypedValue typedVal;
  7538. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_i32, language);
  7539. typedVal.mInt32 = registers->mXmmIRegsARray[xmmMajor].i[xmmMinor];
  7540. typedVal.mRegNum = regNum;
  7541. return typedVal;
  7542. }
  7543. DbgTypedValue typedVal;
  7544. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Single, language);
  7545. typedVal.mSingle = registers->mXmmRegsArray[xmmMajor].f[xmmMinor];
  7546. typedVal.mRegNum = regNum;
  7547. return typedVal;
  7548. }
  7549. #ifdef BF_DBG_32
  7550. if ((lwrRegName.length() == 4) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '7'))
  7551. {
  7552. regNum = CPUReg_M128_XMMREG_FIRST + (lwrRegName[3] - '0');
  7553. }
  7554. #else
  7555. if ((lwrRegName.length() == 4) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '9'))
  7556. {
  7557. regNum = CPUReg_M128_XMMREG_FIRST + (lwrRegName[3] - '0');
  7558. }
  7559. if ((lwrRegName.length() == 5) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] == '1') && (lwrRegName[4] >= '0') && (lwrRegName[4] <= '5'))
  7560. {
  7561. regNum = CPUReg_M128_XMMREG_FIRST + 10 + (lwrRegName[4] - '0');
  7562. }
  7563. #endif
  7564. if (regNum != -1)
  7565. {
  7566. DbgTypedValue typedVal;
  7567. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_RegGroup, language);
  7568. 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)
  7569. typedVal.mRegNum = regNum;
  7570. return typedVal;
  7571. }
  7572. // flags
  7573. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'f') && (lwrRegName[1] == 'l') && (lwrRegName[2] == 'a') && (lwrRegName[3] == 'g') && (lwrRegName[5] == 'f'))
  7574. {
  7575. switch(lwrRegName[4])
  7576. {
  7577. case 'c': regNum = CPUReg_FLAG_CF_CARRY; break;
  7578. case 'p': regNum = CPUReg_FLAG_PF_PARITY; break;
  7579. case 'a': regNum = CPUReg_FLAG_AF_ADJUST; break;
  7580. case 'z': regNum = CPUReg_FLAG_ZF_ZERO; break;
  7581. case 's': regNum = CPUReg_FLAG_SF_SIGN; break;
  7582. case 'i': regNum = CPUReg_FLAG_IF_INTERRUPT; break;
  7583. case 'd': regNum = CPUReg_FLAG_DF_DIRECTION; break;
  7584. case 'o': regNum = CPUReg_FLAG_OF_OVERFLOW; break;
  7585. default: break;
  7586. }
  7587. }
  7588. if (regNum != -1)
  7589. {
  7590. int flagBit = CPURegisters::GetFlagBitForRegister(regNum);
  7591. BF_ASSERT(flagBit >= 0);
  7592. DbgTypedValue typedVal;
  7593. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Bool, language);
  7594. typedVal.mBool = (registers->mIntRegs.efl & ((uint64)1 << flagBit)) != 0;
  7595. typedVal.mRegNum = regNum;
  7596. return typedVal;
  7597. }
  7598. // categories
  7599. if (lwrRegName == "allregs")
  7600. regNum = CPUReg_CAT_ALLREGS;
  7601. else if (lwrRegName == "iregs")
  7602. regNum = CPUReg_CAT_IREGS;
  7603. else if (lwrRegName == "fpregs")
  7604. regNum = CPUReg_CAT_FPREGS;
  7605. else if (lwrRegName == "mmregs")
  7606. regNum = CPUReg_CAT_MMREGS;
  7607. else if (lwrRegName == "xmmregs")
  7608. regNum = CPUReg_CAT_XMMREGS;
  7609. else if (lwrRegName == "flags")
  7610. regNum = CPUReg_CAT_FLAGS;
  7611. if (regNum != -1)
  7612. {
  7613. DbgTypedValue typedVal;
  7614. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_RegGroup, language);
  7615. 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)
  7616. typedVal.mRegNum = regNum;
  7617. return typedVal;
  7618. }
  7619. return DbgTypedValue();
  7620. }
  7621. DbgModule* WinDebugger::GetCallStackDbgModule(int callStackIdx)
  7622. {
  7623. if ((mRunState == RunState_NotStarted) || (!IsPaused()))
  7624. return mEmptyDebugTarget->GetMainDbgModule();
  7625. if (callStackIdx == -1)
  7626. return mDebugTarget->GetMainDbgModule();
  7627. FixCallStackIdx(callStackIdx);
  7628. if (callStackIdx >= mCallStack.size())
  7629. return mDebugTarget->GetMainDbgModule();
  7630. UpdateCallStackMethod(callStackIdx);
  7631. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  7632. if (subProgram != NULL)
  7633. return subProgram->mCompileUnit->mDbgModule;
  7634. auto dbgModule = mDebugTarget->FindDbgModuleForAddress(mCallStack[callStackIdx]->mRegisters.GetPC());
  7635. if (dbgModule != NULL)
  7636. return dbgModule;
  7637. return mDebugTarget->GetMainDbgModule();
  7638. }
  7639. DbgSubprogram* WinDebugger::GetCallStackSubprogram(int callStackIdx)
  7640. {
  7641. if ((IsInRunState()) || (mRunState == RunState_NotStarted) || (callStackIdx == -1))
  7642. return NULL;
  7643. if (callStackIdx >= (int)mCallStack.size())
  7644. UpdateCallStack();
  7645. if (mCallStack.IsEmpty())
  7646. return NULL;
  7647. if (callStackIdx >= (int)mCallStack.size())
  7648. callStackIdx = 0;
  7649. UpdateCallStackMethod(callStackIdx);
  7650. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  7651. return subProgram;
  7652. }
  7653. DbgCompileUnit* WinDebugger::GetCallStackCompileUnit(int callStackIdx)
  7654. {
  7655. if ((IsInRunState()) || (mRunState == RunState_NotStarted) || (callStackIdx == -1))
  7656. return NULL;
  7657. if (callStackIdx >= (int)mCallStack.size())
  7658. UpdateCallStack();
  7659. if (mCallStack.IsEmpty())
  7660. return NULL;
  7661. if (callStackIdx >= (int)mCallStack.size())
  7662. callStackIdx = 0;
  7663. UpdateCallStackMethod(callStackIdx);
  7664. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  7665. if (subProgram == NULL)
  7666. return NULL;
  7667. return subProgram->mCompileUnit;
  7668. }
  7669. String WinDebugger::EvaluateContinue(DbgPendingExpr* pendingExpr, BfPassInstance& bfPassInstance)
  7670. {
  7671. DbgModule* dbgModule = NULL;
  7672. DbgCompileUnit* dbgCompileUnit = NULL;
  7673. if (pendingExpr->mThreadId == -1)
  7674. {
  7675. if ((pendingExpr->mFormatInfo.mLanguage == DbgLanguage_Beef) && (mDebugTarget != NULL) && (mDebugTarget->mTargetBinary != NULL))
  7676. dbgModule = mDebugTarget->mTargetBinary;
  7677. else
  7678. dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  7679. }
  7680. else
  7681. {
  7682. dbgModule = GetCallStackDbgModule(pendingExpr->mCallStackIdx);
  7683. if ((dbgModule != NULL) &&(!dbgModule->mDebugTarget->mIsEmpty))
  7684. dbgCompileUnit = GetCallStackCompileUnit(pendingExpr->mCallStackIdx);
  7685. }
  7686. if (dbgModule == NULL)
  7687. dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  7688. if (!pendingExpr->mException.empty())
  7689. {
  7690. RestoreAllRegisters();
  7691. return "!" + pendingExpr->mException;
  7692. }
  7693. DwAutoComplete autoComplete;
  7694. if (bfPassInstance.HasFailed())
  7695. {
  7696. // Don't allow pending calls if we've already failed in the calling Evaluate()
  7697. pendingExpr->mExpressionFlags = (DwEvalExpressionFlags)(pendingExpr->mExpressionFlags & ~DwEvalExpressionFlag_AllowCalls);
  7698. }
  7699. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, pendingExpr->mCallStackIdx, pendingExpr->mCursorPos);
  7700. dbgExprEvaluator.mLanguage = pendingExpr->mFormatInfo.mLanguage;
  7701. dbgExprEvaluator.mReferenceId = &pendingExpr->mReferenceId;
  7702. dbgExprEvaluator.mExpressionFlags = pendingExpr->mExpressionFlags;
  7703. dbgExprEvaluator.mExplicitThis = pendingExpr->mFormatInfo.mExplicitThis;
  7704. dbgExprEvaluator.mSubjectExpr = pendingExpr->mFormatInfo.mSubjectExpr;
  7705. dbgExprEvaluator.mNamespaceSearchStr = pendingExpr->mFormatInfo.mNamespaceSearch;
  7706. dbgExprEvaluator.mExpectingTypeName = pendingExpr->mFormatInfo.mExpectedType;
  7707. dbgExprEvaluator.mCallResults = &pendingExpr->mCallResults;
  7708. if ((pendingExpr->mExpressionFlags & DwEvalExpressionFlag_ValidateOnly) != 0)
  7709. {
  7710. dbgExprEvaluator.mValidateOnly = true;
  7711. }
  7712. if (pendingExpr->mCursorPos != -1)
  7713. {
  7714. dbgExprEvaluator.mAutoComplete = &autoComplete;
  7715. }
  7716. dbgExprEvaluator.mDbgCompileUnit = dbgCompileUnit;
  7717. DbgTypedValue exprResult;
  7718. if (pendingExpr->mExplitType != NULL)
  7719. {
  7720. exprResult.mHasNoValue = true;
  7721. exprResult.mType = pendingExpr->mExplitType;
  7722. }
  7723. else if (pendingExpr->mExprNode != NULL)
  7724. {
  7725. exprResult = dbgExprEvaluator.Resolve(pendingExpr->mExprNode);
  7726. }
  7727. if (dbgExprEvaluator.mCreatedPendingCall)
  7728. {
  7729. BF_ASSERT(mRunState == RunState_DebugEval);
  7730. //ContinueDebugEvent();
  7731. return "!pending";
  7732. }
  7733. if (dbgExprEvaluator.mCountResultOverride != -1)
  7734. pendingExpr->mFormatInfo.mOverrideCount = dbgExprEvaluator.mCountResultOverride;
  7735. String val;
  7736. if (bfPassInstance.HasFailed())
  7737. {
  7738. BfLogDbgExpr("Evaluate Failed: %s\n", bfPassInstance.mErrors[0]->mError.c_str());
  7739. val = StrFormat("!%d\t%d\t%s", bfPassInstance.mErrors[0]->GetSrcStart(), bfPassInstance.mErrors[0]->GetSrcLength(), bfPassInstance.mErrors[0]->mError.c_str());
  7740. }
  7741. else if (dbgExprEvaluator.mBlockedSideEffects)
  7742. {
  7743. BfLogDbgExpr("Evaluate blocked side effects\n");
  7744. val = "!sideeffects";
  7745. }
  7746. else if (!exprResult)
  7747. {
  7748. if (exprResult.mType != NULL)
  7749. {
  7750. BfLogDbgExpr("Evaluate success\n");
  7751. String typeName = exprResult.mType->ToString();
  7752. DbgType* rawType = exprResult.mType;
  7753. if (rawType->IsBfObjectPtr())
  7754. rawType = rawType->mTypeParam;
  7755. String typeNameRaw = rawType->ToStringRaw();
  7756. val = typeName + "\n" + typeName;
  7757. val += "\n" + GetMemberList(exprResult.mType, typeNameRaw, false, true, false, false, exprResult.mIsReadOnly);
  7758. if (exprResult.mType->mTypeCode == DbgType_Namespace)
  7759. {
  7760. val += "\n:type\tnamespace";
  7761. }
  7762. else
  7763. {
  7764. auto type = exprResult.mType;
  7765. if (type->IsPointer())
  7766. type = type->mTypeParam;
  7767. if (type->IsBfObject())
  7768. val += "\n:type\tclass";
  7769. else
  7770. val += "\n:type\tvaluetype";
  7771. }
  7772. if (!pendingExpr->mReferenceId.empty())
  7773. val += "\n:referenceId\t" + pendingExpr->mReferenceId;
  7774. }
  7775. else
  7776. val = "!";
  7777. }
  7778. else if ((pendingExpr->mExpressionFlags & (DwEvalExpressionFlag_MemoryAddress)) != 0)
  7779. {
  7780. DbgType* resultType = exprResult.mType->RemoveModifiers();
  7781. if ((resultType->IsInteger()) || (resultType->IsPointerOrRef()))
  7782. {
  7783. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", 0);
  7784. }
  7785. else
  7786. {
  7787. if (exprResult.mSrcAddress != 0)
  7788. val = StrFormat("!Type '%s' is invalid. A pointer or address value is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  7789. else
  7790. val = StrFormat("!Type '%s' is invalid. A pointer or address value is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  7791. }
  7792. }
  7793. else if ((pendingExpr->mExpressionFlags & (DwEvalExpressionFlag_MemoryWatch)) != 0)
  7794. {
  7795. DbgType* resultType = exprResult.mType->RemoveModifiers();
  7796. bool isMemoryWatch = (pendingExpr->mExpressionFlags & DwEvalExpressionFlag_MemoryWatch) != 0;
  7797. if (!resultType->IsPointerOrRef())
  7798. {
  7799. if (exprResult.mSrcAddress != 0)
  7800. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  7801. else
  7802. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  7803. }
  7804. else
  7805. {
  7806. auto innerType = resultType->mTypeParam;
  7807. int byteCount = innerType->GetByteCount();
  7808. if (pendingExpr->mFormatInfo.mArrayLength != -1)
  7809. byteCount *= pendingExpr->mFormatInfo.mArrayLength;
  7810. if (byteCount == 0)
  7811. {
  7812. 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());
  7813. }
  7814. #ifdef BF_DBG_32
  7815. else if ((isMemoryWatch) && (!IsMemoryBreakpointSizeValid(exprResult.mPtr, byteCount)))
  7816. {
  7817. if (innerType->mSize > 16)
  7818. 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);
  7819. else if (!IsMemoryBreakpointSizeValid(0, byteCount))
  7820. 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);
  7821. else
  7822. 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);
  7823. }
  7824. #else
  7825. else if ((isMemoryWatch) && (!IsMemoryBreakpointSizeValid(exprResult.mPtr, byteCount)))
  7826. {
  7827. if (innerType->mSize > 32)
  7828. 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);
  7829. else if (!IsMemoryBreakpointSizeValid(0, byteCount))
  7830. 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);
  7831. else
  7832. 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);
  7833. }
  7834. #endif
  7835. else
  7836. {
  7837. auto language = dbgExprEvaluator.GetLanguage();
  7838. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", byteCount) + "\n" + StrFormat("%d\t", language) + innerType->ToStringRaw(language);
  7839. }
  7840. }
  7841. }
  7842. else
  7843. {
  7844. if (pendingExpr->mFormatInfo.mNoEdit)
  7845. exprResult.mIsReadOnly = true;
  7846. if (!pendingExpr->mReferenceId.empty())
  7847. pendingExpr->mFormatInfo.mReferenceId = pendingExpr->mReferenceId;
  7848. val = DbgTypedValueToString(exprResult, pendingExpr->mExprNode->ToString(), pendingExpr->mFormatInfo, &dbgExprEvaluator, (pendingExpr->mExpressionFlags & DwEvalExpressionFlag_FullPrecision) != 0);
  7849. if ((!val.empty()) && (val[0] == '!'))
  7850. return val;
  7851. if (pendingExpr->mFormatInfo.mRawString)
  7852. return val;
  7853. if (exprResult.mIsLiteral)
  7854. val += "\n:literal";
  7855. if (bfPassInstance.HasMessages())
  7856. {
  7857. for (auto error : bfPassInstance.mErrors)
  7858. {
  7859. if (error->mIsWarning)
  7860. {
  7861. val += "\n:warn\t";
  7862. val += error->mError;
  7863. }
  7864. }
  7865. }
  7866. if (!pendingExpr->mFormatInfo.mReferenceId.empty())
  7867. val += "\n:referenceId\t" + pendingExpr->mFormatInfo.mReferenceId;
  7868. if ((exprResult.mSrcAddress != 0) && (HasMemoryBreakpoint(exprResult.mSrcAddress, exprResult.mType->GetByteCount())))
  7869. val += StrFormat("\n:break\t%@", exprResult.mSrcAddress);
  7870. auto checkType = exprResult.mType->RemoveModifiers();
  7871. if (checkType->IsBfObjectPtr())
  7872. val += "\n:type\tobject";
  7873. else if ((checkType->IsPointer()) || (checkType->mTypeCode == DbgType_Subroutine))
  7874. val += "\n:type\tpointer";
  7875. else if (checkType->IsInteger())
  7876. val += "\n:type\tint";
  7877. else if ((exprResult.mRegNum >= X64Reg_M128_XMM0) && (exprResult.mRegNum <= X64Reg_M128_XMM15))
  7878. val += "\n:type\tmm128";
  7879. if (dbgExprEvaluator.mHadSideEffects)
  7880. val += "\n:sideeffects";
  7881. auto underlyingType = exprResult.mType->RemoveModifiers();
  7882. bool canEdit = true;
  7883. if (pendingExpr->mFormatInfo.mLanguage == DbgLanguage_Beef)
  7884. {
  7885. if (exprResult.mType->IsConst())
  7886. canEdit = false;
  7887. }
  7888. if (pendingExpr->mFormatInfo.mNoEdit)
  7889. canEdit = false;
  7890. if (exprResult.mIsReadOnly)
  7891. canEdit = false;
  7892. if (val[0] == '!')
  7893. {
  7894. // Already has an error embedded, can't edit
  7895. }
  7896. else if ((exprResult.mSrcAddress != 0) && (underlyingType->mTypeCode >= DbgType_i8) && (underlyingType->mTypeCode <= DbgType_Ptr) &&
  7897. (underlyingType->mTypeCode != DbgType_Class) && (underlyingType->mTypeCode != DbgType_Struct))
  7898. {
  7899. if (canEdit)
  7900. val += "\n:canEdit";
  7901. if (exprResult.mType->mTypeCode == DbgType_Ptr)
  7902. {
  7903. val += "\n:editVal\t" + EncodeDataPtr(exprResult.mPtr, true);
  7904. }
  7905. }
  7906. else if ((underlyingType->IsStruct()) && (exprResult.mSrcAddress != 0) && (underlyingType->IsTypedPrimitive()))
  7907. {
  7908. auto primType = underlyingType->GetRootBaseType();
  7909. DbgTypedValue primVal = dbgExprEvaluator.ReadTypedValue(primType, exprResult.mSrcAddress, DbgAddrType_Target);
  7910. String primResult = DbgTypedValueToString(primVal, "", pendingExpr->mFormatInfo, NULL);
  7911. int crPos = (int)primResult.IndexOf('\n');
  7912. if (crPos != -1)
  7913. primResult.RemoveToEnd(crPos);
  7914. if (canEdit)
  7915. val += "\n:canEdit";
  7916. val += "\n:editVal\t" + primResult;
  7917. }
  7918. else if (exprResult.mRegNum >= 0)
  7919. {
  7920. bool isPseudoReg = ( ((exprResult.mRegNum >= X86Reg_M128_XMMREG_FIRST) && (exprResult.mRegNum <= X86Reg_M128_XMMREG_LAST))
  7921. || ((exprResult.mRegNum >= X86Reg_CAT_FIRST) && (exprResult.mRegNum <= X86Reg_CAT_LAST)) );
  7922. if (!isPseudoReg)
  7923. {
  7924. if (canEdit)
  7925. val += "\n:canEdit";
  7926. }
  7927. }
  7928. }
  7929. if (pendingExpr->mFormatInfo.mRawString)
  7930. return "";
  7931. if (pendingExpr->mCursorPos != -1)
  7932. val += GetAutocompleteOutput(autoComplete);
  7933. return val;
  7934. }
  7935. String WinDebugger::EvaluateContinue()
  7936. {
  7937. BP_ZONE("WinDebugger::EvaluateContinue");
  7938. AutoCrit autoCrit(mDebugManager->mCritSect);
  7939. if (mDebugPendingExpr == NULL)
  7940. return "!Evaluation canceled";
  7941. if (!IsPaused())
  7942. return "!Not paused";
  7943. if (mRunState == RunState_DebugEval_Done)
  7944. mRunState = RunState_Paused;
  7945. BfPassInstance bfPassInstance(mBfSystem);
  7946. String result = EvaluateContinue(mDebugPendingExpr, bfPassInstance);
  7947. if (result != "!pending")
  7948. {
  7949. BfLogDbg("EvaluateContinue finishing pending expr in thread %d\n", mDebugEvalThreadInfo.mThreadId);
  7950. CleanupDebugEval();
  7951. }
  7952. return result;
  7953. }
  7954. void WinDebugger::EvaluateContinueKeep()
  7955. {
  7956. if (mDebugPendingExpr != NULL)
  7957. mDebugPendingExpr->mIdleTicks = 0;
  7958. }
  7959. String WinDebugger::Evaluate(const StringImpl& expr, DwFormatInfo formatInfo, int callStackIdx, int cursorPos, int language, DwEvalExpressionFlags expressionFlags)
  7960. {
  7961. BP_ZONE_F("WinDebugger::Evaluate %s", BP_DYN_STR(expr.c_str()));
  7962. AutoCrit autoCrit(mDebugManager->mCritSect);
  7963. if ((expressionFlags & DwEvalExpressionFlag_Symbol) != 0)
  7964. {
  7965. DwAutoComplete autoComplete;
  7966. String retVal;
  7967. retVal += GetAutocompleteOutput(autoComplete);
  7968. return retVal;
  7969. }
  7970. UpdateCallStackMethod(callStackIdx);
  7971. BfLogDbgExpr("Evaluate %s in thread %d\n", expr.c_str(), (mActiveThread != NULL) ? mActiveThread->mThreadId : 0);
  7972. if (language != -1)
  7973. formatInfo.mLanguage = (DbgLanguage)language;
  7974. auto activeThread = mActiveThread;
  7975. if ((!IsPaused()) && (mRunState != RunState_NotStarted) && (mRunState != RunState_DebugEval))
  7976. {
  7977. activeThread = NULL;
  7978. callStackIdx = -1;
  7979. }
  7980. if (mDebugPendingExpr != NULL)
  7981. {
  7982. // We already have a pending call
  7983. expressionFlags = (DwEvalExpressionFlags)(expressionFlags & ~DwEvalExpressionFlag_AllowCalls);
  7984. }
  7985. auto dbgModule = GetCallStackDbgModule(callStackIdx);
  7986. auto dbgSubprogram = GetCallStackSubprogram(callStackIdx);
  7987. DbgCompileUnit* dbgCompileUnit = NULL;
  7988. if (dbgSubprogram != NULL)
  7989. dbgCompileUnit = dbgSubprogram->mCompileUnit;
  7990. auto terminatedExpr = expr + ";";
  7991. if ((expr.length() > 0) && (expr[0] == '!'))
  7992. {
  7993. if (expr.StartsWith("!step "))
  7994. {
  7995. expressionFlags = (DwEvalExpressionFlags)(expressionFlags | DwEvalExpressionFlag_StepIntoCalls);
  7996. for (int i = 0; i < 5; i++)
  7997. terminatedExpr[i] = ' ';
  7998. }
  7999. else
  8000. {
  8001. String cmd = expr;
  8002. int commaPos = (int)cmd.IndexOf(',');
  8003. if (commaPos != -1)
  8004. cmd.RemoveToEnd(commaPos);
  8005. if (cmd == "!info")
  8006. {
  8007. OutputMessage(StrFormat("Module: %s\n", dbgModule->mDisplayName.c_str()));
  8008. if (dbgSubprogram == NULL)
  8009. {
  8010. //
  8011. }
  8012. else if (dbgSubprogram->mLinkName != NULL)
  8013. {
  8014. OutputMessage(StrFormat("Link Name: %s\n", dbgSubprogram->mLinkName));
  8015. }
  8016. else
  8017. {
  8018. String outSymbol;
  8019. if (mDebugTarget->FindSymbolAt(dbgSubprogram->mBlock.mLowPC, &outSymbol))
  8020. {
  8021. OutputMessage(StrFormat("Link Name: %s\n", outSymbol.c_str()));
  8022. }
  8023. }
  8024. return "";
  8025. }
  8026. else if (cmd == "!dbg")
  8027. {
  8028. mDbgBreak = true;
  8029. return "";
  8030. }
  8031. }
  8032. }
  8033. bool valIsAddr = false;
  8034. BfParser* parser = new BfParser(mBfSystem);
  8035. parser->mCompatMode = true;
  8036. BfPassInstance bfPassInstance(mBfSystem);
  8037. if ((terminatedExpr.length() > 2) && (terminatedExpr[0] == '@'))
  8038. {
  8039. if (terminatedExpr[1] == '!') // Return string as error
  8040. {
  8041. int errorEnd = (int)terminatedExpr.IndexOf("@!", 2);
  8042. if (errorEnd != -1)
  8043. return terminatedExpr.Substring(1, errorEnd - 1);
  8044. else
  8045. return terminatedExpr.Substring(1);
  8046. }
  8047. else if (terminatedExpr[1] == '>') // Return string as text
  8048. {
  8049. int errorEnd = (int)terminatedExpr.IndexOf("@>", 2);
  8050. if (errorEnd != -1)
  8051. return terminatedExpr.Substring(2, errorEnd - 1);
  8052. else
  8053. return terminatedExpr.Substring(2);
  8054. }
  8055. else // Look for "@:" or "@Beef:" style
  8056. {
  8057. int colonIdx = terminatedExpr.IndexOf(':');
  8058. if (colonIdx > 0)
  8059. {
  8060. bool isValid = true;
  8061. DbgLanguage language = DbgLanguage_Unknown;
  8062. String lang = terminatedExpr.Substring(1, colonIdx - 1);
  8063. lang = ToUpper(lang);
  8064. if ((lang == "") || (lang == "BEEF"))
  8065. {
  8066. language = DbgLanguage_Beef;
  8067. }
  8068. else if (lang == "C")
  8069. {
  8070. language = DbgLanguage_C;
  8071. }
  8072. if (language != DbgLanguage_Unknown)
  8073. {
  8074. for (int i = 0; i < colonIdx + 1; i++)
  8075. terminatedExpr[i] = ' ';
  8076. DbgLanguage curLanguage = DbgLanguage_Unknown;
  8077. if (dbgSubprogram != NULL)
  8078. curLanguage = dbgSubprogram->GetLanguage();
  8079. if (language != curLanguage)
  8080. {
  8081. dbgModule = mDebugTarget->mTargetBinary;
  8082. dbgSubprogram = NULL;
  8083. formatInfo.mLanguage = language;
  8084. callStackIdx = -1;
  8085. }
  8086. }
  8087. }
  8088. }
  8089. }
  8090. parser->SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  8091. parser->Parse(&bfPassInstance);
  8092. BfReducer bfReducer;
  8093. bfReducer.mAlloc = parser->mAlloc;
  8094. bfReducer.mSystem = mBfSystem;
  8095. bfReducer.mPassInstance = &bfPassInstance;
  8096. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser->mRootNode);
  8097. bfReducer.mVisitorPos.MoveNext();
  8098. bfReducer.mCompatMode = parser->mCompatMode;
  8099. bfReducer.mSource = parser;
  8100. auto exprNode = bfReducer.CreateExpression(parser->mRootNode->mChildArr.GetAs<BfAstNode*>(0));
  8101. parser->Close();
  8102. formatInfo.mCallStackIdx = callStackIdx;
  8103. if ((formatInfo.mLanguage == DbgLanguage_Unknown) && (dbgSubprogram != NULL))
  8104. formatInfo.mLanguage = dbgSubprogram->GetLanguage();
  8105. DbgPendingExpr* pendingExpr = new DbgPendingExpr();
  8106. if (activeThread != NULL)
  8107. pendingExpr->mThreadId = activeThread->mThreadId;
  8108. pendingExpr->mParser = parser;
  8109. pendingExpr->mCallStackIdx = callStackIdx;
  8110. pendingExpr->mCursorPos = cursorPos;
  8111. pendingExpr->mExpressionFlags = expressionFlags;
  8112. pendingExpr->mExprNode = exprNode;
  8113. DbgType* explicitType = NULL;
  8114. String formatFlags;
  8115. String assignExpr;
  8116. int assignExprOffset = -1;
  8117. if ((exprNode != NULL) && (exprNode->GetSrcEnd() < (int)expr.length()))
  8118. {
  8119. int formatOffset = exprNode->GetSrcEnd();
  8120. while (formatOffset < (int)expr.length())
  8121. {
  8122. char c = expr[formatOffset];
  8123. if (c == ' ')
  8124. formatOffset++;
  8125. else
  8126. break;
  8127. }
  8128. formatFlags = Trim(expr.Substring(formatOffset));
  8129. bool isComplexType = false;
  8130. for (char c : formatFlags)
  8131. if (c == '>')
  8132. isComplexType = true;
  8133. if (isComplexType)
  8134. {
  8135. explicitType = dbgModule->FindType(expr);
  8136. }
  8137. if ((explicitType == NULL) && (formatFlags.length() > 0))
  8138. {
  8139. String errorString = "Invalid expression";
  8140. if (!ParseFormatInfo(dbgModule, formatFlags, &formatInfo, &bfPassInstance, &assignExprOffset, &assignExpr, &errorString))
  8141. {
  8142. if (formatInfo.mRawString)
  8143. return "";
  8144. bfPassInstance.FailAt(errorString, parser->mSourceData, exprNode->GetSrcEnd(), (int) expr.length() - exprNode->GetSrcEnd());
  8145. formatFlags = "";
  8146. }
  8147. if (assignExprOffset != -1)
  8148. assignExprOffset += formatOffset;
  8149. }
  8150. }
  8151. if (assignExpr.length() > 0)
  8152. {
  8153. String newEvalStr = exprNode->ToString() + " = ";
  8154. int errorOffset = (int)newEvalStr.length();
  8155. newEvalStr += assignExpr;
  8156. String result = Evaluate(newEvalStr, formatInfo, callStackIdx, cursorPos, language, expressionFlags);
  8157. if (result[0] == '!')
  8158. {
  8159. int tabPos = (int)result.IndexOf('\t');
  8160. if (tabPos > 0)
  8161. {
  8162. int errorStart = atoi(result.Substring(1, tabPos - 1).c_str());
  8163. if (errorStart >= errorOffset)
  8164. {
  8165. result = StrFormat("!%d", errorStart - errorOffset + assignExprOffset) + result.Substring(tabPos);
  8166. }
  8167. }
  8168. }
  8169. return result;
  8170. }
  8171. pendingExpr->mExplitType = explicitType;
  8172. pendingExpr->mFormatInfo = formatInfo;
  8173. String result = EvaluateContinue(pendingExpr, bfPassInstance);
  8174. if (result == "!pending")
  8175. {
  8176. BF_ASSERT(mDebugPendingExpr == NULL);
  8177. if (mDebugPendingExpr != NULL)
  8178. {
  8179. return "!retry"; // We already have a pending
  8180. }
  8181. mDebugPendingExpr = pendingExpr;
  8182. mDebugEvalThreadInfo = *mActiveThread;
  8183. mActiveThread->mIsAtBreakpointAddress = 0;
  8184. mActiveThread->mStoppedAtAddress = 0;
  8185. mActiveThread->mBreakpointAddressContinuing = 0;
  8186. }
  8187. else
  8188. delete pendingExpr;
  8189. return result;
  8190. }
  8191. String WinDebugger::Evaluate(const StringImpl& expr, int callStackIdx, int cursorPos, int language, DwEvalExpressionFlags expressionFlags)
  8192. {
  8193. DwFormatInfo formatInfo;
  8194. return Evaluate(expr, formatInfo, callStackIdx, cursorPos, language, expressionFlags);
  8195. }
  8196. static void ConvertDoubleToFloat80(double d, byte fp80[10])
  8197. {
  8198. uint64 di = *reinterpret_cast<uint64*>(&d);
  8199. uint64 m = di & (((uint64)1 << 52) - 1);
  8200. uint64 e = (di >> 52) & 0x7ff;
  8201. memset(fp80, 0, 10);
  8202. // sign bit is directly transferred
  8203. if (di & ((uint64)1 << 63))
  8204. fp80[9] |= 0x80;
  8205. if (!e && !m)
  8206. return; // zero
  8207. fp80[7] |= 0x80; // leading integer bit in mantissa (always 1 in normalized numbers)
  8208. if (e == 0x7ff)
  8209. {
  8210. fp80[9] |= 0x7f;
  8211. fp80[8] = 0xff;
  8212. if (m == 0)
  8213. return; // inf
  8214. fp80[7] |= 0x3f; // any nonzero value will be a NaN (SNaN or QNaN)
  8215. if (m & ((uint64)1 << 51))
  8216. fp80[7] |= 0x40; // QNaN
  8217. return;
  8218. }
  8219. int useExponent = (int)e - 1023;
  8220. if (!e)
  8221. {
  8222. // denormal; can renormalize though since fp80 supports lower exponents
  8223. BF_ASSERT(m != 0); // we should have trapped zero above
  8224. while (!(m & ((uint64)1 << 51)))
  8225. {
  8226. m <<= 1;
  8227. --useExponent;
  8228. }
  8229. // finally we have our leading 1 bit; strip that off and we have a normalized number again
  8230. m <<= 1;
  8231. --useExponent;
  8232. m &= (((uint64)1 << 52) - 1);
  8233. }
  8234. useExponent += 16383;
  8235. BF_ASSERT((useExponent > 0) && (useExponent < 0x7fff));
  8236. *reinterpret_cast<uint16*>(&fp80[8]) |= (uint16)useExponent;
  8237. *reinterpret_cast<uint64*>(&fp80[0]) |= (m << 11);
  8238. }
  8239. bool WinDebugger::AssignToReg(int callStackIdx, DbgTypedValue regVal, DbgTypedValue value, String& outError)
  8240. {
  8241. BF_ASSERT(regVal.mRegNum >= 0);
  8242. if (mCallStack.size() == 0)
  8243. {
  8244. outError = "No call stack";
  8245. return false;
  8246. }
  8247. if (callStackIdx >= (int)mCallStack.size())
  8248. {
  8249. outError = "Invalid call stack index";
  8250. return false;
  8251. }
  8252. auto registers = &mCallStack[callStackIdx]->mRegisters;
  8253. void* regPtr = NULL;
  8254. #ifdef BF_DBG_32
  8255. if ((regVal.mRegNum >= X86Reg_INTREG_FIRST) && (regVal.mRegNum <= X86Reg_INTREG_LAST))
  8256. {
  8257. BF_ASSERT(regVal.mType->mSize == sizeof(int32));
  8258. registers->mIntRegsArray[regVal.mRegNum - X86Reg_INTREG_FIRST] = (uint64)value.mUInt32; // don't sign-extend
  8259. }
  8260. else if ((regVal.mRegNum >= X86Reg_FPSTREG_FIRST) && (regVal.mRegNum <= X86Reg_FPSTREG_LAST))
  8261. {
  8262. BF_ASSERT(regVal.mType->mSize == sizeof(float) || regVal.mType->mSize == sizeof(double));
  8263. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X86Reg_FPSTREG_FIRST];
  8264. double d;
  8265. if (regVal.mType->mSize == sizeof(float))
  8266. d = (double)value.mSingle;
  8267. else
  8268. d = value.mDouble;
  8269. ConvertDoubleToFloat80(d, reg->fp.fp80);
  8270. }
  8271. else if ((regVal.mRegNum >= X86Reg_MMREG_FIRST) && (regVal.mRegNum <= X86Reg_MMREG_LAST))
  8272. {
  8273. BF_ASSERT(regVal.mType->mSize == sizeof(int32) || regVal.mType->mSize == sizeof(int64));
  8274. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X86Reg_MMREG_FIRST];
  8275. if (regVal.mType->mSize == sizeof(int32))
  8276. reg->mm = (uint64)value.mUInt32; // don't sign-extend
  8277. else if (regVal.mType->mSize == sizeof(int64))
  8278. reg->mm = value.mInt64;
  8279. // 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
  8280. reg->fp.fp80[8] = reg->fp.fp80[9] = 0xFF;
  8281. }
  8282. else if ((regVal.mRegNum >= X86Reg_XMMREG_FIRST) && (regVal.mRegNum <= X86Reg_XMMREG_LAST))
  8283. {
  8284. int xmmMajor = (regVal.mRegNum - X86Reg_XMMREG_FIRST) >> 2;
  8285. int xmmMinor = (regVal.mRegNum - X86Reg_XMMREG_FIRST) & 3;
  8286. registers->mXmmRegsArray[xmmMajor].f[xmmMinor] = value.mSingle;
  8287. }
  8288. else if ((regVal.mRegNum >= X86Reg_M128_XMMREG_FIRST) && (regVal.mRegNum <= X86Reg_M128_XMMREG_LAST))
  8289. {
  8290. outError = "Cannot write directly to 128-bit XMM register, please use inner float components";
  8291. return false;
  8292. }
  8293. else if ((regVal.mRegNum >= X86Reg_FLAG_FIRST) && (regVal.mRegNum <= X86Reg_FLAG_LAST))
  8294. {
  8295. int flagBit = CPURegisters::GetFlagBitForRegister(regVal.mRegNum);
  8296. if (flagBit >= 0)
  8297. {
  8298. if (value.mBool)
  8299. registers->mIntRegs.efl |= ((uint64)1 << flagBit);
  8300. else
  8301. registers->mIntRegs.efl &= ~((uint64)1 << flagBit);
  8302. }
  8303. else
  8304. {
  8305. outError = "Unrecognized flag";
  8306. return false;
  8307. }
  8308. }
  8309. else if ((regVal.mRegNum >= X86Reg_CAT_FIRST) && (regVal.mRegNum <= X86Reg_CAT_LAST))
  8310. {
  8311. outError = "Cannot write directly to register categories, please use inner float components";
  8312. return false;
  8313. }
  8314. #else
  8315. if ((regVal.mRegNum >= X64Reg_INTREG_FIRST) && (regVal.mRegNum <= X64Reg_INTREG_LAST))
  8316. {
  8317. //BF_ASSERT(regVal.mType->mSize == sizeof(addr_target));
  8318. registers->mIntRegsArray[regVal.mRegNum - X64Reg_INTREG_FIRST] = value.GetInt64(); // don't sign-extend
  8319. regPtr = &registers->mIntRegsArray[regVal.mRegNum - X64Reg_INTREG_FIRST];
  8320. }
  8321. else if ((regVal.mRegNum >= X64Reg_FPSTREG_FIRST) && (regVal.mRegNum <= X64Reg_FPSTREG_LAST))
  8322. {
  8323. BF_ASSERT(regVal.mType->mSize == sizeof(float) || regVal.mType->mSize == sizeof(double));
  8324. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X64Reg_FPSTREG_FIRST];
  8325. double d;
  8326. if (regVal.mType->mSize == sizeof(float))
  8327. d = (double)value.mSingle;
  8328. else
  8329. d = value.mDouble;
  8330. ConvertDoubleToFloat80(d, reg->fp.fp80);
  8331. regPtr = reg;
  8332. }
  8333. else if ((regVal.mRegNum >= X64Reg_MMREG_FIRST) && (regVal.mRegNum <= X64Reg_MMREG_LAST))
  8334. {
  8335. BF_ASSERT(regVal.mType->mSize == sizeof(int32) || regVal.mType->mSize == sizeof(int64));
  8336. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X64Reg_MMREG_FIRST];
  8337. if (regVal.mType->mSize == sizeof(int32))
  8338. reg->mm = (uint64)value.mUInt32; // don't sign-extend
  8339. else if (regVal.mType->mSize == sizeof(int64))
  8340. reg->mm = value.mInt64;
  8341. // 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
  8342. reg->fp.fp80[8] = reg->fp.fp80[9] = 0xFF;
  8343. regPtr = reg;
  8344. }
  8345. else if ((regVal.mRegNum >= X64Reg_XMMREG_FIRST) && (regVal.mRegNum <= X64Reg_XMMREG_LAST))
  8346. {
  8347. int xmmMajor = (regVal.mRegNum - X64Reg_XMMREG_FIRST) >> 2;
  8348. int xmmMinor = (regVal.mRegNum - X64Reg_XMMREG_FIRST) & 3;
  8349. if (value.mType->GetByteCount() == 4)
  8350. registers->mXmmRegsArray[xmmMajor].f[xmmMinor] = value.mSingle;
  8351. else if (value.mType->GetByteCount() == 8)
  8352. registers->mXmmDRegsArray[xmmMajor].d[xmmMinor] = value.mDouble;
  8353. else
  8354. BF_FATAL("Invalid XMM set value type");
  8355. regPtr = &registers->mXmmRegsArray[xmmMajor];
  8356. }
  8357. else if ((regVal.mRegNum >= X64Reg_M128_XMMREG_FIRST) && (regVal.mRegNum <= X64Reg_M128_XMMREG_LAST))
  8358. {
  8359. outError = "Cannot write directly to 128-bit XMM register, please use inner float components";
  8360. return false;
  8361. }
  8362. else if ((regVal.mRegNum >= X64Reg_FLAG_FIRST) && (regVal.mRegNum <= X64Reg_FLAG_LAST))
  8363. {
  8364. int flagBit = CPURegisters::GetFlagBitForRegister(regVal.mRegNum);
  8365. if (flagBit >= 0)
  8366. {
  8367. if (value.mBool)
  8368. registers->mIntRegs.efl |= ((uint64)1 << flagBit);
  8369. else
  8370. registers->mIntRegs.efl &= ~((uint64)1 << flagBit);
  8371. regPtr = &registers->mIntRegs.efl;
  8372. }
  8373. else
  8374. {
  8375. outError = "Unrecognized flag";
  8376. return false;
  8377. }
  8378. }
  8379. else if ((regVal.mRegNum >= X64Reg_CAT_FIRST) && (regVal.mRegNum <= X64Reg_CAT_LAST))
  8380. {
  8381. outError = "Cannot write directly to register categories, please use inner float components";
  8382. return false;
  8383. }
  8384. else
  8385. BF_FATAL("Not implemented");
  8386. #endif
  8387. if (callStackIdx == 0)
  8388. {
  8389. SetRegisters(&mCallStack[0]->mRegisters);
  8390. return true;
  8391. }
  8392. else
  8393. {
  8394. bool wasSaved = false;
  8395. for (int calleeStackIdx = callStackIdx - 1; calleeStackIdx >= 0; calleeStackIdx--)
  8396. {
  8397. auto calleeRegisters = &mCallStack[calleeStackIdx]->mRegisters;
  8398. if (!mDebugTarget->PropogateRegisterUpCallStack(registers, calleeRegisters, regPtr, wasSaved))
  8399. {
  8400. outError = "Failed to set register";
  8401. return false;
  8402. }
  8403. if (wasSaved)
  8404. return true;
  8405. }
  8406. // This register wasn't saved, so commit it to the callstack top
  8407. return AssignToReg(0, regVal, value, outError);
  8408. }
  8409. }
  8410. String WinDebugger::GetAutocompleteOutput(DwAutoComplete& autoComplete)
  8411. {
  8412. String val = "\n:autocomplete\n";
  8413. if (autoComplete.mInsertStartIdx != -1)
  8414. {
  8415. val += StrFormat("insertRange\t%d %d\n", autoComplete.mInsertStartIdx, autoComplete.mInsertEndIdx);
  8416. }
  8417. Array<AutoCompleteEntry*> entries;
  8418. for (auto& entry : autoComplete.mEntriesSet)
  8419. {
  8420. entries.Add(&entry);
  8421. }
  8422. std::sort(entries.begin(), entries.end(), [](AutoCompleteEntry* lhs, AutoCompleteEntry* rhs)
  8423. {
  8424. return stricmp(lhs->mDisplay, rhs->mDisplay) < 0;
  8425. });
  8426. for (auto entry : entries)
  8427. {
  8428. val += String(entry->mEntryType);
  8429. val += "\t";
  8430. val += String(entry->mDisplay);
  8431. val += "\n";
  8432. }
  8433. /*if (autoComplete.mEntries.size() != 0)
  8434. {
  8435. for (auto& entry : autoComplete.mEntries)
  8436. {
  8437. val += String(entry.mEntryType) + "\t" + String(entry.mDisplay) + "\n";
  8438. }
  8439. }*/
  8440. return val;
  8441. }
  8442. String WinDebugger::EvaluateToAddress(const StringImpl& expr, int callStackIdx, int cursorPos)
  8443. {
  8444. AutoCrit autoCrit(mDebugManager->mCritSect);
  8445. if (IsInRunState())
  8446. return "!Target not paused";
  8447. auto dbgModule = GetCallStackDbgModule(callStackIdx);
  8448. auto dbgCompileUnit = GetCallStackCompileUnit(callStackIdx);
  8449. BfParser parser(mBfSystem);
  8450. parser.mCompatMode = true;
  8451. BfPassInstance bfPassInstance(mBfSystem);
  8452. auto terminatedExpr = expr + ";";
  8453. parser.SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  8454. parser.Parse(&bfPassInstance);
  8455. BfReducer bfReducer;
  8456. bfReducer.mAlloc = parser.mAlloc;
  8457. bfReducer.mSystem = mBfSystem;
  8458. bfReducer.mPassInstance = &bfPassInstance;
  8459. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser.mRootNode);
  8460. bfReducer.mVisitorPos.MoveNext();
  8461. bfReducer.mSource = &parser;
  8462. auto exprNode = bfReducer.CreateExpression(parser.mRootNode->GetFirst());
  8463. parser.Close();
  8464. DwAutoComplete autoComplete;
  8465. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, callStackIdx, cursorPos);
  8466. if (cursorPos != -1)
  8467. dbgExprEvaluator.mAutoComplete = &autoComplete;
  8468. dbgExprEvaluator.mDbgCompileUnit = dbgCompileUnit;
  8469. DwFormatInfo formatInfo;
  8470. formatInfo.mCallStackIdx = callStackIdx;
  8471. DbgTypedValue exprResult;
  8472. if (exprNode != NULL)
  8473. exprResult = dbgExprEvaluator.Resolve(exprNode);
  8474. DbgType* resultType = exprResult.mType->RemoveModifiers();
  8475. String val;
  8476. if (bfPassInstance.HasFailed())
  8477. {
  8478. val = StrFormat("!%d\t%d\t%s", bfPassInstance.mErrors[0]->mSrcStart, bfPassInstance.mErrors[0]->GetSrcLength(), bfPassInstance.mErrors[0]->mError.c_str());
  8479. }
  8480. else if (exprResult.mType == NULL)
  8481. {
  8482. val = "!Invalid expression";
  8483. }
  8484. else if (!resultType->IsPointerOrRef())
  8485. {
  8486. if (exprResult.mSrcAddress != 0)
  8487. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  8488. else
  8489. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  8490. }
  8491. else
  8492. {
  8493. auto innerType = resultType->mTypeParam;
  8494. int byteCount = innerType->GetByteCount();
  8495. if (byteCount == 0)
  8496. {
  8497. 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());
  8498. }
  8499. #ifdef BF_DBG_32
  8500. else if ((byteCount != 1) && (byteCount != 2) && (byteCount != 4))
  8501. {
  8502. 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);
  8503. }
  8504. #else
  8505. else if ((byteCount != 1) && (byteCount != 2) && (byteCount != 4) && (byteCount != 8))
  8506. {
  8507. 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);
  8508. }
  8509. #endif
  8510. else
  8511. {
  8512. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", byteCount);
  8513. }
  8514. }
  8515. if (cursorPos != -1)
  8516. val += GetAutocompleteOutput(autoComplete);
  8517. return val;
  8518. }
  8519. // This is currently only used for autocomplete during conditional breakpoint expression entry.
  8520. // If we want to use it for more than that then remove DwEvalExpressionFlags_ValidateOnly
  8521. String WinDebugger::EvaluateAtAddress(const StringImpl& expr, intptr atAddr, int cursorPos)
  8522. {
  8523. AutoCrit autoCrit(mDebugManager->mCritSect);
  8524. if (IsInRunState())
  8525. return "!Target not paused";
  8526. if (!IsPaused())
  8527. return "!Target not running";
  8528. WdStackFrame stackFrame;
  8529. memset(&stackFrame.mRegisters, 0, sizeof(stackFrame.mRegisters));
  8530. stackFrame.mHasGottenSubProgram = true;
  8531. *stackFrame.mRegisters.GetPCRegisterRef() = (intptr_target)atAddr;
  8532. stackFrame.mSubProgram = mDebugTarget->FindSubProgram((addr_target)atAddr);
  8533. if (stackFrame.mSubProgram == NULL)
  8534. return "!Invalid address";
  8535. mCallStack.push_back(&stackFrame);
  8536. int callStackIdx = (int)mCallStack.size() - 1;
  8537. String val = Evaluate(expr, callStackIdx, cursorPos, -1, DwEvalExpressionFlag_ValidateOnly);
  8538. mCallStack.pop_back();
  8539. return val;
  8540. }
  8541. String WinDebugger::GetAutoExpressions(int callStackIdx, uint64 memoryRangeStart, uint64 memoryRangeLen)
  8542. {
  8543. BP_ZONE("WinDebugger::GetAutoExpressions");
  8544. AutoCrit autoCrit(mDebugManager->mCritSect);
  8545. if (IsInRunState())
  8546. return "!Not paused";
  8547. if (!IsPaused())
  8548. return "!Not running";
  8549. if (!FixCallStackIdx(callStackIdx))
  8550. return "";
  8551. CPUStackFrame* stackFrame = (callStackIdx >= 0) ? mCallStack[callStackIdx] : mCallStack.front();
  8552. String result;
  8553. DbgAutoValueMapType dwarfAutos;
  8554. mDebugTarget->GetAutoValueNames(dwarfAutos, stackFrame, memoryRangeStart, memoryRangeLen);
  8555. for (auto const &a : dwarfAutos)
  8556. {
  8557. std::pair<uint64, uint64> varRange = a.mValue;
  8558. if (varRange.first != 0)
  8559. result += StrFormat("&%s\t%llu\t%llu\n", a.mKey.c_str(), varRange.second, varRange.first);
  8560. else
  8561. result += StrFormat("?%s\t%llu\n", a.mKey.c_str(), varRange.second);
  8562. }
  8563. #ifdef BF_DBG_64
  8564. // add int regs
  8565. const char* regStrs[] = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "rip", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", 0 };
  8566. #else
  8567. // add int regs
  8568. const char* regStrs[] = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "eip", 0 };
  8569. #endif
  8570. for (const char** p = regStrs; *p; ++p)
  8571. result += StrFormat("$%s\t%d\n", *p, sizeof(addr_target));
  8572. if (callStackIdx < (int)mCallStack.size() - 2)
  8573. {
  8574. WdStackFrame* prevStackFrame = mCallStack[callStackIdx + 1];
  8575. // Inlined methods have no stack frame
  8576. int stackSize = prevStackFrame->mRegisters.GetSP() - stackFrame->mRegisters.GetSP();
  8577. result += StrFormat("&$StackFrame\t%llu\t%llu\n", stackSize, stackFrame->mRegisters.GetSP());
  8578. }
  8579. return result;
  8580. }
  8581. String WinDebugger::GetAutoLocals(int stackFrameIdx, bool showRegs)
  8582. {
  8583. BP_ZONE("WinDebugger::GetAutoExpressions");
  8584. AutoCrit autoCrit(mDebugManager->mCritSect);
  8585. if (IsInRunState())
  8586. return "";
  8587. if (!IsPaused())
  8588. return "";
  8589. if (mCallStack.size() == 0)
  8590. UpdateCallStack();
  8591. String result;
  8592. Array<String> localList;
  8593. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  8594. UpdateCallStackMethod(actualStackFrameIdx);
  8595. if (actualStackFrameIdx >= mCallStack.size())
  8596. return "";
  8597. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  8598. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  8599. if (dwSubprogram == NULL)
  8600. return "";
  8601. auto langage = dwSubprogram->GetLanguage();
  8602. DbgLineData* dwLineData = FindLineDataInSubprogram(wdStackFrame->GetSourcePC(), dwSubprogram);
  8603. if (dwLineData == NULL)
  8604. return "";
  8605. dwSubprogram->PopulateSubprogram();
  8606. mDebugTarget->GetAutoLocalsInBlock(localList, dwSubprogram, &dwSubprogram->mBlock, wdStackFrame, dwLineData);
  8607. String lastLocal;
  8608. for (auto local : localList)
  8609. {
  8610. if (langage == DbgLanguage_C)
  8611. {
  8612. if ((local == "this") && (strncmp(dwSubprogram->mName, "<lambda_", 8) == 0))
  8613. {
  8614. // Use explicit "$this" so we can see the actual capture
  8615. result += "$this\n";
  8616. continue;
  8617. }
  8618. }
  8619. bool wasAlias = false;
  8620. for (int i = 0; i < (int)local.length() - 1; i++)
  8621. {
  8622. if ((local[i] == '$') && (local[i + 1] == 'a'))
  8623. {
  8624. // Alias
  8625. wasAlias = true;
  8626. String localName = local.Substring(0, i) + "\n";
  8627. if (localName != lastLocal)
  8628. {
  8629. result += localName;
  8630. lastLocal = localName;
  8631. }
  8632. break;
  8633. }
  8634. }
  8635. if (!wasAlias)
  8636. result += local + "\n";
  8637. }
  8638. if (showRegs)
  8639. {
  8640. result += "$FLAGS\n";
  8641. UpdateRegisterUsage(stackFrameIdx);
  8642. for (int regIdx = 0; regIdx < (int)wdStackFrame->mRegForms.size(); regIdx++)
  8643. {
  8644. if (wdStackFrame->mRegForms[regIdx] != RegForm_Invalid)
  8645. result += "$" + String(CPURegisters::GetRegisterName(regIdx)) + "\n";
  8646. }
  8647. }
  8648. return result;
  8649. }
  8650. String WinDebugger::CompactChildExpression(const StringImpl& expr, const StringImpl& parentExpr, int callStackIdx)
  8651. {
  8652. DbgCompileUnit* compileUnit = GetCallStackCompileUnit(callStackIdx);
  8653. DbgModule* dbgModule = GetCallStackDbgModule(callStackIdx);
  8654. if (dbgModule == NULL)
  8655. return "!failed";
  8656. DbgLanguage language = DbgLanguage_Unknown;
  8657. if (compileUnit != NULL)
  8658. language = compileUnit->mLanguage;
  8659. BfPassInstance bfPassInstance(mBfSystem);
  8660. BfParser parser(mBfSystem);
  8661. parser.mCompatMode = language != DbgLanguage_Beef;
  8662. auto terminatedExpr = expr + ";";
  8663. parser.SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  8664. parser.Parse(&bfPassInstance);
  8665. BfParser parentParser(mBfSystem);
  8666. auto terminatedParentExpr = parentExpr + ";";
  8667. parentParser.mCompatMode = language != DbgLanguage_Beef;
  8668. parentParser.SetSource(terminatedParentExpr.c_str(), terminatedParentExpr.length());
  8669. parentParser.Parse(&bfPassInstance);
  8670. BfReducer bfReducer;
  8671. bfReducer.mCompatMode = true;
  8672. bfReducer.mAlloc = parser.mAlloc;
  8673. bfReducer.mSystem = mBfSystem;
  8674. bfReducer.mPassInstance = &bfPassInstance;
  8675. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser.mRootNode);
  8676. bfReducer.mVisitorPos.MoveNext();
  8677. bfReducer.mSource = &parser;
  8678. auto exprNode = bfReducer.CreateExpression(parser.mRootNode->GetFirst());
  8679. bfReducer.mAlloc = parentParser.mAlloc;
  8680. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parentParser.mRootNode);
  8681. bfReducer.mVisitorPos.MoveNext();
  8682. auto parentExprNode = bfReducer.CreateExpression(parentParser.mRootNode->GetFirst());
  8683. parser.Close();
  8684. if ((exprNode == NULL) || (parentExprNode == NULL))
  8685. return "!failed";
  8686. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, callStackIdx, -1);
  8687. DwFormatInfo formatInfo;
  8688. formatInfo.mCallStackIdx = callStackIdx;
  8689. String formatFlags;
  8690. String assignExpr;
  8691. if ((exprNode != NULL) && (exprNode->GetSrcEnd() < (int) expr.length()))
  8692. {
  8693. formatFlags = Trim(expr.Substring(exprNode->GetSrcEnd()));
  8694. if (formatFlags.length() > 0)
  8695. {
  8696. String errorString = "Invalid expression";
  8697. if (!ParseFormatInfo(dbgModule, formatFlags, &formatInfo, &bfPassInstance, NULL, &assignExpr, &errorString))
  8698. {
  8699. bfPassInstance.FailAt(errorString, parser.mSourceData, exprNode->GetSrcEnd(), (int) expr.length() - exprNode->GetSrcEnd());
  8700. formatFlags = "";
  8701. }
  8702. }
  8703. }
  8704. dbgExprEvaluator.mExplicitThis = formatInfo.mExplicitThis;
  8705. dbgExprEvaluator.mExplicitThisExpr = parentExprNode;
  8706. DbgTypedValue exprResult = dbgExprEvaluator.Resolve(exprNode);
  8707. BfAstNode* headNode = dbgExprEvaluator.FinalizeExplicitThisReferences(exprNode);
  8708. BfPrinter printer(parser.mRootNode, NULL, NULL);
  8709. printer.mIgnoreTrivia = true;
  8710. printer.mReformatting = true;
  8711. printer.VisitChild(headNode);
  8712. auto result = printer.mOutString;
  8713. if (formatInfo.mNoVisualizers)
  8714. result += ", nv";
  8715. if (formatInfo.mNoMembers)
  8716. result += ", nm";
  8717. if (formatInfo.mNoEdit)
  8718. result += ", ne";
  8719. if (formatInfo.mIgnoreDerivedClassInfo)
  8720. result += ", nd";
  8721. if (formatInfo.mDisplayType == DwDisplayType_Ascii)
  8722. result += ", s";
  8723. if (formatInfo.mDisplayType == DwDisplayType_Utf8)
  8724. result += ", s8";
  8725. if (formatInfo.mDisplayType == DwDisplayType_Utf16)
  8726. result += ", s16";
  8727. if (formatInfo.mDisplayType == DwDisplayType_Utf32)
  8728. result += ", s32";
  8729. return result;
  8730. }
  8731. String WinDebugger::GetThreadInfo()
  8732. {
  8733. AutoCrit autoCrit(mDebugManager->mCritSect);
  8734. String retStr;
  8735. if ((mActiveThread == NULL) && (!mIsRunning))
  8736. {
  8737. retStr = "";
  8738. }
  8739. else
  8740. {
  8741. if (mActiveThread != NULL)
  8742. retStr = StrFormat("%d", mActiveThread->mThreadId);
  8743. for (auto threadInfo : mThreadList)
  8744. {
  8745. SetAndRestoreValue<WdThreadInfo*> prevThread(mActiveThread, threadInfo);
  8746. retStr += "\n";
  8747. for (int pass = 0; pass < 2; pass++)
  8748. {
  8749. CPURegisters registers;
  8750. PopulateRegisters(&registers);
  8751. String locString = EncodeDataPtr((addr_target)registers.GetPC(), true);
  8752. TryGetThreadName(threadInfo);
  8753. bool hadThreadName = true;
  8754. String threadName = threadInfo->mName;
  8755. if (threadName.IsEmpty())
  8756. {
  8757. hadThreadName = false;
  8758. if (threadInfo->mThreadId == mProcessInfo.dwThreadId)
  8759. threadName = "Main Thread";
  8760. else
  8761. threadName = "Worker Thread";
  8762. }
  8763. bool isInvalid = false;
  8764. addr_target appendAddr = 0;
  8765. for (int stackIdx = 0; true; stackIdx++)
  8766. {
  8767. auto subProgram = mDebugTarget->FindSubProgram(registers.GetPC(), DbgOnDemandKind_LocalOnly);
  8768. if (subProgram != NULL)
  8769. {
  8770. if (subProgram->mLineInfo != NULL)
  8771. {
  8772. auto module = subProgram->mCompileUnit->mDbgModule;
  8773. if (module->mDisplayName.length() > 0)
  8774. {
  8775. locString = module->mDisplayName + "!" + subProgram->ToString();
  8776. if (!hadThreadName)
  8777. threadName = module->mDisplayName + " thread";
  8778. }
  8779. else
  8780. {
  8781. locString = subProgram->ToString();
  8782. }
  8783. appendAddr = 0;
  8784. break;
  8785. }
  8786. }
  8787. auto module = mDebugTarget->FindDbgModuleForAddress(registers.GetPC());
  8788. if (module == NULL)
  8789. {
  8790. isInvalid = true;
  8791. break;
  8792. }
  8793. appendAddr = (addr_target)registers.GetPC();
  8794. locString = module->mDisplayName + "!" + EncodeDataPtr((addr_target)registers.GetPC(), true);
  8795. if (!hadThreadName)
  8796. threadName = module->mDisplayName + " thread";
  8797. if ((mActiveThread == mExplicitStopThread) && (mActiveBreakpoint != NULL))
  8798. {
  8799. if ((subProgram == NULL) ||
  8800. (mActiveBreakpoint->mAddr < subProgram->mBlock.mLowPC) ||
  8801. (mActiveBreakpoint->mAddr >= subProgram->mBlock.mHighPC))
  8802. break;
  8803. }
  8804. if (pass == 1) // Just take the first item
  8805. break;
  8806. if (stackIdx == 128)
  8807. break; // Too many!
  8808. // if ((ToLower(module->mDisplayName) != "ntdll.dll") && (ToLower(module->mDisplayName) != "kernel32.dll") && (ToLower(module->mDisplayName) != "kernelbase.dll"))
  8809. // break;
  8810. addr_target returnAddr;
  8811. if (!mDebugTarget->RollBackStackFrame(&registers, &returnAddr, true))
  8812. {
  8813. isInvalid = true;
  8814. break;
  8815. }
  8816. }
  8817. if ((isInvalid) && (pass == 0))
  8818. continue;
  8819. if (appendAddr != 0)
  8820. {
  8821. String symbolName;
  8822. addr_target offset;
  8823. DbgModule* dwarf;
  8824. if (mDebugTarget->FindSymbolAt(appendAddr, &symbolName, &offset, &dwarf))
  8825. {
  8826. String demangledName = BfDemangler::Demangle(symbolName, DbgLanguage_Unknown);
  8827. if (!dwarf->mDisplayName.empty())
  8828. demangledName = dwarf->mDisplayName + "!" + demangledName;
  8829. locString = demangledName + StrFormat("+0x%X", offset);
  8830. }
  8831. }
  8832. retStr += StrFormat("%d\t%s\t%s", threadInfo->mThreadId, threadName.c_str(), locString.c_str());
  8833. String attrs;
  8834. if (threadInfo->mFrozen)
  8835. {
  8836. attrs += "Fr";
  8837. }
  8838. if (!attrs.IsEmpty())
  8839. {
  8840. retStr += "\t";
  8841. retStr += attrs;
  8842. }
  8843. break;
  8844. }
  8845. }
  8846. }
  8847. return retStr;
  8848. }
  8849. void WinDebugger::SetActiveThread(int threadId)
  8850. {
  8851. AutoCrit autoCrit(mDebugManager->mCritSect);
  8852. if (mThreadMap.TryGetValue(threadId, &mActiveThread))
  8853. {
  8854. BfLogDbg("SetActiveThread %d\n", threadId);
  8855. ClearCallStack();
  8856. }
  8857. else
  8858. {
  8859. BfLogDbg("SetActiveThread %d FAILED\n", threadId);
  8860. }
  8861. }
  8862. int WinDebugger::GetActiveThread()
  8863. {
  8864. AutoCrit autoCrit(mDebugManager->mCritSect);
  8865. if (mActiveThread == NULL)
  8866. return -1;
  8867. return mActiveThread->mThreadId;
  8868. }
  8869. void WinDebugger::FreezeThread(int threadId)
  8870. {
  8871. AutoCrit autoCrit(mDebugManager->mCritSect);
  8872. BF_ASSERT(!IsInRunState());
  8873. auto thread = mThreadMap[threadId];
  8874. if (!thread->mFrozen)
  8875. {
  8876. thread->mFrozen = true;
  8877. ::SuspendThread(thread->mHThread);
  8878. BfLogDbg("SuspendThread %d from FreezeThread\n", thread->mThreadId);
  8879. }
  8880. }
  8881. void WinDebugger::ThawThread(int threadId)
  8882. {
  8883. AutoCrit autoCrit(mDebugManager->mCritSect);
  8884. BF_ASSERT(!IsInRunState());
  8885. auto thread = mThreadMap[threadId];
  8886. if (thread->mFrozen)
  8887. {
  8888. thread->mFrozen = false;
  8889. ::ResumeThread(thread->mHThread);
  8890. BfLogDbg("ResumeThread %d from ThawThread\n", thread->mThreadId);
  8891. }
  8892. }
  8893. bool WinDebugger::IsActiveThreadWaiting()
  8894. {
  8895. AutoCrit autoCrit(mDebugManager->mCritSect);
  8896. return mActiveThread == mDebuggerWaitingThread;
  8897. }
  8898. void WinDebugger::ClearCallStack()
  8899. {
  8900. AutoCrit autoCrit(mDebugManager->mCritSect);
  8901. BfLogDbg("ClearCallstack\n");
  8902. BF_ASSERT(mRunState != RunState_DebugEval);
  8903. for (auto wdStackFrame : mCallStack)
  8904. delete wdStackFrame;
  8905. mCallStack.Clear();
  8906. mIsPartialCallStack = true;
  8907. }
  8908. void WinDebugger::UpdateCallStack(bool slowEarlyOut)
  8909. {
  8910. AutoCrit autoCrit(mDebugManager->mCritSect);
  8911. if (!mIsPartialCallStack)
  8912. return;
  8913. BF_ASSERT(!IsInRunState());
  8914. uint32 tickStart = BFTickCount();
  8915. CPURegisters registers;
  8916. if (mCallStack.size() > 0)
  8917. {
  8918. WdStackFrame* wdStackFrame = mCallStack.back();
  8919. if (wdStackFrame->mIsEnd)
  8920. {
  8921. return;
  8922. }
  8923. memcpy(&registers, &wdStackFrame->mRegisters, sizeof(registers));
  8924. bool regsRolledBack = RollBackStackFrame(&registers, mCallStack.size() == 1);
  8925. // If we can't roll them back then mIsEnd should have been set for the previous frame
  8926. BF_ASSERT(regsRolledBack);
  8927. }
  8928. else
  8929. {
  8930. BF_ASSERT(mIsPartialCallStack);
  8931. mCallStack.Reserve(1024);
  8932. PopulateRegisters(&registers);
  8933. BfLogDbg("UpdateCallStack starting. Thread=%d PC=0x%p\n", mActiveThread->mThreadId, registers.GetPC());
  8934. }
  8935. bool isPartial = false;
  8936. // Incrementally fill callstack structure to avoid stepping slowdown during deep nesting
  8937. for (int fillIdx = 0; fillIdx < (slowEarlyOut ? 10000 : 100000); fillIdx++)
  8938. {
  8939. WdStackFrame* wdStackFrame = new WdStackFrame();
  8940. memcpy(&wdStackFrame->mRegisters, &registers, sizeof(registers));
  8941. wdStackFrame->mIsStart = mCallStack.size() == 0;
  8942. wdStackFrame->mIsEnd = false;
  8943. bool rollbackSuccess = false;
  8944. for (int tryCount = 0; tryCount < 16; tryCount++)
  8945. {
  8946. if (!RollBackStackFrame(&registers, wdStackFrame->mIsStart))
  8947. {
  8948. break;
  8949. }
  8950. if (registers.GetPC() > 0xFFFF)
  8951. {
  8952. rollbackSuccess = true;
  8953. break;
  8954. }
  8955. if (mCallStack.size() > 0)
  8956. break; // Only retry for the first frame
  8957. }
  8958. if (!rollbackSuccess)
  8959. wdStackFrame->mIsEnd = true;
  8960. if (registers.GetSP() <= wdStackFrame->mRegisters.GetSP())
  8961. {
  8962. // SP went the wrong direction, stop rolling back
  8963. wdStackFrame->mIsEnd = true;
  8964. }
  8965. mCallStack.push_back(wdStackFrame);
  8966. if (IsMiniDumpDebugger())
  8967. {
  8968. // Make sure to queue up any debug stuff we need
  8969. UpdateCallStackMethod((int)mCallStack.size() - 1);
  8970. }
  8971. if (wdStackFrame->mIsEnd)
  8972. break;
  8973. // Time-limit callstack generation. Most useful for debug mode.
  8974. if ((slowEarlyOut) && ((fillIdx % 100) == 0))
  8975. {
  8976. uint32 tickEnd = BFTickCount();
  8977. if (tickEnd - tickStart >= 10)
  8978. {
  8979. isPartial = true;
  8980. break;
  8981. }
  8982. }
  8983. }
  8984. if (!isPartial)
  8985. mIsPartialCallStack = false;
  8986. }
  8987. int WinDebugger::GetCallStackCount()
  8988. {
  8989. AutoCrit autoCrit(mDebugManager->mCritSect);
  8990. return (int)mCallStack.size();
  8991. }
  8992. int WinDebugger::GetRequestedStackFrameIdx()
  8993. {
  8994. AutoCrit autoCrit(mDebugManager->mCritSect);
  8995. if ((mActiveThread == mExplicitStopThread) && (mRequestedStackFrameIdx >= -1))
  8996. {
  8997. if (mActiveBreakpoint != NULL)
  8998. mRequestedStackFrameIdx = GetBreakStackFrameIdx();
  8999. if (mRequestedStackFrameIdx == -1)
  9000. mRequestedStackFrameIdx = 0;
  9001. return mRequestedStackFrameIdx;
  9002. }
  9003. int newCallStackIdx = 0;
  9004. while (true)
  9005. {
  9006. if (newCallStackIdx >= (int)mCallStack.size() - 1)
  9007. UpdateCallStack();
  9008. if (newCallStackIdx >= (int)mCallStack.size() - 1)
  9009. break;
  9010. intptr addr;
  9011. String file;
  9012. int hotIdx;
  9013. int defLineStart;
  9014. int defLineEnd;
  9015. int line;
  9016. int column;
  9017. int language;
  9018. int stackSize;
  9019. int8 flags;
  9020. GetStackFrameInfo(newCallStackIdx, &addr, &file, &hotIdx, &defLineStart, &defLineEnd, &line, &column, &language, &stackSize, &flags);
  9021. if (!file.empty())
  9022. return newCallStackIdx;
  9023. newCallStackIdx++;
  9024. }
  9025. return 0;
  9026. }
  9027. int WinDebugger::GetBreakStackFrameIdx()
  9028. {
  9029. AutoCrit autoCrit(mDebugManager->mCritSect);
  9030. if ((mActiveBreakpoint == NULL) || (mRunState != RunState_Breakpoint))
  9031. return -1;
  9032. if ((mBreakStackFrameIdx != -1) || (mActiveThread != mExplicitStopThread))
  9033. return mBreakStackFrameIdx;
  9034. mBreakStackFrameIdx = 0;
  9035. BF_ASSERT(mActiveBreakpoint != NULL);
  9036. if (mCallStack.IsEmpty())
  9037. UpdateCallStack();
  9038. if (!mCallStack.IsEmpty())
  9039. {
  9040. UpdateCallStackMethod(0);
  9041. for (int stackIdx = 0; stackIdx < (int)mCallStack.size(); stackIdx++)
  9042. {
  9043. auto callStackEntry = mCallStack[stackIdx];
  9044. if (callStackEntry->mSubProgram == NULL)
  9045. break;
  9046. if ((mActiveBreakpoint->mAddr < callStackEntry->mSubProgram->mBlock.mLowPC) ||
  9047. (mActiveBreakpoint->mAddr >= callStackEntry->mSubProgram->mBlock.mHighPC))
  9048. break;
  9049. DbgSubprogram* specificSubprogram = callStackEntry->mSubProgram;
  9050. auto dwLineData = callStackEntry->mSubProgram->FindClosestLine(mActiveBreakpoint->mAddr, &specificSubprogram);
  9051. if (dwLineData == NULL)
  9052. break;
  9053. if (mActiveBreakpoint->mLineData == dwLineData)
  9054. {
  9055. mBreakStackFrameIdx = stackIdx;
  9056. break;
  9057. }
  9058. }
  9059. }
  9060. return mBreakStackFrameIdx;
  9061. }
  9062. static const char* SafeString(const char* str)
  9063. {
  9064. if (str == NULL)
  9065. return "???";
  9066. return str;
  9067. }
  9068. void WinDebugger::UpdateRegisterUsage(int stackFrameIdx)
  9069. {
  9070. WdStackFrame* wdStackFrame = mCallStack[stackFrameIdx];
  9071. if (wdStackFrame->mRegForms.size() != 0)
  9072. return;
  9073. auto dwSubprogram = wdStackFrame->mSubProgram;
  9074. if (dwSubprogram == NULL)
  9075. return;
  9076. addr_target addr = dwSubprogram->mBlock.mLowPC;
  9077. const uint8* baseOp = nullptr;
  9078. while (addr < dwSubprogram->mBlock.mHighPC)
  9079. {
  9080. CPUInst inst;
  9081. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  9082. break;
  9083. bool overrideForm = inst.mAddress <= (addr_target)wdStackFrame->mRegisters.GetPC();
  9084. inst.MarkRegsUsed(wdStackFrame->mRegForms, overrideForm);
  9085. addr += inst.GetLength();
  9086. }
  9087. }
  9088. // It's safe to pass an invalid idx in here
  9089. void WinDebugger::UpdateCallStackMethod(int stackFrameIdx)
  9090. {
  9091. if (mCallStack.empty())
  9092. return;
  9093. int startIdx = std::min(stackFrameIdx, (int)mCallStack.size() - 1);
  9094. while (startIdx >= 0)
  9095. {
  9096. WdStackFrame* wdStackFrame = mCallStack[startIdx];
  9097. if (wdStackFrame->mHasGottenSubProgram)
  9098. break;
  9099. startIdx--;
  9100. }
  9101. startIdx++;
  9102. for (int checkFrameIdx = startIdx; checkFrameIdx <= stackFrameIdx; checkFrameIdx++)
  9103. {
  9104. //BF_ASSERT(checkFrameIdx < mCallStack.size());
  9105. if (checkFrameIdx >= mCallStack.size())
  9106. break;
  9107. WdStackFrame* wdStackFrame = mCallStack[checkFrameIdx];
  9108. wdStackFrame->mHasGottenSubProgram = true;
  9109. addr_target pcAddress = (addr_target)wdStackFrame->GetSourcePC();
  9110. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress, DbgOnDemandKind_LocalOnly);
  9111. wdStackFrame->mHasGottenSubProgram = true;
  9112. wdStackFrame->mSubProgram = dwSubprogram;
  9113. if ((dwSubprogram == NULL) && (IsMiniDumpDebugger()))
  9114. {
  9115. // FindSymbolAt will queue up debug info if necessary...
  9116. String symbolName;
  9117. addr_target offset;
  9118. DbgModule* dbgModule;
  9119. mDebugTarget->FindSymbolAt(pcAddress, &symbolName, &offset, &dbgModule);
  9120. }
  9121. // Insert inlines
  9122. int insertIdx = checkFrameIdx + 1;
  9123. while ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL))
  9124. {
  9125. WdStackFrame* inlineStackFrame = new WdStackFrame();
  9126. *inlineStackFrame = *wdStackFrame;
  9127. inlineStackFrame->mInInlineMethod = true;
  9128. wdStackFrame->mInInlineCall = true;
  9129. inlineStackFrame->mSubProgram = dwSubprogram->mInlineeInfo->mInlineParent;
  9130. mCallStack.Insert(insertIdx, inlineStackFrame);
  9131. dwSubprogram = dwSubprogram->mInlineeInfo->mInlineParent;
  9132. insertIdx++;
  9133. checkFrameIdx++;
  9134. }
  9135. }
  9136. }
  9137. void WinDebugger::GetCodeAddrInfo(intptr addr, String* outFile, int* outHotIdx, int* outDefLineStart, int* outDefLineEnd, int* outLine, int* outColumn)
  9138. {
  9139. AutoCrit autoCrit(mDebugManager->mCritSect);
  9140. DbgSubprogram* subProgram = NULL;
  9141. DbgLineData* callingLineData = FindLineDataAtAddress((addr_target)addr, &subProgram);
  9142. if (subProgram != NULL)
  9143. {
  9144. *outHotIdx = subProgram->mCompileUnit->mDbgModule->mHotIdx;
  9145. *outFile = subProgram->GetLineSrcFile(*callingLineData)->GetLocalPath();
  9146. *outLine = callingLineData->mLine;
  9147. *outColumn = callingLineData->mColumn;
  9148. FixupLineDataForSubprogram(subProgram);
  9149. DbgLineData* dwStartLineData = NULL;
  9150. DbgLineData* dwEndLineData = NULL;
  9151. if (subProgram->mLineInfo != NULL)
  9152. {
  9153. if (subProgram->mLineInfo->mLines.size() > 0)
  9154. {
  9155. dwStartLineData = &subProgram->mLineInfo->mLines[0];
  9156. dwEndLineData = &subProgram->mLineInfo->mLines.back();
  9157. }
  9158. }
  9159. else
  9160. {
  9161. if (subProgram->mInlineeInfo != NULL)
  9162. {
  9163. dwStartLineData = &subProgram->mInlineeInfo->mFirstLineData;
  9164. dwEndLineData = &subProgram->mInlineeInfo->mLastLineData;
  9165. }
  9166. }
  9167. if (dwEndLineData != NULL)
  9168. {
  9169. if (subProgram->mDeclLine != 0)
  9170. *outDefLineStart = subProgram->mDeclLine - 1;
  9171. else
  9172. *outDefLineStart = dwStartLineData->mLine;
  9173. *outDefLineEnd = dwEndLineData->mLine;
  9174. }
  9175. }
  9176. }
  9177. void WinDebugger::GetStackAllocInfo(intptr addr, int* outThreadId, int* outStackIdx)
  9178. {
  9179. AutoCrit autoCrit(mDebugManager->mCritSect);
  9180. *outThreadId = 0;
  9181. if (outStackIdx != NULL)
  9182. *outStackIdx = -1;
  9183. if (!IsPaused())
  9184. return;
  9185. for (auto thread : mThreadList)
  9186. {
  9187. NT_TIB64 tib = { 0 };
  9188. if (!ReadMemory((intptr)thread->mThreadLocalBase, sizeof(tib), &tib))
  9189. continue;
  9190. MEMORY_BASIC_INFORMATION stackInfo = { 0 };
  9191. if (VirtualQueryEx(mProcessInfo.hProcess, (void*)(tib.StackBase - 1), &stackInfo, sizeof(MEMORY_BASIC_INFORMATION)) == 0)
  9192. continue;
  9193. if ((addr >= (intptr)stackInfo.AllocationBase) && (addr < (intptr)tib.StackBase))
  9194. {
  9195. *outThreadId = thread->mThreadId;
  9196. if (outStackIdx == NULL)
  9197. return;
  9198. if (mActiveThread == thread)
  9199. {
  9200. UpdateCallStack(false);
  9201. for (int callStackIdx = 0; callStackIdx < (int)mCallStack.size(); callStackIdx++)
  9202. {
  9203. UpdateCallStackMethod(callStackIdx);
  9204. auto stackFrame = mCallStack[callStackIdx];
  9205. if (addr >= (intptr)stackFrame->mRegisters.GetSP())
  9206. {
  9207. *outStackIdx = callStackIdx;
  9208. }
  9209. }
  9210. }
  9211. return;
  9212. }
  9213. }
  9214. }
  9215. String WinDebugger::GetStackFrameInfo(int stackFrameIdx, intptr* addr, String* outFile, int* outHotIdx, int* outDefLineStart, int* outDefLineEnd,
  9216. int* outLine, int* outColumn, int* outLanguage, int* outStackSize, int8* outFlags)
  9217. {
  9218. enum FrameFlags
  9219. {
  9220. FrameFlags_Optimized = 1,
  9221. FrameFlags_HasPendingDebugInfo = 2,
  9222. FrameFlags_CanGetOldSource = 4,
  9223. FrameFlags_WasHotReplaced = 8,
  9224. };
  9225. AutoCrit autoCrit(mDebugManager->mCritSect);
  9226. if (mCallStack.size() == 0)
  9227. UpdateCallStack();
  9228. *addr = 0;
  9229. *outFile = "";
  9230. *outHotIdx = 0;
  9231. *outDefLineStart = -1;
  9232. *outDefLineEnd = -1;
  9233. *outLine = -1;
  9234. *outColumn = 0;
  9235. *outLanguage = 0;
  9236. *outStackSize = 0;
  9237. *outFlags = 0;
  9238. UpdateCallStackMethod(stackFrameIdx);
  9239. if (stackFrameIdx >= mCallStack.size())
  9240. {
  9241. return "";
  9242. }
  9243. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9244. UpdateCallStackMethod(actualStackFrameIdx);
  9245. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9246. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  9247. if (stackFrameIdx == -1)
  9248. pcAddress = mShowPCOverride;
  9249. *addr = pcAddress;
  9250. if (actualStackFrameIdx < (int)mCallStack.size() - 2)
  9251. {
  9252. WdStackFrame* prevStackFrame = mCallStack[actualStackFrameIdx + 1];
  9253. // Inlined methods have no stack frame
  9254. *outStackSize = prevStackFrame->mRegisters.GetSP() - wdStackFrame->mRegisters.GetSP();
  9255. }
  9256. const auto& _CheckHashSrcFile = [&](String& outStr, DbgModule* dbgModule, DbgSrcFile* srcFile)
  9257. {
  9258. if (srcFile->mHashKind != DbgHashKind_None)
  9259. {
  9260. outStr += "#";
  9261. if (srcFile->mHashKind == DbgHashKind_MD5)
  9262. {
  9263. for (int i = 0; i < 16; i++)
  9264. {
  9265. outStr += StrFormat("%02X", srcFile->mHash[i]);
  9266. }
  9267. }
  9268. else
  9269. {
  9270. for (int i = 0; i < 32; i++)
  9271. {
  9272. outStr += StrFormat("%02X", srcFile->mHash[i]);
  9273. }
  9274. }
  9275. }
  9276. };
  9277. if (wdStackFrame->mInInlineMethod)
  9278. {
  9279. WdStackFrame* nextStackFrame = mCallStack[actualStackFrameIdx - 1];
  9280. auto subProgram = nextStackFrame->mSubProgram;
  9281. // int callFileIdx = subProgram->mDeclFileIdx;
  9282. // if (callFileIdx > 0)
  9283. // {
  9284. // DbgSrcFile* srcFile = subProgram->mCompileUnit->mSrcFileRefs[callFileIdx - 1].mSrcFile;
  9285. // _CheckHashSrcFile(*outFile, subProgram->mCompileUnit->mDbgModule, srcFile);
  9286. // *outFile = srcFile->GetLocalPath();
  9287. // *outLine = subProgram->mDeclLine - 1;
  9288. // }
  9289. // else
  9290. {
  9291. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  9292. DbgSubprogram* parentSubprogram = subProgram->mInlineeInfo->mInlineParent; // Require it be in the inline parent
  9293. auto foundLine = parentSubprogram->FindClosestLine(subProgram->mBlock.mLowPC, &parentSubprogram);
  9294. if (foundLine != NULL)
  9295. {
  9296. auto srcFile = parentSubprogram->GetLineSrcFile(*foundLine);
  9297. *outFile = srcFile->GetLocalPath();
  9298. _CheckHashSrcFile(*outFile, subProgram->mCompileUnit->mDbgModule, srcFile);
  9299. *outLine = foundLine->mLine;
  9300. }
  9301. }
  9302. *outLanguage = subProgram->GetLanguage();
  9303. *outHotIdx = subProgram->mCompileUnit->mDbgModule->mHotIdx;
  9304. *outColumn = -1;
  9305. DbgSubprogram* callingSubProgram = NULL;
  9306. DbgLineData* callingLineData = FindLineDataAtAddress(nextStackFrame->mSubProgram->mBlock.mLowPC - 1, &callingSubProgram);
  9307. if ((callingLineData != NULL) && (callingSubProgram == wdStackFrame->mSubProgram))
  9308. {
  9309. auto callingSrcFile = callingSubProgram->GetLineSrcFile(*callingLineData);
  9310. *outLanguage = callingSubProgram->mCompileUnit->mLanguage;
  9311. auto srcFile = callingSrcFile;
  9312. *outFile = srcFile->GetLocalPath();
  9313. _CheckHashSrcFile(*outFile, subProgram->mCompileUnit->mDbgModule, srcFile);
  9314. if (*outLine == callingLineData->mLine)
  9315. *outColumn = callingLineData->mColumn;
  9316. }
  9317. String name = wdStackFrame->mSubProgram->ToString();
  9318. DbgModule* dbgModule = wdStackFrame->mSubProgram->mCompileUnit->mDbgModule;
  9319. if (!dbgModule->mDisplayName.empty())
  9320. name = dbgModule->mDisplayName + "!" + name;
  9321. return name;
  9322. }
  9323. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  9324. if (dwSubprogram != NULL)
  9325. {
  9326. if (dwSubprogram->mIsOptimized)
  9327. *outFlags |= FrameFlags_Optimized;
  9328. String demangledName;
  9329. if ((dwSubprogram->mName != NULL) && (strncmp(dwSubprogram->mName, ":Sep@", 5) == 0))
  9330. {
  9331. char* p;
  9332. auto addr = strtoll(dwSubprogram->mName + 5, &p, 16);
  9333. if (addr != 0)
  9334. {
  9335. auto parentSubprogram = mDebugTarget->FindSubProgram(addr);
  9336. if (parentSubprogram != NULL)
  9337. demangledName = parentSubprogram->ToString();
  9338. }
  9339. }
  9340. if (demangledName.IsEmpty())
  9341. demangledName = dwSubprogram->ToString();
  9342. DbgSrcFile* dwSrcFile = NULL;
  9343. DbgLineData* dwLineData = NULL;
  9344. FixupLineDataForSubprogram(dwSubprogram);
  9345. addr_target findAddress = wdStackFrame->GetSourcePC();
  9346. DbgSubprogram* specificSubprogram = dwSubprogram;
  9347. dwLineData = dwSubprogram->FindClosestLine(findAddress, &specificSubprogram);
  9348. if (dwLineData != NULL)
  9349. dwSrcFile = dwSubprogram->GetLineSrcFile(*dwLineData);
  9350. DbgLineData* dwStartLineData = NULL;
  9351. DbgLineData* dwEndLineData = NULL;
  9352. if (dwSubprogram->mLineInfo != NULL)
  9353. {
  9354. if (dwSubprogram->mLineInfo->mLines.size() > 0)
  9355. {
  9356. dwStartLineData = &dwSubprogram->mLineInfo->mLines[0];
  9357. dwEndLineData = &dwSubprogram->mLineInfo->mLines.back();
  9358. }
  9359. }
  9360. else
  9361. {
  9362. if (dwSubprogram->mInlineeInfo != NULL)
  9363. {
  9364. dwStartLineData = &dwSubprogram->mInlineeInfo->mFirstLineData;
  9365. dwEndLineData = &dwSubprogram->mInlineeInfo->mLastLineData;
  9366. }
  9367. }
  9368. DbgModule* dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  9369. if (!dbgModule->mDisplayName.empty())
  9370. demangledName = dbgModule->mDisplayName + "!" + demangledName;
  9371. if (dwSubprogram->mWasHotReplaced)
  9372. demangledName = "#" + demangledName;
  9373. if (dbgModule->HasPendingDebugInfo())
  9374. *outFlags |= FrameFlags_HasPendingDebugInfo;
  9375. if (dbgModule->CanGetOldSource())
  9376. *outFlags |= FrameFlags_CanGetOldSource;
  9377. if (dwSubprogram->mWasHotReplaced)
  9378. *outFlags |= FrameFlags_WasHotReplaced;
  9379. if ((dwLineData != NULL) && (dwSrcFile != NULL))
  9380. {
  9381. *outFile = dwSrcFile->GetLocalPath();
  9382. _CheckHashSrcFile(*outFile, dbgModule, dwSrcFile);
  9383. *outHotIdx = dbgModule->mHotIdx;
  9384. *outLine = dwLineData->mLine;
  9385. *outColumn = dwLineData->mColumn;
  9386. *outLanguage = (int)dwSubprogram->mCompileUnit->mLanguage;
  9387. if (dwEndLineData != NULL)
  9388. {
  9389. if (dwSubprogram->mDeclLine != 0)
  9390. *outDefLineStart = dwSubprogram->mDeclLine - 1;
  9391. else
  9392. *outDefLineStart = dwStartLineData->mLine;
  9393. *outDefLineEnd = dwEndLineData->mLine;
  9394. }
  9395. return demangledName;
  9396. }
  9397. else
  9398. {
  9399. return demangledName + StrFormat("+0x%X", pcAddress - dwSubprogram->mBlock.mLowPC);
  9400. }
  9401. }
  9402. else
  9403. {
  9404. String symbolName;
  9405. addr_target offset;
  9406. DbgModule* dbgModule;
  9407. if (mDebugTarget->FindSymbolAt(pcAddress, &symbolName, &offset, &dbgModule))
  9408. {
  9409. if (dbgModule->HasPendingDebugInfo())
  9410. {
  9411. *outFlags |= FrameFlags_HasPendingDebugInfo;
  9412. if (mPendingDebugInfoLoad.Contains(dbgModule))
  9413. {
  9414. String outName = EncodeDataPtr(pcAddress, true);
  9415. if ((dbgModule != NULL) && (!dbgModule->mDisplayName.empty()))
  9416. outName = dbgModule->mDisplayName + "!<Loading...>" + outName;
  9417. return outName;
  9418. }
  9419. }
  9420. String demangledName = BfDemangler::Demangle(symbolName, DbgLanguage_Unknown);
  9421. if (!dbgModule->mDisplayName.empty())
  9422. demangledName = dbgModule->mDisplayName + "!" + demangledName;
  9423. return demangledName + StrFormat("+0x%X", offset);
  9424. }
  9425. }
  9426. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress(pcAddress);
  9427. if (dbgModule != NULL)
  9428. {
  9429. if (dbgModule->HasPendingDebugInfo())
  9430. *outFlags |= FrameFlags_HasPendingDebugInfo;
  9431. }
  9432. String outName = EncodeDataPtr(pcAddress, true);
  9433. if ((dbgModule != NULL) && (!dbgModule->mDisplayName.empty()))
  9434. outName = dbgModule->mDisplayName + "!" + outName;
  9435. return outName;
  9436. }
  9437. String WinDebugger::Callstack_GetStackFrameOldFileInfo(int stackFrameIdx)
  9438. {
  9439. AutoCrit autoCrit(mDebugManager->mCritSect);
  9440. if (!FixCallStackIdx(stackFrameIdx))
  9441. return "";
  9442. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9443. UpdateCallStackMethod(actualStackFrameIdx);
  9444. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9445. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  9446. if (dwSubprogram != NULL)
  9447. {
  9448. DbgSrcFile* dwSrcFile = NULL;
  9449. DbgLineData* dwLineData = NULL;
  9450. FixupLineDataForSubprogram(dwSubprogram);
  9451. addr_target findAddress = wdStackFrame->GetSourcePC();
  9452. DbgSubprogram* dbgSubprogram = NULL;
  9453. DbgSrcFile* dbgSrcFile = NULL;
  9454. dwLineData = dwSubprogram->FindClosestLine(findAddress, &dbgSubprogram, &dbgSrcFile);
  9455. DbgModule* dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  9456. if (dbgSrcFile != NULL)
  9457. {
  9458. // Note: we must use mFilePath here, make sure we don't use GetLocalPath()
  9459. return dbgModule->GetOldSourceCommand(dbgSrcFile->mFilePath);
  9460. }
  9461. }
  9462. return "";
  9463. }
  9464. int WinDebugger::GetJmpState(int stackFrameIdx)
  9465. {
  9466. AutoCrit autoCrit(mDebugManager->mCritSect);
  9467. if (mCallStack.size() == 0)
  9468. UpdateCallStack();
  9469. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9470. UpdateCallStackMethod(actualStackFrameIdx);
  9471. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9472. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  9473. CPUInst inst;
  9474. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  9475. return -1;
  9476. return inst.GetJmpState(wdStackFrame->mRegisters.mIntRegs.efl);
  9477. }
  9478. intptr WinDebugger::GetStackFrameCalleeAddr(int stackFrameIdx)
  9479. {
  9480. AutoCrit autoCrit(mDebugManager->mCritSect);
  9481. if (mCallStack.size() == 0)
  9482. UpdateCallStack();
  9483. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9484. UpdateCallStackMethod(actualStackFrameIdx);
  9485. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9486. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  9487. if (stackFrameIdx == -1)
  9488. pcAddress = mShowPCOverride;
  9489. if (wdStackFrame->mInInlineMethod)
  9490. {
  9491. WdStackFrame* inlineStackFrame = mCallStack[actualStackFrameIdx - 1];
  9492. return inlineStackFrame->mSubProgram->mBlock.mLowPC - 1;
  9493. }
  9494. return pcAddress - 1;
  9495. }
  9496. String WinDebugger::GetStackMethodOwner(int stackFrameIdx, int& language)
  9497. {
  9498. AutoCrit autoCrit(mDebugManager->mCritSect);
  9499. if (mCallStack.size() == 0)
  9500. UpdateCallStack();
  9501. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9502. if (actualStackFrameIdx >= (int)mCallStack.size())
  9503. actualStackFrameIdx = 0;
  9504. UpdateCallStackMethod(actualStackFrameIdx);
  9505. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9506. if (wdStackFrame->mSubProgram == NULL)
  9507. return "";
  9508. auto parentType = wdStackFrame->mSubProgram->GetParent();
  9509. if (parentType == NULL)
  9510. return "";
  9511. parentType = parentType->GetPrimaryType();
  9512. language = (int)parentType->GetLanguage();
  9513. return parentType->ToString();
  9514. }
  9515. String WinDebugger::FindCodeAddresses(const StringImpl& fileName, int line, int column, bool allowAutoResolve)
  9516. {
  9517. String result;
  9518. if (mDebugTarget == NULL)
  9519. return "";
  9520. DbgSrcFile* srcFile = mDebugTarget->GetSrcFile(fileName);
  9521. if (srcFile == NULL)
  9522. return result;
  9523. bool foundInSequence = false;
  9524. WdBreakpoint* prevBreakpoint = NULL;
  9525. int bestLineOffset = 0x7FFFFFFF;
  9526. for (auto dbgSubprogram : srcFile->mLineDataRefs)
  9527. {
  9528. for (auto& lineData : dbgSubprogram->mLineInfo->mLines)
  9529. {
  9530. auto lineSrcFile = dbgSubprogram->GetLineSrcFile(lineData);
  9531. if (lineSrcFile != srcFile)
  9532. continue;
  9533. int lineOffset = lineData.mLine - line;
  9534. if ((lineOffset >= 0) && (lineOffset <= 12) && (lineOffset <= bestLineOffset))
  9535. {
  9536. if (lineOffset < bestLineOffset)
  9537. {
  9538. bestLineOffset = lineOffset;
  9539. result = "";
  9540. }
  9541. if (!foundInSequence)
  9542. {
  9543. auto addr = dbgSubprogram->GetLineAddr(lineData);
  9544. result += EncodeDataPtr(addr, false) + "\t" + dbgSubprogram->ToString() + "\n";
  9545. }
  9546. }
  9547. // New sequence?
  9548. if (!lineData.IsStackFrameSetup())
  9549. foundInSequence = false;
  9550. }
  9551. }
  9552. return result;
  9553. }
  9554. String WinDebugger::GetAddressSourceLocation(intptr address)
  9555. {
  9556. DbgSubprogram* subProgram = NULL;
  9557. DbgLineData* lineData = FindLineDataAtAddress(address, &subProgram);
  9558. if (lineData != NULL)
  9559. return StrFormat("%s:%d:%d", subProgram->GetLineSrcFile(*lineData)->GetLocalPath().c_str(), lineData->mLine + 1, lineData->mColumn + 1);
  9560. String outSymbol;
  9561. addr_target offset = 0;
  9562. DbgModule* dbgModule;
  9563. if (mDebugTarget->FindSymbolAt(address, &outSymbol, &offset, &dbgModule))
  9564. {
  9565. if (offset < 0x10000)
  9566. {
  9567. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9568. if (offset > 0)
  9569. outSymbol += StrFormat("+%x", offset);
  9570. return outSymbol;
  9571. }
  9572. }
  9573. return StrFormat("0x%@", address);
  9574. }
  9575. String WinDebugger::GetAddressSymbolName(intptr address, bool demangle)
  9576. {
  9577. String outSymbol;
  9578. addr_target offset = 0;
  9579. DbgModule* dbgModule;
  9580. if (mDebugTarget->FindSymbolAt(address, &outSymbol, &offset, &dbgModule))
  9581. {
  9582. if (offset < 0x10000)
  9583. {
  9584. if (demangle)
  9585. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9586. if (offset > 0)
  9587. outSymbol += StrFormat("+%x", offset);
  9588. return outSymbol;
  9589. }
  9590. }
  9591. return StrFormat("0x%@", address);
  9592. }
  9593. String WinDebugger::DisassembleAtRaw(intptr inAddress)
  9594. {
  9595. addr_target address = (addr_target)inAddress;
  9596. const int addrBorder = 1024;
  9597. for (int offset = 0; offset < 8; offset++)
  9598. {
  9599. String result;
  9600. bool addOffset = true;
  9601. bool hadAddr = false;
  9602. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress(address);
  9603. DbgModuleMemoryCache* memCache = NULL;
  9604. defer
  9605. {
  9606. if (dbgModule == NULL)
  9607. delete memCache;
  9608. };
  9609. if ((dbgModule != NULL) && (dbgModule->mOrigImageData == NULL))
  9610. dbgModule = NULL;
  9611. result += "R\n"; // Raw
  9612. addr_target addrStart = address;
  9613. if (dbgModule != NULL)
  9614. {
  9615. dbgModule->ParseSymbolData();
  9616. memCache = dbgModule->mOrigImageData;
  9617. addrStart = BF_MAX((addr_target)dbgModule->mImageBase, address - addrBorder - offset);
  9618. }
  9619. else
  9620. {
  9621. memCache = new DbgModuleMemoryCache(addrStart & (4096 - 1), 4096 * 2);
  9622. }
  9623. //addr_target imageBase = dbgModule->mImageBase;
  9624. //int imageSize = dbgModule->mImageSize;
  9625. addr_target dataAddr = addrStart;
  9626. addr_target addrEnd = addrStart + addrBorder * 2 + 16;
  9627. while (dataAddr < addrEnd)
  9628. {
  9629. if (dataAddr == address)
  9630. hadAddr = true;
  9631. if (dataAddr > address)
  9632. {
  9633. if (!hadAddr)
  9634. {
  9635. if (offset == 7)
  9636. {
  9637. dataAddr = address;
  9638. }
  9639. break;
  9640. }
  9641. }
  9642. String outSymbol;
  9643. addr_target symOffset = 0;
  9644. DbgModule* symDWARF;
  9645. if (mDebugTarget->FindSymbolAt(dataAddr, &outSymbol, &symOffset, &symDWARF))
  9646. {
  9647. if (symOffset == 0)
  9648. {
  9649. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9650. if ((symDWARF != NULL) && (!symDWARF->mDisplayName.empty()))
  9651. outSymbol = symDWARF->mDisplayName + "!" + outSymbol;
  9652. result += "T " + outSymbol + ":\n";
  9653. }
  9654. }
  9655. CPUInst inst;
  9656. if (!mCPU->Decode(dataAddr, memCache, &inst))
  9657. {
  9658. if ((offset == 7) && (!hadAddr))
  9659. {
  9660. uint8 instData[1];
  9661. memCache->Read(dataAddr, instData, 1);
  9662. int instLen = 1;
  9663. #ifdef BF_DBG_32
  9664. result += StrFormat("D %08X: ", dataAddr);
  9665. #else
  9666. result += StrFormat("D %@: ", dataAddr);
  9667. #endif
  9668. for (int i = 0; i < instLen; i++)
  9669. result += StrFormat("%02X ", instData[i]);
  9670. for (int i = instLen; i < 8; i++)
  9671. result += " ";
  9672. result += "\n";
  9673. dataAddr++;
  9674. continue;
  9675. }
  9676. break;
  9677. }
  9678. int instLen = inst.GetLength();
  9679. #ifdef BF_DBG_32
  9680. result += StrFormat("D %08X: ", dataAddr);
  9681. #else
  9682. result += StrFormat("D %@: ", dataAddr);
  9683. #endif
  9684. uint8 instData[32];
  9685. int showInstLen = BF_MIN(32, instLen);
  9686. memCache->Read(dataAddr, instData, showInstLen);
  9687. for (int i = 0; i < showInstLen; i++)
  9688. result += StrFormat("%02X ", instData[i]);
  9689. for (int i = instLen; i < 8; i++)
  9690. result += " ";
  9691. result += mCPU->InstructionToString(&inst, dataAddr);
  9692. if ((inst.IsCall()) || (inst.IsBranch()))
  9693. {
  9694. addr_target targetAddr = inst.GetTarget();
  9695. if (targetAddr != 0)
  9696. {
  9697. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &symOffset))
  9698. {
  9699. if (symOffset < 0x10000)
  9700. {
  9701. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9702. result += " ; " + outSymbol;
  9703. if (symOffset > 0)
  9704. result += StrFormat("+%x", symOffset);
  9705. //result += ">";
  9706. }
  9707. }
  9708. }
  9709. }
  9710. result += "\n";
  9711. dataAddr += instLen;
  9712. }
  9713. if (!hadAddr)
  9714. continue;
  9715. return result;
  9716. }
  9717. return "";
  9718. }
  9719. String WinDebugger::DisassembleAt(intptr inAddress)
  9720. {
  9721. BP_ZONE("WinDebugger::DisassembleAt");
  9722. AutoCrit autoCrit(mDebugManager->mCritSect);
  9723. addr_target address = (addr_target)inAddress;
  9724. if (mDebugTarget == NULL)
  9725. return "";
  9726. String result;
  9727. auto dwSubProgram = mDebugTarget->FindSubProgram(address);
  9728. if (dwSubProgram == NULL)
  9729. return DisassembleAtRaw(address);
  9730. dwSubProgram = dwSubProgram->GetRootInlineParent();
  9731. DbgModule* dwarf = dwSubProgram->mCompileUnit->mDbgModule;
  9732. int frameBaseRegister = mDebugTarget->GetFrameBaseRegister(dwSubProgram);
  9733. addr_target addrStart = dwSubProgram->mBlock.mLowPC;
  9734. addr_target addrEnd = dwSubProgram->mBlock.mHighPC;
  9735. auto dwCompileUnit = dwSubProgram->mCompileUnit;
  9736. {
  9737. FixupLineData(dwCompileUnit);
  9738. }
  9739. DbgSrcFile* dwSrcFile = NULL;
  9740. FixupLineDataForSubprogram(dwSubProgram);
  9741. DbgLineData* dwLineData = NULL;
  9742. if (dwSubProgram->mLineInfo != NULL)
  9743. dwLineData = &dwSubProgram->mLineInfo->mLines[0];
  9744. int nextLineDataIdx = 1;
  9745. if (dwSubProgram->mIsOptimized)
  9746. result += "O\n";
  9747. DbgSrcFile* srcFile = NULL;
  9748. int firstLine = 0;
  9749. int curLine = 0;
  9750. if (dwLineData != NULL)
  9751. {
  9752. srcFile = dwSubProgram->GetLineSrcFile(*dwLineData);
  9753. result += "S " + srcFile->GetLocalPath() + "\n";
  9754. curLine = BF_MAX(0, dwLineData->mLine - 5);
  9755. //for (; curLine <= dwLineData->mLine; curLine++)
  9756. result += StrFormat("L %d %d\n", curLine, dwLineData->mLine - curLine + 1);
  9757. curLine = dwLineData->mLine + 1;
  9758. firstLine = dwLineData->mLine;
  9759. }
  9760. Array<DbgSubprogram*> inlineStack;
  9761. Array<DbgBlock*> blockList;
  9762. blockList.push_back(&dwSubProgram->mBlock);
  9763. addr_target dataAddr = addrStart;
  9764. int decodeFailureCount = 0;
  9765. auto& _PopInlineStack = [&]()
  9766. {
  9767. int depth = inlineStack.size();
  9768. auto curStackEntry = inlineStack.back();
  9769. if (depth > 1)
  9770. result += StrFormat("T <<<%d Inline End ", depth);
  9771. else
  9772. result += "T <<< Inline End ";
  9773. result += curStackEntry->ToString();
  9774. result += "\n";
  9775. inlineStack.pop_back();
  9776. };
  9777. std::function<void(DbgSubprogram* subprogram, int depth)> _UpdateInlineStackHelper = [&](DbgSubprogram* subprogram, int depth)
  9778. {
  9779. int stackIdx = depth - 1;
  9780. if (stackIdx < inlineStack.size())
  9781. {
  9782. auto curStackEntry = inlineStack[stackIdx];
  9783. if (curStackEntry != subprogram)
  9784. _PopInlineStack();
  9785. }
  9786. if (depth > 1)
  9787. {
  9788. _UpdateInlineStackHelper(subprogram->mInlineeInfo->mInlineParent, depth - 1);
  9789. }
  9790. if (stackIdx >= inlineStack.size())
  9791. {
  9792. if (depth > 1)
  9793. result += StrFormat("T >>>%d Inline ", depth);
  9794. else
  9795. result += "T >>> Inline ";
  9796. result += subprogram->ToString();
  9797. result += "\n";
  9798. inlineStack.push_back(subprogram);
  9799. }
  9800. };
  9801. auto _UpdateInlineStack = [&](DbgSubprogram* subprogram)
  9802. {
  9803. if (subprogram == NULL)
  9804. {
  9805. while (!inlineStack.IsEmpty())
  9806. _PopInlineStack();
  9807. return;
  9808. }
  9809. int inlineDepth = subprogram->GetInlineDepth();
  9810. while (inlineDepth < inlineStack.size())
  9811. _PopInlineStack();
  9812. if (inlineDepth > 0)
  9813. _UpdateInlineStackHelper(subprogram, inlineDepth);
  9814. };
  9815. while (dataAddr < addrEnd)
  9816. {
  9817. // Pop off old scopes
  9818. while (blockList.size() > 0)
  9819. {
  9820. auto lastBlock = blockList.back();
  9821. if (dataAddr < lastBlock->mHighPC)
  9822. break;
  9823. blockList.pop_back();
  9824. }
  9825. // Check entry into new child scopes
  9826. auto lastBlock = blockList.back();
  9827. for (auto checkBlock : lastBlock->mSubBlocks)
  9828. {
  9829. if ((dataAddr >= checkBlock->mLowPC) && (dataAddr < checkBlock->mHighPC))
  9830. {
  9831. blockList.push_back(checkBlock);
  9832. break;
  9833. }
  9834. }
  9835. bool allowSourceJump = false;
  9836. if ((dwLineData != NULL) && (dwLineData->mContribSize != 0) && (dataAddr >= dwSubProgram->GetLineAddr(*dwLineData) + dwLineData->mContribSize))
  9837. {
  9838. DbgSubprogram* inlinedSubprogram = NULL;
  9839. auto inlinedLine = dwSubProgram->FindClosestLine(dataAddr, &inlinedSubprogram);
  9840. _UpdateInlineStack(dwSubProgram);
  9841. }
  9842. // Update line data
  9843. while ((dwLineData != NULL) && (dwSubProgram->GetLineAddr(*dwLineData) <= dataAddr))
  9844. {
  9845. _UpdateInlineStack(dwSubProgram->GetLineInlinee(*dwLineData));
  9846. const int lineLimit = 5; // 15
  9847. if (allowSourceJump)
  9848. curLine = dwLineData->mLine;
  9849. auto lineSrcFile = dwSubProgram->GetLineSrcFile(*dwLineData);
  9850. if (lineSrcFile != srcFile)
  9851. {
  9852. srcFile = lineSrcFile;
  9853. result += "S ";
  9854. result += srcFile->GetLocalPath();
  9855. result += "\n";
  9856. // Just show the one line from the new file
  9857. curLine = dwLineData->mLine;
  9858. }
  9859. if (dwLineData->mLine < curLine - 1)
  9860. {
  9861. // Jumping backwards - possibly into inlined method, or possibly in current method.
  9862. // Show previous 6 lines, for context
  9863. curLine = BF_MAX(0, dwLineData->mLine - lineLimit);
  9864. }
  9865. if ((curLine <= firstLine) && (dwLineData->mLine >= firstLine))
  9866. {
  9867. // Jumping from inlined method (declared above) back into main method
  9868. curLine = dwLineData->mLine;
  9869. }
  9870. if (curLine < dwLineData->mLine - lineLimit)
  9871. {
  9872. // Don't show huge span of source - only show the last 6 lines at maximum
  9873. curLine = dwLineData->mLine - lineLimit;
  9874. }
  9875. //for ( ; curLine <= dwLineData->mLine; curLine++)
  9876. result += StrFormat("L %d %d\n", curLine, dwLineData->mLine - curLine + 1);
  9877. curLine = dwLineData->mLine + 1;
  9878. DbgLineData* nextLineData = NULL;
  9879. while (nextLineDataIdx < dwSubProgram->mLineInfo->mLines.mSize)
  9880. {
  9881. nextLineData = &dwSubProgram->mLineInfo->mLines[nextLineDataIdx];
  9882. //TODO:
  9883. /*{
  9884. result += StrFormat("T LineIdx: %d (%@ to %@)", nextLineDataIdx, dwSubProgram->GetLineAddr(*nextLineData), dwSubProgram->GetLineAddr(*nextLineData) + nextLineData->mContribSize);
  9885. auto inlinee = dwSubProgram->GetLineInlinee(*nextLineData);
  9886. if (inlinee != NULL)
  9887. {
  9888. result += StrFormat(" Inlinee: %s Depth: %d", inlinee->mName, inlinee->GetInlineDepth());
  9889. }
  9890. result += "\n";
  9891. }*/
  9892. auto nextLineAddr = dwSubProgram->GetLineAddr(*nextLineData);
  9893. if (nextLineAddr > dataAddr)
  9894. {
  9895. if (nextLineDataIdx + 1 < dwSubProgram->mLineInfo->mLines.mSize)
  9896. {
  9897. auto peekLineData = &dwSubProgram->mLineInfo->mLines[nextLineDataIdx + 1];
  9898. if (peekLineData->mRelAddress == nextLineData->mRelAddress)
  9899. {
  9900. // Use the later entry
  9901. ++nextLineDataIdx;
  9902. continue;
  9903. }
  9904. }
  9905. break;
  9906. }
  9907. // If we go back to an older entry beacuse of a gap then we need to catch back up...
  9908. ++nextLineDataIdx;
  9909. nextLineData = NULL; // Keep searching...
  9910. }
  9911. dwLineData = nextLineData;
  9912. nextLineDataIdx++;
  9913. }
  9914. // Have we gone off the end of the inline function?
  9915. // We may not have an explicit non-inlined line data at the transition point...
  9916. while (!inlineStack.IsEmpty())
  9917. {
  9918. auto subProgram = inlineStack.back();
  9919. if (dataAddr < subProgram->mBlock.mHighPC)
  9920. break;
  9921. _PopInlineStack();
  9922. }
  9923. bool hadDecodeFailure = false;
  9924. CPUInst inst;
  9925. if (!mCPU->Decode(dataAddr, dwarf->mOrigImageData, &inst))
  9926. hadDecodeFailure = true;
  9927. if ((decodeFailureCount == 8) || ((decodeFailureCount > 0) && (!hadDecodeFailure)))
  9928. {
  9929. for (int i = decodeFailureCount; i < 4 + sizeof(addr_target); i++)
  9930. result += " ";
  9931. result += " ???\n";
  9932. decodeFailureCount = 0;
  9933. }
  9934. if (decodeFailureCount == 0)
  9935. {
  9936. #ifdef BF_DBG_32
  9937. result += StrFormat("D %08X: ", dataAddr);
  9938. #else
  9939. result += StrFormat("D %@: ", dataAddr);
  9940. #endif
  9941. }
  9942. if (hadDecodeFailure)
  9943. {
  9944. uint8 byte = 0;
  9945. dwarf->mOrigImageData->Read(dataAddr, &byte, 1);
  9946. result += StrFormat("%02X ", byte);
  9947. dataAddr++;
  9948. decodeFailureCount++;
  9949. continue;
  9950. }
  9951. int instLen = inst.GetLength();
  9952. uint8 instData[32];
  9953. int showInstLen = BF_MIN(32, instLen);
  9954. dwarf->mOrigImageData->Read(dataAddr, instData, showInstLen);
  9955. for (int i = 0; i < showInstLen; i++)
  9956. result += StrFormat("%02X ", instData[i]);
  9957. for (int i = instLen; i < 4 + sizeof(addr_target); i++)
  9958. result += " ";
  9959. result += " ";
  9960. result += mCPU->InstructionToString(&inst, dataAddr);
  9961. int reg;
  9962. int offset;
  9963. if (inst.GetIndexRegisterAndOffset(&reg, &offset))
  9964. {
  9965. for (int blockIdx = (int)blockList.size() - 1; blockIdx >= 0; blockIdx--)
  9966. {
  9967. auto dwBlock = blockList[blockIdx];
  9968. for (auto variable : dwBlock->mVariables)
  9969. {
  9970. int varRegister;
  9971. int varOffset;
  9972. if (mDebugTarget->GetVariableIndexRegisterAndOffset(variable, &varRegister, &varOffset))
  9973. {
  9974. if (varRegister == -1)
  9975. varRegister = frameBaseRegister;
  9976. if ((reg == varRegister) && (offset == varOffset))
  9977. {
  9978. result += " ; ";
  9979. result += variable->mName;
  9980. break;
  9981. }
  9982. }
  9983. }
  9984. }
  9985. }
  9986. else if ((inst.IsCall()) || (inst.IsBranch()) || (inst.IsLoadAddress()))
  9987. {
  9988. addr_target targetAddr = inst.GetTarget();
  9989. if (targetAddr != 0)
  9990. {
  9991. if ((targetAddr >= addrStart) && (targetAddr < addrEnd))
  9992. {
  9993. result += StrFormat("\nJ %s", EncodeDataPtr(targetAddr, false).c_str());
  9994. }
  9995. else
  9996. {
  9997. String outSymbol;
  9998. addr_target offset = 0;
  9999. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &offset))
  10000. {
  10001. if (offset < 0x10000)
  10002. {
  10003. outSymbol = BfDemangler::Demangle(outSymbol, dwSubProgram->GetLanguage());
  10004. result += " ; " + outSymbol;
  10005. if (offset > 0)
  10006. result += StrFormat("+%x", offset);
  10007. }
  10008. }
  10009. }
  10010. }
  10011. }
  10012. result += "\n";
  10013. dataAddr += instLen;
  10014. }
  10015. // Why did we want to "show lines at end"??
  10016. // Show lines at end
  10017. /*if (curLine > 0)
  10018. {
  10019. for (int i = 0; i < 6; i++, curLine++)
  10020. result += StrFormat("L %d\n", curLine);
  10021. }*/
  10022. return result;
  10023. }
  10024. String WinDebugger::FindLineCallAddresses(intptr inAddress)
  10025. {
  10026. String callAddresses;
  10027. addr_target address = (addr_target)inAddress;
  10028. DbgSubprogram* dwSubprogram = NULL;
  10029. DbgLineData* startLineData = FindLineDataAtAddress(address, &dwSubprogram, NULL);
  10030. if (dwSubprogram == NULL)
  10031. return "";
  10032. CPURegisters registers;
  10033. PopulateRegisters(&registers);
  10034. auto inlinerSubprogram = dwSubprogram->GetRootInlineParent();
  10035. FixupLineDataForSubprogram(inlinerSubprogram);
  10036. if (inlinerSubprogram->mLineInfo->mLines.mSize == 0)
  10037. return "";
  10038. auto lineData = &inlinerSubprogram->mLineInfo->mLines[0];
  10039. addr_target addr = dwSubprogram->mBlock.mLowPC;
  10040. addr_target endAddr = dwSubprogram->mBlock.mHighPC;
  10041. DbgSubprogram* checkSubprogram = dwSubprogram;
  10042. DbgLineData* checkLineData = lineData;
  10043. addr_target checkLineAddr = 0;
  10044. int lineIdx = 0;
  10045. while (checkLineData != NULL)
  10046. {
  10047. //auto nextLineData = dwSubprogram->mCompileUnit->mLineDataMap.GetNext(checkLineData);
  10048. ++lineIdx;
  10049. DbgLineData* nextLineData = NULL;
  10050. addr_target nextLineAddr;
  10051. if (lineIdx < inlinerSubprogram->mLineInfo->mLines.size())
  10052. {
  10053. nextLineData = &inlinerSubprogram->mLineInfo->mLines[lineIdx];
  10054. nextLineAddr = dwSubprogram->GetLineAddr(*nextLineData);
  10055. }
  10056. else
  10057. nextLineAddr = inlinerSubprogram->mBlock.mHighPC;
  10058. // This stuff doesn't make sense...
  10059. DbgSubprogram* nextSubProgram;
  10060. if (nextLineData != NULL)
  10061. {
  10062. if (nextLineAddr > dwSubprogram->mBlock.mHighPC)
  10063. break;
  10064. endAddr = nextLineAddr;
  10065. nextSubProgram = mDebugTarget->FindSubProgram(endAddr);
  10066. if (nextSubProgram != NULL)
  10067. {
  10068. auto dbgModule = nextSubProgram->mCompileUnit->mDbgModule;
  10069. dbgModule->ParseSymbolData();
  10070. }
  10071. }
  10072. else
  10073. {
  10074. nextSubProgram = dwSubprogram;
  10075. endAddr = dwSubprogram->mBlock.mHighPC;
  10076. }
  10077. auto _HandleSection = [&]()
  10078. {
  10079. while (addr < endAddr)
  10080. {
  10081. CPUInst inst;
  10082. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  10083. break;
  10084. if (inst.IsCall())
  10085. {
  10086. bool addSymbol = true;
  10087. if (addr < (addr_target)inAddress)
  10088. callAddresses += "-";
  10089. callAddresses += EncodeDataPtr(addr, false);
  10090. addr_target targetAddr = inst.GetTarget(&registers);
  10091. if (targetAddr != 0)
  10092. {
  10093. String outSymbol;
  10094. auto subprogram = mDebugTarget->FindSubProgram(targetAddr);
  10095. if (subprogram != NULL)
  10096. {
  10097. CreateFilterName(outSymbol, subprogram);
  10098. addSymbol = true;
  10099. }
  10100. else
  10101. {
  10102. addr_target offset = 0;
  10103. String fullSymbolName;
  10104. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &offset))
  10105. {
  10106. if (offset < 0x200)
  10107. {
  10108. //outSymbol = BfDemangler::Demangle(outSymbol, dwSubprogram->GetLanguage());
  10109. if (outSymbol == "___chkstk_ms")
  10110. addSymbol = false;
  10111. else
  10112. {
  10113. String demangledName = BfDemangler::Demangle(outSymbol, DbgLanguage_C);
  10114. outSymbol.clear();
  10115. CreateFilterName(outSymbol, demangledName.c_str(), DbgLanguage_C);
  10116. }
  10117. }
  10118. else
  10119. outSymbol.clear();
  10120. }
  10121. }
  10122. if (addSymbol)
  10123. {
  10124. if (outSymbol.empty())
  10125. callAddresses += "\tFunc@" + EncodeDataPtr(targetAddr, false);
  10126. else
  10127. callAddresses += "\t" + outSymbol;
  10128. String attrs;
  10129. bool isFiltered = false;
  10130. if (subprogram != NULL)
  10131. {
  10132. subprogram->PopulateSubprogram();
  10133. isFiltered = subprogram->mIsStepFilteredDefault;
  10134. if (isFiltered)
  10135. attrs += "d"; // 'd' for default filtered
  10136. }
  10137. StepFilter* stepFilterPtr = NULL;
  10138. if (mDebugManager->mStepFilters.TryGetValue(outSymbol, &stepFilterPtr))
  10139. isFiltered = stepFilterPtr->IsFiltered(isFiltered);
  10140. if (isFiltered)
  10141. attrs += "f"; // 'f' for filter
  10142. if (!attrs.IsEmpty())
  10143. callAddresses += "\t" + attrs;
  10144. }
  10145. }
  10146. if (addSymbol)
  10147. callAddresses += "\n";
  10148. }
  10149. addr += inst.GetLength();
  10150. }
  10151. };
  10152. // For inlining - only add calls that are found either directly in our main block (not an inlined block)
  10153. // But add inlined methods when their parent is our current block
  10154. if ((checkSubprogram == dwSubprogram) && (checkLineData->mLine == startLineData->mLine))
  10155. {
  10156. _HandleSection();
  10157. }
  10158. else if ((checkSubprogram->mInlineeInfo != NULL) && (checkSubprogram->mInlineeInfo->mInlineParent == dwSubprogram))
  10159. {
  10160. if (checkLineAddr == checkSubprogram->mBlock.mLowPC)
  10161. {
  10162. addr_target inlineStartAddr = checkSubprogram->mBlock.mLowPC;
  10163. // Find the calling line
  10164. DbgSubprogram* callingSubprogram = dwSubprogram;
  10165. auto checkLineData = dwSubprogram->FindClosestLine(inlineStartAddr, &callingSubprogram);
  10166. if ((checkLineData != NULL) && (checkLineData->mCtxIdx == startLineData->mCtxIdx) && (checkLineData->mLine == startLineData->mLine))
  10167. {
  10168. if (inlineStartAddr <= (addr_target)inAddress)
  10169. callAddresses += "-";
  10170. callAddresses += EncodeDataPtr(inlineStartAddr, false);
  10171. String outSymbol;
  10172. CreateFilterName(outSymbol, checkSubprogram);
  10173. callAddresses += "\t" + outSymbol;
  10174. bool isFiltered = dwSubprogram->mIsStepFilteredDefault;
  10175. StepFilter* stepFilterPtr;
  10176. if (mDebugManager->mStepFilters.TryGetValue(outSymbol, &stepFilterPtr))
  10177. isFiltered = stepFilterPtr->IsFiltered(isFiltered);
  10178. if (isFiltered)
  10179. callAddresses += "\tf"; // 'f' for filter
  10180. callAddresses += "\n";
  10181. }
  10182. // if (checkSubprogram->mBlock.mHighPC < endAddr)
  10183. // {
  10184. // addr = checkSubprogram->mBlock.mHighPC;
  10185. // _HandleSection();
  10186. // }
  10187. }
  10188. // If we have unattributed data after the end of an inlined method, add that
  10189. if ((endAddr > checkSubprogram->mBlock.mHighPC) && (nextSubProgram == dwSubprogram))
  10190. {
  10191. addr = checkSubprogram->mBlock.mHighPC;
  10192. _HandleSection();
  10193. }
  10194. }
  10195. checkLineData = nextLineData;
  10196. checkSubprogram = nextSubProgram;
  10197. checkLineAddr = nextLineAddr;
  10198. addr = endAddr;
  10199. }
  10200. return callAddresses;
  10201. }
  10202. String WinDebugger::GetCurrentException()
  10203. {
  10204. AutoCrit autoCrit(mDebugManager->mCritSect);
  10205. String result = StrFormat("%s\n%08X",
  10206. EncodeDataPtr((addr_target)(intptr)mCurException.ExceptionAddress, true).c_str(),
  10207. mCurException.ExceptionCode);
  10208. String exStr;
  10209. switch (mCurException.ExceptionCode)
  10210. {
  10211. case EXCEPTION_ACCESS_VIOLATION:
  10212. {
  10213. String accessType;
  10214. if (mCurException.ExceptionInformation[0] == 0)
  10215. accessType = "reading from";
  10216. else if (mCurException.ExceptionInformation[0] == 8)
  10217. accessType = "executing";
  10218. else
  10219. accessType = "writing to";
  10220. exStr = StrFormat("EXCEPTION_ACCESS_VIOLATION %s %s", accessType.c_str(), EncodeDataPtr((addr_target)mCurException.ExceptionInformation[1], true).c_str());
  10221. }
  10222. break;
  10223. case EXCEPTION_DATATYPE_MISALIGNMENT:
  10224. exStr = "EXCEPTION_DATATYPE_MISALIGNMENT";
  10225. case EXCEPTION_SINGLE_STEP:
  10226. exStr = "EXCEPTION_SINGLE_STEP";
  10227. break;
  10228. case EXCEPTION_BREAKPOINT:
  10229. exStr = "EXCEPTION_BREAKPOINT";
  10230. break;
  10231. case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
  10232. exStr = "EXCEPTION_ARRAY_BOUNDS_EXCEEDED";
  10233. break;
  10234. case EXCEPTION_FLT_DENORMAL_OPERAND:
  10235. exStr = "EXCEPTION_FLT_DENORMAL_OPERAND";
  10236. break;
  10237. case EXCEPTION_FLT_DIVIDE_BY_ZERO:
  10238. exStr = "EXCEPTION_FLT_DIVIDE_BY_ZERO";
  10239. break;
  10240. case EXCEPTION_FLT_INEXACT_RESULT:
  10241. exStr = "EXCEPTION_FLT_INEXACT_RESULT";
  10242. break;
  10243. case EXCEPTION_FLT_INVALID_OPERATION:
  10244. exStr = "EXCEPTION_FLT_INVALID_OPERATIO";
  10245. break;
  10246. case EXCEPTION_FLT_OVERFLOW:
  10247. exStr = "EXCEPTION_FLT_OVERFLOW";
  10248. break;
  10249. case EXCEPTION_FLT_STACK_CHECK:
  10250. exStr = "EXCEPTION_FLT_STACK_CHECK";
  10251. break;
  10252. case EXCEPTION_FLT_UNDERFLOW:
  10253. exStr = "EXCEPTION_FLT_UNDERFLOW";
  10254. break;
  10255. case EXCEPTION_INT_DIVIDE_BY_ZERO:
  10256. exStr = "EXCEPTION_INT_DIVIDE_BY_ZERO";
  10257. break;
  10258. case EXCEPTION_INT_OVERFLOW:
  10259. exStr = "EXCEPTION_INT_OVERFLOW";
  10260. break;
  10261. case EXCEPTION_PRIV_INSTRUCTION:
  10262. exStr = "EXCEPTION_PRIV_INSTRUCTION";
  10263. break;
  10264. case EXCEPTION_IN_PAGE_ERROR:
  10265. exStr = "EXCEPTION_IN_PAGE_ERROR";
  10266. break;
  10267. case EXCEPTION_ILLEGAL_INSTRUCTION:
  10268. exStr = "EXCEPTION_ILLEGAL_INSTRUCTION";
  10269. break;
  10270. case EXCEPTION_NONCONTINUABLE_EXCEPTION:
  10271. exStr = "EXCEPTION_NONCONTINUABLE_EXCEPTION";
  10272. break;
  10273. case EXCEPTION_STACK_OVERFLOW:
  10274. exStr = "EXCEPTION_STACK_OVERFLOW";
  10275. break;
  10276. case EXCEPTION_INVALID_DISPOSITION:
  10277. exStr = "EXCEPTION_INVALID_DISPOSITION";
  10278. break;
  10279. case EXCEPTION_GUARD_PAGE:
  10280. exStr = "EXCEPTION_GUARD_PAGE";
  10281. break;
  10282. case EXCEPTION_INVALID_HANDLE:
  10283. exStr = "EXCEPTION_INVALID_HANDLE";
  10284. break;
  10285. case CONTROL_C_EXIT:
  10286. exStr = "CONTROL_C_EXIT";
  10287. break;
  10288. default:
  10289. exStr += StrFormat("EXCEPTION %08X", mCurException.ExceptionCode);
  10290. }
  10291. if (mActiveThread != NULL)
  10292. exStr += StrFormat(" in thread %d", mActiveThread->mThreadId);
  10293. if (!exStr.empty())
  10294. result += "\n" + exStr;
  10295. // After we retrieve the exception then we can go back to just being normal 'paused'
  10296. // This allows us to evaluate stuff, Set Next Statement, etc.
  10297. mRunState = RunState_Paused;
  10298. return result.c_str();
  10299. }
  10300. void WinDebugger::SetAliasPath(const StringImpl& origPath, const StringImpl& localPath)
  10301. {
  10302. AutoCrit autoCrit(mDebugManager->mCritSect);
  10303. String fixedOrigPath = FixPathAndCase(origPath);
  10304. String fixedLocalPath = FixPathAndCase(localPath);
  10305. auto origFile = mDebugTarget->AddSrcFile(origPath);
  10306. origFile->mLocalPath = FixPath(localPath);
  10307. mDebugTarget->mLocalToOrigSrcMap[fixedLocalPath] = fixedOrigPath;
  10308. // We invalidate the step filters, because previously-failing 'CheckSourceFileExist' checks may now succeed
  10309. mDebugManager->mStepFilterVersion++;
  10310. }
  10311. String WinDebugger::GetModulesInfo()
  10312. {
  10313. AutoCrit autoCrit(mDebugManager->mCritSect);
  10314. String str;
  10315. for (auto module : mDebugTarget->mDbgModules)
  10316. {
  10317. COFF* coff = (COFF*)module;
  10318. if (module->mHotIdx > 0)
  10319. continue;
  10320. str += module->mDisplayName;
  10321. str += "\t";
  10322. str += module->mFilePath;
  10323. str += "\t";
  10324. str += coff->mPDBPath;
  10325. str += "\t";
  10326. str += module->mVersion;
  10327. str += StrFormat("\t%@-%@\t%dk\t", module->mImageBase, module->mImageBase + module->mImageSize, module->mImageSize / 1024);
  10328. time_t timestamp = coff->mTimeStamp;
  10329. if (timestamp == 0)
  10330. timestamp = GetFileTimeWrite(coff->mFilePath);
  10331. if (timestamp != 0)
  10332. {
  10333. char timeString[256];
  10334. auto time_info = localtime(&timestamp);
  10335. strftime(timeString, sizeof(timeString), "%D %T", time_info);
  10336. str += timeString;
  10337. }
  10338. str += "\n";
  10339. }
  10340. return str;
  10341. }
  10342. void WinDebugger::CancelSymSrv()
  10343. {
  10344. AutoCrit autoCrit(mDebugManager->mCritSect);
  10345. if (mActiveSymSrvRequest != NULL)
  10346. mActiveSymSrvRequest->Cancel();
  10347. }
  10348. bool WinDebugger::HasPendingDebugLoads()
  10349. {
  10350. AutoCrit autoCrit(mDebugManager->mCritSect);
  10351. return (!mPendingImageLoad.IsEmpty()) || (!mPendingDebugInfoLoad.IsEmpty());
  10352. }
  10353. int WinDebugger::LoadDebugInfoForModule(DbgModule* dbgModule)
  10354. {
  10355. if (!dbgModule->HasPendingDebugInfo())
  10356. return 0;
  10357. if (dbgModule->RequestDebugInfo())
  10358. {
  10359. ClearCallStack(); // Make this re-resolve with debug info
  10360. return 1;
  10361. }
  10362. if (!mPendingDebugInfoLoad.Contains(dbgModule))
  10363. {
  10364. mPendingDebugInfoLoad.Add(dbgModule);
  10365. return 2;
  10366. }
  10367. return 0;
  10368. }
  10369. int WinDebugger::LoadDebugInfoForModule(const StringImpl& moduleName)
  10370. {
  10371. AutoCrit autoCrit(mDebugManager->mCritSect);
  10372. for (auto dbgModule : mDebugTarget->mDbgModules)
  10373. {
  10374. String checkModuleName = GetFileName(dbgModule->mFilePath);
  10375. if (moduleName.Equals(checkModuleName, StringImpl::CompareKind_OrdinalIgnoreCase))
  10376. {
  10377. return LoadDebugInfoForModule(dbgModule);
  10378. }
  10379. }
  10380. return 0;
  10381. }
  10382. int WinDebugger::LoadDebugInfoForModule(const StringImpl& modulePath, const StringImpl& debugFileName)
  10383. {
  10384. AutoCrit autoCrit(mDebugManager->mCritSect);
  10385. for (auto dbgModule : mDebugTarget->mDbgModules)
  10386. {
  10387. if (modulePath.Equals(dbgModule->mFilePath, StringImpl::CompareKind_OrdinalIgnoreCase))
  10388. {
  10389. auto coff = (COFF*)dbgModule;
  10390. String err;
  10391. if (coff->mDbgSymRequest != NULL)
  10392. {
  10393. dbgModule->mFailMsgPtr = &err;
  10394. if (coff->TryLoadPDB(debugFileName, coff->mDbgSymRequest->mWantGuid, coff->mDbgSymRequest->mWantAge))
  10395. {
  10396. ModuleChanged(dbgModule);
  10397. }
  10398. dbgModule->mFailMsgPtr = NULL;
  10399. }
  10400. else
  10401. {
  10402. err = StrFormat("Module '%s' already has debug information loaded", GetFileName(modulePath).c_str());
  10403. }
  10404. if (!err.IsEmpty())
  10405. {
  10406. mDebugManager->mOutMessages.push_back("error " + err);
  10407. }
  10408. return 0;
  10409. }
  10410. }
  10411. return 0;
  10412. }
  10413. void WinDebugger::FixupLineData(DbgCompileUnit* compileUnit)
  10414. {
  10415. if (!compileUnit || !compileUnit->mNeedsLineDataFixup)
  10416. return;
  10417. compileUnit->mNeedsLineDataFixup = false;
  10418. }
  10419. static int CompareLineData(const void* lineDataP1, const void* lineDataP2)
  10420. {
  10421. int cmpResult = (int)(((DbgLineData*)lineDataP1)->mRelAddress - ((DbgLineData*)lineDataP2)->mRelAddress);
  10422. if (cmpResult != 0)
  10423. return cmpResult;
  10424. // A larger contrib size means it's the 'outer' inlinee
  10425. cmpResult = -(((DbgLineData*)lineDataP1)->mContribSize - ((DbgLineData*)lineDataP2)->mContribSize);
  10426. if (cmpResult != 0)
  10427. return cmpResult;
  10428. return -(((DbgLineData*)lineDataP1)->mCtxIdx - ((DbgLineData*)lineDataP2)->mCtxIdx);
  10429. }
  10430. void WinDebugger::FixupLineDataForSubprogram(DbgSubprogram* subProgram)
  10431. {
  10432. if ((subProgram == NULL) || (!subProgram->mNeedLineDataFixup))
  10433. return;
  10434. BP_ZONE("FixupLineDataForSubprogram");
  10435. subProgram->mNeedLineDataFixup = false;
  10436. if (subProgram->mInlineeInfo != NULL)
  10437. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  10438. if ((subProgram->mLineInfo == NULL) || (subProgram->mLineInfo->mLines.mSize == 0))
  10439. return;
  10440. //TODO: I think this was covering up a bug in DWARF line encoding? Figure this out
  10441. // if (subProgram->mLineInfo->mLines.mSize >= 2)
  10442. // {
  10443. // DbgLineData* line0 = &subProgram->mLineInfo->mLines[0];
  10444. // DbgLineData* line1 = &subProgram->mLineInfo->mLines[1];
  10445. //
  10446. //
  10447. // if ((line0->mRelAddress == line1->mRelAddress) && (!line0->IsStackFrameSetup()) && (line1->IsStackFrameSetup()))
  10448. // {
  10449. // CPUInst inst;
  10450. // if (mCPU->Decode(line0->mAddress, subProgram->mCompileUnit->mDbgModule->mOrigImageData, &inst))
  10451. // line1->mAddress += inst.GetLength();
  10452. // }
  10453. // }
  10454. qsort(subProgram->mLineInfo->mLines.mVals, subProgram->mLineInfo->mLines.mSize, sizeof(DbgLineData), CompareLineData);
  10455. // If we have multiple lines with the same line/column/context, merge them
  10456. if (!subProgram->mLineInfo->mLines.IsEmpty())
  10457. {
  10458. auto prevLine = &subProgram->mLineInfo->mLines[0];
  10459. for (int i = 1; i < subProgram->mLineInfo->mLines.mSize; i++)
  10460. {
  10461. auto nextLine = &subProgram->mLineInfo->mLines[i];
  10462. if ((nextLine->mLine == prevLine->mLine) && (nextLine->mColumn == prevLine->mColumn) && (nextLine->mCtxIdx == prevLine->mCtxIdx) &&
  10463. (nextLine->mRelAddress == prevLine->mRelAddress + prevLine->mContribSize))
  10464. {
  10465. prevLine->mContribSize += nextLine->mContribSize;
  10466. // This messed up inline cases because mContribSize actually INCLUDES inlined lines so it caused the address to skip too far
  10467. //nextLine->mRelAddress += nextLine->mContribSize;
  10468. //nextLine->mContribSize = 0;
  10469. }
  10470. else
  10471. {
  10472. prevLine = nextLine;
  10473. }
  10474. }
  10475. }
  10476. }
  10477. void WinDebugger::ReserveHotTargetMemory(int size)
  10478. {
  10479. HotTargetMemory hotTargetMemory;
  10480. hotTargetMemory.mOffset = 0;
  10481. hotTargetMemory.mSize = 0;
  10482. hotTargetMemory.mPtr = NULL;
  10483. if (size > 0)
  10484. {
  10485. // In 64-bit mode we have a reserved region on program load that we commit here because the offsets
  10486. // must be within 32-bits of the original EXE image, but in 32-bit mode we don't reserve anything
  10487. // until here
  10488. #ifdef BF_DBG_32
  10489. //hotTargetMemory.mSize = std::max(1024 * 1024, size);
  10490. BF_ASSERT((size & (mPageSize - 1)) == 0);
  10491. hotTargetMemory.mSize = size;
  10492. hotTargetMemory.mPtr = (addr_target)(intptr)VirtualAllocEx(mProcessInfo.hProcess, NULL, hotTargetMemory.mSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
  10493. mDebugTarget->mHotHeap->AddTrackedRegion(hotTargetMemory.mPtr, hotTargetMemory.mSize);
  10494. #else
  10495. hotTargetMemory.mSize = size;
  10496. hotTargetMemory.mPtr = mDebugTarget->mHotHeap->Alloc(size);
  10497. BF_ASSERT(hotTargetMemory.mPtr != 0);
  10498. auto ptr = ::VirtualAllocEx(mProcessInfo.hProcess, (void*)(intptr)hotTargetMemory.mPtr, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  10499. BF_ASSERT(ptr == (void*)(intptr)hotTargetMemory.mPtr);
  10500. #endif
  10501. }
  10502. BfLogDbg("ReserveHotTargetMemory %p %d", hotTargetMemory.mPtr, hotTargetMemory.mSize);
  10503. int err = GetLastError();
  10504. mHotTargetMemory.push_back(hotTargetMemory);
  10505. }
  10506. addr_target WinDebugger::AllocHotTargetMemory(int size, bool canExecute, bool canWrite, int* outAllocSize)
  10507. {
  10508. int prot = PAGE_READWRITE;
  10509. if (canExecute && canWrite)
  10510. prot = PAGE_EXECUTE_READWRITE;
  10511. else if (canExecute)
  10512. prot = PAGE_EXECUTE_READ;
  10513. auto hotTargetMemory = (HotTargetMemory*)&mHotTargetMemory.back();
  10514. if (hotTargetMemory->mPtr == 0)
  10515. {
  10516. Fail("Failed to allocate memory for hot loading");
  10517. return 0;
  10518. }
  10519. size = (size + (mPageSize - 1)) & ~(mPageSize - 1);
  10520. *outAllocSize = size;
  10521. BF_ASSERT(hotTargetMemory->mOffset + size <= hotTargetMemory->mSize);
  10522. addr_target result = hotTargetMemory->mPtr + hotTargetMemory->mOffset;
  10523. ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)result, size, prot, NULL);
  10524. BfLogDbg("AllocHotTargetMemory: %p %d %d %d\n", result, size, canExecute, canWrite);
  10525. hotTargetMemory->mOffset += size;
  10526. return result;
  10527. }
  10528. void WinDebugger::ReleaseHotTargetMemory(addr_target addr, int size)
  10529. {
  10530. #ifdef BF_DBG_32
  10531. ::VirtualFreeEx(mProcessInfo.hProcess, (void*)(intptr)addr, 0, MEM_RELEASE);
  10532. #else
  10533. mDebugTarget->mHotHeap->Release(addr, size);
  10534. ::VirtualFreeEx(mProcessInfo.hProcess, (void*)(intptr)addr, size, MEM_DECOMMIT);
  10535. #endif
  10536. }
  10537. void WinDebugger::CleanupHotHeap()
  10538. {
  10539. mDebugTarget->mLastHotHeapCleanIdx = mDebugTarget->mHotHeap->mBlockAllocIdx;
  10540. // Our criteria for determining whether a hot loaded file is still being used:
  10541. // 1) If we are currently executing a method from that object file.
  10542. // 2) If the symbol map has a symbol with that address.
  10543. // 3) If the static variable map contains a reference - including a conservative scan of the data
  10544. // This handles vdata references
  10545. // This is a conservative check which won't purge hot reloads that contain deleted
  10546. // methods (for example), but it will purge hot reloads where all the changed
  10547. // data has been overwritten.
  10548. // For delegate bindings, the original module declaring the bind creates a "preserve"
  10549. // global such as "bf_hs_preserve@_ZN5TestO4TestEv", whose preserved symbol ensures it
  10550. // doesn't get unloaded. The current version of that method resides in "_ZN5TestO4TestEv",
  10551. // ensuring that the method pointed to by the global variable is valid
  10552. mDebugTarget->mHotHeap->ClearReferencedFlags();
  10553. addr_target lowAddr = mDebugTarget->mHotHeap->mHotAreaStart;
  10554. addr_target highAddr = lowAddr + mDebugTarget->mHotHeap->mHotAreaSize;
  10555. // Do conservative scan through all thread stacks. Stack traces aren't 100% reliable, so we
  10556. // need to do a full conservative scan of any addresses stored in the stack
  10557. // to ensure we don't miss any return addresses
  10558. for (int threadIdx = 0; threadIdx < (int)mThreadList.size(); threadIdx++)
  10559. {
  10560. WdThreadInfo* threadInfo = mThreadList[threadIdx];
  10561. BF_CONTEXT lcContext;
  10562. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  10563. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  10564. addr_target checkStackAddr = BF_CONTEXT_SP(lcContext);
  10565. checkStackAddr &= ~(sizeof(addr_target) - 1);
  10566. // Conservative check on registers
  10567. for (int regNum = 0; regNum < sizeof(BF_CONTEXT)/sizeof(addr_target); regNum++)
  10568. {
  10569. addr_target checkAddr = ((addr_target*)&lcContext)[regNum];
  10570. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  10571. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  10572. }
  10573. // Conservative check on all stack data
  10574. while (checkStackAddr < threadInfo->mStartSP)
  10575. {
  10576. addr_target checkAddrArr[1024];
  10577. int numAddrsChecking = BF_MIN(1024, (int)((threadInfo->mStartSP - checkStackAddr) / sizeof(addr_target)));
  10578. ReadMemory(checkStackAddr, numAddrsChecking * sizeof(addr_target), checkAddrArr);
  10579. checkStackAddr += numAddrsChecking * sizeof(addr_target);
  10580. for (int addrIdx = 0; addrIdx < numAddrsChecking; addrIdx++)
  10581. {
  10582. addr_target checkAddr = checkAddrArr[addrIdx];
  10583. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  10584. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  10585. }
  10586. }
  10587. }
  10588. auto mainModule = mDebugTarget->mTargetBinary;
  10589. for (auto entry : mainModule->mSymbolNameMap)
  10590. {
  10591. auto dwSymbol = entry->mValue;
  10592. addr_target checkAddr = dwSymbol->mAddress;
  10593. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  10594. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  10595. }
  10596. mDebugTarget->CleanupHotHeap();
  10597. BfLogDbg("Hot load memory used: %dk\n", (int)mDebugTarget->mHotHeap->GetUsedSize() / 1024);
  10598. }
  10599. int WinDebugger::EnableWriting(intptr address, int size)
  10600. {
  10601. DWORD oldProt;
  10602. bool success = ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)address, size, PAGE_READWRITE, &oldProt);
  10603. if (!success)
  10604. {
  10605. int err = GetLastError();
  10606. }
  10607. return (int)oldProt;
  10608. }
  10609. int WinDebugger::SetProtection(intptr address, int size, int prot)
  10610. {
  10611. DWORD oldProt;
  10612. ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)address, size, prot, &oldProt);
  10613. return (int)oldProt;
  10614. }
  10615. void WinDebugger::EnableMemCache()
  10616. {
  10617. mMemCacheAddr = 1;
  10618. }
  10619. void WinDebugger::DisableMemCache()
  10620. {
  10621. mMemCacheAddr = 0;
  10622. }
  10623. bool WinDebugger::ReadMemory(intptr address, uint64 length, void* dest, bool local)
  10624. {
  10625. if (local)
  10626. {
  10627. __try
  10628. {
  10629. memcpy(dest, (void*)address, length);
  10630. return true;
  10631. }
  10632. __except(EXCEPTION_EXECUTE_HANDLER)
  10633. {
  10634. return false;
  10635. }
  10636. }
  10637. if (mMemCacheAddr != 0)
  10638. {
  10639. addr_target targetAddr = (addr_target)address;
  10640. if ((targetAddr >= mMemCacheAddr) && (targetAddr + length <= mMemCacheAddr + WD_MEMCACHE_SIZE) && (mMemCacheAddr > 1))
  10641. {
  10642. memcpy(dest, mMemCacheData + (targetAddr - mMemCacheAddr), length);
  10643. return true;
  10644. }
  10645. // We need a new block
  10646. SIZE_T dwReadBytes;
  10647. if (::ReadProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, mMemCacheData, (SIZE_T)WD_MEMCACHE_SIZE, &dwReadBytes) != 0)
  10648. {
  10649. mMemCacheAddr = targetAddr;
  10650. memcpy(dest, mMemCacheData, length);
  10651. return true;
  10652. }
  10653. // Failed, turn off caching
  10654. mMemCacheAddr = 0;
  10655. }
  10656. SIZE_T dwReadBytes;
  10657. if (::ReadProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, dest, (SIZE_T)length, &dwReadBytes) != 0)
  10658. return true;
  10659. int lastErr = ::GetLastError();
  10660. memset(dest, 0, length);
  10661. return false;
  10662. }
  10663. bool WinDebugger::WriteMemory(intptr address, void* src, uint64 length)
  10664. {
  10665. SIZE_T dwBytesWritten = 0;
  10666. int result = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, src, (SIZE_T)length, &dwBytesWritten);
  10667. return result != 0;
  10668. }
  10669. addr_target WinDebugger::GetTLSOffset(int tlsIndex)
  10670. {
  10671. typedef LONG NTSTATUS;
  10672. typedef DWORD KPRIORITY;
  10673. typedef WORD UWORD;
  10674. enum THREADINFOCLASS
  10675. {
  10676. ThreadBasicInformation,
  10677. };
  10678. struct CLIENT_ID
  10679. {
  10680. HANDLE UniqueProcess;
  10681. HANDLE UniqueThread;
  10682. };
  10683. struct
  10684. {
  10685. NTSTATUS mExitStatus;
  10686. void* mTebBaseAddress;
  10687. CLIENT_ID mClientId;
  10688. KAFFINITY mAffinityMask;
  10689. KPRIORITY mPriority;
  10690. KPRIORITY mBasePriority;
  10691. } threadInfo = { 0 };
  10692. ULONG len = 0;
  10693. bool loadedManually = false;
  10694. static HMODULE module = NULL;
  10695. static NTSTATUS(__stdcall *NtQueryInformationThread)(HANDLE ThreadHandle, THREADINFOCLASS ThreadInformationClass, PVOID ThreadInformation, ULONG ThreadInformationLength, PULONG ReturnLength);
  10696. if (module == NULL)
  10697. {
  10698. module = GetModuleHandleA("ntdll.dll");
  10699. NtQueryInformationThread = reinterpret_cast<decltype(NtQueryInformationThread)>(GetProcAddress(module, "NtQueryInformationThread"));
  10700. }
  10701. if (NtQueryInformationThread == NULL)
  10702. return 0;
  10703. NTSTATUS status = NtQueryInformationThread(mActiveThread->mHThread, (THREADINFOCLASS)0, &threadInfo, sizeof(threadInfo), nullptr);
  10704. if (status < 0)
  10705. return 0;
  10706. #ifdef BF_DBG_32
  10707. addr_target tibAddr = ReadMemory<addr_target>((intptr)threadInfo.mTebBaseAddress + 0x0);
  10708. addr_target tlsTable = ReadMemory<addr_target>((intptr)tibAddr + 0x2C);
  10709. #else
  10710. addr_target tlsTable = ReadMemory<addr_target>((intptr)threadInfo.mTebBaseAddress + 0x58);
  10711. #endif
  10712. return ReadMemory<addr_target>(tlsTable + tlsIndex * sizeof(addr_target));
  10713. }
  10714. bool WinDebugger::WriteInstructions(intptr address, void* src, uint64 length)
  10715. {
  10716. SIZE_T dwBytesWritten = 0;
  10717. bool result = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, src, (SIZE_T)length, &dwBytesWritten) != 0;
  10718. result |= ::FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, (SIZE_T)length) != 0;
  10719. BF_ASSERT(result);
  10720. BfLogDbg("WriteInstructions: %p %d\n", address, length);
  10721. return result;
  10722. }
  10723. DbgMemoryFlags WinDebugger::GetMemoryFlags(intptr address)
  10724. {
  10725. MEMORY_BASIC_INFORMATION memBasicInfo;
  10726. if (::VirtualQueryEx(mProcessInfo.hProcess, (void*)address, &memBasicInfo, sizeof(MEMORY_BASIC_INFORMATION)) == 0)
  10727. {
  10728. //BfLogDbg("VirtualQueryEx failed with %d\n", GetLastError());
  10729. return DbgMemoryFlags_None;
  10730. }
  10731. DbgMemoryFlags flags = DbgMemoryFlags_None;
  10732. if (memBasicInfo.AllocationProtect & PAGE_READWRITE)
  10733. {
  10734. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  10735. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  10736. }
  10737. if (memBasicInfo.AllocationProtect & PAGE_READONLY)
  10738. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  10739. if (memBasicInfo.AllocationProtect & PAGE_WRITECOPY)
  10740. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  10741. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE)
  10742. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  10743. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_READ)
  10744. {
  10745. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  10746. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  10747. }
  10748. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_READWRITE)
  10749. {
  10750. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  10751. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  10752. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  10753. }
  10754. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_WRITECOPY)
  10755. {
  10756. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  10757. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  10758. }
  10759. return flags;
  10760. }
  10761. #ifdef BF_DBG_32
  10762. Debugger* Beefy::CreateDebugger32(DebugManager* debugManager, DbgMiniDump* miniDump)
  10763. #else
  10764. Debugger* Beefy::CreateDebugger64(DebugManager* debugManager, DbgMiniDump* miniDump)
  10765. #endif
  10766. {
  10767. if (miniDump != NULL)
  10768. {
  10769. auto debugger = new MiniDumpDebugger(debugManager, miniDump);
  10770. return debugger;
  10771. }
  10772. return new WinDebugger(debugManager);
  10773. }
  10774. #ifdef BF_DBG_32
  10775. void WdAllocTest()
  10776. {
  10777. Array<BeefyDbg32::WdStackFrame*> stackFrameList;
  10778. for (int i = 0; true; i++)
  10779. {
  10780. WdStackFrame* stackFrame = new WdStackFrame();
  10781. stackFrameList.push_back(stackFrame);
  10782. }
  10783. }
  10784. #endif
  10785. #endif //!defined BF32 || !defined BF_DBG_64
  10786. //ab