WinDebugger.cpp 401 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875
  1. #pragma warning(disable:4996)
  2. // TODO: Remove for 64-bit
  3. #pragma warning(disable:4244)
  4. #pragma warning(disable:4267)
  5. #define NTDDI_VERSION 0x06020000
  6. #include "WinDebugger.h"
  7. #include "CPU.h"
  8. #include "DbgModule.h"
  9. #include "DebugVisualizers.h"
  10. #include "MiniDumpDebugger.h"
  11. #include "X86.h"
  12. #include "BeefySysLib/Common.h"
  13. #include "BeefySysLib/util/PerfTimer.h"
  14. #include "BeefySysLib/util/BeefPerf.h"
  15. #include "BeefySysLib/util/CritSect.h"
  16. #include "BeefySysLib/util/UTF8.h"
  17. #include "BeefySysLib/FileStream.h"
  18. #include "BeefySysLib/FileHandleStream.h"
  19. #include "BeefySysLib/util/FileEnumerator.h"
  20. #include <inttypes.h>
  21. #include <windows.h>
  22. #include "DbgExprEvaluator.h"
  23. #include "Compiler/BfSystem.h"
  24. #include "Compiler/BfParser.h"
  25. #include "Compiler/BfReducer.h"
  26. #include "Compiler/BfDemangler.h"
  27. #include "Compiler/BfPrinter.h"
  28. #include <Shlobj.h>
  29. #include "NetManager.h"
  30. #include "DebugManager.h"
  31. #include "X86Target.h"
  32. #include "HotHeap.h"
  33. #include "HotScanner.h"
  34. #include "Profiler.h"
  35. #include <float.h>
  36. #include <psapi.h>
  37. #if !defined BF32 || !defined BF_DBG_64
  38. #define STATUS_WX86_CONTINUE 0x4000001DL
  39. #define STATUS_WX86_SINGLE_STEP 0x4000001EL
  40. #define STATUS_WX86_BREAKPOINT 0x4000001FL
  41. #define STATUS_WX86_EXCEPTION_CONTINUE 0x40000020L
  42. #pragma pack(push, 1)
  43. struct HotJumpOp
  44. {
  45. uint8 mOpCode;
  46. int32 mRelTarget;
  47. };
  48. #pragma pack(pop)
  49. #include "BeefySysLib/util/AllocDebug.h"
  50. #include <limits>
  51. USING_NS_BF_DBG;
  52. static void FilterThreadName(String& name)
  53. {
  54. for (int i = 0; i < (int)name.length(); i++)
  55. {
  56. uint8 c = name[i];
  57. if (c == 0)
  58. {
  59. name.RemoveToEnd(i);
  60. return;
  61. }
  62. if (c < 32)
  63. {
  64. name.Remove(i);
  65. i--;
  66. continue;
  67. }
  68. }
  69. }
  70. static bool IsHandleValid(HANDLE handle)
  71. {
  72. return (handle != NULL) && (handle != INVALID_HANDLE_VALUE);
  73. }
  74. //////////////////////////////////////////////////////////////////////////
  75. WdBreakpointCondition::~WdBreakpointCondition()
  76. {
  77. delete mDbgEvaluationContext;
  78. }
  79. //////////////////////////////////////////////////////////////////////////
  80. DbgEvaluationContext::DbgEvaluationContext(WinDebugger* winDebugger, DbgModule* dbgModule, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  81. {
  82. Init(winDebugger, dbgModule, expr, formatInfo, contextValue);
  83. }
  84. DbgEvaluationContext::DbgEvaluationContext(WinDebugger* winDebugger, DbgCompileUnit* dbgCompileUnit, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  85. {
  86. DbgModule* dbgModule = NULL;
  87. if (dbgCompileUnit != NULL)
  88. dbgModule = dbgCompileUnit->mDbgModule;
  89. Init(winDebugger, dbgModule, expr, formatInfo, contextValue);
  90. }
  91. void DbgEvaluationContext::Init(WinDebugger* winDebugger, DbgModule* dbgModule, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  92. {
  93. if (expr.empty())
  94. {
  95. mParser = NULL;
  96. mReducer = NULL;
  97. mPassInstance = NULL;
  98. mDbgExprEvaluator = NULL;
  99. mExprNode = NULL;
  100. return;
  101. }
  102. mParser = new BfParser(winDebugger->mBfSystem);
  103. mParser->mCompatMode = true;
  104. mPassInstance = new BfPassInstance(winDebugger->mBfSystem);
  105. auto terminatedExpr = expr + ";";
  106. mParser->SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  107. mParser->Parse(mPassInstance);
  108. mReducer = new BfReducer();
  109. mReducer->mAlloc = mParser->mAlloc;
  110. mReducer->mSystem = winDebugger->mBfSystem;
  111. mReducer->mPassInstance = mPassInstance;
  112. mReducer->mVisitorPos = BfReducer::BfVisitorPos(mParser->mRootNode);
  113. mReducer->mVisitorPos.MoveNext();
  114. mReducer->mCompatMode = mParser->mCompatMode;
  115. mReducer->mSource = mParser;
  116. mExprNode = mReducer->CreateExpression(mParser->mRootNode->GetFirst());
  117. mParser->Close();
  118. mDbgExprEvaluator = new DbgExprEvaluator(winDebugger, dbgModule, mPassInstance, -1, -1);
  119. if ((formatInfo != NULL) && (mExprNode != NULL) && (mExprNode->GetSrcEnd() < (int) expr.length()))
  120. {
  121. String formatFlags = expr.Substring(mExprNode->GetSrcEnd());
  122. String errorString = "Invalid expression";
  123. if (!winDebugger->ParseFormatInfo(dbgModule, formatFlags, formatInfo, mPassInstance, NULL, NULL, &errorString, contextValue))
  124. {
  125. mPassInstance->FailAt(errorString, mParser->mSourceData, mExprNode->GetSrcEnd(), (int)expr.length() - mExprNode->GetSrcEnd());
  126. formatFlags = "";
  127. }
  128. }
  129. if (formatInfo != NULL)
  130. {
  131. mDbgExprEvaluator->mExplicitThis = formatInfo->mExplicitThis;
  132. mDbgExprEvaluator->mCallStackIdx = formatInfo->mCallStackIdx;
  133. mDbgExprEvaluator->mLanguage = formatInfo->mLanguage;
  134. }
  135. }
  136. bool DbgEvaluationContext::HasExpression()
  137. {
  138. return mExprNode != NULL;
  139. }
  140. DbgEvaluationContext::~DbgEvaluationContext()
  141. {
  142. delete mParser;
  143. delete mReducer;
  144. delete mDbgExprEvaluator;
  145. delete mPassInstance;
  146. }
  147. DbgTypedValue DbgEvaluationContext::EvaluateInContext(DbgTypedValue contextTypedValue)
  148. {
  149. if (mExprNode == NULL)
  150. return DbgTypedValue();
  151. mPassInstance->ClearErrors();
  152. if (contextTypedValue)
  153. {
  154. mDbgExprEvaluator->mExplicitThis = contextTypedValue;
  155. if ((mDbgExprEvaluator->mExplicitThis.mType->IsPointer()) && (mDbgExprEvaluator->mExplicitThis.mType->mTypeParam->WantsRefThis()))
  156. {
  157. mDbgExprEvaluator->mExplicitThis.mType = mDbgExprEvaluator->mExplicitThis.mType->mTypeParam;
  158. mDbgExprEvaluator->mExplicitThis.mSrcAddress = mDbgExprEvaluator->mExplicitThis.mPtr;
  159. mDbgExprEvaluator->mExplicitThis.mPtr = 0;
  160. }
  161. if ((mDbgExprEvaluator->mExplicitThis.mType->IsCompositeType()) && (!mDbgExprEvaluator->mExplicitThis.mType->WantsRefThis()))
  162. {
  163. if (mDbgExprEvaluator->mExplicitThis.mSrcAddress != 0)
  164. {
  165. mDbgExprEvaluator->mExplicitThis.mType = mDbgExprEvaluator->mDbgModule->GetPointerType(mDbgExprEvaluator->mExplicitThis.mType);
  166. mDbgExprEvaluator->mExplicitThis.mPtr = mDbgExprEvaluator->mExplicitThis.mSrcAddress;
  167. mDbgExprEvaluator->mExplicitThis.mSrcAddress = 0;
  168. }
  169. }
  170. }
  171. if (contextTypedValue.mType != NULL)
  172. mDbgExprEvaluator->mDbgCompileUnit = contextTypedValue.mType->mCompileUnit;
  173. DbgTypedValue exprResult;
  174. auto result = mDbgExprEvaluator->Resolve(mExprNode);
  175. return result;
  176. }
  177. bool DbgEvaluationContext::HadError()
  178. {
  179. return mPassInstance->mFailedIdx != 0;
  180. }
  181. String DbgEvaluationContext::GetErrorStr()
  182. {
  183. String errorStr = mPassInstance->mErrors[0]->mError;
  184. if (mExprNode != NULL)
  185. {
  186. errorStr += ": ";
  187. errorStr += mExprNode->ToString();
  188. }
  189. return errorStr;
  190. }
  191. //////////////////////////////////////////////////////////////////////////
  192. typedef HRESULT(WINAPI* SetThreadDescription_t)(HANDLE hThread, PCWSTR lpThreadDescription);
  193. typedef HRESULT(WINAPI* GetThreadDescription_t)(HANDLE hThread, PWSTR* lpThreadDescription);
  194. static SetThreadDescription_t gSetThreadDescription = NULL;
  195. static GetThreadDescription_t gGetThreadDescription = NULL;
  196. static HMODULE gKernelDll = NULL;
  197. static void ImportKernel()
  198. {
  199. if (gKernelDll != NULL)
  200. return;
  201. WCHAR path[MAX_PATH];
  202. GetSystemDirectory(path, MAX_PATH);
  203. wcscat(path, L"\\kernel32.dll");
  204. gKernelDll = GetModuleHandle(path);
  205. if (gKernelDll == NULL)
  206. {
  207. return;
  208. }
  209. gSetThreadDescription = (SetThreadDescription_t)GetProcAddress(gKernelDll, "SetThreadDescription");
  210. gGetThreadDescription = (GetThreadDescription_t)GetProcAddress(gKernelDll, "GetThreadDescription");
  211. }
  212. void WinDebugger::TryGetThreadName(WdThreadInfo* threadInfo)
  213. {
  214. if (threadInfo->mHThread == NULL)
  215. return;
  216. ImportKernel();
  217. PWSTR wStr = NULL;
  218. if (gGetThreadDescription != NULL)
  219. {
  220. gGetThreadDescription(threadInfo->mHThread, &wStr);
  221. if (wStr == NULL)
  222. return;
  223. threadInfo->mName = UTF8Encode(wStr);
  224. FilterThreadName(threadInfo->mName);
  225. LocalFree(wStr);
  226. }
  227. }
  228. static void CreateFilterName(String& name, DbgType* type)
  229. {
  230. CreateFilterName(name, type->mParent);
  231. switch (type->mTypeCode)
  232. {
  233. case DbgType_Namespace:
  234. case DbgType_Struct:
  235. case DbgType_Class:
  236. name += type->mName;
  237. break;
  238. }
  239. }
  240. static void CreateFilterName(String& name, const char* srcStr, DbgLanguage language)
  241. {
  242. int chevronDepth = 0;
  243. const char* cPtr = srcStr;
  244. for (; true; cPtr++)
  245. {
  246. char c = *cPtr;
  247. if (c == 0)
  248. break;
  249. if (c == '>')
  250. chevronDepth--;
  251. bool inGeneric = chevronDepth > 0;
  252. if (c == '<')
  253. chevronDepth++;
  254. if (inGeneric) // Bundle all generic instances together
  255. continue;
  256. if (c == '[') // Bundle all arrays together
  257. name.clear();
  258. if (c == '(')
  259. return; // Start of params
  260. if ((c == ':') && (cPtr[1] == ':') && (language == DbgLanguage_Beef))
  261. {
  262. name.Append('.');
  263. cPtr++;
  264. }
  265. else
  266. name.Append(c);
  267. }
  268. }
  269. static void CreateFilterName(String& name, DbgSubprogram* subprogram)
  270. {
  271. auto language = subprogram->GetLanguage();
  272. if (subprogram->mName == NULL)
  273. {
  274. if (subprogram->mLinkName[0] == '<')
  275. {
  276. name += subprogram->mLinkName;
  277. return;
  278. }
  279. name = BfDemangler::Demangle(subprogram->mLinkName, language);
  280. // Strip off the params since we need to generate those ourselves
  281. int parenPos = (int)name.IndexOf('(');
  282. if (parenPos != -1)
  283. name.RemoveToEnd(parenPos);
  284. return;
  285. }
  286. else if (subprogram->mHasQualifiedName)
  287. {
  288. const char* cPtr = subprogram->mName;
  289. if (strncmp(cPtr, "_bf::", 5) == 0)
  290. {
  291. CreateFilterName(name, cPtr + 5, DbgLanguage_Beef);
  292. name.Replace(".__BfStaticCtor", ".this$static");
  293. name.Replace(".__BfCtorClear", ".this$clear");
  294. name.Replace(".__BfCtor", ".this");
  295. }
  296. else
  297. CreateFilterName(name, subprogram->mName, language);
  298. return;
  299. }
  300. else
  301. {
  302. if (subprogram->mParentType != NULL)
  303. {
  304. String parentName = subprogram->mParentType->ToString();
  305. CreateFilterName(name, parentName.c_str(), language);
  306. if (!name.empty())
  307. {
  308. if (language == DbgLanguage_Beef)
  309. name += ".";
  310. else
  311. name += "::";
  312. }
  313. }
  314. if ((language == DbgLanguage_Beef) && (subprogram->mParentType != NULL) && (subprogram->mParentType->mTypeName != NULL) &&
  315. (strcmp(subprogram->mName, subprogram->mParentType->mTypeName) == 0))
  316. name += "this";
  317. else if ((language == DbgLanguage_Beef) && (subprogram->mName[0] == '~'))
  318. name += "~this";
  319. else if (strncmp(subprogram->mName, "_bf::", 5) == 0)
  320. {
  321. CreateFilterName(name, subprogram->mName + 5, DbgLanguage_Beef);
  322. }
  323. else
  324. {
  325. CreateFilterName(name, subprogram->mName, language);
  326. }
  327. }
  328. if (name.empty())
  329. name += "`anon";
  330. if ((name[name.length() - 1] == '!') || (name[0] == '<'))
  331. {
  332. if (language == DbgLanguage_Beef)
  333. {
  334. // It's a mixin - assert that there's no params
  335. //BF_ASSERT(subprogram->mParams.Size() == 0);
  336. }
  337. return;
  338. }
  339. }
  340. //////////////////////////////////////////////////////////////////////////
  341. DbgPendingExpr::DbgPendingExpr()
  342. {
  343. mThreadId = -1;
  344. mCallStackIdx = -1;
  345. mParser = NULL;
  346. mCursorPos = -1;
  347. mExprNode = NULL;
  348. mIdleTicks = 0;
  349. mExplitType = NULL;
  350. mExpressionFlags = DwEvalExpressionFlag_None;
  351. mUsedSpecifiedLock = false;
  352. mStackIdxOverride = -1;
  353. }
  354. DbgPendingExpr::~DbgPendingExpr()
  355. {
  356. delete mParser;
  357. }
  358. // conversion logic based on table at http://en.wikipedia.org/wiki/Extended_precision
  359. //CDH TODO put this somewhere more general
  360. static double ConvertFloat80ToDouble(const byte fp80[10])
  361. {
  362. uint16 e = *((uint16*)&fp80[8]);
  363. uint64 m = *((uint64*)&fp80[0]);
  364. uint64 bit63 = (uint64)1 << 63;
  365. uint64 bit62 = (uint64)1 << 62;
  366. bool isNegative = (e & 0x8000) != 0;
  367. double s = isNegative ? -1.0 : 1.0;
  368. e &= 0x7fff;
  369. if (!e)
  370. {
  371. // the high bit and mantissa content will determine whether it's an actual zero, or a denormal or
  372. // pseudo-denormal number with an effective exponent of -16382. But since that exponent is so far
  373. // below anything we can handle in double-precision (even accounting for denormal bit shifts), we're
  374. // effectively still dealing with zero.
  375. return s * 0.0;
  376. }
  377. else if (e == 0x7fff)
  378. {
  379. if (m & bit63)
  380. {
  381. if (m & bit62)
  382. {
  383. return std::numeric_limits<double>::quiet_NaN();
  384. }
  385. else
  386. {
  387. if (m == bit63)
  388. return s * std::numeric_limits<double>::infinity();
  389. else
  390. return std::numeric_limits<double>::signaling_NaN();
  391. }
  392. }
  393. else
  394. {
  395. return std::numeric_limits<double>::quiet_NaN();
  396. }
  397. }
  398. else
  399. {
  400. if (!(m & bit63))
  401. return std::numeric_limits<double>::quiet_NaN(); // unnormal (we don't handle these since 80387 and later treat them as invalid operands anyway)
  402. // else is a normalized value
  403. }
  404. int useExponent = (int)e - 16383;
  405. if (useExponent < -1022)
  406. return s * 0.0; // we could technically support e from -1023 to -1074 as denormals, but don't bother with that for now.
  407. else if (useExponent > 1023)
  408. return s * HUGE_VAL;
  409. useExponent += 1023;
  410. BF_ASSERT((useExponent > 0) && (useExponent < 0x7ff)); // assume we've filtered for valid exponent range
  411. BF_ASSERT(m & bit63); // assume we've filtered out values that aren't normalized by now
  412. uint64 result = 0;
  413. if (isNegative)
  414. result |= bit63;
  415. result |= (uint64)useExponent << 52;
  416. result |= (m & ~bit63) >> 11;
  417. return *reinterpret_cast<double*>(&result);
  418. }
  419. addr_target NS_BF_DBG::DecodeTargetDataPtr(const char*& strRef)
  420. {
  421. addr_target val = (addr_target)stouln(strRef, sizeof(intptr_target) * 2);
  422. strRef += sizeof(intptr_target) * 2;
  423. return val;
  424. }
  425. WinDebugger::WinDebugger(DebugManager* debugManager) : mDbgSymSrv(this)
  426. {
  427. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  428. mActiveHotIdx = -1;
  429. mGotStartupEvent = false;
  430. mIsContinuingFromException = false;
  431. mDestroying = false;
  432. mDebugManager = debugManager;
  433. mNeedsRehupBreakpoints = false;
  434. mStepInAssembly = false;
  435. mStepSP = 0;
  436. mStepIsRecursing = false;
  437. mStepStopOnNextInstruction = false;
  438. mDebugTarget = NULL;
  439. mShuttingDown = false;
  440. mBfSystem = new BfSystem();
  441. mAtBreakThread = NULL;
  442. mActiveThread = NULL;
  443. mActiveBreakpoint = NULL;
  444. mSteppingThread = NULL;
  445. mExplicitStopThread = NULL;
  446. mStepSwitchedThreads = false;
  447. mIsDebuggerWaiting = false;
  448. mWantsDebugContinue = false;
  449. mContinueFromBreakpointFailed = false;
  450. mIsStepIntoSpecific = false;
  451. mDbgBreak = false;
  452. mDebuggerWaitingThread = NULL;
  453. mStepType = StepType_None;
  454. mOrigStepType = StepType_None;
  455. mLastValidStepIntoPC = 0;
  456. mActiveSymSrvRequest = NULL;
  457. mStdInputPipe = INVALID_HANDLE_VALUE;
  458. mStdOutputPipe = INVALID_HANDLE_VALUE;
  459. mStdErrorPipe = INVALID_HANDLE_VALUE;
  460. mStoredReturnValueAddr = 0;
  461. #ifdef BF_DBG_32
  462. mCPU = gX86Target->mX86CPU;
  463. #else
  464. mCPU = gX86Target->mX64CPU;
  465. #endif
  466. mRunState = RunState_NotStarted;
  467. mIsRunning = false;
  468. mSavedAtBreakpointAddress = 0;
  469. mSavedBreakpointAddressContinuing = 0;
  470. mRequestedStackFrameIdx = 0;
  471. mShowPCOverride = 0;
  472. mCurNoInfoStepTries = 0;
  473. mDbgAttachFlags = BfDbgAttachFlag_None;
  474. mDbgProcessHandle = 0;
  475. mDbgThreadHandle = 0;
  476. mDbgProcessId = 0;
  477. mDbgHeapData = NULL;
  478. mIsPartialCallStack = true;
  479. mHotSwapEnabled = false;
  480. mOpenFileFlags = DbgOpenFileFlag_None;
  481. for (int i = 0; i < 4; i++)
  482. {
  483. mFreeMemoryBreakIndices.push_back(i);
  484. }
  485. mMemoryBreakpointVersion = 0;
  486. SYSTEM_INFO systemInfo;
  487. GetSystemInfo(&systemInfo);
  488. mPageSize = systemInfo.dwPageSize;
  489. mEmptyDebugTarget = new DebugTarget(this);
  490. mEmptyDebugTarget->CreateEmptyTarget();
  491. mEmptyDebugTarget->mIsEmpty = true;
  492. mDebugTarget = mEmptyDebugTarget;
  493. mDebugPendingExpr = NULL;
  494. mDebugEvalThreadInfo = WdThreadInfo();
  495. mMemCacheAddr = 0;
  496. mDebuggerThreadId = 0;
  497. }
  498. WinDebugger::~WinDebugger()
  499. {
  500. mDestroying = true;
  501. delete gDbgPerfManager;
  502. gDbgPerfManager = NULL;
  503. if ((mDebugTarget != NULL) && (mDebugTarget != mEmptyDebugTarget))
  504. Detach();
  505. for (auto breakpoint : mBreakpoints)
  506. {
  507. auto checkBreakpoint = breakpoint->mLinkedSibling;
  508. while (checkBreakpoint != NULL)
  509. {
  510. auto nextBreakpoint = checkBreakpoint->mLinkedSibling;
  511. delete checkBreakpoint;
  512. checkBreakpoint = nextBreakpoint;
  513. }
  514. delete breakpoint;
  515. }
  516. delete mEmptyDebugTarget;
  517. delete mBfSystem;
  518. for (auto kv : mPendingProfilerMap)
  519. delete kv.mValue;
  520. for (auto profiler : mNewProfilerList)
  521. delete profiler;
  522. delete mDebugPendingExpr;
  523. }
  524. void WinDebugger::Fail(const StringImpl& error)
  525. {
  526. if (mIsRunning)
  527. mDebugManager->mOutMessages.push_back(StrFormat("error %s", error.c_str()));
  528. }
  529. // Leave active thread unpaused
  530. void WinDebugger::ThreadRestorePause(WdThreadInfo* onlyPauseThread, WdThreadInfo* dontPauseThread)
  531. {
  532. BfLogDbg("ThreadRestorePause %d %d\n", (onlyPauseThread != NULL) ? onlyPauseThread->mThreadId : 0, (dontPauseThread != NULL) ? dontPauseThread->mThreadId : 0);
  533. for (auto threadInfo : mThreadList)
  534. {
  535. if (((threadInfo != dontPauseThread) && (!threadInfo->mIsBreakRestorePaused)) &&
  536. ((onlyPauseThread == NULL) || (threadInfo == onlyPauseThread)))
  537. {
  538. BF_ASSERT(!threadInfo->mIsBreakRestorePaused);
  539. BfLogDbg("SuspendThread %d\n", threadInfo->mThreadId);
  540. ::SuspendThread(threadInfo->mHThread);
  541. threadInfo->mIsBreakRestorePaused = true;
  542. }
  543. }
  544. }
  545. void WinDebugger::ThreadRestoreUnpause()
  546. {
  547. BfLogDbg("ThreadRestoreUnpause\n");
  548. for (auto threadInfo : mThreadList)
  549. {
  550. if (threadInfo->mIsBreakRestorePaused)
  551. {
  552. BfLogDbg("ResumeThread %d\n", threadInfo->mThreadId);
  553. ::ResumeThread(threadInfo->mHThread);
  554. threadInfo->mIsBreakRestorePaused = false;
  555. }
  556. }
  557. }
  558. void WinDebugger::UpdateThreadDebugRegisters(WdThreadInfo* threadInfo)
  559. {
  560. if (threadInfo->mMemoryBreakpointVersion == mMemoryBreakpointVersion)
  561. return;
  562. auto threadId = threadInfo->mHThread;
  563. BF_CONTEXT lcContext;
  564. lcContext.ContextFlags = BF_CONTEXT_DEBUG_REGISTERS;
  565. BF_GetThreadContext(threadId, &lcContext);
  566. for (int memoryBreakIdx = 0; memoryBreakIdx < 4; memoryBreakIdx++)
  567. {
  568. WdMemoryBreakpointBind memoryBreakpointBind = mMemoryBreakpoints[memoryBreakIdx];
  569. WdBreakpoint* wdBreakpoint = memoryBreakpointBind.mBreakpoint;
  570. if (wdBreakpoint == NULL)
  571. {
  572. *(&lcContext.Dr0 + memoryBreakIdx) = 0;
  573. lcContext.Dr7 &= ~((1 << (memoryBreakIdx * 2)) | (1 << (16 + memoryBreakIdx * 4)) | (3 << (18 + memoryBreakIdx * 4)));
  574. }
  575. else
  576. {
  577. int sizeCode = 0;
  578. if (memoryBreakpointBind.mByteCount == 2)
  579. sizeCode = 1;
  580. else if (memoryBreakpointBind.mByteCount == 4)
  581. sizeCode = 3;
  582. else if (memoryBreakpointBind.mByteCount == 8)
  583. sizeCode = 2;
  584. addr_target calcAddr = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress + memoryBreakpointBind.mOfs;
  585. BF_ASSERT(calcAddr == memoryBreakpointBind.mAddress);
  586. *(&lcContext.Dr0 + memoryBreakIdx) = calcAddr;
  587. lcContext.Dr7 |= (1 << (memoryBreakIdx * 2)) | (1 << (16 + memoryBreakIdx * 4)) | (sizeCode << (18 + memoryBreakIdx * 4));
  588. }
  589. }
  590. bool worked = BF_SetThreadContext(threadId, &lcContext) != 0;
  591. BF_ASSERT(worked || (mRunState == RunState_Terminating) || (mRunState == RunState_Terminated));
  592. threadInfo->mMemoryBreakpointVersion = mMemoryBreakpointVersion;
  593. }
  594. void WinDebugger::UpdateThreadDebugRegisters()
  595. {
  596. for (auto threadInfo : mThreadList)
  597. {
  598. ::SuspendThread(threadInfo->mHThread);
  599. UpdateThreadDebugRegisters(threadInfo);
  600. ::ResumeThread(threadInfo->mHThread);
  601. }
  602. }
  603. void WinDebugger::PhysSetBreakpoint(addr_target address)
  604. {
  605. BfLogDbg("PhysSetBreakpoint %p\n", address);
  606. uint8 newData = 0xCC;
  607. // This ensure that we have the orig image data cached
  608. DbgMemoryFlags flags = mDebugTarget->ReadOrigImageData(address, NULL, 1);
  609. if ((flags & DbgMemoryFlags_Execute) == 0)
  610. {
  611. BfLogDbg("Breakpoint ignored - execute flag NOT set in breakpoint address\n", address);
  612. BfLogDbg("Memory Flags = %d\n", gDebugger->GetMemoryFlags(address));
  613. return;
  614. }
  615. // Replace it with Breakpoint
  616. SIZE_T dwReadBytes;
  617. BOOL worked = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, &newData, 1, &dwReadBytes);
  618. if (!worked)
  619. {
  620. int err = GetLastError();
  621. BfLogDbg("SetBreakpoint FAILED %p\n", address);
  622. }
  623. FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, 1);
  624. {
  625. uint8 mem = ReadMemory<uint8>(address);
  626. BfLogDbg("Breakpoint byte %X\n", mem);
  627. }
  628. }
  629. void WinDebugger::SetBreakpoint(addr_target address, bool fromRehup)
  630. {
  631. int* countPtr = NULL;
  632. if (mPhysBreakpointAddrMap.TryAdd(address, NULL, &countPtr))
  633. {
  634. BfLogDbg("SetBreakpoint %p\n", address);
  635. *countPtr = 1;
  636. }
  637. else
  638. {
  639. if (fromRehup)
  640. {
  641. BfLogDbg("SetBreakpoint %p Count: %d. Rehup (ignored).\n", address, *countPtr);
  642. return;
  643. }
  644. (*countPtr)++;
  645. BfLogDbg("SetBreakpoint %p Count: %d\n", address, *countPtr);
  646. return;
  647. }
  648. PhysSetBreakpoint(address);
  649. }
  650. void WinDebugger::SetTempBreakpoint(addr_target address)
  651. {
  652. BfLogDbg("SetTempBreakpoint %p\n", address);
  653. mTempBreakpoint.push_back(address);
  654. SetBreakpoint(address);
  655. }
  656. void WinDebugger::PhysRemoveBreakpoint(addr_target address)
  657. {
  658. BfLogDbg("PhysRemoveBreakpoint %p\n", address);
  659. uint8 origData;
  660. DbgMemoryFlags flags = mDebugTarget->ReadOrigImageData(address, &origData, 1);
  661. if ((flags & DbgMemoryFlags_Execute) == 0)
  662. {
  663. //BF_ASSERT("Failed" == 0);
  664. return;
  665. }
  666. SIZE_T dwReadBytes;
  667. if (!WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, &origData, 1, &dwReadBytes))
  668. {
  669. int err = GetLastError();
  670. BfLogDbg("RemoveBreakpoint FAILED %p\n", address);
  671. }
  672. FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, 1);
  673. }
  674. void WinDebugger::RemoveBreakpoint(addr_target address)
  675. {
  676. int* countPtr = NULL;
  677. mPhysBreakpointAddrMap.TryGetValue(address, &countPtr);
  678. // This can happen when we shutdown and we're continuing from a breakpoint
  679. //BF_ASSERT(*countPtr != NULL);
  680. if (countPtr == NULL)
  681. {
  682. BfLogDbg("RemoveBreakpoint %p FAILED\n", address);
  683. return;
  684. }
  685. BfLogDbg("RemoveBreakpoint %p count: %d\n", address, *countPtr);
  686. if (*countPtr > 1)
  687. {
  688. (*countPtr)--;
  689. return;
  690. }
  691. mPhysBreakpointAddrMap.Remove(address);
  692. PhysRemoveBreakpoint(address);
  693. }
  694. void WinDebugger::SingleStepX86()
  695. {
  696. // In what cases did this catch bugs?
  697. // This caused other failures (caught in tests)
  698. // if (mActiveThread->mIsAtBreakpointAddress != 0)
  699. // {
  700. // ContinueFromBreakpoint();
  701. // return;
  702. // }
  703. BfLogDbg("Setup SingleStepX86 ActiveThread: %d\n", (mActiveThread != NULL) ? mActiveThread->mThreadId : -1);
  704. BF_CONTEXT lcContext;
  705. lcContext.ContextFlags = BF_CONTEXT_ALL;
  706. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  707. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  708. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  709. }
  710. bool WinDebugger::IsInRunState()
  711. {
  712. return (mRunState == RunState_Running) || (mRunState == RunState_Running_ToTempBreakpoint);
  713. }
  714. bool WinDebugger::ContinueFromBreakpoint()
  715. {
  716. if (mDebuggerWaitingThread->mFrozen)
  717. {
  718. BfLogDbg("ContinueFromBreakpoint bailout on frozen thread\n");
  719. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  720. mDebuggerWaitingThread->mIsAtBreakpointAddress = 0;
  721. return true;
  722. }
  723. mActiveThread = mDebuggerWaitingThread;
  724. mActiveBreakpoint = NULL;
  725. BfLogDbg("ContinueFromBreakpoint. ActiveThread: %d\n", (mActiveThread != NULL) ? mActiveThread->mThreadId : -1);
  726. BfLogDbg("ResumeThread %d\n", mActiveThread->mThreadId);
  727. BOOL success = ::ResumeThread(mActiveThread->mHThread);
  728. if (success)
  729. {
  730. // It's possible the active thread is suspended - possibly by the GC, so we would deadlock if we
  731. // attempted to pause the other threads
  732. BfLogDbg("SuspendThread %d\n", mActiveThread->mThreadId);
  733. BfLogDbg("Thread already paused!\n");
  734. ::SuspendThread(mActiveThread->mHThread);
  735. return false;
  736. }
  737. ThreadRestorePause(NULL, mActiveThread);
  738. PhysRemoveBreakpoint(mActiveThread->mIsAtBreakpointAddress);
  739. BF_CONTEXT lcContext;
  740. lcContext.ContextFlags = BF_CONTEXT_ALL;
  741. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  742. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  743. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  744. mActiveThread->mStoppedAtAddress = 0;
  745. mActiveThread->mBreakpointAddressContinuing = mActiveThread->mIsAtBreakpointAddress;
  746. mActiveThread->mIsAtBreakpointAddress = 0;
  747. BfLogDbg("ContinueFromBreakpoint set mIsAtBreakpointAddress = 0\n");
  748. return true;
  749. }
  750. void WinDebugger::ValidateBreakpoints()
  751. {
  752. HashSet<addr_target> usedBreakpoints;
  753. std::function<void(WdBreakpoint*)> _AddBreakpoint = [&](WdBreakpoint* breakpoint)
  754. {
  755. if (breakpoint->mAddr != 0)
  756. {
  757. usedBreakpoints.Add(breakpoint->mAddr);
  758. WdBreakpoint* foundBreakpoint = NULL;
  759. auto itr = mBreakpointAddrMap.Find(breakpoint->mAddr);
  760. bool found = false;
  761. while (itr != mBreakpointAddrMap.end())
  762. {
  763. WdBreakpoint* foundBreakpoint = itr->mValue;
  764. found |= foundBreakpoint == breakpoint;
  765. itr.NextWithSameKey(breakpoint->mAddr);
  766. }
  767. BF_ASSERT(found);
  768. }
  769. auto checkSibling = (WdBreakpoint*)breakpoint->mLinkedSibling;
  770. while (checkSibling != NULL)
  771. {
  772. _AddBreakpoint(checkSibling);
  773. checkSibling = (WdBreakpoint*)checkSibling->mLinkedSibling;
  774. }
  775. };
  776. for (auto breakpoint : mBreakpoints)
  777. _AddBreakpoint(breakpoint);
  778. for (auto& entry : mBreakpointAddrMap)
  779. {
  780. BF_ASSERT(usedBreakpoints.Contains(entry.mKey));
  781. }
  782. }
  783. Breakpoint* WinDebugger::FindBreakpointAt(intptr address)
  784. {
  785. #ifdef _DEBUG
  786. //ValidateBreakpoints();
  787. #endif
  788. WdBreakpoint* breakpoint = NULL;
  789. mBreakpointAddrMap.TryGetValue(address, &breakpoint);
  790. return breakpoint;
  791. }
  792. Breakpoint* WinDebugger::GetActiveBreakpoint()
  793. {
  794. if ((mActiveBreakpoint != NULL) && (mActiveBreakpoint->mHead != NULL))
  795. return mActiveBreakpoint->mHead;
  796. return mActiveBreakpoint;
  797. }
  798. void WinDebugger::DebugThreadProc()
  799. {
  800. BpSetThreadName("DebugThread");
  801. BfpThread_SetName(NULL, "DebugThread", NULL);
  802. mDebuggerThreadId = GetCurrentThreadId();
  803. if (!IsMiniDumpDebugger())
  804. {
  805. if (!DoOpenFile(mLaunchPath, mArgs, mWorkingDir, mEnvBlock, mOpenFileFlags))
  806. {
  807. if (mDbgProcessId != 0)
  808. OutputRawMessage("error Unable to attach to process");
  809. else
  810. OutputRawMessage(StrFormat("error Failed to launch: %s", mLaunchPath.c_str()));
  811. mShuttingDown = true;
  812. mRunState = RunState_Terminated;
  813. }
  814. }
  815. while (!mShuttingDown)
  816. {
  817. DoUpdate();
  818. }
  819. mIsRunning = false;
  820. for (int i = 0; i < (int) mBreakpoints.size(); i++)
  821. {
  822. WdBreakpoint* wdBreakpoint = mBreakpoints[i];
  823. if (wdBreakpoint->mAddr != 0)
  824. mBreakpointAddrMap.Remove(wdBreakpoint->mAddr, wdBreakpoint);
  825. wdBreakpoint->mAddr = 0;
  826. wdBreakpoint->mLineData = DbgLineDataEx();
  827. wdBreakpoint->mSrcFile = NULL;
  828. if (wdBreakpoint->mLinkedSibling != NULL)
  829. {
  830. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  831. wdBreakpoint->mLinkedSibling = NULL;
  832. }
  833. }
  834. if (!IsMiniDumpDebugger())
  835. {
  836. while (true)
  837. {
  838. if (!mIsDebuggerWaiting)
  839. {
  840. if (!WaitForDebugEvent(&mDebugEvent, 0))
  841. break;
  842. }
  843. if (mDebuggerWaitingThread != NULL)
  844. {
  845. BF_ASSERT_REL((mDebuggerWaitingThread->mIsAtBreakpointAddress == 0) || (mShuttingDown));
  846. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_CONTINUE);
  847. BfLogDbg("::ContinueDebugEvent startup ThreadId:%d\n", mDebuggerWaitingThread->mThreadId);
  848. }
  849. mIsDebuggerWaiting = false;
  850. mDebuggerWaitingThread = NULL;
  851. }
  852. }
  853. mDebuggerThreadId = 0;
  854. }
  855. static void DebugThreadProcThunk(void* winDebugger)
  856. {
  857. ((WinDebugger*) winDebugger)->DebugThreadProc();
  858. }
  859. int WinDebugger::GetAddrSize()
  860. {
  861. return sizeof(addr_target);
  862. }
  863. bool WinDebugger::CanOpen(const StringImpl& fileName, DebuggerResult* outResult)
  864. {
  865. FILE* fp = fopen(fileName.c_str(), "rb");
  866. if (fp == NULL)
  867. {
  868. *outResult = DebuggerResult_CannotOpen;
  869. return false;
  870. }
  871. FileStream fs;
  872. fs.mFP = fp;
  873. *outResult = DebuggerResult_Ok;
  874. bool canRead = DbgModule::CanRead(&fs, outResult);
  875. fclose(fp);
  876. return canRead;
  877. }
  878. void WinDebugger::OpenFile(const StringImpl& launchPath, const StringImpl& targetPath, const StringImpl& args, const StringImpl& workingDir, const Array<uint8>& envBlock, bool hotSwapEnabled, DbgOpenFileFlags openFileFlags)
  879. {
  880. BF_ASSERT(!mIsRunning);
  881. mLaunchPath = launchPath;
  882. mTargetPath = targetPath;
  883. mArgs = args;
  884. mWorkingDir = workingDir;
  885. mEnvBlock = envBlock;
  886. mHotSwapEnabled = hotSwapEnabled;
  887. mOpenFileFlags = openFileFlags;
  888. mDebugTarget = new DebugTarget(this);
  889. }
  890. bool WinDebugger::Attach(int processId, BfDbgAttachFlags attachFlags)
  891. {
  892. BF_ASSERT(!mIsRunning);
  893. mDbgAttachFlags = attachFlags;
  894. mDbgProcessHandle = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)processId);
  895. if (mDbgProcessHandle == 0)
  896. return false;
  897. BOOL is32Bit = false;
  898. if (!IsWow64Process(mDbgProcessHandle, &is32Bit))
  899. {
  900. mDbgProcessHandle = 0;
  901. ::CloseHandle(mDbgProcessHandle);
  902. return false;
  903. }
  904. bool want32Bit = sizeof(intptr_target) == 4;
  905. if (want32Bit != (is32Bit != 0))
  906. {
  907. mDbgProcessHandle = 0;
  908. ::CloseHandle(mDbgProcessHandle);
  909. return false;
  910. }
  911. HMODULE mainModule = 0;
  912. DWORD memNeeded = 0;
  913. ::EnumProcessModules(mDbgProcessHandle, &mainModule, sizeof(HMODULE), &memNeeded);
  914. WCHAR fileName[MAX_PATH] = {0};
  915. GetModuleFileNameExW(mDbgProcessHandle, mainModule, fileName, MAX_PATH);
  916. mLaunchPath = UTF8Encode(fileName);
  917. mTargetPath = mLaunchPath;
  918. mDbgProcessId = processId;
  919. mDbgProcessHandle = 0;
  920. ::CloseHandle(mDbgProcessHandle);
  921. mDebugTarget = new DebugTarget(this);
  922. return true;
  923. }
  924. void WinDebugger::GetStdHandles(BfpFile** outStdIn, BfpFile** outStdOut, BfpFile** outStdErr)
  925. {
  926. AutoCrit autoCrit(mDebugManager->mCritSect);
  927. if ((outStdIn != NULL) && (IsHandleValid(mStdInputPipe)))
  928. {
  929. *outStdIn = BfpFile_GetFromHandle((intptr)mStdInputPipe, NULL);
  930. mStdInputPipe = 0;
  931. }
  932. if ((outStdOut != NULL) && (IsHandleValid(mStdOutputPipe)))
  933. {
  934. *outStdOut = BfpFile_GetFromHandle((intptr)mStdOutputPipe, NULL);
  935. mStdOutputPipe = 0;
  936. }
  937. if ((outStdErr != NULL) && (IsHandleValid(mStdErrorPipe)))
  938. {
  939. *outStdErr = BfpFile_GetFromHandle((intptr)mStdErrorPipe, NULL);
  940. mStdErrorPipe = 0;
  941. }
  942. }
  943. void WinDebugger::Run()
  944. {
  945. mIsRunning = true;
  946. DWORD localThreadId;
  947. HANDLE hThread = ::CreateThread(NULL, 64 * 1024, (LPTHREAD_START_ROUTINE) &DebugThreadProcThunk, (void*)this, 0, &localThreadId);
  948. CloseHandle(hThread);
  949. }
  950. bool WinDebugger::HasLoadedTargetBinary()
  951. {
  952. if (mDebugTarget == NULL)
  953. return false;
  954. return mDebugTarget->mTargetBinary != NULL;
  955. }
  956. void WinDebugger::HotLoad(const Array<String>& objectFiles, int hotIdx)
  957. {
  958. AutoCrit autoCrit(mDebugManager->mCritSect);
  959. if (mDebugTarget->mTargetBinary == NULL)
  960. {
  961. Fail("Hot swapping failed because the hot target binary has not yet been loaded.");
  962. return;
  963. }
  964. if (mDebugTarget->mHotHeap == NULL)
  965. {
  966. Fail("There is no hot heap space available for hot swapping.");
  967. return;
  968. }
  969. BfLogDbg("WinDebugger::HotLoad Start %d\n", hotIdx);
  970. SetAndRestoreValue<int> prevHotIdx(mActiveHotIdx, hotIdx);
  971. BF_ASSERT(mHotThreadStates.empty());
  972. mHotThreadStates.Resize(mThreadList.size());
  973. for (int threadIdx = 0; threadIdx < (int)mThreadList.size(); threadIdx++)
  974. {
  975. WdThreadInfo* threadInfo = mThreadList[threadIdx];
  976. SetAndRestoreValue<WdThreadInfo*> prevActiveThread(mActiveThread, threadInfo);
  977. BfLogDbg("SuspendThread %d\n", threadInfo->mThreadId);
  978. ::SuspendThread(threadInfo->mHThread);
  979. mHotThreadStates[threadIdx].mThreadId = threadInfo->mThreadId;
  980. PopulateRegisters(&mHotThreadStates[threadIdx].mRegisters);
  981. }
  982. for (auto address : mTempBreakpoint)
  983. RemoveBreakpoint(address);
  984. mTempBreakpoint.Clear();
  985. mStepBreakpointAddrs.Clear();
  986. for (auto breakpoint : mBreakpoints)
  987. {
  988. DetachBreakpoint(breakpoint);
  989. }
  990. int startingModuleIdx = (int)mDebugTarget->mDbgModules.size();
  991. bool hasHotVData = false;
  992. bool failed = false;
  993. for (auto fileName : objectFiles)
  994. {
  995. if ((fileName.IndexOf("/vdata.") != -1) || (fileName.IndexOf("\\vdata.") != -1))
  996. hasHotVData = true;
  997. BfLogDbg("WinDebugger::HotLoad: %s\n", fileName.c_str());
  998. DbgModule* newBinary = mDebugTarget->HotLoad(fileName, hotIdx);
  999. if ((newBinary != NULL) && (newBinary->mFailed))
  1000. failed = true;
  1001. }
  1002. for (int moduleIdx = startingModuleIdx; moduleIdx < (int)mDebugTarget->mDbgModules.size(); moduleIdx++)
  1003. {
  1004. auto dbgModule = mDebugTarget->mDbgModules[moduleIdx];
  1005. BF_ASSERT(dbgModule->IsObjectFile());
  1006. BF_ASSERT(dbgModule->mHotIdx == hotIdx);
  1007. dbgModule->FinishHotSwap();
  1008. }
  1009. for (auto dwarf : mDebugTarget->mDbgModules)
  1010. dwarf->RevertWritingEnable();
  1011. int blockAllocSinceClean = mDebugTarget->mHotHeap->mBlockAllocIdx - mDebugTarget->mLastHotHeapCleanIdx;
  1012. // Clean up the hot heap every 64MB
  1013. int blocksBetweenCleans = (64 * 1024 * 1024) / HotHeap::BLOCK_SIZE;
  1014. #ifdef _DEBUG
  1015. //TODO: This is just for testing
  1016. blocksBetweenCleans = 1;
  1017. #endif
  1018. //TODO: Put this back after we fix the cleanup
  1019. if (blockAllocSinceClean >= blocksBetweenCleans)
  1020. CleanupHotHeap();
  1021. mDebugTarget->RehupSrcFiles();
  1022. if (hasHotVData)
  1023. mDebugTarget->mVDataHotIdx = hotIdx;
  1024. for (int breakIdx = 0; breakIdx < (int)mBreakpoints.size(); breakIdx++)
  1025. {
  1026. auto breakpoint = mBreakpoints[breakIdx];
  1027. CheckBreakpoint(breakpoint);
  1028. }
  1029. for (int hotThreadIdx = 0; hotThreadIdx < (int)mHotThreadStates.size(); hotThreadIdx++)
  1030. {
  1031. auto& hotThreadState = mHotThreadStates[hotThreadIdx];
  1032. WdThreadInfo* threadInfo = NULL;
  1033. if (!mThreadMap.TryGetValue((uint32)hotThreadState.mThreadId, &threadInfo))
  1034. continue;
  1035. BfLogDbg("ResumeThread %d\n", threadInfo->mThreadId);
  1036. ::ResumeThread(threadInfo->mHThread);
  1037. }
  1038. mHotThreadStates.Clear();
  1039. if (IsPaused())
  1040. {
  1041. ClearCallStack();
  1042. UpdateCallStack();
  1043. }
  1044. }
  1045. void WinDebugger::InitiateHotResolve(DbgHotResolveFlags flags)
  1046. {
  1047. AutoCrit autoCrit(mDebugManager->mCritSect);
  1048. delete mHotResolveData;
  1049. mHotResolveData = NULL;
  1050. mHotResolveData = new DbgHotResolveData();
  1051. DbgHotScanner* hotScanner = new DbgHotScanner(this);
  1052. hotScanner->Scan(flags);
  1053. delete hotScanner;
  1054. }
  1055. intptr WinDebugger::GetDbgAllocHeapSize()
  1056. {
  1057. if (mDbgHeapData == NULL)
  1058. {
  1059. Beefy::String memName = StrFormat("BFGC_stats_%d", mProcessInfo.dwProcessId);
  1060. mDbgHeapData = new WinDbgHeapData();
  1061. mDbgHeapData->mFileMapping = ::OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, memName.c_str());
  1062. if (mDbgHeapData->mFileMapping == 0)
  1063. {
  1064. delete mDbgHeapData;
  1065. mDbgHeapData = NULL;
  1066. return 0;
  1067. }
  1068. mDbgHeapData->mStats = (WinDbgHeapData::Stats*)MapViewOfFile(mDbgHeapData->mFileMapping, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(WinDbgHeapData::Stats));
  1069. }
  1070. if (mDbgHeapData->mStats == NULL)
  1071. return 0;
  1072. return mDbgHeapData->mStats->mHeapSize;
  1073. }
  1074. String WinDebugger::GetDbgAllocInfo()
  1075. {
  1076. AutoCrit autoCrit(mDebugManager->mCritSect);
  1077. for (auto threadInfo : mThreadList)
  1078. ::SuspendThread(threadInfo->mHThread);
  1079. delete mHotResolveData;
  1080. mHotResolveData = NULL;
  1081. mHotResolveData = new DbgHotResolveData();
  1082. DbgHotScanner* hotScanner = new DbgHotScanner(this);
  1083. hotScanner->Scan((DbgHotResolveFlags)(DbgHotResolveFlag_Allocations | DbgHotResolveFlag_KeepThreadState));
  1084. delete hotScanner;
  1085. String result;
  1086. if (mHotResolveData != NULL)
  1087. {
  1088. DbgExprEvaluator exprEvaluator(this, NULL, NULL, -1, -1);
  1089. exprEvaluator.mDebugTarget = mDebugTarget;
  1090. String typeName;
  1091. result += ":types\n";
  1092. for (int typeId = 0; typeId < mHotResolveData->mTypeData.size(); typeId++)
  1093. {
  1094. auto& typeData = mHotResolveData->mTypeData[typeId];
  1095. if (typeData.mCount > 0)
  1096. {
  1097. auto type = exprEvaluator.GetBeefTypeById(typeId);
  1098. typeName.Clear();
  1099. exprEvaluator.BeefTypeToString(type, typeName);
  1100. if (typeName.IsEmpty())
  1101. typeName = StrFormat("Type #%d", typeId);
  1102. result += StrFormat("type\t%d\t%s\t%lld\t%lld\n", typeId, typeName.c_str(), typeData.mCount, typeData.mSize);
  1103. }
  1104. }
  1105. }
  1106. for (auto threadInfo : mThreadList)
  1107. ::ResumeThread(threadInfo->mHThread);
  1108. return result;
  1109. }
  1110. static bool CreatePipeWithSecurityAttributes(HANDLE& hReadPipe, HANDLE& hWritePipe, SECURITY_ATTRIBUTES* lpPipeAttributes, int32 nSize)
  1111. {
  1112. hReadPipe = 0;
  1113. hWritePipe = 0;
  1114. bool ret = ::CreatePipe(&hReadPipe, &hWritePipe, lpPipeAttributes, nSize);
  1115. if (!ret || (hReadPipe == INVALID_HANDLE_VALUE) || (hWritePipe == INVALID_HANDLE_VALUE))
  1116. return false;
  1117. return true;
  1118. }
  1119. static bool CreatePipe(HANDLE& parentHandle, HANDLE& childHandle, bool parentInputs)
  1120. {
  1121. SECURITY_ATTRIBUTES securityAttributesParent = { 0 };
  1122. securityAttributesParent.bInheritHandle = 1;
  1123. HANDLE hTmp = INVALID_HANDLE_VALUE;
  1124. if (parentInputs)
  1125. CreatePipeWithSecurityAttributes(childHandle, hTmp, &securityAttributesParent, 0);
  1126. else
  1127. CreatePipeWithSecurityAttributes(hTmp, childHandle, &securityAttributesParent, 0);
  1128. HANDLE dupHandle = 0;
  1129. // Duplicate the parent handle to be non-inheritable so that the child process
  1130. // doesn't have access. This is done for correctness sake, exact reason is unclear.
  1131. // One potential theory is that child process can do something brain dead like
  1132. // closing the parent end of the pipe and there by getting into a blocking situation
  1133. // as parent will not be draining the pipe at the other end anymore.
  1134. if (!::DuplicateHandle(GetCurrentProcess(), hTmp,
  1135. GetCurrentProcess(), &dupHandle,
  1136. 0, false, DUPLICATE_SAME_ACCESS))
  1137. {
  1138. return false;
  1139. }
  1140. parentHandle = dupHandle;
  1141. if (hTmp != INVALID_HANDLE_VALUE)
  1142. ::CloseHandle(hTmp);
  1143. return true;
  1144. }
  1145. bool WinDebugger::DoOpenFile(const StringImpl& fileName, const StringImpl& args, const StringImpl& workingDir, const Array<uint8>& envBlock, DbgOpenFileFlags openFileFlags)
  1146. {
  1147. BP_ZONE("WinDebugger::DoOpenFile");
  1148. AutoCrit autoCrit(mDebugManager->mCritSect);
  1149. //gDbgPerfManager->StartRecording();
  1150. STARTUPINFOW si;
  1151. ZeroMemory(&si, sizeof(si));
  1152. si.cb = sizeof(si);
  1153. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  1154. DWORD flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS | CREATE_DEFAULT_ERROR_MODE;
  1155. BOOL inheritHandles = false;
  1156. // set up the streams
  1157. if ((openFileFlags & (DbgOpenFileFlag_RedirectStdInput | DbgOpenFileFlag_RedirectStdOutput | DbgOpenFileFlag_RedirectStdError)) != 0)
  1158. {
  1159. if ((openFileFlags & DbgOpenFileFlag_RedirectStdInput) != 0)
  1160. CreatePipe(mStdInputPipe, si.hStdInput, true);
  1161. else if (::GetConsoleWindow() != NULL)
  1162. si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
  1163. else
  1164. si.hStdInput = INVALID_HANDLE_VALUE;
  1165. if ((openFileFlags & DbgOpenFileFlag_RedirectStdOutput) != 0)
  1166. CreatePipe(mStdOutputPipe, si.hStdOutput, false);
  1167. else
  1168. si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  1169. if ((openFileFlags & DbgOpenFileFlag_RedirectStdError) != 0)
  1170. CreatePipe(mStdErrorPipe, si.hStdError, false);
  1171. else
  1172. si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
  1173. flags |= CREATE_NO_WINDOW;
  1174. si.dwFlags = STARTF_USESTDHANDLES;
  1175. inheritHandles = true;
  1176. }
  1177. if (mDbgProcessId != 0)
  1178. {
  1179. BOOL success = ::DebugActiveProcess(mDbgProcessId);
  1180. if (!success)
  1181. return false;
  1182. mProcessInfo.dwProcessId = mDbgProcessId;
  1183. }
  1184. else
  1185. {
  1186. BP_ZONE("DoOpenFile_CreateProcessW");
  1187. UTF16String envW;
  1188. void* envPtr = NULL;
  1189. if (!envBlock.IsEmpty())
  1190. {
  1191. //UTF16?
  1192. if (envBlock[1] == 0)
  1193. {
  1194. envPtr = (void*)&envBlock[0];
  1195. flags |= CREATE_UNICODE_ENVIRONMENT;
  1196. }
  1197. else
  1198. {
  1199. String str8((char*)&envBlock[0], (int)envBlock.size());
  1200. envW = UTF8Decode(str8);
  1201. envPtr = (void*)envW.c_str();
  1202. flags |= CREATE_UNICODE_ENVIRONMENT;
  1203. }
  1204. }
  1205. String cmdLine = "\"";
  1206. cmdLine += fileName;
  1207. cmdLine += "\"";
  1208. if (!args.IsEmpty())
  1209. {
  1210. cmdLine += " ";
  1211. cmdLine += args;
  1212. }
  1213. BOOL worked = CreateProcessW(NULL, (WCHAR*)UTF8Decode(cmdLine).c_str(), NULL, NULL, inheritHandles,
  1214. flags, envPtr, (WCHAR*)UTF8Decode(workingDir).c_str(), &si, &mProcessInfo);
  1215. if ((openFileFlags & DbgOpenFileFlag_RedirectStdInput) != 0)
  1216. ::CloseHandle(si.hStdInput);
  1217. if ((openFileFlags & DbgOpenFileFlag_RedirectStdOutput) != 0)
  1218. ::CloseHandle(si.hStdOutput);
  1219. if ((openFileFlags & DbgOpenFileFlag_RedirectStdError) != 0)
  1220. ::CloseHandle(si.hStdError);
  1221. if (!worked)
  1222. {
  1223. if (IsHandleValid(mStdInputPipe))
  1224. {
  1225. ::CloseHandle(mStdInputPipe);
  1226. mStdInputPipe = 0;
  1227. }
  1228. if (IsHandleValid(mStdOutputPipe))
  1229. {
  1230. ::CloseHandle(mStdOutputPipe);
  1231. mStdOutputPipe = 0;
  1232. }
  1233. if (IsHandleValid(mStdErrorPipe))
  1234. {
  1235. ::CloseHandle(mStdErrorPipe);
  1236. mStdErrorPipe = 0;
  1237. }
  1238. auto lastError = ::GetLastError();
  1239. if (lastError == ERROR_DIRECTORY)
  1240. {
  1241. mDebugManager->mOutMessages.push_back(StrFormat("error Unable to locate specified working directory '%s'", SlashString(workingDir, false, false).c_str()));
  1242. }
  1243. return false;
  1244. }
  1245. WdThreadInfo* threadInfo = new WdThreadInfo();
  1246. threadInfo->mProcessId = mProcessInfo.dwProcessId;
  1247. threadInfo->mThreadId = mProcessInfo.dwThreadId;
  1248. threadInfo->mHThread = mProcessInfo.hThread;
  1249. threadInfo->mThreadLocalBase = NULL;
  1250. threadInfo->mStartAddress = NULL;
  1251. mThreadMap[mProcessInfo.dwThreadId] = threadInfo;
  1252. mThreadList.push_back(threadInfo);
  1253. }
  1254. mRunState = RunState_Running;
  1255. while (true)
  1256. {
  1257. BP_ZONE("DoOpenFile_WaitForImageBase");
  1258. autoCrit.mCritSect->Unlock();
  1259. DoUpdate();
  1260. autoCrit.mCritSect->Lock();
  1261. ContinueDebugEvent();
  1262. if ((mDebugTarget->mLaunchBinary != NULL) && (mDebugTarget->mLaunchBinary->mOrigImageData != NULL))
  1263. break;
  1264. }
  1265. RehupBreakpoints(true);
  1266. //gDbgPerfManager->StopRecording();
  1267. //gDbgPerfManager->DbgPrint();
  1268. return true;
  1269. }
  1270. void WinDebugger::StopDebugging()
  1271. {
  1272. AutoCrit autoCrit(mDebugManager->mCritSect);
  1273. BfLogDbg("WinDebugger::Terminate\n");
  1274. if (mActiveSymSrvRequest != NULL)
  1275. mActiveSymSrvRequest->Cancel();
  1276. if ((mRunState == RunState_NotStarted) || (mRunState == RunState_Terminated) || (mRunState == RunState_Terminating))
  1277. return;
  1278. if ((mDbgProcessId != 0) && ((mDbgAttachFlags & BfDbgAttachFlag_ShutdownOnExit) == 0))
  1279. {
  1280. for (auto address : mTempBreakpoint)
  1281. RemoveBreakpoint(address);
  1282. for (auto breakpoint : mBreakpoints)
  1283. DetachBreakpoint(breakpoint);
  1284. BfLogDbg("StopDebugging\n");
  1285. ::DebugActiveProcessStop(mDbgProcessId);
  1286. mRunState = RunState_Terminated;
  1287. BfLogDbg("mRunState = RunState_Terminated\n");
  1288. }
  1289. else
  1290. {
  1291. TerminateProcess(mProcessInfo.hProcess, 0);
  1292. mRunState = RunState_Terminating;
  1293. BfLogDbg("mRunState = RunState_Terminating\n");
  1294. }
  1295. }
  1296. void WinDebugger::Terminate()
  1297. {
  1298. AutoCrit autoCrit(mDebugManager->mCritSect);
  1299. BfLogDbg("WinDebugger::Terminate\n");
  1300. if (mActiveSymSrvRequest != NULL)
  1301. mActiveSymSrvRequest->Cancel();
  1302. if ((mRunState == RunState_NotStarted) || (mRunState == RunState_Terminated) || (mRunState == RunState_Terminating))
  1303. return;
  1304. TerminateProcess(mProcessInfo.hProcess, 0);
  1305. mRunState = RunState_Terminating;
  1306. BfLogDbg("mRunState = RunState_Terminating\n");
  1307. }
  1308. static int gDebugUpdateCnt = 0;
  1309. void WinDebugger::Detach()
  1310. {
  1311. BfLogDbg("Debugger Detach\n");
  1312. mDebugManager->mNetManager->CancelAll();
  1313. while ((mIsRunning) || (mDebuggerThreadId != 0))
  1314. {
  1315. mShuttingDown = true;
  1316. Sleep(1);
  1317. }
  1318. for (auto profiler : mProfilerSet)
  1319. profiler->Stop();
  1320. BfLogDbg("Debugger Detach - thread finished\n");
  1321. mPendingProfilerMap.Clear();
  1322. for (auto profiler : mNewProfilerList)
  1323. delete profiler;
  1324. mNewProfilerList.Clear();
  1325. mPendingImageLoad.Clear();
  1326. mPendingDebugInfoLoad.Clear();
  1327. RemoveTempBreakpoints();
  1328. mContinueEvent.Reset();
  1329. if (mDebugTarget != mEmptyDebugTarget)
  1330. delete mDebugTarget;
  1331. mDebugTarget = mEmptyDebugTarget;
  1332. mShuttingDown = false;
  1333. mStepSP = 0;
  1334. ClearCallStack();
  1335. mRunState = RunState_NotStarted;
  1336. mStepType = StepType_None;
  1337. mHadImageFindError = false;
  1338. mIsPartialCallStack = true;
  1339. delete mDebugPendingExpr;
  1340. mDebugPendingExpr = NULL;
  1341. for (auto threadPair : mThreadMap)
  1342. {
  1343. auto threadInfo = threadPair.mValue;
  1344. delete threadInfo;
  1345. }
  1346. mThreadMap.Clear();
  1347. mThreadList.Clear();
  1348. mHotTargetMemory.Clear();
  1349. // We don't need to close the hThread when we have attached to a process
  1350. if (mDbgProcessId == 0)
  1351. {
  1352. CloseHandle(mProcessInfo.hThread);
  1353. CloseHandle(mProcessInfo.hProcess);
  1354. }
  1355. for (auto breakpoint : mBreakpoints)
  1356. {
  1357. if (!mDestroying)
  1358. {
  1359. BF_FATAL("Breakpoints should be deleted already");
  1360. }
  1361. if (breakpoint->mMemoryBreakpointInfo != NULL)
  1362. {
  1363. DetachBreakpoint(breakpoint);
  1364. }
  1365. }
  1366. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  1367. mStepBreakpointAddrs.Clear();
  1368. mIsRunning = false;
  1369. mDbgAttachFlags = BfDbgAttachFlag_None;
  1370. mDbgProcessId = 0;
  1371. delete mDbgHeapData;
  1372. mDbgHeapData = NULL;
  1373. mDbgProcessHandle = 0;
  1374. ClearCallStack();
  1375. mWantsDebugContinue = false;
  1376. mAtBreakThread = NULL;
  1377. mActiveThread = NULL;
  1378. mActiveBreakpoint = NULL;
  1379. mSteppingThread = NULL;
  1380. mExplicitStopThread = NULL;
  1381. mIsContinuingFromException = false;
  1382. mGotStartupEvent = false;
  1383. mIsDebuggerWaiting = false;
  1384. mPhysBreakpointAddrMap.Clear();
  1385. mBreakpointAddrMap.Clear();
  1386. gDebugUpdateCnt = 0;
  1387. if (IsHandleValid(mStdInputPipe))
  1388. ::CloseHandle(mStdInputPipe);
  1389. mStdInputPipe = INVALID_HANDLE_VALUE;
  1390. if (IsHandleValid(mStdOutputPipe))
  1391. ::CloseHandle(mStdOutputPipe);
  1392. mStdOutputPipe = INVALID_HANDLE_VALUE;
  1393. if (IsHandleValid(mStdErrorPipe))
  1394. ::CloseHandle(mStdErrorPipe);
  1395. mStdErrorPipe = INVALID_HANDLE_VALUE;
  1396. }
  1397. Profiler* WinDebugger::StartProfiling()
  1398. {
  1399. return new DbgProfiler(this);
  1400. }
  1401. Profiler* WinDebugger::PopProfiler()
  1402. {
  1403. AutoCrit autoCrit(mDebugManager->mCritSect);
  1404. if (mNewProfilerList.IsEmpty())
  1405. return NULL;
  1406. auto profiler = (DbgProfiler*)mNewProfilerList[0];
  1407. mNewProfilerList.erase(mNewProfilerList.begin());
  1408. return profiler;
  1409. }
  1410. void WinDebugger::AddProfiler(DbgProfiler * profiler)
  1411. {
  1412. AutoCrit autoCrit(mDebugManager->mCritSect);
  1413. mProfilerSet.Add(profiler);
  1414. }
  1415. void WinDebugger::RemoveProfiler(DbgProfiler * profiler)
  1416. {
  1417. AutoCrit autoCrit(mDebugManager->mCritSect);
  1418. mProfilerSet.Remove(profiler);
  1419. }
  1420. void WinDebugger::ReportMemory(MemReporter* memReporter)
  1421. {
  1422. mEmptyDebugTarget->ReportMemory(memReporter);
  1423. if (mDebugTarget != mEmptyDebugTarget)
  1424. mDebugTarget->ReportMemory(memReporter);
  1425. }
  1426. bool WinDebugger::GetEmitSource(const StringImpl& filePath, String& outText)
  1427. {
  1428. if (!filePath.StartsWith("$Emit"))
  1429. return false;
  1430. int dollarPos = filePath.IndexOf('$', 1);
  1431. String numStr = filePath.Substring(5, dollarPos - 5);
  1432. int id = atoi(numStr.c_str());
  1433. for (auto dbgModule : mDebugTarget->mDbgModules)
  1434. {
  1435. if (dbgModule->mId == id)
  1436. return dbgModule->GetEmitSource(filePath, outText);
  1437. }
  1438. return false;
  1439. }
  1440. void WinDebugger::ModuleChanged(DbgModule* dbgModule)
  1441. {
  1442. mDebugManager->mOutMessages.push_back(String("dbgInfoLoaded ") + dbgModule->mFilePath);
  1443. }
  1444. bool WinDebugger::DoUpdate()
  1445. {
  1446. if ((mDbgProcessId != 0) && ((mDbgAttachFlags & BfDbgAttachFlag_ShutdownOnExit) == 0))
  1447. ::DebugSetProcessKillOnExit(FALSE);
  1448. else
  1449. ::DebugSetProcessKillOnExit(TRUE);
  1450. //
  1451. {
  1452. AutoCrit autoCrit(mDebugManager->mCritSect);
  1453. auto _ModuleChanged = [&](DbgModule* dbgModule)
  1454. {
  1455. ModuleChanged(dbgModule);
  1456. ClearCallStack(); // We may have actual dbgSubprograms and stuff now...
  1457. };
  1458. for (auto dbgModule : mPendingImageLoad)
  1459. {
  1460. dbgModule->PreCacheImage();
  1461. }
  1462. for (auto kv : mPendingDebugInfoLoad)
  1463. {
  1464. kv.mKey->PreCacheDebugInfo();
  1465. }
  1466. while (!mPendingImageLoad.IsEmpty())
  1467. {
  1468. auto dbgModule = mPendingImageLoad.back();
  1469. mPendingImageLoad.pop_back();
  1470. dbgModule->RequestImage();
  1471. _ModuleChanged(dbgModule);
  1472. }
  1473. if (!mPendingDebugInfoLoad.IsEmpty())
  1474. {
  1475. Array<DbgPendingDebugInfoLoad> pendingList;
  1476. for (auto kv : mPendingDebugInfoLoad)
  1477. pendingList.Add(kv.mValue);
  1478. mPendingDebugInfoLoad.Clear();
  1479. for (auto& entry : pendingList)
  1480. {
  1481. auto dbgModule = entry.mModule;
  1482. entry.mModule->RequestDebugInfo(entry.mAllowRemote);
  1483. // We do a "_ModuleChanged" even if the load failed, so we rehup the callstack and stop
  1484. // saying "<Loading...>"
  1485. _ModuleChanged(entry.mModule);
  1486. }
  1487. }
  1488. }
  1489. if (IsMiniDumpDebugger())
  1490. {
  1491. //
  1492. {
  1493. AutoCrit autoCrit(mDebugManager->mCritSect);
  1494. if (mRunState == RunState_Terminating)
  1495. {
  1496. mRunState = RunState_Terminated;
  1497. return false;
  1498. }
  1499. }
  1500. Sleep(20);
  1501. return false;
  1502. }
  1503. if (mIsDebuggerWaiting)
  1504. {
  1505. if ((IsInRunState()) || (mRunState == RunState_Terminating) || (mRunState == RunState_DebugEval))
  1506. ContinueDebugEvent();
  1507. if (mContinueEvent.WaitFor(8))
  1508. {
  1509. BF_ASSERT(!mWantsDebugContinue); // mWantsDebugContinue should already been reset
  1510. BfLogDbg("::ContinueDebugEvent 1 ThreadId:%d\n", mDebuggerWaitingThread->mThreadId);
  1511. BF_ASSERT_REL(mDebuggerWaitingThread->mIsAtBreakpointAddress == 0);
  1512. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, mIsContinuingFromException ? DBG_EXCEPTION_NOT_HANDLED : DBG_CONTINUE);
  1513. mIsContinuingFromException = false;
  1514. mIsDebuggerWaiting = false;
  1515. mDebuggerWaitingThread = NULL;
  1516. }
  1517. else
  1518. return false;
  1519. }
  1520. if (!WaitForDebugEvent(&mDebugEvent, 8))
  1521. return false;
  1522. gDebugUpdateCnt++;
  1523. static const char* eventNames[] = { "DBG_EVENT ?",
  1524. "EXCEPTION_DEBUG_EVENT",
  1525. "CREATE_THREAD_DEBUG_EVENT",
  1526. "CREATE_PROCESS_DEBUG_EVENT",
  1527. "EXIT_THREAD_DEBUG_EVENT",
  1528. "EXIT_PROCESS_DEBUG_EVENT",
  1529. "LOAD_DLL_DEBUG_EVENT",
  1530. "UNLOAD_DLL_DEBUG_EVENT",
  1531. "OUTPUT_DEBUG_STRING_EVENT",
  1532. "RIP_EVENT"};
  1533. BfLogDbg("WaitForDebugEvent %s ThreadId:%d\n", eventNames[mDebugEvent.dwDebugEventCode], mDebugEvent.dwThreadId);
  1534. BP_ZONE(eventNames[mDebugEvent.dwDebugEventCode]);
  1535. AutoCrit autoCrit(mDebugManager->mCritSect);
  1536. mActiveBreakpoint = NULL;
  1537. mIsDebuggerWaiting = true;
  1538. mWantsDebugContinue = true;
  1539. mRequestedStackFrameIdx = 0;
  1540. mBreakStackFrameIdx = 0;
  1541. mShowPCOverride = 0;
  1542. WdThreadInfo* threadInfo = NULL;
  1543. mThreadMap.TryGetValue(mDebugEvent.dwThreadId, &threadInfo);
  1544. mDebuggerWaitingThread = threadInfo;
  1545. mExplicitStopThread = mDebuggerWaitingThread;
  1546. switch (mDebugEvent.dwDebugEventCode)
  1547. {
  1548. case CREATE_PROCESS_DEBUG_EVENT:
  1549. {
  1550. if (threadInfo == NULL)
  1551. {
  1552. BF_ASSERT(mThreadMap.size() == 0);
  1553. WdThreadInfo* newThreadInfo = new WdThreadInfo();
  1554. newThreadInfo->mProcessId = mDebugEvent.dwProcessId;
  1555. newThreadInfo->mThreadId = mDebugEvent.dwThreadId;
  1556. newThreadInfo->mHThread = mDebugEvent.u.CreateProcessInfo.hThread;
  1557. newThreadInfo->mThreadLocalBase = mDebugEvent.u.CreateProcessInfo.lpThreadLocalBase;
  1558. newThreadInfo->mStartAddress = (void*)mDebugEvent.u.CreateProcessInfo.lpStartAddress;
  1559. BF_CONTEXT lcContext;
  1560. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1561. BF_GetThreadContext(newThreadInfo->mHThread, &lcContext);
  1562. newThreadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1563. mThreadMap[mDebugEvent.dwThreadId] = newThreadInfo;
  1564. mDebuggerWaitingThread = newThreadInfo;
  1565. mThreadList.push_back(mDebuggerWaitingThread);
  1566. UpdateThreadDebugRegisters();
  1567. if (!(gDebugManager->GetOutputFilterFlags() & BfOutputFilterFlags_ThreadCreateMessages))
  1568. OutputMessage(StrFormat("Creating thread from CREATE_PROCESS_DEBUG_EVENT %d\n", mDebugEvent.dwThreadId));
  1569. threadInfo = mDebuggerWaitingThread;
  1570. mProcessInfo.dwThreadId = threadInfo->mThreadId;
  1571. mProcessInfo.hThread = threadInfo->mHThread;
  1572. mProcessInfo.hProcess = mDebugEvent.u.CreateProcessInfo.hProcess;
  1573. }
  1574. else
  1575. {
  1576. threadInfo->mThreadLocalBase = mDebugEvent.u.CreateProcessInfo.lpThreadLocalBase;
  1577. threadInfo->mStartAddress = (void*)mDebugEvent.u.CreateProcessInfo.lpStartAddress;
  1578. }
  1579. BF_CONTEXT lcContext;
  1580. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1581. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1582. threadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1583. DbgModule* launchBinary = mDebugTarget->Init(mLaunchPath, mTargetPath, (addr_target)(intptr)mDebugEvent.u.CreateProcessInfo.lpBaseOfImage);
  1584. addr_target gotImageBase = (addr_target)(intptr)mDebugEvent.u.CreateProcessInfo.lpBaseOfImage;
  1585. if (launchBinary->mImageBase != gotImageBase)
  1586. {
  1587. BF_FATAL("Image base didn't match");
  1588. }
  1589. launchBinary->mImageBase = gotImageBase;
  1590. launchBinary->mImageSize = (int)launchBinary->GetImageSize();
  1591. launchBinary->mOrigImageData = new DbgModuleMemoryCache(launchBinary->mImageBase, launchBinary->mImageSize);
  1592. if (launchBinary == mDebugTarget->mTargetBinary)
  1593. mDebugTarget->SetupTargetBinary();
  1594. if (mDebugEvent.u.CreateProcessInfo.hFile != NULL)
  1595. CloseHandle(mDebugEvent.u.CreateProcessInfo.hFile);
  1596. mDbgProcessHandle = mDebugEvent.u.CreateProcessInfo.hProcess;
  1597. mDbgThreadHandle = mDebugEvent.u.CreateProcessInfo.hThread;
  1598. mGotStartupEvent = true;
  1599. mDebugManager->mOutMessages.push_back("modulesChanged");
  1600. }
  1601. break;
  1602. case EXIT_PROCESS_DEBUG_EVENT:
  1603. {
  1604. BfLogDbg("EXIT_PROCESS_DEBUG_EVENT\n");
  1605. DWORD exitCode = mDebugEvent.u.ExitProcess.dwExitCode;
  1606. String exitMessage;
  1607. switch (exitCode)
  1608. {
  1609. case STATUS_DLL_NOT_FOUND:
  1610. exitMessage = "STATUS_DLL_NOT_FOUND";
  1611. break;
  1612. case STATUS_DLL_INIT_FAILED:
  1613. exitMessage = "STATUS_DLL_INIT_FAILED";
  1614. break;
  1615. case STATUS_ENTRYPOINT_NOT_FOUND:
  1616. exitMessage = "STATUS_ENTRYPOINT_NOT_FOUND";
  1617. break;
  1618. }
  1619. String exitCodeStr;
  1620. if ((exitCode >= 0x10000000) && (exitCode <= 0xF7000000))
  1621. exitCodeStr = StrFormat("0x%X", exitCode);
  1622. else
  1623. exitCodeStr = StrFormat("%d", exitCode);
  1624. if (!(gDebugManager->GetOutputFilterFlags() & BfOutputFilterFlags_ProcessExitMessages))
  1625. {
  1626. if (!exitMessage.IsEmpty())
  1627. OutputMessage(StrFormat("Process terminated. ExitCode: %s (%s).\n", exitCodeStr.c_str(), exitMessage.c_str()));
  1628. else
  1629. OutputMessage(StrFormat("Process terminated. ExitCode: %s.\n", exitCodeStr.c_str()));
  1630. }
  1631. mRunState = RunState_Terminated;
  1632. mDebugManager->mOutMessages.push_back("modulesChanged");
  1633. }
  1634. break;
  1635. case LOAD_DLL_DEBUG_EVENT:
  1636. {
  1637. WCHAR moduleNameStr[MAX_PATH] = { 0 };
  1638. GetFinalPathNameByHandleW(mDebugEvent.u.LoadDll.hFile, moduleNameStr, MAX_PATH, FILE_NAME_NORMALIZED);
  1639. std::wstring wow64Dir;
  1640. std::wstring systemDir;
  1641. PWSTR wow64DirPtr = NULL;
  1642. SHGetKnownFolderPath(FOLDERID_SystemX86, KF_FLAG_NO_ALIAS, NULL, &wow64DirPtr);
  1643. if (wow64DirPtr != NULL)
  1644. {
  1645. wow64Dir = wow64DirPtr;
  1646. CoTaskMemFree(wow64DirPtr);
  1647. }
  1648. PWSTR systemDirPtr = NULL;
  1649. SHGetKnownFolderPath(FOLDERID_System, KF_FLAG_NO_ALIAS, NULL, &systemDirPtr);
  1650. if (systemDirPtr != NULL)
  1651. {
  1652. systemDir = systemDirPtr;
  1653. CoTaskMemFree(systemDirPtr);
  1654. }
  1655. if ((mDebugEvent.u.LoadDll.lpImageName != 0) && (mDebugEvent.u.LoadDll.fUnicode))
  1656. {
  1657. addr_target strAddr = ReadMemory<addr_target>((addr_target)(intptr)mDebugEvent.u.LoadDll.lpImageName);
  1658. for (int i = 0; i < MAX_PATH - 1; i++)
  1659. {
  1660. WCHAR c = ReadMemory<WCHAR>(strAddr + i*2);
  1661. moduleNameStr[i] = (WCHAR)c;
  1662. if (c == 0)
  1663. break;
  1664. }
  1665. }
  1666. String origModuleName = UTF8Encode(moduleNameStr);
  1667. String moduleName = origModuleName;
  1668. String loadMsg;
  1669. HANDLE altFileHandle = INVALID_HANDLE_VALUE;
  1670. if (moduleName != origModuleName)
  1671. {
  1672. loadMsg = StrFormat("Loading DLL: %s(%s) @ %s", origModuleName.c_str(), moduleName.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.LoadDll.lpBaseOfDll, true).c_str());
  1673. altFileHandle = ::CreateFileW(UTF8Decode(moduleName).c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  1674. }
  1675. else
  1676. {
  1677. loadMsg = StrFormat("Loading DLL: %s @ %s", moduleName.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.LoadDll.lpBaseOfDll, true).c_str());
  1678. }
  1679. BfLogDbg("LOAD_DLL_DEBUG_EVENT %s\n", moduleName.c_str());
  1680. bool skipLoad = false;
  1681. #ifdef BF_DBG_32
  1682. if (((uintptr)mDebugEvent.u.LoadDll.lpBaseOfDll & 0xFFFFFFFF00000000LL) != 0)
  1683. {
  1684. skipLoad = true;
  1685. loadMsg += " - Skipped";
  1686. }
  1687. #endif
  1688. if (!skipLoad)
  1689. {
  1690. FileHandleStream stream;
  1691. stream.mFileHandle = mDebugEvent.u.LoadDll.hFile;
  1692. if (altFileHandle != INVALID_HANDLE_VALUE)
  1693. stream.mFileHandle = altFileHandle;
  1694. if (mDebugTarget->SetupDyn(moduleName, &stream, (intptr)mDebugEvent.u.LoadDll.lpBaseOfDll) == NULL)
  1695. loadMsg += " - Failed to load";
  1696. stream.mFileHandle = 0;
  1697. }
  1698. if (!(gDebugManager->GetOutputFilterFlags() & BfOutputFilterFlags_ModuleLoadMessages))
  1699. OutputMessage(loadMsg + "\n");
  1700. if (altFileHandle != INVALID_HANDLE_VALUE)
  1701. ::CloseHandle(altFileHandle);
  1702. ::CloseHandle(mDebugEvent.u.LoadDll.hFile);
  1703. // Try to bind any breakpoints tied to this DLL
  1704. RehupBreakpoints(true);
  1705. mDebugManager->mOutMessages.push_back("modulesChanged");
  1706. }
  1707. break;
  1708. case UNLOAD_DLL_DEBUG_EVENT:
  1709. {
  1710. bool needsBreakpointRehup = false;
  1711. String name = "???";
  1712. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress((addr_target)(intptr)mDebugEvent.u.UnloadDll.lpBaseOfDll);
  1713. if (dbgModule != NULL)
  1714. {
  1715. name = dbgModule->mFilePath;
  1716. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  1717. {
  1718. auto breakpoint = mBreakpoints[i];
  1719. auto checkBreakpoint = breakpoint;
  1720. bool hasAddr = false;
  1721. while (checkBreakpoint != NULL)
  1722. {
  1723. if ((checkBreakpoint->mAddr >= dbgModule->mImageBase) && (checkBreakpoint->mAddr < dbgModule->mImageBase + dbgModule->mImageSize))
  1724. hasAddr = true;
  1725. checkBreakpoint = (WdBreakpoint*)checkBreakpoint->mLinkedSibling;
  1726. }
  1727. if (hasAddr)
  1728. {
  1729. DetachBreakpoint(breakpoint);
  1730. needsBreakpointRehup = true;
  1731. }
  1732. }
  1733. bool hadTarget = mDebugTarget->mTargetBinary != NULL;
  1734. mDebugTarget->UnloadDyn(dbgModule->mImageBase);
  1735. if (needsBreakpointRehup)
  1736. RehupBreakpoints(true);
  1737. if ((mDebugTarget->mTargetBinary == NULL) && (hadTarget))
  1738. {
  1739. mRunState = RunState_TargetUnloaded;
  1740. }
  1741. mPendingDebugInfoLoad.Remove(dbgModule);
  1742. mPendingDebugInfoRequests.Remove(dbgModule);
  1743. mDebugManager->mOutMessages.push_back("modulesChanged");
  1744. }
  1745. if (!(gDebugManager->GetOutputFilterFlags() & BfOutputFilterFlags_ModuleUnloadMessages) && !name.empty())
  1746. OutputMessage(StrFormat("Unloading DLL: %s @ %0s\n", name.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.UnloadDll.lpBaseOfDll, true).c_str()));
  1747. BfLogDbg("UNLOAD_DLL_DEBUG_EVENT %s\n", name.c_str());
  1748. }
  1749. break;
  1750. case OUTPUT_DEBUG_STRING_EVENT:
  1751. {
  1752. const int maxChars = 1024 * 1024;
  1753. int len = BF_MIN(maxChars, (int)mDebugEvent.u.DebugString.nDebugStringLength); // 1MB max
  1754. char* message = new char[len + 1];
  1755. message[0] = 0;
  1756. message[len] = 0;
  1757. ReadMemory((addr_target)(intptr)mDebugEvent.u.DebugString.lpDebugStringData, len, message);
  1758. if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId == mDebugEvalThreadInfo.mThreadId))
  1759. mDebugManager->mOutMessages.push_back(String("dbgEvalMsg ") + message);
  1760. else
  1761. mDebugManager->mOutMessages.push_back(String("msg ") + message);
  1762. BfLogDbg("OUTPUT_DEBUG_STRING_EVENT (BreakAddr:%@): %s\n", threadInfo->mIsAtBreakpointAddress, message);
  1763. BF_ASSERT_REL(threadInfo->mIsAtBreakpointAddress == 0);
  1764. delete [] message;
  1765. }
  1766. break;
  1767. case CREATE_THREAD_DEBUG_EVENT:
  1768. {
  1769. WdThreadInfo* threadInfo = new WdThreadInfo();
  1770. threadInfo->mProcessId = mDebugEvent.dwProcessId;
  1771. threadInfo->mThreadId = mDebugEvent.dwThreadId;
  1772. threadInfo->mHThread = mDebugEvent.u.CreateThread.hThread;
  1773. threadInfo->mThreadLocalBase = mDebugEvent.u.CreateThread.lpThreadLocalBase;
  1774. threadInfo->mStartAddress = (void*)mDebugEvent.u.CreateThread.lpStartAddress;
  1775. BF_CONTEXT lcContext;
  1776. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1777. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1778. threadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1779. mThreadMap[mDebugEvent.dwThreadId] = threadInfo;
  1780. mDebuggerWaitingThread = threadInfo;
  1781. mThreadList.push_back(mDebuggerWaitingThread);
  1782. UpdateThreadDebugRegisters();
  1783. if (!(gDebugManager->GetOutputFilterFlags() & BfOutputFilterFlags_ThreadCreateMessages))
  1784. OutputMessage(StrFormat("Creating thread %d\n", mDebugEvent.dwThreadId));
  1785. }
  1786. break;
  1787. case EXIT_THREAD_DEBUG_EVENT:
  1788. {
  1789. if (!(gDebugManager->GetOutputFilterFlags() & BfOutputFilterFlags_ThreadExitMessages))
  1790. OutputMessage(StrFormat("Exiting thread %d\n", mDebugEvent.dwThreadId));
  1791. if (mSteppingThread == threadInfo)
  1792. {
  1793. // We were attempting stepping on this thread, but not anymore!
  1794. ClearStep();
  1795. }
  1796. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_CONTINUE);
  1797. mIsDebuggerWaiting = false;
  1798. mWantsDebugContinue = false;
  1799. if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId == mDebugEvalThreadInfo.mThreadId))
  1800. {
  1801. // Thread terminated while evaluating! Is there a more graceful way of handling this?
  1802. CleanupDebugEval(false);
  1803. mRunState = RunState_Running;
  1804. }
  1805. mThreadList.Remove(mDebuggerWaitingThread);
  1806. delete mDebuggerWaitingThread;
  1807. mDebuggerWaitingThread = NULL;
  1808. mThreadMap.Remove(mDebugEvent.dwThreadId);
  1809. return true;
  1810. }
  1811. break;
  1812. case RIP_EVENT:
  1813. OutputMessage("RIP Event\n");
  1814. break;
  1815. case EXCEPTION_DEBUG_EVENT:
  1816. {
  1817. auto exceptionRecord = &mDebugEvent.u.Exception.ExceptionRecord;
  1818. switch (exceptionRecord->ExceptionCode)
  1819. {
  1820. case STATUS_WX86_BREAKPOINT:
  1821. case EXCEPTION_BREAKPOINT:
  1822. {
  1823. if (mRunState == RunState_Terminating)
  1824. {
  1825. BfLogDbg("Ignoring event because of RunState_Terminating\n");
  1826. break;
  1827. }
  1828. mAtBreakThread = threadInfo;
  1829. mActiveThread = mAtBreakThread;
  1830. bool isHighAddr = false;
  1831. #ifdef BF_DBG_32
  1832. if (((uintptr)exceptionRecord->ExceptionAddress & 0xFFFFFFFF00000000) != 0)
  1833. {
  1834. if (mActiveThread == mThreadList.front())
  1835. {
  1836. // Skip the initial Wow64 ntdll.dll!LdrpDoDebuggerBreak
  1837. mRunState = RunState_Running;
  1838. break;
  1839. }
  1840. isHighAddr = true;
  1841. }
  1842. #endif
  1843. addr_target pcAddress = (addr_target)(intptr)exceptionRecord->ExceptionAddress;
  1844. if (isHighAddr)
  1845. pcAddress = (addr_target)-1;
  1846. //mStoppedAtAddress = pcAddress;
  1847. bool isStepOut = false;
  1848. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto))
  1849. {
  1850. isStepOut = mStepBreakpointAddrs.Contains(pcAddress);
  1851. }
  1852. BF_CONTEXT lcContext;
  1853. lcContext.ContextFlags = BF_CONTEXT_ALL;
  1854. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1855. BfLogDbg("EXCEPTION_BREAKPOINT Thread:%d %p SP:%p\n", mActiveThread->mThreadId, pcAddress, BF_CONTEXT_SP(lcContext));
  1856. uint8 origImageData = 0xCC;
  1857. mDebugTarget->ReadOrigImageData(pcAddress, &origImageData, 1);
  1858. bool wasDebugBreakpoint = origImageData != 0xCC;
  1859. DbgSubprogram* dwSubprogram = NULL;
  1860. DbgLineData* dwLineData = NULL;
  1861. if (!isStepOut)
  1862. {
  1863. dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  1864. if (dwSubprogram == NULL)
  1865. dwSubprogram = mDebugTarget->FindSubProgram(pcAddress, DbgOnDemandKind_LocalOnly);
  1866. }
  1867. bool isLineStart = (dwLineData != NULL) && (dwSubprogram->GetLineAddr(*dwLineData) == pcAddress);
  1868. bool isNonDebuggerBreak = false;
  1869. if (wasDebugBreakpoint)
  1870. {
  1871. // Go ahead and set EIP back one instruction
  1872. BF_CONTEXT_IP(lcContext)--;
  1873. BF_SetThreadContext(threadInfo->mHThread, &lcContext);
  1874. if ((dwSubprogram != NULL) && (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid) &&
  1875. (pcAddress == dwSubprogram->mBlock.mLowPC))
  1876. {
  1877. BfLogDbg("Hit HotReplaceKind_Invalid breakpoint\n");
  1878. mRunState = RunState_Paused;
  1879. mDebugManager->mOutMessages.push_back("error This lambda was replaced by a new version that has incompatible captures. A program restart is required.");
  1880. PhysRemoveBreakpoint(pcAddress);
  1881. break;
  1882. }
  1883. }
  1884. else
  1885. {
  1886. // This was an actual "break" instruction
  1887. BfLogDbg("Non-debugger break\n");
  1888. isNonDebuggerBreak = true;
  1889. auto prevState = mRunState;
  1890. // Make it an "auto" stop, so for example when we have an assert/retry we won't stop inside assembly
  1891. mRequestedStackFrameIdx = -2;
  1892. mRunState = RunState_Paused;
  1893. CheckNonDebuggerBreak();
  1894. if (IsInRunState())
  1895. {
  1896. BF_ASSERT((prevState == RunState_Running) || (prevState == RunState_DebugEval));
  1897. mRunState = prevState;
  1898. break; // Continue as if nothing happened
  1899. }
  1900. if (prevState == RunState_DebugEval)
  1901. mRequestedStackFrameIdx = -1; // Don't show a rolled back stack idx if a debug eval fails
  1902. ClearStep();
  1903. }
  1904. if (threadInfo->mIsBreakRestorePaused)
  1905. {
  1906. // The thread is supposed to be paused, but the IP has been reset
  1907. // so just break here so we'll hit that breakpoint again once we're
  1908. // actually unpaused properly
  1909. BfLogDbg("Ignoring EXCEPTION_BREAKPOINT\n", threadInfo->mThreadId);
  1910. break;
  1911. }
  1912. if ((mRunState == RunState_DebugEval) || (mRunState == RunState_HotStep))
  1913. {
  1914. // If we hit a breakpoint while doing a debug eval, we just remove the breakpoint
  1915. // and expect to reinstate it during a rehup after the evaluation has completed
  1916. WdBreakpoint* breakpoint = (WdBreakpoint*)FindBreakpointAt((uintptr_t) exceptionRecord->ExceptionAddress);
  1917. if (breakpoint != NULL)
  1918. {
  1919. mNeedsRehupBreakpoints = true;
  1920. RemoveBreakpoint(breakpoint->mLineData.GetAddress());
  1921. }
  1922. break;
  1923. }
  1924. bool isDeeper = false;
  1925. int stepBreakAddrIdx = (int)mStepBreakpointAddrs.IndexOf(pcAddress);
  1926. WdBreakpoint* breakpoint = NULL;
  1927. bool ignoreBreakpoint = false;
  1928. if ((mStepType != StepType_None) && (mSteppingThread == mAtBreakThread))
  1929. {
  1930. if (mStepType == StepType_ToTempBreakpoint)
  1931. {
  1932. RemoveTempBreakpoints();
  1933. mRunState = RunState_Paused;
  1934. break;
  1935. }
  1936. if (mContinueFromBreakpointFailed)
  1937. {
  1938. BfLogDbg("Continuing from ContinueFromBreakpointFailed\n");
  1939. SetupStep(mStepType);
  1940. mRunState = RunState_Running;
  1941. break;
  1942. }
  1943. if (!isStepOut)
  1944. breakpoint = (WdBreakpoint*)FindBreakpointAt(pcAddress);
  1945. // Ignore breakpoint if it's on the line we're stepping off of
  1946. if ((breakpoint != NULL) && (breakpoint->mAddr == mStepPC) &&
  1947. (mStepSP == BF_CONTEXT_SP(lcContext)))
  1948. {
  1949. ignoreBreakpoint = true;
  1950. }
  1951. else if ((breakpoint != NULL) && (stepBreakAddrIdx == -1) && (!CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress)))
  1952. {
  1953. ignoreBreakpoint = true;
  1954. }
  1955. if ((stepBreakAddrIdx == -1) && (breakpoint == NULL) && (!isNonDebuggerBreak))
  1956. {
  1957. // If a breakpoint is removed in a prior thread
  1958. BfLogDbg("Ignoring step break (old breakpoint)\n");
  1959. if ((mSteppingThread == mAtBreakThread) && (mStepSwitchedThreads))
  1960. {
  1961. SetupStep(mStepType);
  1962. }
  1963. break;
  1964. }
  1965. if ((stepBreakAddrIdx != -1) && (breakpoint == NULL) && (mSteppingThread != mActiveThread))
  1966. {
  1967. BfLogDbg("Ignoring break (wrong thread)\n");
  1968. ThreadRestorePause(mSteppingThread, mActiveThread);
  1969. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1970. break;
  1971. }
  1972. isDeeper = mStepSP > BF_CONTEXT_SP(lcContext);
  1973. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto))
  1974. {
  1975. isDeeper = mStepSP >= BF_CONTEXT_SP(lcContext);
  1976. BfLogDbg("StepOut Iteration SP:%p StartSP:%p IsDeeper:%d\n", BF_CONTEXT_SP(lcContext), mStepSP, isDeeper);
  1977. }
  1978. if (((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto)) && (breakpoint == NULL) && (isDeeper))
  1979. {
  1980. // We're encountered recursion
  1981. // Make sure we don't already have one of these stored
  1982. BF_ASSERT(mStoredReturnValueAddr == 0);
  1983. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1984. break; // Don't fall through, we don't want to set mIsAtBreakpointAddress
  1985. }
  1986. if (isStepOut)
  1987. {
  1988. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1989. if (mStepType == StepType_StepOut_ThenInto)
  1990. {
  1991. dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  1992. if ((dwLineData != NULL) && (pcAddress == dwSubprogram->GetLineAddr(*dwLineData)))
  1993. {
  1994. // Our step out from a filtered function put us at the start of a new line. Stop here
  1995. // <do nothing>
  1996. }
  1997. else
  1998. {
  1999. // .. otherwise keep going until we get to the start of a new line
  2000. SetupStep(StepType_StepInto);
  2001. mRunState = RunState_Running;
  2002. break;
  2003. }
  2004. }
  2005. if (!mStepInAssembly)
  2006. {
  2007. // Keep stepping out until we find a frame that we have source for
  2008. DbgSubprogram* dwSubprogram = NULL;
  2009. DbgLineData* dwLineData = FindLineDataAtAddress(BF_CONTEXT_IP(lcContext), &dwSubprogram);
  2010. if (dwLineData == NULL)
  2011. {
  2012. SetupStep(StepType_StepOut);
  2013. break;
  2014. }
  2015. if ((dwLineData->mColumn == -1) && (!dwSubprogram->HasValidLines()))
  2016. {
  2017. // This is a method we don't actually want to be in, it has no valid lines!
  2018. SetupStep(StepType_StepOut);
  2019. break;
  2020. }
  2021. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  2022. {
  2023. // We've stepped out, but right into the start of an inlined method, so step out of this inlined method now...
  2024. SetupStep(StepType_StepOut);
  2025. break;
  2026. }
  2027. }
  2028. ClearStep();
  2029. mRunState = RunState_Paused;
  2030. threadInfo->mStoppedAtAddress = pcAddress;
  2031. break;
  2032. }
  2033. mRunState = RunState_Paused;
  2034. if (breakpoint != NULL)
  2035. {
  2036. // While stepping we hit a legit breakpoint
  2037. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  2038. // Ignore breakpoint on return statement if we're return-stepping
  2039. mRunState = RunState_Breakpoint;
  2040. }
  2041. if ((mStepType == StepType_StepInto) && (dwSubprogram != NULL))
  2042. {
  2043. // Don't filter out the current subprogram (would break cases where we explicitly stepped into or hit breakpoint in a filtered subprogram)
  2044. bool isInStartSubprogram = (mStepStartPC >= dwSubprogram->mBlock.mLowPC) && (mStepStartPC < dwSubprogram->mBlock.mHighPC);
  2045. if ((!isInStartSubprogram) && (IsStepFiltered(dwSubprogram, dwLineData)))
  2046. {
  2047. BfLogDbg("Hit step filter\n");
  2048. mRunState = RunState_Running;
  2049. SetupStep(StepType_StepOut_ThenInto);
  2050. break;
  2051. }
  2052. }
  2053. if ((mStepType == StepType_StepOver) && (stepBreakAddrIdx == 0) && (mStepBreakpointAddrs[0] != 0) && (mStepBreakpointAddrs.size() > 1))
  2054. {
  2055. // Break was on the 'call' instruction, not the instruction after it -- means recursion
  2056. BfLogDbg("StepOver detected recursing\n");
  2057. mStepIsRecursing = true;
  2058. if (mTempBreakpoint.Remove(mStepBreakpointAddrs[0]))
  2059. {
  2060. RemoveBreakpoint(mStepBreakpointAddrs[0]);
  2061. }
  2062. mStepBreakpointAddrs[0] = 0;
  2063. mRunState = RunState_Running;
  2064. break;
  2065. }
  2066. if ((mStepType == StepType_StepOver) && (stepBreakAddrIdx > 0) && (mStepBreakpointAddrs[0] != 0) && (isDeeper))
  2067. {
  2068. // This is the first time we've hit the target breakpoint.
  2069. if (HasSteppedIntoCall())
  2070. {
  2071. mStepIsRecursing = true;
  2072. RemoveBreakpoint(mStepBreakpointAddrs[0]);
  2073. mStepBreakpointAddrs[0] = 0;
  2074. //mStepBreakpointAddrs.erase(mStepBreakpointAddrs.begin());
  2075. }
  2076. }
  2077. if ((mStepType == StepType_StepOver) && (mStepIsRecursing) && (stepBreakAddrIdx != -1) && (isDeeper))
  2078. {
  2079. // Decrement so the equality test on "step out" marks us as not being deeper when we
  2080. // hit the expected SP
  2081. BfLogDbg("Converting StepOver to StepOut\n");
  2082. mStepSP--;
  2083. mStepType = StepType_StepOut_ThenInto;
  2084. //SetupStep(StepType_StepOut);
  2085. mRunState = RunState_Running;
  2086. break;
  2087. }
  2088. if ((mStepType == StepType_StepOver) && (!ignoreBreakpoint) && (breakpoint == NULL) && (!mStepInAssembly))
  2089. {
  2090. // Test for stepping over inline method
  2091. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  2092. // mTempBreakpoints will have 2 entries if we are on a 'call' line. If we have an inlined call immediately following a call, then we
  2093. // assume we're hitting a return break
  2094. /*if ((dwSubprogram != NULL) && (dwSubprogram->mInlineParent != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC) && (mTempBreakpoint.size() < 2))
  2095. {
  2096. BfLogDbg("Attempting StepOver of inlined method\n");
  2097. SetupStep(StepType_StepOut);
  2098. mRunState = RunState_Running;
  2099. break;
  2100. } */
  2101. //TODO: The previous logic with the "(mTempBreakpoint.size() < 2)" was causing Try!(Method()); stepovers to enter into Try!. What did we mean by
  2102. // "assume we're hitting a return break"?
  2103. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  2104. {
  2105. RemoveTempBreakpoints();
  2106. BfLogDbg("Attempting StepOver of inlined method\n");
  2107. SetupStep(StepType_StepOut);
  2108. mRunState = RunState_Running;
  2109. break;
  2110. }
  2111. }
  2112. if (mStepType == StepType_StepOut_Inline)
  2113. {
  2114. if (mOrigStepType == StepType_StepOver)
  2115. {
  2116. // For the step over, if we are still inside the source line after an inline then step over again...
  2117. DbgSubprogram* origSubprogram = NULL;
  2118. auto origLineData = FindLineDataAtAddress(mStepStartPC, &origSubprogram);
  2119. DbgSubprogram* curSubprogram = NULL;
  2120. auto curLineData = FindLineDataAtAddress(pcAddress, &curSubprogram);
  2121. if ((origLineData != NULL) &&
  2122. ((origLineData == curLineData) ||
  2123. ((origSubprogram == curSubprogram) && (origLineData->mLine == curLineData->mLine))))
  2124. {
  2125. mRunState = RunState_Running;
  2126. SetupStep(StepType_StepOver);
  2127. break;
  2128. }
  2129. }
  2130. ClearStep();
  2131. break;
  2132. }
  2133. if ((mStepType != StepType_None) && (ignoreBreakpoint) && (!mStepInAssembly) && (stepBreakAddrIdx == -1))
  2134. {
  2135. // Ignore breakpoint by just continuing...
  2136. mRunState = RunState_Running;
  2137. break;
  2138. }
  2139. RemoveTempBreakpoints();
  2140. if ((mStepType != StepType_None) && (!mStepInAssembly) && (!isLineStart) && (stepBreakAddrIdx != -1))
  2141. {
  2142. SetupStep(mStepType);
  2143. mRunState = RunState_Running;
  2144. }
  2145. else
  2146. {
  2147. //if (mStepType != StepType_Return)
  2148. if (stepBreakAddrIdx != -1)
  2149. {
  2150. // Even if we've detected we're at a breakpoint, we mark ourselves as just stepping if we also
  2151. // have a step breakpoint here
  2152. StepLineTryPause(pcAddress, true);
  2153. }
  2154. if (mRunState == RunState_Paused)
  2155. ClearStep();
  2156. }
  2157. if (ignoreBreakpoint)
  2158. {
  2159. SetupStep(mStepType);
  2160. mRunState = RunState_Running;
  2161. }
  2162. if ((mRunState == RunState_Paused) && (breakpoint != NULL))
  2163. {
  2164. // Just do the 'check' here so we can do the logging/condition stuff
  2165. CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress);
  2166. }
  2167. }
  2168. else
  2169. {
  2170. breakpoint = (WdBreakpoint*)FindBreakpointAt((uintptr_t)exceptionRecord->ExceptionAddress);
  2171. if ((breakpoint != NULL) && (!CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress)))
  2172. {
  2173. ClearCallStack();
  2174. BfLogDbg("Skipping conditional breakpoint. Setting mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  2175. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  2176. mRunState = RunState_Running;
  2177. break;
  2178. }
  2179. if (breakpoint != NULL)
  2180. {
  2181. BfLogDbg("Breakpoint hit. mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  2182. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  2183. mRunState = RunState_Breakpoint;
  2184. }
  2185. else if ((stepBreakAddrIdx != -1) || (isNonDebuggerBreak))
  2186. {
  2187. if (mRunState != RunState_DebugEval)
  2188. {
  2189. // Was in mStepBreakpointAddrs list
  2190. if ((isNonDebuggerBreak) || (mStepType == StepType_None) || (mSteppingThread == mAtBreakThread))
  2191. {
  2192. BfLogDbg("Hit mStepBreakpointAddrs breakpoint\n");
  2193. mRunState = RunState_Paused;
  2194. }
  2195. else
  2196. {
  2197. BfLogDbg("Ignored mStepBreakpointAddrs breakpoint (wrong thread)\n");
  2198. mRunState = RunState_Running;
  2199. }
  2200. }
  2201. }
  2202. else
  2203. {
  2204. BfLogDbg("Ignoring break (old or ignored breakpoint)\n");
  2205. mRunState = RunState_Running;
  2206. }
  2207. }
  2208. if ((breakpoint != NULL) && (!ignoreBreakpoint))
  2209. {
  2210. mActiveBreakpoint = breakpoint;
  2211. mBreakStackFrameIdx = -1;
  2212. }
  2213. if ((mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint))
  2214. threadInfo->mStoppedAtAddress = pcAddress;
  2215. }
  2216. break;
  2217. case STATUS_WX86_SINGLE_STEP:
  2218. case EXCEPTION_SINGLE_STEP:
  2219. {
  2220. if (mRunState == RunState_Terminating)
  2221. {
  2222. BfLogDbg("Ignoring event because of RunState_Terminating\n");
  2223. break;
  2224. }
  2225. if ((mStepSwitchedThreads) && (mActiveThread == mSteppingThread) && (mActiveThread->mIsAtBreakpointAddress != NULL))
  2226. {
  2227. ContinueFromBreakpoint();
  2228. break;
  2229. }
  2230. if (mRunState == RunState_HotStep)
  2231. {
  2232. BF_ASSERT(mActiveThread == mDebuggerWaitingThread);
  2233. mRunState = RunState_Paused;
  2234. break;
  2235. }
  2236. mActiveThread = mDebuggerWaitingThread;
  2237. BF_CONTEXT lcContext;
  2238. lcContext.ContextFlags = BF_CONTEXT_ALL;
  2239. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  2240. addr_target pcAddress = BF_CONTEXT_IP(lcContext);
  2241. bool wasUnfilteredStep = mStepType == StepType_StepInto_Unfiltered;
  2242. if (mStepType == StepType_StepInto_UnfilteredSingle)
  2243. {
  2244. wasUnfilteredStep = true;
  2245. mStepType = StepType_StepInto;
  2246. mStepStartPC = pcAddress;
  2247. }
  2248. BfLogDbg("EXCEPTION_SINGLE_STEP Thread:%d PC:%p\n", mActiveThread->mThreadId, exceptionRecord->ExceptionAddress);
  2249. if (lcContext.Dr6 & 0x0F) // Memory breakpoint hit
  2250. {
  2251. WdBreakpoint* foundBreakpoint = NULL;
  2252. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  2253. {
  2254. if ((lcContext.Dr6 & ((intptr_target)1 << memoryWatchSlot)) != 0)
  2255. {
  2256. foundBreakpoint = mMemoryBreakpoints[memoryWatchSlot].mBreakpoint;
  2257. break;
  2258. }
  2259. }
  2260. BF_ASSERT(foundBreakpoint != NULL);
  2261. DbgSubprogram* subprogram = mDebugTarget->FindSubProgram(pcAddress);
  2262. if (CheckConditionalBreakpoint(foundBreakpoint, subprogram, pcAddress))
  2263. {
  2264. if (foundBreakpoint != NULL)
  2265. {
  2266. mDebugManager->mOutMessages.push_back(StrFormat("memoryBreak %s", EncodeDataPtr(foundBreakpoint->mMemoryBreakpointInfo->mMemoryAddress, false).c_str()));
  2267. mRunState = RunState_Paused;
  2268. }
  2269. mActiveBreakpoint = foundBreakpoint;
  2270. mBreakStackFrameIdx = -1;
  2271. RemoveTempBreakpoints();
  2272. BfLogDbg("Memory breakpoint hit: %p\n", foundBreakpoint);
  2273. }
  2274. else
  2275. ClearCallStack();
  2276. break;
  2277. }
  2278. if ((mRunState == RunState_DebugEval) && (mDebugEvalThreadInfo.mThreadId == mDebuggerWaitingThread->mThreadId))
  2279. {
  2280. if ((addr_target)(intptr)exceptionRecord->ExceptionAddress == mDebugEvalSetRegisters.GetPC())
  2281. {
  2282. // This indicates we are returning from kernel mode and our registers are clobbered
  2283. SetRegisters(&mDebugEvalSetRegisters);
  2284. }
  2285. break;
  2286. }
  2287. bool hadBreakpointContinue = true;
  2288. if (threadInfo->mBreakpointAddressContinuing != 0)
  2289. {
  2290. bool wantsBreakpoint = WantsBreakpointAt(threadInfo->mBreakpointAddressContinuing);
  2291. BfLogDbg("Continuing breakpoint at %p WantsReset:%d\n", threadInfo->mBreakpointAddressContinuing, wantsBreakpoint);
  2292. if (wantsBreakpoint)
  2293. {
  2294. PhysSetBreakpoint(threadInfo->mBreakpointAddressContinuing);
  2295. }
  2296. threadInfo->mBreakpointAddressContinuing = NULL;
  2297. hadBreakpointContinue = true;
  2298. ThreadRestoreUnpause();
  2299. }
  2300. if ((mSteppingThread != NULL) && (mSteppingThread != mActiveThread))
  2301. {
  2302. // This SINGLE_STEP happened in the wrong thread - we need the stepping thread to do the stepping!
  2303. // Try again.
  2304. mActiveThread = mSteppingThread;
  2305. SingleStepX86();
  2306. break;
  2307. }
  2308. bool isDeeper = mStepSP > BF_CONTEXT_SP(lcContext);
  2309. if ((mStepSwitchedThreads) && (mStepType == StepType_StepOver) && (isDeeper))
  2310. {
  2311. if (HasSteppedIntoCall())
  2312. {
  2313. // Since we switched threads, we needed to do a hardware step which has placed us inside a
  2314. // call, so we need to step out of that now...
  2315. SetupStep(StepType_StepOut_NoFrame);
  2316. break;
  2317. }
  2318. }
  2319. // If we don't have a mStepBreakpointAddrs set, that means we're stepping through individual instructions --
  2320. // so process the new location here
  2321. if (((mStepType == StepType_StepInto) || (mStepType == StepType_StepInto_Unfiltered) || (mStepType == StepType_StepOver)) && (mStepBreakpointAddrs.size() == 0))
  2322. {
  2323. DbgSubprogram* dwSubprogram = NULL;
  2324. DbgLineData* dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  2325. if ((dwSubprogram != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC) && (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced))
  2326. {
  2327. BfLogDbg("Stepping through hot thunk\n");
  2328. mRunState = RunState_Running;
  2329. SingleStepX86();
  2330. break;
  2331. }
  2332. if ((mStepType == StepType_StepOver) && (!mStepInAssembly))
  2333. {
  2334. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  2335. {
  2336. BfLogDbg("Attempting StepOver of inlined method - SingleStep\n");
  2337. SetupStep(StepType_StepOut);
  2338. mRunState = RunState_Running;
  2339. break;
  2340. }
  2341. }
  2342. // Column of -1 means "Illegal", keep stepping!
  2343. if ((mStepInAssembly) ||
  2344. ((dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dwLineData->mColumn >= 0) &&
  2345. ((dwSubprogram->GetLineAddr(*dwLineData) == pcAddress) || (mStepStopOnNextInstruction))))
  2346. {
  2347. // Hit a line while stepping, we're done!
  2348. mRunState = RunState_Paused;
  2349. StepLineTryPause(pcAddress, false);
  2350. if (mRunState == RunState_Paused)
  2351. {
  2352. if ((mStepType == StepType_StepInto) && (!wasUnfilteredStep) && (!mStepInAssembly) && (dwSubprogram != NULL))
  2353. {
  2354. // Don't filter out the current subprogram (would break cases where we explicitly stepped into or hit breakpoint in a filtered subprogram)
  2355. bool isInStartSubprogram = (mStepStartPC >= dwSubprogram->mBlock.mLowPC) && (mStepStartPC < dwSubprogram->mBlock.mHighPC);
  2356. if ((!isInStartSubprogram) && (IsStepFiltered(dwSubprogram, dwLineData)))
  2357. {
  2358. BfLogDbg("Hit step filter (2)\n");
  2359. mRunState = RunState_Running;
  2360. SetupStep(StepType_StepOut_ThenInto);
  2361. break;
  2362. }
  2363. }
  2364. ClearStep();
  2365. mCurNoInfoStepTries = 0; // Reset
  2366. }
  2367. else
  2368. SetupStep(mStepType);
  2369. }
  2370. else if (dwSubprogram != NULL)
  2371. {
  2372. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && ((mStepType == StepType_StepInto) || (mStepType == StepType_StepInto_Unfiltered)))
  2373. {
  2374. SingleStepX86();
  2375. }
  2376. else
  2377. {
  2378. // Inside a line's instruction, keep going
  2379. SetupStep(mStepType);
  2380. mCurNoInfoStepTries = 0; // Reset
  2381. }
  2382. }
  2383. else if (mStepType == StepType_StepInto_Unfiltered)
  2384. {
  2385. CPUInst inst;
  2386. if (mDebugTarget->DecodeInstruction(pcAddress, &inst))
  2387. {
  2388. if (inst.IsBranch())
  2389. {
  2390. auto target = inst.GetTarget();
  2391. if (target != 0)
  2392. {
  2393. DbgSubprogram* destSubprogram = mDebugTarget->FindSubProgram(target);
  2394. if ((destSubprogram != NULL) && (target == destSubprogram->mBlock.mLowPC))
  2395. {
  2396. // We're jumping to an actual subprogram, so continue stepping here
  2397. mStepType = StepType_StepInto_UnfilteredSingle;
  2398. SingleStepX86();
  2399. break;
  2400. }
  2401. }
  2402. }
  2403. }
  2404. // We requested to step into this method so stop here even if we don't have source
  2405. mRunState = RunState_Paused;
  2406. }
  2407. else
  2408. {
  2409. // No debug info!
  2410. bool doStepOut = false;
  2411. if (mCurNoInfoStepTries < 16)
  2412. {
  2413. mCurNoInfoStepTries++;
  2414. BfLogDbg("NoInfoStepTries: %d\n", mCurNoInfoStepTries);
  2415. if (!SetupStep(mStepType))
  2416. doStepOut = true;
  2417. }
  2418. else
  2419. doStepOut = true;
  2420. if (doStepOut)
  2421. {
  2422. // Step out of current call.
  2423. mStepSP = 0;
  2424. SetupStep(StepType_StepOut_NoFrame);
  2425. // Aggressive stepout - don't monitor BP
  2426. mStepSP = 0;
  2427. }
  2428. }
  2429. }
  2430. else if (!hadBreakpointContinue)
  2431. {
  2432. BF_DBG_FATAL("EXCEPTION_SINGLE_STEP bad debugger state");
  2433. }
  2434. if (mRunState == RunState_Paused)
  2435. threadInfo->mStoppedAtAddress = pcAddress;
  2436. }
  2437. break;
  2438. default:
  2439. {
  2440. bool isSystemException =
  2441. (exceptionRecord->ExceptionCode >= STATUS_ACCESS_VIOLATION) &&
  2442. (exceptionRecord->ExceptionCode <= STATUS_ASSERTION_FAILURE);
  2443. bool isFirstChance = mDebugEvent.u.Exception.dwFirstChance != 0;
  2444. bool handled = false;
  2445. //TODO: Use a user-defined filter here to determine whether to stop or continue
  2446. if (isFirstChance)
  2447. {
  2448. if (exceptionRecord->ExceptionCode == 0x406D1388) // Visual C
  2449. {
  2450. if ((int32)exceptionRecord->ExceptionInformation[0] == 0x1000)
  2451. {
  2452. struct THREADNAME_INFO
  2453. {
  2454. DWORD dwType; // Must be 0x1000.
  2455. LPCSTR szName; // Pointer to name (in user addr space).
  2456. DWORD dwThreadID; // Thread ID (-1=caller thread).
  2457. DWORD dwFlags; // Reserved for future use, must be zero.
  2458. };
  2459. THREADNAME_INFO* threadNameInfo = (THREADNAME_INFO*)exceptionRecord->ExceptionInformation;
  2460. DwFormatInfo formatInfo;
  2461. formatInfo.mRawString = true;
  2462. String nameStr = ReadString(DbgType_SChar, (intptr)threadNameInfo->szName, false, 1024, formatInfo, false);
  2463. WdThreadInfo* namingThreadInfo = threadInfo;
  2464. if (threadNameInfo->dwThreadID != (DWORD)-1)
  2465. {
  2466. namingThreadInfo = NULL;
  2467. mThreadMap.TryGetValue(threadNameInfo->dwThreadID, &namingThreadInfo);
  2468. }
  2469. if (namingThreadInfo != NULL)
  2470. {
  2471. namingThreadInfo->mName = nameStr;
  2472. FilterThreadName(namingThreadInfo->mName);
  2473. }
  2474. }
  2475. else if (((int32)exceptionRecord->ExceptionInformation[0] == 0x1001) && ((int32)exceptionRecord->ExceptionInformation[1] == 0x1002))
  2476. {
  2477. struct FailMessage
  2478. {
  2479. addr_target mPtr0; // Unknown
  2480. addr_target mPtr1; // 0
  2481. addr_target mPtr2; // 0
  2482. addr_target mPtr3; // Unknown
  2483. addr_target mErrorStr;
  2484. };
  2485. FailMessage failMessage = ReadMemory<FailMessage>(exceptionRecord->ExceptionInformation[2]);
  2486. DwFormatInfo formatInfo;
  2487. String failStr = ReadString(DbgType_SChar16, failMessage.mErrorStr, false, 8192, formatInfo, false);
  2488. mDebugManager->mOutMessages.push_back(StrFormat("error Run-Time Check Failure %d - %s", exceptionRecord->ExceptionInformation[6], failStr.c_str()));
  2489. mRunState = RunState_Paused;
  2490. mRequestedStackFrameIdx = -2; // -2 = "auto"
  2491. handled = true;
  2492. }
  2493. }
  2494. if (!handled)
  2495. {
  2496. if (mRunState != RunState_DebugEval)
  2497. OutputMessage(StrFormat("Skipping first chance exception %08X at address %@ in thread %d\n", exceptionRecord->ExceptionCode, exceptionRecord->ExceptionAddress, threadInfo->mThreadId));
  2498. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_EXCEPTION_NOT_HANDLED);
  2499. mIsDebuggerWaiting = false;
  2500. }
  2501. }
  2502. else
  2503. {
  2504. BfLogDbg("EXCEPTION in thread %d at %p\n", threadInfo->mThreadId, exceptionRecord->ExceptionAddress);
  2505. OutputDebugStrF("EXCEPTION\n");
  2506. mActiveThread = threadInfo;
  2507. memcpy(&mCurException, exceptionRecord, sizeof(EXCEPTION_RECORD));
  2508. if (mRunState == RunState_DebugEval)
  2509. {
  2510. if ((intptr)mCurException.ExceptionAddress == 42)
  2511. {
  2512. BfLogDbg("RunState_DebugEval_Done\n");
  2513. OutputDebugStrF(" RunState_DebugEval_Done\n");
  2514. }
  2515. else
  2516. {
  2517. BfLogDbg("Exception at 0x%@ in thread %d, exception code 0x%08X",
  2518. mCurException.ExceptionAddress, mActiveThread->mThreadId, mCurException.ExceptionCode);
  2519. mDebugPendingExpr->mException = StrFormat("Exception at 0x%@ in thread %d, exception code 0x%08X",
  2520. mCurException.ExceptionAddress, mActiveThread->mThreadId, mCurException.ExceptionCode);
  2521. }
  2522. mRunState = RunState_DebugEval_Done;
  2523. mExplicitStopThread = mActiveThread;
  2524. mRequestedStackFrameIdx = mDebugPendingExpr->mCallStackIdx;
  2525. }
  2526. else
  2527. {
  2528. mRunState = RunState_Exception;
  2529. }
  2530. }
  2531. }
  2532. break;
  2533. }
  2534. }
  2535. break;
  2536. }
  2537. if ((mDebugEvalThreadInfo.mThreadId != 0) && (mRunState != RunState_DebugEval) && (mRunState != RunState_DebugEval_Done))
  2538. {
  2539. CleanupDebugEval();
  2540. }
  2541. // Stepping done?
  2542. if (mStepType == StepType_None)
  2543. {
  2544. mLastValidStepIntoPC = 0;
  2545. }
  2546. BF_ASSERT(mDebuggerWaitingThread != NULL);
  2547. return true;
  2548. }
  2549. void WinDebugger::Update()
  2550. {
  2551. AutoCrit autoCrit(mDebugManager->mCritSect);
  2552. // if (mRunState == RunState_DebugEval)
  2553. // ContinueDebugEvent();
  2554. if (mRunState == RunState_DebugEval_Done)
  2555. {
  2556. if (mDebugPendingExpr != NULL)
  2557. {
  2558. mDebugPendingExpr->mIdleTicks++;
  2559. if (mDebugPendingExpr->mIdleTicks >= 2)
  2560. {
  2561. BfLogDbg("Finishing pending expr in thread %d\n", mDebugEvalThreadInfo.mThreadId);
  2562. mRunState = RunState_Paused;
  2563. CleanupDebugEval();
  2564. }
  2565. }
  2566. }
  2567. else if (mDebugPendingExpr != NULL)
  2568. {
  2569. mDebugPendingExpr->mIdleTicks = 0;
  2570. }
  2571. }
  2572. void WinDebugger::ContinueDebugEvent()
  2573. {
  2574. AutoCrit autoCrit(mDebugManager->mCritSect);
  2575. BF_ASSERT(mRunState != RunState_DebugEval_Done);
  2576. if (!mWantsDebugContinue)
  2577. return;
  2578. if (!TryRunContinue())
  2579. return;
  2580. // if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId != mDebugEvalThreadInfo.mThreadId))
  2581. // {
  2582. // // Don't process the 'mIsAtBreakpointAddress' stuff
  2583. // mWantsDebugContinue = false;
  2584. // mContinueEvent.Set();
  2585. // return;
  2586. // }
  2587. if ((mDebuggerWaitingThread->mIsAtBreakpointAddress == 0) && (mDebuggerWaitingThread->mStoppedAtAddress != 0))
  2588. {
  2589. auto breakpoint = FindBreakpointAt(mDebuggerWaitingThread->mStoppedAtAddress);
  2590. if (breakpoint != NULL)
  2591. {
  2592. mDebuggerWaitingThread->mIsAtBreakpointAddress = mDebuggerWaitingThread->mStoppedAtAddress;
  2593. }
  2594. }
  2595. if (mDebuggerWaitingThread->mIsAtBreakpointAddress != 0)
  2596. {
  2597. if (!ContinueFromBreakpoint())
  2598. {
  2599. BfLogDbg("ContinueFromBreakpoint failed\n");
  2600. ClearCallStack();
  2601. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  2602. mDebuggerWaitingThread->mIsAtBreakpointAddress = 0;
  2603. mWantsDebugContinue = false;
  2604. mContinueFromBreakpointFailed = true;
  2605. mContinueEvent.Set();
  2606. return;
  2607. }
  2608. }
  2609. if ((mRunState == RunState_Breakpoint) || (mRunState == RunState_Paused) || (mRunState == RunState_TargetUnloaded))
  2610. {
  2611. ClearCallStack();
  2612. mRunState = RunState_Running;
  2613. }
  2614. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  2615. mWantsDebugContinue = false;
  2616. BF_ASSERT_REL(mDebuggerWaitingThread->mIsAtBreakpointAddress == 0);
  2617. mContinueEvent.Set();
  2618. }
  2619. static BOOL CALLBACK WdEnumWindowsProc(HWND hwnd, LPARAM lParam)
  2620. {
  2621. int wantProcessId = lParam;
  2622. HWND owner = GetWindow(hwnd, GW_OWNER);
  2623. if (!IsWindowVisible(hwnd))
  2624. return TRUE;
  2625. DWORD processId = 0;
  2626. DWORD threadId = GetWindowThreadProcessId(hwnd, &processId);
  2627. if (processId != wantProcessId)
  2628. return TRUE;
  2629. while (true)
  2630. {
  2631. HWND parentHWnd = GetParent(hwnd);
  2632. if (parentHWnd != NULL)
  2633. {
  2634. hwnd = parentHWnd;
  2635. continue;
  2636. }
  2637. SetForegroundWindow(hwnd);
  2638. break;
  2639. }
  2640. return TRUE;
  2641. }
  2642. void WinDebugger::ForegroundTarget(int altProcessId)
  2643. {
  2644. int wantProcessId = altProcessId;
  2645. if (wantProcessId == 0)
  2646. wantProcessId = ((WinDebugger*)gDebugger)->mProcessInfo.dwProcessId;
  2647. HWND hwnd = ::GetForegroundWindow();
  2648. if (hwnd != INVALID_HANDLE_VALUE)
  2649. {
  2650. DWORD processId = 0;
  2651. GetWindowThreadProcessId(hwnd, &processId);
  2652. if (processId == ((WinDebugger*)gDebugger)->mProcessInfo.dwProcessId)
  2653. return; // Already good
  2654. }
  2655. EnumWindows(WdEnumWindowsProc, wantProcessId);
  2656. }
  2657. static int gFindLineDataAt = 0;
  2658. DbgLineData* WinDebugger::FindLineDataAtAddress(addr_target address, DbgSubprogram** outSubProgram, DbgSrcFile** outSrcFile, int* outLineIdx, DbgOnDemandKind onDemandKind)
  2659. {
  2660. gFindLineDataAt++;
  2661. BP_ZONE("WinDebugger::FindLineDataAtAddress");
  2662. auto dwSubprogram = mDebugTarget->FindSubProgram((addr_target)address, onDemandKind);
  2663. if (dwSubprogram == NULL)
  2664. return NULL;
  2665. FixupLineDataForSubprogram(dwSubprogram);
  2666. auto lineData = dwSubprogram->FindClosestLine(address, outSubProgram, outSrcFile, outLineIdx);
  2667. return lineData;
  2668. }
  2669. DbgLineData* WinDebugger::FindLineDataInSubprogram(addr_target address, DbgSubprogram* dwSubprogram)
  2670. {
  2671. auto dwCompileUnit = dwSubprogram->mCompileUnit;
  2672. FixupLineDataForSubprogram(dwSubprogram);
  2673. auto lineData = dwSubprogram->FindClosestLine(address);
  2674. return lineData;
  2675. }
  2676. bool WinDebugger::IsStepFiltered(DbgSubprogram* dbgSubprogram, DbgLineData* dbgLineData)
  2677. {
  2678. if (mIsStepIntoSpecific)
  2679. return false;
  2680. if (dbgSubprogram->mStepFilterVersion != mDebugManager->mStepFilterVersion)
  2681. {
  2682. String filterName;
  2683. CreateFilterName(filterName, dbgSubprogram);
  2684. dbgSubprogram->PopulateSubprogram();
  2685. bool doDefault = false;
  2686. StepFilter* stepFilterPtr;
  2687. if (mDebugManager->mStepFilters.TryGetValue(filterName, &stepFilterPtr))
  2688. {
  2689. switch (stepFilterPtr->mFilterKind)
  2690. {
  2691. case BfStepFilterKind_Default:
  2692. doDefault = true;
  2693. break;
  2694. case BfStepFilterKind_Filtered:
  2695. dbgSubprogram->mIsStepFiltered = true;
  2696. break;
  2697. case BfStepFilterKind_NotFiltered:
  2698. dbgSubprogram->mIsStepFiltered = false;
  2699. break;
  2700. }
  2701. }
  2702. else
  2703. {
  2704. doDefault = true;
  2705. }
  2706. if (doDefault)
  2707. {
  2708. dbgSubprogram->mIsStepFiltered = dbgSubprogram->mIsStepFilteredDefault;
  2709. }
  2710. dbgSubprogram->mStepFilterVersion = mDebugManager->mStepFilterVersion;
  2711. }
  2712. if (!dbgSubprogram->mIsStepFiltered)
  2713. {
  2714. if (dbgLineData != NULL)
  2715. {
  2716. auto dbgSrcFile = dbgSubprogram->GetLineSrcFile(*dbgLineData);
  2717. if (dbgSrcFile->mStepFilterVersion != mDebugManager->mStepFilterVersion)
  2718. {
  2719. dbgSrcFile->mFileExistKind = dbgSubprogram->mCompileUnit->mDbgModule->CheckSourceFileExist(dbgSrcFile->GetLocalPath());
  2720. dbgSrcFile->mStepFilterVersion = mDebugManager->mStepFilterVersion;
  2721. }
  2722. switch (dbgSrcFile->mFileExistKind)
  2723. {
  2724. case DbgFileExistKind_NotFound:
  2725. return true;
  2726. case DbgFileExistKind_HasOldSourceCommand:
  2727. if (mDebugManager->mStepOverExternalFiles)
  2728. return true;
  2729. }
  2730. }
  2731. }
  2732. return dbgSubprogram->mIsStepFiltered;
  2733. }
  2734. void WinDebugger::RemoveTempBreakpoints()
  2735. {
  2736. BfLogDbg("RemoveTempBreakpoints\n");
  2737. for (auto address : mTempBreakpoint)
  2738. {
  2739. RemoveBreakpoint(address);
  2740. // if (FindBreakpointAt(address) == NULL)
  2741. // {
  2742. // RemoveBreakpoint(address);
  2743. // }
  2744. // else
  2745. // {
  2746. // BfLogDbg("Ignoring remove on temp breakpoint %p\n", address);
  2747. // }
  2748. }
  2749. mTempBreakpoint.Clear();
  2750. mStepBreakpointAddrs.Clear();
  2751. }
  2752. void WinDebugger::RehupBreakpoints(bool doFlush)
  2753. {
  2754. BfLogDbg("RehupBreakpoints\n");
  2755. // First pass- detach breakpoints that need to be rebound
  2756. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  2757. {
  2758. auto breakpoint = mBreakpoints[i];
  2759. while (breakpoint != NULL)
  2760. {
  2761. if (((breakpoint->mSrcFile != NULL) && (breakpoint->mSrcFile->mDeferredRefs.size() > 0)) ||
  2762. (!breakpoint->mSymbolName.IsEmpty()))
  2763. {
  2764. // This breakpoint was already bound, but we loaded a debug module that also had this file so rebind it
  2765. DetachBreakpoint(breakpoint);
  2766. }
  2767. breakpoint = (WdBreakpoint*)breakpoint->mLinkedSibling;
  2768. }
  2769. }
  2770. // Second pass- actually set breakpoints
  2771. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  2772. {
  2773. auto breakpoint = mBreakpoints[i];
  2774. while (breakpoint != NULL)
  2775. {
  2776. CheckBreakpoint(breakpoint);
  2777. if (breakpoint->mAddr != 0)
  2778. SetBreakpoint(breakpoint->mAddr, true);
  2779. breakpoint = (WdBreakpoint*)breakpoint->mLinkedSibling;
  2780. }
  2781. }
  2782. mNeedsRehupBreakpoints = false;
  2783. }
  2784. bool WinDebugger::WantsBreakpointAt(addr_target address)
  2785. {
  2786. if (mTempBreakpoint.Contains(address))
  2787. return true;
  2788. for (auto breakpoint : mBreakpoints)
  2789. {
  2790. WdBreakpoint* checkBreakpoint = breakpoint;
  2791. while (checkBreakpoint != NULL)
  2792. {
  2793. if (address == checkBreakpoint->mAddr)
  2794. return true;
  2795. checkBreakpoint = (WdBreakpoint*)checkBreakpoint->mLinkedSibling;
  2796. }
  2797. }
  2798. return false;
  2799. }
  2800. void WinDebugger::CheckBreakpoint(WdBreakpoint* wdBreakpoint, DbgSrcFile* srcFile, int lineNum, int hotIdx)
  2801. {
  2802. BP_ZONE("WinDebugger::CheckBreakpoint:atLoc");
  2803. if (hotIdx == -1)
  2804. {
  2805. BF_ASSERT(wdBreakpoint->mPendingHotBindIdx == -1);
  2806. }
  2807. WdBreakpoint* headBreakpoint = wdBreakpoint;
  2808. headBreakpoint->mPendingHotBindIdx = -1;
  2809. bool foundInSequence = false;
  2810. DbgSubprogram* lastFoundSubprogram = NULL;
  2811. int highestHotIdx = -1;
  2812. bool foundLine = false;
  2813. int bestLineNum = -1;
  2814. int bestLineOffset = 0x7FFFFFFF;
  2815. auto _CheckLineInfo = [&](DbgSubprogram* dbgSubprogram, DbgLineInfo* dbgLineInfo)
  2816. {
  2817. // Scan first so we can determine if we want to do fix up line data or not.
  2818. bool hasNear = false;
  2819. int maxLineDist = 6;
  2820. for (int lineIdx = 0; lineIdx < dbgLineInfo->mLines.mSize; lineIdx++)
  2821. {
  2822. auto lineData = &dbgLineInfo->mLines[lineIdx];
  2823. auto& ctx = dbgLineInfo->mContexts[lineData->mCtxIdx];
  2824. if (ctx.mSrcFile != srcFile)
  2825. continue;
  2826. int lineOffset = lineData->mLine - lineNum;
  2827. if ((lineOffset >= 0) && (lineOffset <= maxLineDist))
  2828. hasNear = true;
  2829. }
  2830. if (!hasNear)
  2831. return;
  2832. FixupLineDataForSubprogram(dbgSubprogram);
  2833. for (int lineIdx = 0; lineIdx < dbgLineInfo->mLines.mSize; lineIdx++)
  2834. {
  2835. //TODO: Do fixup lineData... ?
  2836. auto lineData = &dbgLineInfo->mLines[lineIdx];
  2837. auto& ctx = dbgLineInfo->mContexts[lineData->mCtxIdx];
  2838. if (ctx.mSrcFile != srcFile)
  2839. continue;
  2840. // if (ctx.mInlinee != NULL)
  2841. // {
  2842. // if (lineIdx + 1 < dbgLineInfo->mLines.mSize)
  2843. // {
  2844. // auto nextLineData = &dbgLineInfo->mLines[lineIdx + 1];
  2845. // if (nextLineData->mRelAddress == lineData->mRelAddress)
  2846. // {
  2847. // // Use the later entry (same logic from DisassembleAt)
  2848. // continue;
  2849. // }
  2850. // }
  2851. // }
  2852. if ((lineData->mColumn == -1) && (wdBreakpoint->mInstrOffset == -1))
  2853. continue;
  2854. int lineOffset = lineData->mLine - lineNum;
  2855. if (lineOffset == 0)
  2856. {
  2857. foundLine = true;
  2858. auto address = dbgSubprogram->GetLineAddr(*lineData);
  2859. auto subProgram = mDebugTarget->FindSubProgram(address);
  2860. if (subProgram->mNeedLineDataFixup)
  2861. FixupLineDataForSubprogram(subProgram);
  2862. if (subProgram != NULL)
  2863. highestHotIdx = BF_MAX(highestHotIdx, subProgram->mCompileUnit->mDbgModule->mHotIdx);
  2864. if ((foundInSequence) && (subProgram != lastFoundSubprogram))
  2865. foundInSequence = false;
  2866. if ((subProgram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && (address < subProgram->mBlock.mLowPC + sizeof(HotJumpOp)))
  2867. {
  2868. // If this breakpoint ends up on the hot jmp instruction
  2869. continue;
  2870. }
  2871. if (!foundInSequence)
  2872. {
  2873. lastFoundSubprogram = subProgram;
  2874. if ((subProgram != NULL) && (subProgram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && (address == subProgram->mBlock.mLowPC))
  2875. {
  2876. // This instruction is actually the hot jump, we don't need a breakpoint here
  2877. foundInSequence = true;
  2878. continue;
  2879. }
  2880. if (wdBreakpoint->mSrcFile != NULL)
  2881. {
  2882. wdBreakpoint = new WdBreakpoint();
  2883. // Insert at head
  2884. wdBreakpoint->mLinkedSibling = headBreakpoint->mLinkedSibling;
  2885. headBreakpoint->mLinkedSibling = wdBreakpoint;
  2886. wdBreakpoint->mRequestedLineNum = headBreakpoint->mRequestedLineNum;
  2887. wdBreakpoint->mLineNum = headBreakpoint->mLineNum;
  2888. wdBreakpoint->mColumn = headBreakpoint->mColumn;
  2889. wdBreakpoint->mInstrOffset = headBreakpoint->mInstrOffset;
  2890. wdBreakpoint->mIsLinkedSibling = true;
  2891. wdBreakpoint->mHead = headBreakpoint;
  2892. }
  2893. if (wdBreakpoint->mInstrOffset > 0)
  2894. {
  2895. for (int instIdx = 0; instIdx < wdBreakpoint->mInstrOffset; instIdx++)
  2896. {
  2897. CPUInst inst;
  2898. if (!mDebugTarget->DecodeInstruction(address, &inst))
  2899. break;
  2900. address += inst.mSize;
  2901. }
  2902. }
  2903. wdBreakpoint->mSrcFile = ctx.mSrcFile;
  2904. wdBreakpoint->mLineData = DbgLineDataEx(lineData, subProgram);
  2905. wdBreakpoint->mBreakpointType = BreakpointType_User;
  2906. wdBreakpoint->mAddr = address;
  2907. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mStoppedAtAddress == address))
  2908. {
  2909. BfLogDbg("CheckBreakpoint setting mIsAtBreakpointAddress = %p\n", address);
  2910. mDebuggerWaitingThread->mIsAtBreakpointAddress = address;
  2911. }
  2912. BfLogDbg("Breakpoint %p found at %s in %s\n", wdBreakpoint, subProgram->mName, GetFileName(subProgram->mCompileUnit->mDbgModule->mFilePath).c_str());
  2913. mBreakpointAddrMap.ForceAdd(address, wdBreakpoint);
  2914. SetBreakpoint(address);
  2915. foundInSequence = true;
  2916. }
  2917. }
  2918. else
  2919. {
  2920. //TODO: We didn't have this here, but if we don't have this then there are some cases where the method-closing brace generates code in
  2921. // multiple places so we need to ensure this will break on them all
  2922. foundInSequence = false;
  2923. }
  2924. if ((lineOffset >= 0) && (lineOffset <= maxLineDist) && (lineOffset <= bestLineOffset))
  2925. {
  2926. if (lineOffset < bestLineOffset)
  2927. {
  2928. bestLineNum = lineData->mLine;
  2929. bestLineOffset = lineOffset;
  2930. }
  2931. }
  2932. }
  2933. };
  2934. for (int pass = 0; pass < 2; pass++)
  2935. {
  2936. if (lineNum == -1)
  2937. break;
  2938. bestLineNum = -1;
  2939. bestLineOffset = 0x7FFFFFFF;
  2940. if (hotIdx >= 0)
  2941. {
  2942. if (hotIdx >= srcFile->mHotReplacedDbgLineInfo.size())
  2943. return;
  2944. auto hotReplacedLineInfo = srcFile->mHotReplacedDbgLineInfo[hotIdx];
  2945. for (auto& hotReplacedEntry : hotReplacedLineInfo->mEntries)
  2946. {
  2947. _CheckLineInfo(hotReplacedEntry.mSubprogram, hotReplacedEntry.mLineInfo);
  2948. }
  2949. }
  2950. else
  2951. {
  2952. for (auto subprogram : srcFile->mLineDataRefs)
  2953. _CheckLineInfo(subprogram, subprogram->mLineInfo);
  2954. }
  2955. if (foundLine)
  2956. break;
  2957. // Don't allow the breakpoint to be inexactly bound -- only match on pass 0
  2958. if (hotIdx != -1)
  2959. break;
  2960. if (bestLineNum == -1)
  2961. break;
  2962. lineNum = bestLineNum;
  2963. wdBreakpoint->mLineNum = bestLineNum;
  2964. }
  2965. int highestCheckHotIdx = highestHotIdx - 1;
  2966. if (hotIdx != -1)
  2967. highestCheckHotIdx = hotIdx - 1;
  2968. for (int hotFileIdx = highestCheckHotIdx; hotFileIdx >= 0; hotFileIdx--)
  2969. {
  2970. auto& hotReplacedDbgLineData = wdBreakpoint->mSrcFile->mHotReplacedDbgLineInfo;
  2971. // Only try to bind to an old hot version if we haven't unloaded the hot module
  2972. if ((hotFileIdx < (int)hotReplacedDbgLineData.size()) && (hotReplacedDbgLineData[hotFileIdx]->mEntries.size() > 0))
  2973. {
  2974. headBreakpoint->mPendingHotBindIdx = hotFileIdx;
  2975. break;
  2976. }
  2977. }
  2978. }
  2979. void WinDebugger::HotBindBreakpoint(Breakpoint* breakpoint, int lineNum, int hotIdx)
  2980. {
  2981. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  2982. CheckBreakpoint(wdBreakpoint, wdBreakpoint->mSrcFile, lineNum, hotIdx);
  2983. }
  2984. void WinDebugger::CheckBreakpoint(WdBreakpoint* wdBreakpoint)
  2985. {
  2986. if (!mGotStartupEvent)
  2987. return;
  2988. if (wdBreakpoint->mThreadId == 0) // Not bound to threadId yet...
  2989. {
  2990. return;
  2991. }
  2992. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  2993. {
  2994. if (wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap != 0)
  2995. return;
  2996. if (mFreeMemoryBreakIndices.size() == 0)
  2997. return;
  2998. if ((IsInRunState()) || (mActiveThread == NULL))
  2999. return;
  3000. int wantBytes[4];
  3001. int wantBindCount = 0;
  3002. int bytesLeft = wdBreakpoint->mMemoryBreakpointInfo->mByteCount;
  3003. addr_target curAddr = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress;
  3004. while (bytesLeft > 0)
  3005. {
  3006. if (wantBindCount >= mFreeMemoryBreakIndices.size())
  3007. return;
  3008. int curByteCount = 1;
  3009. #ifdef BF_DBG_64
  3010. if ((bytesLeft >= 8) && ((curAddr & 7) == 0))
  3011. curByteCount = 8;
  3012. else
  3013. #endif
  3014. if ((bytesLeft >= 4) && ((curAddr & 3) == 0))
  3015. curByteCount = 4;
  3016. else if ((bytesLeft >= 2) && ((curAddr & 1) == 0))
  3017. curByteCount = 2;
  3018. wantBytes[wantBindCount++] = curByteCount;
  3019. bytesLeft -= curByteCount;
  3020. curAddr += curByteCount;
  3021. }
  3022. addr_target curOfs = 0;
  3023. for (int i = 0; i < wantBindCount; i++)
  3024. {
  3025. int memoryBreakIdx = mFreeMemoryBreakIndices.back();
  3026. mFreeMemoryBreakIndices.pop_back();
  3027. mMemoryBreakpoints[memoryBreakIdx].mBreakpoint = wdBreakpoint;
  3028. mMemoryBreakpoints[memoryBreakIdx].mAddress = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress + curOfs;
  3029. mMemoryBreakpoints[memoryBreakIdx].mByteCount = wantBytes[i];
  3030. mMemoryBreakpoints[memoryBreakIdx].mOfs = curOfs;
  3031. curOfs += wantBytes[i];
  3032. mMemoryBreakpointVersion++;
  3033. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap |= 1<<memoryBreakIdx;
  3034. }
  3035. UpdateThreadDebugRegisters();
  3036. }
  3037. if (wdBreakpoint->mAddr != 0)
  3038. return;
  3039. if (!wdBreakpoint->mSymbolName.IsEmpty())
  3040. {
  3041. auto headBreakpoint = wdBreakpoint->GetHeadBreakpoint();
  3042. String symbolName = wdBreakpoint->mSymbolName;
  3043. bool onlyBindFirst = false;
  3044. if (symbolName.StartsWith("-"))
  3045. {
  3046. symbolName.Remove(0);
  3047. onlyBindFirst = true;
  3048. }
  3049. for (auto dbgModule : mDebugTarget->mDbgModules)
  3050. {
  3051. dbgModule->ParseSymbolData();
  3052. addr_target targetAddr = -1;
  3053. auto entry = dbgModule->mSymbolNameMap.Find(symbolName.c_str());
  3054. if (entry != NULL)
  3055. {
  3056. DbgSymbol* dwSymbol = entry->mValue;
  3057. targetAddr = dwSymbol->mAddress;
  3058. }
  3059. if (targetAddr == -1)
  3060. {
  3061. if (symbolName == ".")
  3062. {
  3063. targetAddr = mDebugTarget->mLaunchBinary->mImageBase + mDebugTarget->mLaunchBinary->mEntryPoint;
  3064. onlyBindFirst = true;
  3065. }
  3066. }
  3067. if (targetAddr != -1)
  3068. {
  3069. if (wdBreakpoint->mAddr == 0)
  3070. {
  3071. wdBreakpoint->mAddr = targetAddr;
  3072. wdBreakpoint->mBreakpointType = BreakpointType_User;
  3073. mBreakpointAddrMap.ForceAdd(wdBreakpoint->mAddr, wdBreakpoint);
  3074. SetBreakpoint(wdBreakpoint->mAddr);
  3075. }
  3076. else
  3077. {
  3078. wdBreakpoint = new WdBreakpoint();
  3079. // Insert at head
  3080. wdBreakpoint->mLinkedSibling = headBreakpoint->mLinkedSibling;
  3081. headBreakpoint->mLinkedSibling = wdBreakpoint;
  3082. wdBreakpoint->mSymbolName = headBreakpoint->mSymbolName;
  3083. wdBreakpoint->mIsLinkedSibling = true;
  3084. wdBreakpoint->mHead = headBreakpoint;
  3085. }
  3086. if (onlyBindFirst)
  3087. break;
  3088. }
  3089. }
  3090. return;
  3091. }
  3092. BP_ZONE("WinDebugger::CheckBreakpoint");
  3093. // Rehup if we load a DLL that also uses this file we bound to (thus the mDeferredRefs check)
  3094. if (wdBreakpoint->mSrcFile == NULL)
  3095. {
  3096. DbgSrcFile* srcFile = mDebugTarget->GetSrcFile(wdBreakpoint->mFilePath);
  3097. if (srcFile == NULL)
  3098. return;
  3099. for (auto& deferredSrcFileRef : srcFile->mDeferredRefs)
  3100. {
  3101. deferredSrcFileRef.mDbgModule->ParseCompileUnit(deferredSrcFileRef.mCompileUnitId);
  3102. }
  3103. srcFile->mDeferredRefs.Clear();
  3104. CheckBreakpoint(wdBreakpoint, srcFile, wdBreakpoint->mRequestedLineNum, -1);
  3105. }
  3106. }
  3107. bool WinDebugger::IsMemoryBreakpointSizeValid(addr_target addr, int size)
  3108. {
  3109. int wantBindCount = 0;
  3110. int bytesLeft = size;
  3111. addr_target curAddr = addr;
  3112. for (int i = 0; i < 4; i++)
  3113. {
  3114. int curByteCount = 1;
  3115. #ifdef BF_DBG_64
  3116. if ((bytesLeft >= 8) && ((curAddr & 7) == 0))
  3117. curByteCount = 8;
  3118. else
  3119. #endif
  3120. if ((bytesLeft >= 4) && ((curAddr & 3) == 0))
  3121. curByteCount = 4;
  3122. else if ((bytesLeft >= 2) && ((curAddr & 1) == 0))
  3123. curByteCount = 2;
  3124. bytesLeft -= curByteCount;
  3125. curAddr += curByteCount;
  3126. if (bytesLeft == 0)
  3127. return true;
  3128. }
  3129. return false;
  3130. }
  3131. bool WinDebugger::HasMemoryBreakpoint(addr_target addr, int size)
  3132. {
  3133. for (int i = 0; i < 4; i++)
  3134. {
  3135. if ((mMemoryBreakpoints[i].mAddress == addr) &&
  3136. (mMemoryBreakpoints[i].mOfs == 0) &&
  3137. (mMemoryBreakpoints[i].mBreakpoint->mMemoryBreakpointInfo->mByteCount == size))
  3138. return true;
  3139. }
  3140. return false;
  3141. }
  3142. Breakpoint* WinDebugger::CreateBreakpoint(const StringImpl& fileName, int lineNum, int wantColumn, int instrOffset)
  3143. {
  3144. AutoCrit autoCrit(mDebugManager->mCritSect);
  3145. BfLogDbg("CreateBreakpoint %s %d %d\n", fileName.c_str(), lineNum, wantColumn);
  3146. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  3147. wdBreakpoint->mFilePath = FixPathAndCase(fileName);
  3148. wdBreakpoint->mRequestedLineNum = lineNum;
  3149. wdBreakpoint->mLineNum = lineNum;
  3150. wdBreakpoint->mColumn = wantColumn;
  3151. wdBreakpoint->mInstrOffset = instrOffset;
  3152. mBreakpoints.push_back(wdBreakpoint);
  3153. BfLogDbg("CreateBreakpoint Created %p\n", wdBreakpoint);
  3154. return wdBreakpoint;
  3155. }
  3156. void WinDebugger::CheckBreakpoint(Breakpoint* checkBreakpoint)
  3157. {
  3158. AutoCrit autoCrit(mDebugManager->mCritSect);
  3159. CheckBreakpoint((WdBreakpoint*)checkBreakpoint);
  3160. }
  3161. Breakpoint* WinDebugger::CreateMemoryBreakpoint(intptr addr, int byteCount)
  3162. {
  3163. AutoCrit autoCrit(mDebugManager->mCritSect);
  3164. BfLogDbg("CreateMemoryBreakpoint %p %d\n", addr, byteCount);
  3165. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  3166. WdMemoryBreakpointInfo* memoryBreakInfo = new WdMemoryBreakpointInfo();
  3167. memoryBreakInfo->mMemoryAddress = addr;
  3168. memoryBreakInfo->mByteCount = byteCount;
  3169. wdBreakpoint->mMemoryBreakpointInfo = memoryBreakInfo;
  3170. mBreakpoints.push_back(wdBreakpoint);
  3171. CheckBreakpoint(wdBreakpoint);
  3172. return wdBreakpoint;
  3173. }
  3174. Breakpoint* WinDebugger::CreateSymbolBreakpoint(const StringImpl& symbolName)
  3175. {
  3176. AutoCrit autoCrit(mDebugManager->mCritSect);
  3177. BfLogDbg("CreateSymbolBreakpoint %s\n", symbolName.c_str());
  3178. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  3179. wdBreakpoint->mSymbolName = symbolName;
  3180. mBreakpoints.push_back(wdBreakpoint);
  3181. CheckBreakpoint(wdBreakpoint);
  3182. return wdBreakpoint;
  3183. }
  3184. Breakpoint* WinDebugger::CreateAddressBreakpoint(intptr inAddress)
  3185. {
  3186. AutoCrit autoCrit(mDebugManager->mCritSect);
  3187. BfLogDbg("CreateAddressBreakpoint %p\n", inAddress);
  3188. addr_target address = (addr_target)inAddress;
  3189. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  3190. wdBreakpoint->mAddr = address;
  3191. mBreakpointAddrMap.ForceAdd(wdBreakpoint->mAddr, wdBreakpoint);
  3192. SetBreakpoint(address);
  3193. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mStoppedAtAddress == address))
  3194. {
  3195. BfLogDbg("CreateAddressBreakpoint setting mIsAtBreakpointAddress = %p\n", address);
  3196. mDebuggerWaitingThread->mIsAtBreakpointAddress = address;
  3197. }
  3198. mBreakpoints.push_back(wdBreakpoint);
  3199. return wdBreakpoint;
  3200. }
  3201. void WinDebugger::DeleteBreakpoint(Breakpoint* breakpoint)
  3202. {
  3203. AutoCrit autoCrit(mDebugManager->mCritSect);
  3204. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3205. while (wdBreakpoint != NULL)
  3206. {
  3207. BfLogDbg("WinDebugger::DeleteBreakpoint %p Count:%d\n", wdBreakpoint, mBreakpoints.size());
  3208. if (wdBreakpoint == mActiveBreakpoint)
  3209. mActiveBreakpoint = NULL;
  3210. if (wdBreakpoint->mCondition != NULL)
  3211. {
  3212. if (!wdBreakpoint->mIsLinkedSibling)
  3213. delete wdBreakpoint->mCondition;
  3214. }
  3215. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  3216. {
  3217. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  3218. {
  3219. if (mMemoryBreakpoints[memoryWatchSlot].mBreakpoint == wdBreakpoint)
  3220. {
  3221. mFreeMemoryBreakIndices.push_back(memoryWatchSlot);
  3222. mMemoryBreakpoints[memoryWatchSlot] = WdMemoryBreakpointBind();
  3223. mMemoryBreakpointVersion++;
  3224. UpdateThreadDebugRegisters();
  3225. }
  3226. }
  3227. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap = 0;
  3228. }
  3229. if (wdBreakpoint->mAddr != 0)
  3230. {
  3231. mBreakpointAddrMap.Remove(wdBreakpoint->mAddr, wdBreakpoint);
  3232. RemoveBreakpoint(wdBreakpoint->mAddr);
  3233. for (auto thread : mThreadList)
  3234. {
  3235. if (thread->mIsAtBreakpointAddress == wdBreakpoint->mAddr)
  3236. thread->mIsAtBreakpointAddress = NULL;
  3237. if (thread->mBreakpointAddressContinuing == wdBreakpoint->mAddr)
  3238. thread->mBreakpointAddressContinuing = NULL;
  3239. }
  3240. }
  3241. if (!wdBreakpoint->mIsLinkedSibling)
  3242. {
  3243. mBreakpoints.Remove(wdBreakpoint);
  3244. }
  3245. auto nextBreakpoint = (WdBreakpoint*)wdBreakpoint->mLinkedSibling;
  3246. delete wdBreakpoint;
  3247. wdBreakpoint = nextBreakpoint;
  3248. }
  3249. }
  3250. void WinDebugger::DetachBreakpoint(Breakpoint* breakpoint)
  3251. {
  3252. AutoCrit autoCrit(mDebugManager->mCritSect);
  3253. BfLogDbg("WinDebugger::DetachBreakpoint %p\n", breakpoint);
  3254. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3255. if (wdBreakpoint->mAddr != 0)
  3256. {
  3257. mBreakpointAddrMap.Remove(wdBreakpoint->mAddr, wdBreakpoint);
  3258. RemoveBreakpoint(wdBreakpoint->mAddr);
  3259. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mIsAtBreakpointAddress == wdBreakpoint->mAddr))
  3260. mDebuggerWaitingThread->mIsAtBreakpointAddress = NULL;
  3261. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mBreakpointAddressContinuing == wdBreakpoint->mAddr))
  3262. mDebuggerWaitingThread->mBreakpointAddressContinuing = NULL;
  3263. wdBreakpoint->mLineData = DbgLineDataEx();
  3264. wdBreakpoint->mAddr = 0;
  3265. }
  3266. if (wdBreakpoint->mCondition != NULL)
  3267. {
  3268. delete wdBreakpoint->mCondition->mDbgEvaluationContext;
  3269. wdBreakpoint->mCondition->mDbgEvaluationContext = NULL;
  3270. }
  3271. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  3272. {
  3273. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  3274. {
  3275. if (mMemoryBreakpoints[memoryWatchSlot].mBreakpoint == wdBreakpoint)
  3276. {
  3277. mFreeMemoryBreakIndices.push_back(memoryWatchSlot);
  3278. mMemoryBreakpoints[memoryWatchSlot] = WdMemoryBreakpointBind();
  3279. mMemoryBreakpointVersion++;
  3280. UpdateThreadDebugRegisters();
  3281. }
  3282. }
  3283. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap = 0;
  3284. }
  3285. if (wdBreakpoint->mLinkedSibling != NULL)
  3286. {
  3287. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  3288. wdBreakpoint->mLinkedSibling = NULL;
  3289. }
  3290. wdBreakpoint->mSrcFile = NULL;
  3291. wdBreakpoint->mPendingHotBindIdx = -1;
  3292. }
  3293. void WinDebugger::MoveBreakpoint(Breakpoint* breakpoint, int lineNum, int wantColumn, bool rebindNow)
  3294. {
  3295. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3296. AutoCrit autoCrit(mDebugManager->mCritSect);
  3297. DetachBreakpoint(wdBreakpoint);
  3298. //TODO: This doesn't actually rebind correctly while the app is running
  3299. if ((lineNum != -1) && (wantColumn != -1))
  3300. {
  3301. wdBreakpoint->mRequestedLineNum = lineNum;
  3302. wdBreakpoint->mLineNum = lineNum;
  3303. wdBreakpoint->mColumn = wantColumn;
  3304. }
  3305. if (rebindNow)
  3306. CheckBreakpoint(wdBreakpoint);
  3307. }
  3308. void WinDebugger::MoveMemoryBreakpoint(Breakpoint* breakpoint, intptr addr, int byteCount)
  3309. {
  3310. AutoCrit autoCrit(mDebugManager->mCritSect);
  3311. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3312. DetachBreakpoint(wdBreakpoint);
  3313. wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress = addr;
  3314. wdBreakpoint->mMemoryBreakpointInfo->mByteCount = byteCount;
  3315. CheckBreakpoint(wdBreakpoint);
  3316. }
  3317. void WinDebugger::DisableBreakpoint(Breakpoint* breakpoint)
  3318. {
  3319. AutoCrit autoCrit(mDebugManager->mCritSect);
  3320. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3321. DetachBreakpoint(wdBreakpoint);
  3322. delete wdBreakpoint->mMemoryBreakpointInfo;
  3323. wdBreakpoint->mMemoryBreakpointInfo = NULL;
  3324. }
  3325. void WinDebugger::SetBreakpointCondition(Breakpoint* breakpoint, const StringImpl& conditionExpr)
  3326. {
  3327. AutoCrit autoCrit(mDebugManager->mCritSect);
  3328. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3329. BF_ASSERT(!wdBreakpoint->mIsLinkedSibling);
  3330. if (conditionExpr.empty())
  3331. {
  3332. delete wdBreakpoint->mCondition;
  3333. WdBreakpoint* curBreakpoint = wdBreakpoint;
  3334. wdBreakpoint->mCondition = NULL;
  3335. }
  3336. else
  3337. {
  3338. delete wdBreakpoint->mCondition;
  3339. auto condition = new WdBreakpointCondition();
  3340. condition->mExpr = conditionExpr;
  3341. wdBreakpoint->mCondition = condition;
  3342. }
  3343. }
  3344. void WinDebugger::SetBreakpointLogging(Breakpoint* breakpoint, const StringImpl& logging, bool breakAfterLogging)
  3345. {
  3346. AutoCrit autoCrit(mDebugManager->mCritSect);
  3347. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3348. BF_ASSERT(!wdBreakpoint->mIsLinkedSibling);
  3349. wdBreakpoint->mLogging = logging;
  3350. wdBreakpoint->mBreakAfterLogging = breakAfterLogging;
  3351. }
  3352. bool WinDebugger::CheckConditionalBreakpoint(WdBreakpoint* breakpoint, DbgSubprogram* dbgSubprogram, addr_target pcAddress)
  3353. {
  3354. // What was this assertion for?
  3355. //BF_ASSERT(mCallStack.size() == 0);
  3356. auto headBreakpoint = breakpoint->GetHeadBreakpoint();
  3357. if (headBreakpoint->mThreadId != -1)
  3358. {
  3359. if ((mActiveThread != NULL) && (mActiveThread->mThreadId != headBreakpoint->mThreadId))
  3360. return false;
  3361. }
  3362. auto _SplitExpr = [&](const StringImpl& expr, StringImpl& outExpr, StringImpl& outSubject)
  3363. {
  3364. int crPos = expr.IndexOf('\n');
  3365. if (crPos != -1)
  3366. {
  3367. outExpr += expr.Substring(0, crPos);
  3368. outSubject += expr.Substring(crPos + 1);
  3369. }
  3370. else
  3371. {
  3372. outExpr += expr;
  3373. }
  3374. };
  3375. if (headBreakpoint->mCondition != NULL)
  3376. {
  3377. ClearCallStack();
  3378. auto conditional = headBreakpoint->mCondition;
  3379. if (conditional->mDbgEvaluationContext == NULL)
  3380. {
  3381. CPURegisters registers;
  3382. PopulateRegisters(&registers);
  3383. auto pcAddress = registers.GetPC();
  3384. DbgSubprogram* subprogram = mDebugTarget->FindSubProgram(pcAddress);
  3385. if (subprogram == NULL)
  3386. {
  3387. return false;
  3388. }
  3389. StringT<256> expr;
  3390. StringT<256> subjectExpr;
  3391. if (breakpoint->mMemoryBreakpointInfo != NULL)
  3392. {
  3393. subjectExpr += "*";
  3394. }
  3395. _SplitExpr(conditional->mExpr, expr, subjectExpr);
  3396. DbgLanguage language = DbgLanguage_Unknown;
  3397. if (expr.StartsWith("@Beef:"))
  3398. {
  3399. expr.Remove(0, 6);
  3400. language = DbgLanguage_Beef;
  3401. }
  3402. else if (expr.StartsWith("@C:"))
  3403. {
  3404. expr.Remove(0, 3);
  3405. language = DbgLanguage_C;
  3406. }
  3407. conditional->mDbgEvaluationContext = new DbgEvaluationContext(this, subprogram->mCompileUnit->mDbgModule, expr);
  3408. if (language != DbgLanguage_Unknown)
  3409. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mLanguage = language;
  3410. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mSubjectExpr = subjectExpr;
  3411. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mDbgCompileUnit = subprogram->mCompileUnit;
  3412. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mCallStackIdx = 0;
  3413. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mExpressionFlags = (DwEvalExpressionFlags)(DwEvalExpressionFlag_AllowSideEffects);
  3414. }
  3415. WdStackFrame* wdStackFrame = new WdStackFrame();
  3416. PopulateRegisters(&wdStackFrame->mRegisters);
  3417. mCallStack.Add(wdStackFrame);
  3418. DbgTypedValue result = conditional->mDbgEvaluationContext->EvaluateInContext(DbgTypedValue());
  3419. ClearCallStack();
  3420. if ((result.mType != NULL) && (result.mType->mTypeCode == DbgType_Bitfield))
  3421. result.mType = result.mType->mTypeParam;
  3422. if (conditional->mDbgEvaluationContext->mPassInstance->HasFailed())
  3423. {
  3424. String errorStr = "FAILED";
  3425. for (auto error : conditional->mDbgEvaluationContext->mPassInstance->mErrors)
  3426. {
  3427. if (!error->mIsWarning)
  3428. errorStr = error->mError;
  3429. }
  3430. String condError = StrFormat("error Conditional breakpoint expression '%s' failed: %s", conditional->mExpr.c_str(), errorStr.c_str());
  3431. mDebugManager->mOutMessages.push_back(condError);
  3432. return true;
  3433. }
  3434. else if (conditional->mDbgEvaluationContext->mDbgExprEvaluator->mBlockedSideEffects)
  3435. {
  3436. mDebugManager->mOutMessages.push_back(StrFormat("error Conditional breakpoint expression '%s' contained function calls, which is not allowed", conditional->mExpr.c_str()));
  3437. return true;
  3438. }
  3439. else if ((!result) || (!result.mType->IsBoolean()))
  3440. {
  3441. mDebugManager->mOutMessages.push_back(StrFormat("error Conditional breakpoint expression '%s' must result in a boolean value", conditional->mExpr.c_str()));
  3442. return true;
  3443. }
  3444. else if (!result.mBool)
  3445. return false;
  3446. }
  3447. headBreakpoint->mHitCount++;
  3448. switch (headBreakpoint->mHitCountBreakKind)
  3449. {
  3450. case DbgHitCountBreakKind_Equals:
  3451. if (headBreakpoint->mHitCount != headBreakpoint->mTargetHitCount)
  3452. return false;
  3453. break;
  3454. case DbgHitCountBreakKind_GreaterEquals:
  3455. if (headBreakpoint->mHitCount < headBreakpoint->mTargetHitCount)
  3456. return false;
  3457. break;
  3458. case DbgHitCountBreakKind_Multiple:
  3459. if ((headBreakpoint->mHitCount % headBreakpoint->mTargetHitCount) != 0)
  3460. return false;
  3461. break;
  3462. }
  3463. mActiveBreakpoint = breakpoint;
  3464. mBreakStackFrameIdx = -1;
  3465. if (!headBreakpoint->mLogging.IsEmpty())
  3466. {
  3467. ClearCallStack();
  3468. DwFormatInfo formatInfo;
  3469. formatInfo.mCallStackIdx = 0;
  3470. DbgCompileUnit* dbgCompileUnit = NULL;
  3471. if (dbgSubprogram == NULL)
  3472. dbgSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3473. if (dbgSubprogram != NULL)
  3474. {
  3475. dbgCompileUnit = dbgSubprogram->mCompileUnit;
  3476. formatInfo.mLanguage = dbgSubprogram->GetLanguage();
  3477. }
  3478. auto prevRunState = mRunState;
  3479. mRunState = RunState_Paused; // We need to be paused to avoid certain errors in the eval
  3480. String displayString;
  3481. String expr;
  3482. _SplitExpr(headBreakpoint->mLogging, expr, formatInfo.mSubjectExpr);
  3483. if (expr.StartsWith("@Script:"))
  3484. {
  3485. displayString = "script ";
  3486. displayString += expr.Substring(8);
  3487. }
  3488. else
  3489. {
  3490. if (expr.StartsWith("@Beef:"))
  3491. {
  3492. expr.Remove(0, 6);
  3493. formatInfo.mLanguage = DbgLanguage_Beef;
  3494. }
  3495. else if (expr.StartsWith("@C:"))
  3496. {
  3497. expr.Remove(0, 3);
  3498. formatInfo.mLanguage = DbgLanguage_C;
  3499. }
  3500. ProcessEvalString(dbgCompileUnit, DbgTypedValue(), expr, displayString, formatInfo, NULL, false);
  3501. mRunState = prevRunState;
  3502. displayString.Insert(0, "log ");
  3503. displayString.Append("\n");
  3504. }
  3505. mDebugManager->mOutMessages.push_back(displayString);
  3506. if (!headBreakpoint->mBreakAfterLogging)
  3507. return false;
  3508. }
  3509. return true;
  3510. }
  3511. void WinDebugger::CleanupDebugEval(bool restoreRegisters)
  3512. {
  3513. BfLogDbg("CleanupDebugEval ThreadId=%d\n", mDebugEvalThreadInfo.mThreadId);
  3514. WdThreadInfo* evalThreadInfo = NULL;
  3515. if (mThreadMap.TryGetValue(mDebugEvalThreadInfo.mThreadId, &evalThreadInfo))
  3516. {
  3517. if ((restoreRegisters) && (!mDbgBreak))
  3518. {
  3519. SetAndRestoreValue<WdThreadInfo*> activeThread(mActiveThread, evalThreadInfo);
  3520. RestoreAllRegisters();
  3521. // if (mRunState == RunState_Running_ToTempBreakpoint)
  3522. // mRunState = RunState_Paused;
  3523. }
  3524. evalThreadInfo->mStartSP = mDebugEvalThreadInfo.mStartSP;
  3525. evalThreadInfo->mStoppedAtAddress = mDebugEvalThreadInfo.mStoppedAtAddress;
  3526. evalThreadInfo->mIsAtBreakpointAddress = mDebugEvalThreadInfo.mIsAtBreakpointAddress;
  3527. evalThreadInfo->mBreakpointAddressContinuing = mDebugEvalThreadInfo.mBreakpointAddressContinuing;
  3528. }
  3529. delete mDebugPendingExpr;
  3530. mDebugPendingExpr = NULL;
  3531. mDebugEvalThreadInfo = WdThreadInfo();
  3532. OutputRawMessage("rehupLoc");
  3533. }
  3534. bool WinDebugger::FixCallStackIdx(int& callStackIdx)
  3535. {
  3536. callStackIdx = BF_MAX(callStackIdx, 0);
  3537. if (mCallStack.IsEmpty())
  3538. UpdateCallStack();
  3539. int stackSize = (int)mCallStack.size();
  3540. while (callStackIdx >= mCallStack.size())
  3541. {
  3542. UpdateCallStack();
  3543. if (stackSize == (int)mCallStack.size())
  3544. break; // Didn't change
  3545. stackSize = (int)mCallStack.size();
  3546. }
  3547. if (callStackIdx >= stackSize)
  3548. {
  3549. callStackIdx = 0;
  3550. return false;
  3551. }
  3552. return true;
  3553. }
  3554. bool WinDebugger::HasLineInfoAt(addr_target address)
  3555. {
  3556. BP_ZONE("WinDebugger::HasLineInfoAt");
  3557. DbgSubprogram* dbgSubprogram = NULL;
  3558. auto dwLineData = FindLineDataAtAddress(address, &dbgSubprogram);
  3559. return (dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dbgSubprogram->GetLineAddr(*dwLineData) == address);
  3560. }
  3561. void WinDebugger::StepLineTryPause(addr_target address, bool requireExactMatch)
  3562. {
  3563. if (mStepInAssembly)
  3564. return;
  3565. if (mStepLineData.mLineData != NULL)
  3566. {
  3567. DbgSubprogram* dbgSubprogram = NULL;
  3568. DbgSrcFile* dbgSrcFile = NULL;
  3569. auto dwLineData = FindLineDataAtAddress(address, &dbgSubprogram, &dbgSrcFile);
  3570. if ((dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && ((!requireExactMatch) || (dbgSubprogram->GetLineAddr(*dwLineData) == address)))
  3571. {
  3572. // "Invalid" line
  3573. if (dwLineData->mColumn == -1)
  3574. {
  3575. SetupStep(mStepType);
  3576. mRunState = RunState_Running;
  3577. return;
  3578. }
  3579. // If we're on the same line but a different column or a <= address then keep it keep looking
  3580. if ((dbgSrcFile == mStepLineData.GetSrcFile()) &&
  3581. ((!requireExactMatch) || (dwLineData != mStepLineData.mLineData) || (address <= mStepStartPC)) &&
  3582. (dwLineData->mLine == mStepLineData.mLineData->mLine))
  3583. {
  3584. SetupStep(mStepType);
  3585. mRunState = RunState_Running;
  3586. return;
  3587. }
  3588. }
  3589. }
  3590. mRunState = RunState_Paused;
  3591. }
  3592. void WinDebugger::BreakAll()
  3593. {
  3594. AutoCrit autoCrit(mDebugManager->mCritSect);
  3595. ::DebugBreakProcess(mProcessInfo.hProcess);
  3596. }
  3597. void WinDebugger::StepInto(bool inAssembly)
  3598. {
  3599. AutoCrit autoCrit(mDebugManager->mCritSect);
  3600. if (!TryRunContinue())
  3601. return;
  3602. BfLogDbg("StepInto\n");
  3603. mCurNoInfoStepTries = 0; // Reset
  3604. mStepInAssembly = inAssembly;
  3605. SetupStep(StepType_StepInto);
  3606. ContinueDebugEvent();
  3607. }
  3608. void WinDebugger::StepIntoSpecific(intptr inAddr)
  3609. {
  3610. addr_target addr = (addr_target)inAddr;
  3611. AutoCrit autoCrit(mDebugManager->mCritSect);
  3612. if (!TryRunContinue())
  3613. return;
  3614. BfLogDbg("StepIntoSpecific %p\n", addr);
  3615. mCurNoInfoStepTries = 0; // Reset
  3616. mStepInAssembly = false;
  3617. SetupStep(StepType_StepInto);
  3618. mIsStepIntoSpecific = true;
  3619. mStepType = StepType_StepInto_Unfiltered;
  3620. if (mStepStartPC != addr)
  3621. {
  3622. RemoveTempBreakpoints();
  3623. SetTempBreakpoint(addr);
  3624. mStepBreakpointAddrs.push_back(addr);
  3625. }
  3626. ContinueDebugEvent();
  3627. }
  3628. void WinDebugger::PushValue(CPURegisters* registers, int64 val)
  3629. {
  3630. addr_target* regSP = registers->GetSPRegisterRef();
  3631. *regSP -= sizeof(addr_target);
  3632. WriteMemory<addr_target>(*regSP, (addr_target)val);
  3633. }
  3634. void WinDebugger::PushValue(CPURegisters* registers, const DbgTypedValue& typedValue)
  3635. {
  3636. addr_target* regSP = registers->GetSPRegisterRef();
  3637. int byteCount = typedValue.mType->GetByteCount();
  3638. if ((byteCount == 8) || (sizeof(addr_target) == 8))
  3639. {
  3640. *regSP -= sizeof(int64);
  3641. addr_target val = typedValue.mInt64;
  3642. if (typedValue.mType->IsCompositeType())
  3643. val = typedValue.mSrcAddress;
  3644. WriteMemory<int64>(*regSP, val);
  3645. }
  3646. else
  3647. {
  3648. *regSP -= sizeof(int32);
  3649. addr_target val = typedValue.mInt32;
  3650. if (typedValue.mType->IsCompositeType())
  3651. val = typedValue.mSrcAddress;
  3652. WriteMemory<int32>(*regSP, val);
  3653. }
  3654. }
  3655. void WinDebugger::SetThisRegister(CPURegisters* registers, addr_target val)
  3656. {
  3657. #if BF_DBG_32
  3658. registers->mIntRegs.ecx = val;
  3659. #else
  3660. registers->mIntRegs.rcx = val;
  3661. #endif
  3662. }
  3663. void WinDebugger::AddParamValue(int paramIdx, bool hadThis, CPURegisters* registers, const DbgTypedValue& typedValue)
  3664. {
  3665. #if BF_DBG_32
  3666. PushValue(registers, typedValue);
  3667. #else
  3668. int regIdx = paramIdx + (hadThis ? 1 : 0);
  3669. if (typedValue.mType->IsFloat())
  3670. {
  3671. PushValue(registers, typedValue);
  3672. if (regIdx < 4)
  3673. {
  3674. if (typedValue.mType->mTypeCode == DbgType_Single)
  3675. {
  3676. registers->mXmmRegsArray[regIdx].f[0] = typedValue.mSingle;
  3677. }
  3678. else
  3679. {
  3680. registers->mXmmDRegsArray[regIdx].d[0] = typedValue.mDouble;
  3681. }
  3682. }
  3683. }
  3684. else
  3685. {
  3686. PushValue(registers, typedValue);
  3687. if (regIdx < 4)
  3688. {
  3689. int64 val;
  3690. if (typedValue.mType->IsCompositeType())
  3691. val = typedValue.mSrcAddress;
  3692. else
  3693. val = typedValue.mPtr;
  3694. if (regIdx == 0)
  3695. registers->mIntRegs.rcx = val;
  3696. else if (regIdx == 1)
  3697. registers->mIntRegs.rdx = val;
  3698. else if (regIdx == 2)
  3699. registers->mIntRegs.r8 = val;
  3700. else if (regIdx == 3)
  3701. registers->mIntRegs.r9 = val;
  3702. }
  3703. }
  3704. #endif
  3705. }
  3706. bool WinDebugger::CheckNeedsSRetArgument(DbgType* retType)
  3707. {
  3708. if (!retType->IsCompositeType())
  3709. return false;
  3710. if (retType->GetByteCount() == 0)
  3711. return false;
  3712. //TODO: Change when we change the calling convention
  3713. if (retType->GetLanguage() == DbgLanguage_Beef)
  3714. return true;
  3715. int retSize = retType->GetByteCount();
  3716. //TODO: Check for 'POD' type?
  3717. if ((retSize == 1) || (retSize == 2) || (retSize == 4) || (retSize == sizeof(addr_target)))
  3718. return false;
  3719. return true;
  3720. }
  3721. DbgTypedValue WinDebugger::ReadReturnValue(CPURegisters* registers, DbgType* type)
  3722. {
  3723. DbgTypedValue retValue;
  3724. if (type->IsFloat())
  3725. {
  3726. retValue.mType = type;
  3727. #if BF_DBG_32
  3728. retValue.mDouble = ConvertFloat80ToDouble(registers->mFpMmRegsArray[0].fp.fp80);
  3729. if (type->mSize == 4)
  3730. retValue.mSingle = (float)retValue.mDouble;
  3731. #else
  3732. if (retValue.mType->mTypeCode == DbgType_Single)
  3733. retValue.mSingle = registers->mXmmRegsArray[0].f[0];
  3734. else
  3735. retValue.mDouble = registers->mXmmDRegsArray[0].d[0];
  3736. #endif
  3737. }
  3738. else if (type->IsCompositeType())
  3739. {
  3740. retValue.mType = type;
  3741. if (CheckNeedsSRetArgument(type))
  3742. {
  3743. #ifdef BF_DBG_32
  3744. retValue.mSrcAddress = mSavedContext.Esp - BF_ALIGN(type->GetByteCount(), 16);
  3745. #else
  3746. retValue.mSrcAddress = mSavedContext.Rsp - BF_ALIGN(type->GetByteCount(), 16);
  3747. #endif
  3748. }
  3749. else
  3750. {
  3751. #ifdef BF_DBG_32
  3752. retValue.mInt32 = mSavedContext.Eax;
  3753. #else
  3754. retValue.mInt64 = mSavedContext.Rax;
  3755. #endif
  3756. }
  3757. }
  3758. else
  3759. {
  3760. #ifdef BF_DBG_32
  3761. retValue.mType = type;
  3762. retValue.mInt32 = registers->mIntRegs.eax;
  3763. if (type->mSize == 8)
  3764. (&retValue.mInt32)[1] = registers->mIntRegs.edx;
  3765. #else
  3766. retValue.mType = type;
  3767. retValue.mInt64 = registers->mIntRegs.rax;
  3768. #endif
  3769. return retValue;
  3770. }
  3771. return retValue;
  3772. }
  3773. bool WinDebugger::SetRegisters(CPURegisters* registers)
  3774. {
  3775. BF_CONTEXT lcContext;
  3776. lcContext.ContextFlags = BF_CONTEXT_CONTROL | BF_CONTEXT_INTEGER | BF_CONTEXT_FLOATING_POINT | BF_CONTEXT_EXTENDED_REGISTERS | BF_CONTEXT_SEGMENTS;
  3777. lcContext.ContextFlags |= BF_CONTEXT_EXCEPTION_REQUEST;
  3778. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  3779. #ifdef BF_DBG_32
  3780. lcContext.Eax = registers->mIntRegs.eax;
  3781. lcContext.Ecx = registers->mIntRegs.ecx;
  3782. lcContext.Edx = registers->mIntRegs.edx;
  3783. lcContext.Ebx = registers->mIntRegs.ebx;
  3784. lcContext.Esp = registers->mIntRegs.esp;
  3785. lcContext.Ebp = registers->mIntRegs.ebp;
  3786. lcContext.Esi = registers->mIntRegs.esi;
  3787. lcContext.Edi = registers->mIntRegs.edi;
  3788. lcContext.Eip = registers->mIntRegs.eip;
  3789. lcContext.EFlags = registers->mIntRegs.efl;
  3790. BF_ASSERT(sizeof(lcContext.FloatSave.RegisterArea) == sizeof(registers->mFpMmRegsArray));
  3791. memcpy(lcContext.FloatSave.RegisterArea, registers->mFpMmRegsArray, sizeof(lcContext.FloatSave.RegisterArea));
  3792. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 32*sizeof(float));
  3793. memcpy(&lcContext.ExtendedRegisters[160], registers->mXmmRegsArray, sizeof(registers->mXmmRegsArray));
  3794. #else
  3795. lcContext.Rax = registers->mIntRegs.rax;
  3796. lcContext.Rcx = registers->mIntRegs.rcx;
  3797. lcContext.Rdx = registers->mIntRegs.rdx;
  3798. lcContext.Rbx = registers->mIntRegs.rbx;
  3799. lcContext.Rsp = registers->mIntRegs.rsp;
  3800. lcContext.Rbp = registers->mIntRegs.rbp;
  3801. lcContext.Rsi = registers->mIntRegs.rsi;
  3802. lcContext.Rdi = registers->mIntRegs.rdi;
  3803. lcContext.Rip = registers->mIntRegs.rip;
  3804. lcContext.EFlags = (DWORD)registers->mIntRegs.efl;
  3805. lcContext.R8 = registers->mIntRegs.r8;
  3806. lcContext.R9 = registers->mIntRegs.r9;
  3807. lcContext.R10 = registers->mIntRegs.r10;
  3808. lcContext.R11 = registers->mIntRegs.r11;
  3809. lcContext.R12 = registers->mIntRegs.r12;
  3810. lcContext.R13 = registers->mIntRegs.r13;
  3811. lcContext.R14 = registers->mIntRegs.r14;
  3812. lcContext.R15 = registers->mIntRegs.r15;
  3813. for (int i = 0; i < 8; i++)
  3814. {
  3815. memcpy(&lcContext.FltSave.FloatRegisters[i], &registers->mFpMmRegsArray[i], 10);
  3816. }
  3817. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 64 * sizeof(float));
  3818. memcpy(BF_CONTEXT_XMMDATA(lcContext), registers->mXmmRegsArray, sizeof(registers->mXmmRegsArray));
  3819. #endif
  3820. //lcContext.ContextFlags |= BF_CONTEXT_EXCEPTION_REQUEST;
  3821. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  3822. return (lcContext.ContextFlags & (BF_CONTEXT_EXCEPTION_ACTIVE | BF_CONTEXT_SERVICE_ACTIVE)) == 0;
  3823. }
  3824. void WinDebugger::SaveAllRegisters()
  3825. {
  3826. BfLogDbg("SaveAllRegisters setting mSavedAtBreakpointAddress = %p\n", mActiveThread->mIsAtBreakpointAddress);
  3827. mSavedAtBreakpointAddress = mActiveThread->mIsAtBreakpointAddress;
  3828. mSavedBreakpointAddressContinuing = mActiveThread->mBreakpointAddressContinuing;
  3829. mSavedContext.ContextFlags = BF_CONTEXT_ALL;
  3830. BF_GetThreadContext(mActiveThread->mHThread, &mSavedContext);
  3831. }
  3832. void WinDebugger::RestoreAllRegisters()
  3833. {
  3834. BfLogDbg("RestoreAllRegisters setting mIsAtBreakpointAddress = %p\n", mSavedAtBreakpointAddress);
  3835. mActiveThread->mIsAtBreakpointAddress = mSavedAtBreakpointAddress;
  3836. mActiveThread->mBreakpointAddressContinuing = mSavedBreakpointAddressContinuing;
  3837. BF_SetThreadContext(mActiveThread->mHThread, &mSavedContext);
  3838. #ifdef BF_DBG_32
  3839. //TODO: Find the test that this was required for...
  3840. // if (mActiveThread->mIsAtBreakpointAddress == mSavedContext.Eip)
  3841. // {
  3842. // if (mRunState == RunState_Running_ToTempBreakpoint)
  3843. // mRunState = RunState_Paused;
  3844. // }
  3845. // else
  3846. // {
  3847. // SetTempBreakpoint(mSavedContext.Eip);
  3848. // mRunState = RunState_Running_ToTempBreakpoint;
  3849. // mStepType = StepType_ToTempBreakpoint;
  3850. // mSteppingThread = mActiveThread;
  3851. // }
  3852. #endif
  3853. }
  3854. void WinDebugger::OutputMessage(const StringImpl& msg)
  3855. {
  3856. if (this == NULL)
  3857. return;
  3858. AutoCrit autoCrit(mDebugManager->mCritSect);
  3859. mDebugManager->mOutMessages.push_back("msg " + msg);
  3860. }
  3861. void WinDebugger::OutputRawMessage(const StringImpl& msg)
  3862. {
  3863. if (this == NULL)
  3864. return;
  3865. AutoCrit autoCrit(mDebugManager->mCritSect);
  3866. mDebugManager->mOutMessages.push_back(msg);
  3867. }
  3868. void WinDebugger::SetRunState(RunState runState)
  3869. {
  3870. mRunState = runState;
  3871. }
  3872. bool WinDebugger::TryRunContinue()
  3873. {
  3874. if (mRunState == RunState_Exception)
  3875. {
  3876. mIsContinuingFromException = true;
  3877. mRunState = RunState_Paused;
  3878. }
  3879. if (((mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint)) && (mNeedsRehupBreakpoints))
  3880. RehupBreakpoints(true);
  3881. return true;
  3882. }
  3883. void WinDebugger::ClearStep()
  3884. {
  3885. BfLogDbg("ClearStep\n");
  3886. RemoveTempBreakpoints();
  3887. mOrigStepType = StepType_None;
  3888. mStepType = StepType_None;
  3889. mStepStartPC = 0;
  3890. mStepSP = 0;
  3891. mStepPC = 0;
  3892. mIsStepIntoSpecific = false;
  3893. mStepIsRecursing = false;
  3894. mStepStopOnNextInstruction = false;
  3895. mStepLineData = DbgLineDataEx();
  3896. }
  3897. bool WinDebugger::SetupStep(StepType stepType)
  3898. {
  3899. BP_ZONE("SetupStep");
  3900. RemoveTempBreakpoints();
  3901. if (mNeedsRehupBreakpoints)
  3902. RehupBreakpoints(true);
  3903. if (mOrigStepType == StepType_None)
  3904. mOrigStepType = stepType;
  3905. mStepType = stepType;
  3906. mSteppingThread = mActiveThread;
  3907. mStepSwitchedThreads = false;
  3908. mContinueFromBreakpointFailed = false;
  3909. CPURegisters registers;
  3910. PopulateRegisters(&registers);
  3911. addr_target pcAddress = registers.GetPC();
  3912. if (mStepLineData.IsNull())
  3913. {
  3914. DbgSubprogram* dbgSubprogram = NULL;
  3915. auto dbgLineData = FindLineDataAtAddress(pcAddress, &dbgSubprogram);
  3916. mStepLineData = DbgLineDataEx(dbgLineData, dbgSubprogram);
  3917. mStepStartPC = registers.GetPC();
  3918. }
  3919. bool isDeeper = mStepSP > registers.GetSP();
  3920. 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);
  3921. mStepSP = registers.GetSP();
  3922. mStepPC = registers.GetPC();
  3923. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_NoFrame) || (mStepType == StepType_StepOut_ThenInto))
  3924. {
  3925. if (mStepType != StepType_StepOut_NoFrame)
  3926. {
  3927. // Test for stepping out of an inline method
  3928. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3929. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL))
  3930. {
  3931. DbgSubprogram* topSubprogram = dwSubprogram->GetRootInlineParent();
  3932. if ((mOrigStepType == StepType_StepInto) || (mOrigStepType == StepType_StepInto_Unfiltered))
  3933. {
  3934. mStepType = mOrigStepType;
  3935. }
  3936. else
  3937. {
  3938. mStepType = StepType_StepOut_Inline;
  3939. // Set up pcAddress to detect recursion
  3940. //TODO: We can't set a physical breakpoint here because we will immediately hit it when attempting to step over an inlined method.
  3941. // An inlined method can't recurse anyway, but store the pcAddress in mTempBreakpoints because we still check that for recursion
  3942. // SetTempBreakpoint(pcAddress);
  3943. //mTempBreakpoint.push_back(pcAddress);
  3944. mStepBreakpointAddrs.push_back(pcAddress);
  3945. }
  3946. addr_target endAddress = dwSubprogram->mBlock.mHighPC;
  3947. if (dwSubprogram->mHasLineAddrGaps)
  3948. {
  3949. // Keep bumping out the address as long as we can find lines that contain the nextPC
  3950. addr_target nextAddr = pcAddress;
  3951. for (auto& lineInfo : topSubprogram->mLineInfo->mLines)
  3952. {
  3953. auto lineAddr = topSubprogram->GetLineAddr(lineInfo);
  3954. if ((nextAddr >= lineAddr) && (nextAddr < lineAddr + lineInfo.mContribSize))
  3955. {
  3956. auto ctx = topSubprogram->mLineInfo->mContexts[lineInfo.mCtxIdx];
  3957. if (ctx.mInlinee == dwSubprogram)
  3958. {
  3959. nextAddr = lineAddr + lineInfo.mContribSize;
  3960. }
  3961. }
  3962. }
  3963. if (nextAddr != pcAddress)
  3964. endAddress = nextAddr;
  3965. }
  3966. BfLogDbg("Stepping out of inlined method, end address: %p\n", endAddress);
  3967. SetTempBreakpoint(endAddress);
  3968. mStepBreakpointAddrs.push_back(endAddress);
  3969. addr_target decodeAddress = dwSubprogram->mBlock.mLowPC;
  3970. while (decodeAddress < endAddress)
  3971. {
  3972. CPUInst inst;
  3973. if (!mDebugTarget->DecodeInstruction(decodeAddress, &inst))
  3974. break;
  3975. addr_target targetAddress = inst.GetTarget();
  3976. // We need to find a targetAddress
  3977. if ((targetAddress != 0) &&
  3978. !((targetAddress >= dwSubprogram->mBlock.mLowPC) && (targetAddress < dwSubprogram->mBlock.mHighPC)) &&
  3979. ((targetAddress >= topSubprogram->mBlock.mLowPC) && (targetAddress < topSubprogram->mBlock.mHighPC)))
  3980. {
  3981. BfLogDbg("Stepping out of inlined method, branch address: %p\n", targetAddress);
  3982. SetTempBreakpoint(targetAddress);
  3983. mStepBreakpointAddrs.push_back(targetAddress);
  3984. }
  3985. decodeAddress += inst.GetLength();
  3986. }
  3987. return true;
  3988. }
  3989. }
  3990. if ((mStepType != StepType_StepOut_NoFrame) && (RollBackStackFrame(&registers, true)))
  3991. {
  3992. bool isStackAdjust = false;
  3993. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3994. if (dwSubprogram != NULL)
  3995. {
  3996. if ((strcmp(dwSubprogram->mName, "_chkstk") == 0) ||
  3997. (strcmp(dwSubprogram->mName, "__chkstk") == 0) ||
  3998. (strcmp(dwSubprogram->mName, "_alloca_probe") == 0))
  3999. isStackAdjust = true;
  4000. }
  4001. pcAddress = registers.GetPC();
  4002. if (isStackAdjust)
  4003. {
  4004. // We set it to zero so we never detect an "isDeeper" condition which would skip over the return-location breakpoint
  4005. mStepSP = 0;
  4006. }
  4007. else
  4008. {
  4009. addr_target oldAddress = pcAddress;
  4010. CPUInst inst;
  4011. while (true)
  4012. {
  4013. if (mStepInAssembly)
  4014. break;
  4015. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  4016. break;
  4017. if ((inst.IsBranch()) || (inst.IsCall()) || (inst.IsReturn()))
  4018. break;
  4019. #ifdef BF_DBG_32
  4020. if (!inst.StackAdjust(mStepSP))
  4021. break;
  4022. #endif
  4023. DbgSubprogram* checkSubprogram = NULL;
  4024. auto checkLineData = FindLineDataAtAddress(pcAddress, &checkSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  4025. if (checkLineData == NULL)
  4026. break;
  4027. if (checkSubprogram->GetLineAddr(*checkLineData) == pcAddress)
  4028. break;
  4029. pcAddress += inst.GetLength();
  4030. }
  4031. if (pcAddress != oldAddress)
  4032. {
  4033. BfLogDbg("Adjusting stepout address from %p to %p\n", oldAddress, pcAddress);
  4034. }
  4035. }
  4036. BfLogDbg("SetupStep Stepout SetTempBreakpoint %p\n", pcAddress);
  4037. SetTempBreakpoint(pcAddress);
  4038. mStepBreakpointAddrs.push_back(pcAddress);
  4039. if (mStepType != StepType_StepOut_ThenInto)
  4040. mStepType = StepType_StepOut;
  4041. }
  4042. else
  4043. {
  4044. // Try to handle the case where we just entered this call so the return address is the first entry on the stack
  4045. addr_target* regSP = registers.GetSPRegisterRef();
  4046. pcAddress = ReadMemory<addr_target>(*regSP);
  4047. *regSP += sizeof(addr_target);
  4048. if (mDebugTarget->FindSubProgram(pcAddress) != NULL)
  4049. {
  4050. BfLogDbg("SetupStep Stepout SetTempBreakpoint (2) %p\n", pcAddress);
  4051. SetTempBreakpoint(pcAddress);
  4052. mStepBreakpointAddrs.push_back(pcAddress);
  4053. if (mOrigStepType == StepType_StepInto)
  4054. mStepType = StepType_StepInto;
  4055. else
  4056. mStepType = StepType_StepOver;
  4057. return true;
  4058. }
  4059. else
  4060. {
  4061. // Just do stepovers until we eventually step out
  4062. //BF_DBG_FATAL("StepOut Failed");
  4063. BfLogDbg("StepOut Failed\n");
  4064. if (mLastValidStepIntoPC != 0)
  4065. {
  4066. BfLogDbg("Using mLastValidStepIntoPC: %p\n", mLastValidStepIntoPC);
  4067. if (mOrigStepType == StepType_StepInto)
  4068. mStepType = StepType_StepInto;
  4069. else
  4070. mStepType = StepType_StepOver;
  4071. SetTempBreakpoint(mLastValidStepIntoPC);
  4072. mStepBreakpointAddrs.push_back(0);
  4073. mStepBreakpointAddrs.push_back(mLastValidStepIntoPC);
  4074. mLastValidStepIntoPC = 0;
  4075. return true;
  4076. }
  4077. else
  4078. {
  4079. BfLogDbg("Stopping");
  4080. mStepType = StepType_None;
  4081. mRunState = RunState_Paused;
  4082. return true;
  4083. }
  4084. }
  4085. }
  4086. }
  4087. if ((mStepType != StepType_StepOut) && (mStepType != StepType_StepOut_ThenInto))
  4088. {
  4089. if (mDebuggerWaitingThread != mSteppingThread)
  4090. {
  4091. // We've switched threads, so there's a possible race condition:
  4092. // This new thread may already have an EXCEPTION_BREAKPOINT queued up so the PC is actually
  4093. // located one byte past the BREAK instruction, which is one byte into whatever instruction
  4094. // was previously there. We can't insert normal BREAK instructions because we don't know
  4095. // if the current PC is actually at an instruction start, so we do a single step with a
  4096. // slower stack call check to see if we need to step out after a "step over"
  4097. BfLogDbg("Step - switched threads mIsAtBreakpointAddress:%p\n", mSteppingThread->mIsAtBreakpointAddress);
  4098. mStepSwitchedThreads = true;
  4099. SingleStepX86();
  4100. return true;
  4101. }
  4102. bool breakOnNext = false;
  4103. int instIdx = 0;
  4104. for (instIdx = 0; true; instIdx++)
  4105. {
  4106. bool isAtLine = false;
  4107. DbgSubprogram* dwSubprogram = NULL;
  4108. auto dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  4109. isAtLine = (instIdx > 0) && (dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dwSubprogram->GetLineAddr(*dwLineData) == pcAddress);
  4110. // "Never step into" line
  4111. if ((dwLineData != NULL) && (dwLineData->mColumn == -2) && (stepType == StepType_StepInto))
  4112. stepType = StepType_StepOver;
  4113. CPUInst inst;
  4114. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  4115. {
  4116. BfLogDbg("Decode failed, set up SingleStepX86 %p\n", pcAddress);
  4117. SingleStepX86();
  4118. mStepStopOnNextInstruction = true;
  4119. return true;
  4120. }
  4121. if (instIdx > 256)
  4122. {
  4123. BfLogDbg("Too many SetupStep iterations");
  4124. breakOnNext = true;
  4125. }
  4126. if ((inst.IsReturn()) && (instIdx == 0) && (!mStepInAssembly))
  4127. {
  4128. // Do actual STEP OUT so we set up proper "stepping over unimportant post-return instructions"
  4129. if (stepType == StepType_StepInto)
  4130. return SetupStep(StepType_StepOut_ThenInto);
  4131. else
  4132. return SetupStep(StepType_StepOut);
  4133. }
  4134. if ((breakOnNext) || (mStepInAssembly) || (isAtLine) || (inst.IsBranch()) || (inst.IsCall()) || (inst.IsReturn()))
  4135. {
  4136. if (((instIdx == 0) || (mStepInAssembly)) && (!breakOnNext))
  4137. {
  4138. if ((stepType == StepType_StepOver) && (inst.IsCall()))
  4139. {
  4140. // Continue - sets a breakpoint on the call line to detect recursion.
  4141. // The next loop through will set a breakpoint on the line after the return
  4142. BfLogDbg("StepHadCall\n");
  4143. breakOnNext = true;
  4144. BfLogDbg("StepHadCall setting mIsAtBreakpointAddress = %p\n", pcAddress);
  4145. mSteppingThread->mIsAtBreakpointAddress = pcAddress;
  4146. SetTempBreakpoint(pcAddress);
  4147. mStepBreakpointAddrs.push_back(pcAddress);
  4148. }
  4149. else
  4150. {
  4151. if (inst.IsCall())
  4152. {
  4153. if ((mLastValidStepIntoPC == 0) || (dwSubprogram != NULL))
  4154. mLastValidStepIntoPC = pcAddress + inst.mSize;
  4155. }
  4156. if ((dwLineData != NULL) && (inst.IsBranch()))
  4157. {
  4158. addr_target targetAddr = inst.GetTarget();
  4159. if (targetAddr < dwSubprogram->GetLineAddr(*dwLineData))
  4160. {
  4161. // Jumping backwards, stop at next instruction
  4162. mStepStopOnNextInstruction = true;
  4163. }
  4164. }
  4165. bool isPrefixOnly = false;
  4166. if ((mStepInAssembly) && (stepType == StepType_StepOver) && (inst.IsRep(isPrefixOnly)))
  4167. {
  4168. if (isPrefixOnly)
  4169. {
  4170. CPUInst nextInst;
  4171. if (mDebugTarget->DecodeInstruction(pcAddress + inst.GetLength(), &nextInst))
  4172. {
  4173. if (nextInst.IsBranch())
  4174. {
  4175. // repne jmp - this appears in __chkstk (for example)
  4176. // We don't have a good way to "step over" this one, so just do a single step
  4177. }
  4178. else
  4179. {
  4180. // Step over the rep + target instruction
  4181. auto doneAddr = pcAddress + inst.GetLength() + nextInst.GetLength();
  4182. BfLogDbg("SetupStep SetTempBreakpoint %p\n", doneAddr);
  4183. SetTempBreakpoint(doneAddr);
  4184. mStepBreakpointAddrs.push_back(doneAddr);
  4185. break;
  4186. }
  4187. }
  4188. }
  4189. else
  4190. {
  4191. // Step over the instruction
  4192. auto doneAddr = pcAddress + inst.GetLength();
  4193. BfLogDbg("SetupStep SetTempBreakpoint %p\n", doneAddr);
  4194. SetTempBreakpoint(doneAddr);
  4195. mStepBreakpointAddrs.push_back(doneAddr);
  4196. break;
  4197. }
  4198. }
  4199. // Just step a single instruction
  4200. BfLogDbg("SetupStep SingleStepX86 %p\n", pcAddress);
  4201. SingleStepX86();
  4202. if (inst.IsReturn())
  4203. mStepStopOnNextInstruction = true;
  4204. break;
  4205. }
  4206. }
  4207. else
  4208. {
  4209. // Move us to this instruction so we can hardware single-step into it
  4210. BfLogDbg("SetupStep SetTempBreakpoint %p\n", pcAddress);
  4211. SetTempBreakpoint(pcAddress);
  4212. mStepBreakpointAddrs.push_back(pcAddress);
  4213. break;
  4214. }
  4215. }
  4216. // Not an interesting instruction - move to next
  4217. pcAddress += inst.mSize;
  4218. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress >= dwSubprogram->mBlock.mHighPC))
  4219. {
  4220. auto endAddress = dwSubprogram->mBlock.mHighPC;
  4221. BfLogDbg("Stepping past end of inlined method, end address: %p\n", endAddress);
  4222. mStepType = StepType_StepOut_Inline;
  4223. SetTempBreakpoint(endAddress);
  4224. mStepBreakpointAddrs.push_back(endAddress);
  4225. return true;
  4226. }
  4227. }
  4228. if (instIdx > 1)
  4229. BfLogDbg("SetupStep instIdx: %d\n", instIdx);
  4230. }
  4231. return true;
  4232. }
  4233. void WinDebugger::CheckNonDebuggerBreak()
  4234. {
  4235. enum MessageType
  4236. {
  4237. MessageType_None = 0,
  4238. MessageType_Error = 1,
  4239. MessageType_ProfilerCmd = 2
  4240. };
  4241. CPURegisters registers;
  4242. PopulateRegisters(&registers);
  4243. addr_target pcAddress = registers.GetPC();
  4244. addr_target debugMessageDataAddr = (addr_target)-1;
  4245. if (mDebugTarget->mTargetBinary != NULL)
  4246. {
  4247. mDebugTarget->mTargetBinary->ParseSymbolData();
  4248. debugMessageDataAddr = mDebugTarget->FindSymbolAddr("gBfDebugMessageData");
  4249. }
  4250. if (debugMessageDataAddr != (addr_target)-1)
  4251. {
  4252. struct BfDebugMessageData
  4253. {
  4254. int mMessageType; // 0 = none, 1 = error
  4255. int mStackWindbackCount;
  4256. int mBufParamLen;
  4257. addr_target mBufParam;
  4258. addr_target mPCOverride;
  4259. };
  4260. BfDebugMessageData messageData = ReadMemory<BfDebugMessageData>(debugMessageDataAddr);
  4261. WriteMemory<int>(debugMessageDataAddr, 0); // Zero out type so we won't trigger again
  4262. if (messageData.mMessageType != 0)
  4263. {
  4264. llvm::SmallVector<char, 4096> strBuf;
  4265. int strLen = messageData.mBufParamLen;
  4266. strBuf.resize(strLen + 1);
  4267. char* str = &strBuf[0];
  4268. str[strLen] = 0;
  4269. if (ReadMemory(messageData.mBufParam, strLen, str))
  4270. {
  4271. if (messageData.mMessageType == MessageType_Error)
  4272. {
  4273. mRequestedStackFrameIdx = messageData.mStackWindbackCount;
  4274. if (messageData.mPCOverride != 0)
  4275. {
  4276. mShowPCOverride = messageData.mPCOverride;
  4277. mRequestedStackFrameIdx = -2;
  4278. }
  4279. mDebugManager->mOutMessages.push_back(StrFormat("error %s", str));
  4280. }
  4281. else if (messageData.mMessageType == MessageType_ProfilerCmd)
  4282. {
  4283. // It's important to set this here, because we unlock the critSect during StopSampling and we can't have the
  4284. // IDE thinking that we're actually paused when it checks the mRunState
  4285. mRunState = RunState_Running;
  4286. char* cmd = strtok(str, "\t");
  4287. if (strcmp(cmd, "StartSampling") == 0)
  4288. {
  4289. char* sessionIdStr = strtok(NULL, "\t");
  4290. char* threadIdStr = strtok(NULL, "\t");
  4291. char* sampleRateStr = strtok(NULL, "\t");
  4292. char* descStr = strtok(NULL, "\t");
  4293. if (threadIdStr != NULL)
  4294. {
  4295. int threadId = atoi(threadIdStr);
  4296. int sampleRate = atoi(sampleRateStr);
  4297. int sessionId = atoi(sessionIdStr);
  4298. Profiler** profilerPtr;
  4299. if (mPendingProfilerMap.TryAdd(sessionId, NULL, &profilerPtr))
  4300. {
  4301. DbgProfiler* profiler = new DbgProfiler(this);
  4302. if (descStr != NULL)
  4303. profiler->mDescription = descStr;
  4304. if (sampleRate > 0)
  4305. profiler->mSamplesPerSecond = sampleRate;
  4306. profiler->Start();
  4307. *profilerPtr = profiler;
  4308. mDebugManager->mOutMessages.push_back("newProfiler");
  4309. mNewProfilerList.push_back(profiler);
  4310. }
  4311. }
  4312. }
  4313. else if (strcmp(cmd, "StopSampling") == 0)
  4314. {
  4315. char* sessionIdStr = strtok(NULL, "\t");
  4316. if (sessionIdStr != NULL)
  4317. {
  4318. int sessionId = atoi(sessionIdStr);
  4319. Profiler* profiler;
  4320. if (mPendingProfilerMap.Remove(sessionId, &profiler))
  4321. {
  4322. if (profiler->IsSampling())
  4323. {
  4324. // Need to unlock so we don't deadlock
  4325. mDebugManager->mCritSect.Unlock();
  4326. profiler->Stop();
  4327. mDebugManager->mCritSect.Lock();
  4328. }
  4329. }
  4330. }
  4331. }
  4332. else if (strcmp(cmd, "ClearSampling") == 0)
  4333. {
  4334. for (auto& kv : mPendingProfilerMap)
  4335. {
  4336. auto profiler = kv.mValue;
  4337. profiler->Clear();
  4338. }
  4339. }
  4340. else if (strcmp(cmd, "ClearOutput") == 0)
  4341. {
  4342. mDebugManager->mOutMessages.push_back("clearOutput");
  4343. }
  4344. }
  4345. return;
  4346. }
  4347. }
  4348. }
  4349. intptr_target objAddr;
  4350. auto dbgBreakKind = mDebugTarget->GetDbgBreakKind(pcAddress, &registers, &objAddr);
  4351. if (dbgBreakKind == DbgBreakKind_ObjectAccess)
  4352. {
  4353. String errorStr = "error Attempted to access deleted object";
  4354. String objectAddr = EncodeDataPtr((addr_target)objAddr, true);
  4355. errorStr += StrFormat("\x1LEAK\t(System.Object)%s\n (%s)%s\n", objectAddr.c_str(), "System.Object", objectAddr.c_str());
  4356. mDebugManager->mOutMessages.push_back(errorStr);
  4357. return;
  4358. }
  4359. else if (dbgBreakKind == DbgBreakKind_ArithmeticOverflow)
  4360. {
  4361. String errorStr = "error Arithmetic overflow detected";
  4362. mDebugManager->mOutMessages.push_back(errorStr);
  4363. return;
  4364. }
  4365. bool showMainThread = false;
  4366. String symbol;
  4367. addr_target offset;
  4368. DbgModule* dbgModule;
  4369. if (mDebugTarget->FindSymbolAt(pcAddress, &symbol, &offset, &dbgModule))
  4370. {
  4371. if ((symbol == "DbgBreakPoint") || (symbol == "RtlUserThreadStart") || (symbol == "RtlUserThreadStart@8"))
  4372. {
  4373. showMainThread = true;
  4374. }
  4375. }
  4376. #ifdef BF_DBG_32
  4377. else if ((dbgModule != NULL) && (dbgModule->mDisplayName.Equals("kernel32.dll", StringImpl::CompareKind_OrdinalIgnoreCase)))
  4378. {
  4379. showMainThread = true;
  4380. }
  4381. #endif
  4382. if (showMainThread)
  4383. {
  4384. // This is a manual break, show the main thread
  4385. mActiveThread = mThreadList.front();
  4386. if (mDebugPendingExpr != NULL)
  4387. {
  4388. for (auto thread : mThreadList)
  4389. {
  4390. if (thread->mThreadId == mDebugEvalThreadInfo.mThreadId)
  4391. {
  4392. mActiveThread = thread;
  4393. break;
  4394. }
  4395. }
  4396. }
  4397. }
  4398. }
  4399. bool WinDebugger::HasSteppedIntoCall()
  4400. {
  4401. // Some calls (like __chkstk) actually push results to the stack, so we need to check
  4402. // if we're REALLY deeper or not, by rolling back the callstack once
  4403. CPURegisters registers;
  4404. PopulateRegisters(&registers);
  4405. if (RollBackStackFrame(&registers, true))
  4406. {
  4407. // If the previous frames SP is equal or deeper than our step start then we are indeed inside a call!
  4408. if (mStepSP >= registers.GetSP())
  4409. return true;
  4410. }
  4411. return false;
  4412. }
  4413. void WinDebugger::StepOver(bool inAssembly)
  4414. {
  4415. AutoCrit autoCrit(mDebugManager->mCritSect);
  4416. BfLogDbg("StepOver\n");
  4417. if (!TryRunContinue())
  4418. return;
  4419. mCurNoInfoStepTries = 0; // Reset
  4420. mStepInAssembly = inAssembly;
  4421. SetupStep(StepType_StepOver);
  4422. ContinueDebugEvent();
  4423. }
  4424. void WinDebugger::StepOut(bool inAssembly)
  4425. {
  4426. AutoCrit autoCrit(mDebugManager->mCritSect);
  4427. BfLogDbg("StepOut\n");
  4428. if (!TryRunContinue())
  4429. return;
  4430. mCurNoInfoStepTries = 0; // Reset
  4431. mStepInAssembly = inAssembly;
  4432. SetupStep(StepType_StepOut);
  4433. ContinueDebugEvent();
  4434. }
  4435. void WinDebugger::SetNextStatement(bool inAssembly, const StringImpl& fileName, int64 lineNumOrAsmAddr, int wantColumn)
  4436. {
  4437. AutoCrit autoCrit(mDebugManager->mCritSect);
  4438. DbgSubprogram* subProgram = NULL;
  4439. if (!inAssembly)
  4440. {
  4441. if (mCallStack.size() == 0)
  4442. UpdateCallStack();
  4443. if (mCallStack.size() > 0)
  4444. {
  4445. UpdateCallStackMethod(0);
  4446. subProgram = mCallStack[0]->mSubProgram;
  4447. }
  4448. if (subProgram == NULL)
  4449. return;
  4450. }
  4451. DbgSubprogram* rootInlineParent = NULL;
  4452. if (subProgram != NULL)
  4453. rootInlineParent = subProgram->GetRootInlineParent();
  4454. String result;
  4455. if (mDebugTarget == NULL)
  4456. return;
  4457. DbgSrcFile* srcFile = NULL;
  4458. if (!fileName.IsEmpty())
  4459. {
  4460. srcFile = mDebugTarget->GetSrcFile(fileName);
  4461. if (srcFile == NULL)
  4462. return;
  4463. }
  4464. addr_target pcAddress = 0;
  4465. if (inAssembly)
  4466. {
  4467. pcAddress = lineNumOrAsmAddr;
  4468. }
  4469. else
  4470. {
  4471. int lineNum = (int)lineNumOrAsmAddr;
  4472. addr_target bestAddr[2] = { 0, 0 };
  4473. int checkLineNum[2] = { lineNum - 1, lineNum };
  4474. auto _CheckLineInfo = [&](DbgSubprogram* dbgSubprogram, DbgLineInfo* dbgLineInfo)
  4475. {
  4476. for (int iPass = 0; iPass < 2; ++iPass)
  4477. {
  4478. int bestLineOffset = 0x7FFFFFFF;
  4479. for (auto& lineData : dbgLineInfo->mLines)
  4480. {
  4481. auto addr = dbgSubprogram->GetLineAddr(lineData);
  4482. if ((addr < subProgram->mBlock.mLowPC) || (addr >= subProgram->mBlock.mHighPC))
  4483. continue;
  4484. int lineOffset = lineData.mLine - checkLineNum[iPass];
  4485. if ((lineOffset >= 0) && (lineOffset <= 6) && (lineOffset <= bestLineOffset))
  4486. {
  4487. if (lineOffset < bestLineOffset)
  4488. {
  4489. bestLineOffset = lineOffset;
  4490. bestAddr[iPass] = addr;
  4491. }
  4492. }
  4493. }
  4494. }
  4495. };
  4496. for (int checkHotIdx = -1; checkHotIdx < (int)srcFile->mHotReplacedDbgLineInfo.size(); checkHotIdx++)
  4497. {
  4498. if (checkHotIdx >= 0)
  4499. {
  4500. auto hotReplacedLineInfo = srcFile->mHotReplacedDbgLineInfo[checkHotIdx];
  4501. for (auto& hotReplacedEntry : hotReplacedLineInfo->mEntries)
  4502. {
  4503. _CheckLineInfo(hotReplacedEntry.mSubprogram, hotReplacedEntry.mLineInfo);
  4504. }
  4505. }
  4506. else
  4507. {
  4508. for (auto subprogram : srcFile->mLineDataRefs)
  4509. _CheckLineInfo(subprogram, subprogram->mLineInfo);
  4510. }
  4511. if (bestAddr[1] != 0)
  4512. break;
  4513. }
  4514. if (bestAddr[1] != 0)
  4515. {
  4516. const int kMaxAddrDist = 64; // within reasonable range
  4517. if ((bestAddr[0] != 0) && (bestAddr[1] - bestAddr[0] <= kMaxAddrDist))
  4518. {
  4519. addr_target addrStart = bestAddr[0];
  4520. addr_target addrEnd = bestAddr[1];
  4521. addr_target addr = addrStart;
  4522. BF_ASSERT(addrEnd - addr <= kMaxAddrDist);
  4523. addr_target lastOp = 0;
  4524. while (addr < addrEnd)
  4525. {
  4526. CPUInst inst;
  4527. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  4528. break;
  4529. lastOp = addr;
  4530. addr += inst.GetLength();
  4531. }
  4532. }
  4533. pcAddress = (uint64)bestAddr[1];
  4534. }
  4535. }
  4536. if (pcAddress)
  4537. {
  4538. BF_ASSERT(mActiveThread->mBreakpointAddressContinuing == 0);
  4539. mActiveThread->mIsAtBreakpointAddress = 0;
  4540. mActiveThread->mStoppedAtAddress = pcAddress;
  4541. if (mCallStack.size() == 0)
  4542. UpdateCallStack();
  4543. CPURegisters* regs = &mCallStack.front()->mRegisters;
  4544. *regs->GetPCRegisterRef() = pcAddress;
  4545. SetRegisters(regs);
  4546. WdBreakpoint* breakpoint = (WdBreakpoint*)FindBreakpointAt(pcAddress);
  4547. if (breakpoint != NULL)
  4548. {
  4549. BfLogDbg("SetNextStatement setting mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  4550. mActiveThread->mIsAtBreakpointAddress = breakpoint->mAddr;
  4551. }
  4552. }
  4553. }
  4554. bool WinDebugger::PopulateRegisters(CPURegisters* registers, BF_CONTEXT& lcContext)
  4555. {
  4556. #ifdef BF_DBG_32
  4557. registers->mIntRegs.eax = lcContext.Eax;
  4558. registers->mIntRegs.ecx = lcContext.Ecx;
  4559. registers->mIntRegs.edx = lcContext.Edx;
  4560. registers->mIntRegs.ebx = lcContext.Ebx;
  4561. registers->mIntRegs.esp = lcContext.Esp;
  4562. registers->mIntRegs.ebp = lcContext.Ebp;
  4563. registers->mIntRegs.esi = lcContext.Esi;
  4564. registers->mIntRegs.edi = lcContext.Edi;
  4565. registers->mIntRegs.eip = lcContext.Eip;
  4566. registers->mIntRegs.efl = lcContext.EFlags;
  4567. BF_ASSERT(sizeof(lcContext.FloatSave.RegisterArea) == sizeof(registers->mFpMmRegsArray));
  4568. memcpy(registers->mFpMmRegsArray, lcContext.FloatSave.RegisterArea, sizeof(lcContext.FloatSave.RegisterArea));
  4569. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 32 * sizeof(float));
  4570. memcpy(registers->mXmmRegsArray, &lcContext.ExtendedRegisters[160], sizeof(registers->mXmmRegsArray));
  4571. #else
  4572. registers->mIntRegs.rax = lcContext.Rax;
  4573. registers->mIntRegs.rcx = lcContext.Rcx;
  4574. registers->mIntRegs.rdx = lcContext.Rdx;
  4575. registers->mIntRegs.rbx = lcContext.Rbx;
  4576. registers->mIntRegs.rsp = lcContext.Rsp;
  4577. registers->mIntRegs.rbp = lcContext.Rbp;
  4578. registers->mIntRegs.rsi = lcContext.Rsi;
  4579. registers->mIntRegs.rdi = lcContext.Rdi;
  4580. registers->mIntRegs.rip = lcContext.Rip;
  4581. registers->mIntRegs.efl = lcContext.EFlags;
  4582. registers->mIntRegs.r8 = lcContext.R8;
  4583. registers->mIntRegs.r9 = lcContext.R9;
  4584. registers->mIntRegs.r10 = lcContext.R10;
  4585. registers->mIntRegs.r11 = lcContext.R11;
  4586. registers->mIntRegs.r12 = lcContext.R12;
  4587. registers->mIntRegs.r13 = lcContext.R13;
  4588. registers->mIntRegs.r14 = lcContext.R14;
  4589. registers->mIntRegs.r15 = lcContext.R15;
  4590. registers->mIntRegs.gs = lcContext.SegGs;
  4591. for (int i = 0; i < 8; i++)
  4592. {
  4593. memcpy(&registers->mFpMmRegsArray[i], &lcContext.FltSave.FloatRegisters[i], 10);
  4594. }
  4595. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 64 * sizeof(float));
  4596. memcpy(registers->mXmmRegsArray, BF_CONTEXT_XMMDATA(lcContext), sizeof(registers->mXmmRegsArray));
  4597. #endif
  4598. return (lcContext.ContextFlags & (BF_CONTEXT_EXCEPTION_ACTIVE | BF_CONTEXT_SERVICE_ACTIVE)) == 0;
  4599. }
  4600. bool WinDebugger::PopulateRegisters(CPURegisters* registers)
  4601. {
  4602. /*static bool sCheckedProcessorFeatures = false;
  4603. static bool sMmxAvailable = false;
  4604. static bool sXmmAvailable = false;
  4605. if (!sCheckedProcessorFeatures)
  4606. {
  4607. //CDH we don't do anything with these yet since we grab BF_CONTEXT_ALL anyway, but could be useful
  4608. sMmxAvailable = ::IsProcessorFeaturePresent(PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  4609. sXmmAvailable = ::IsProcessorFeaturePresent(PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  4610. sCheckedProcessorFeatures = true;
  4611. }*/
  4612. BF_ASSERT(registers != nullptr);
  4613. BF_CONTEXT lcContext;
  4614. lcContext.ContextFlags = BF_CONTEXT_ALL | BF_CONTEXT_EXCEPTION_REQUEST;
  4615. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4616. return PopulateRegisters(registers, lcContext);
  4617. }
  4618. bool WinDebugger::RollBackStackFrame(CPURegisters* registers, bool isStackStart)
  4619. {
  4620. BF_ASSERT(registers != nullptr);
  4621. return mDebugTarget->RollBackStackFrame(registers, NULL, isStackStart);
  4622. }
  4623. bool WinDebugger::SetHotJump(DbgSubprogram* oldSubprogram, addr_target newTarget, int newTargetSize)
  4624. {
  4625. BfLogDbg("SetHotJump %s %p->%p\n", oldSubprogram->mName, oldSubprogram->mBlock.mLowPC, newTarget);
  4626. //AutoCrit autoCrit(mDebugManager->mCritSect);
  4627. BF_ASSERT(mDebugManager->mCritSect.mLockCount == 1);
  4628. addr_target jmpInstStart = oldSubprogram->mBlock.mLowPC;
  4629. addr_target jmpInstEnd = jmpInstStart + sizeof(HotJumpOp);
  4630. if (jmpInstEnd > oldSubprogram->mBlock.mHighPC)
  4631. {
  4632. if ((oldSubprogram->mBlock.mHighPC - oldSubprogram->mBlock.mLowPC == 1) &&
  4633. (newTargetSize == 1))
  4634. return true; // Special case for just stub 'ret' methods
  4635. String err = StrFormat("Failed to hot replace method, method '%s' too small to insert hot thunk", oldSubprogram->ToString().c_str());
  4636. Fail(err);
  4637. return false;
  4638. }
  4639. if (oldSubprogram->mHotReplaceKind != DbgSubprogram::HotReplaceKind_Replaced)
  4640. {
  4641. for (int hotThreadIdx = 0; hotThreadIdx < (int)mHotThreadStates.size(); hotThreadIdx++)
  4642. {
  4643. auto& hotThreadState = mHotThreadStates[hotThreadIdx];
  4644. WdThreadInfo* threadInfo = NULL;
  4645. if (!mThreadMap.TryGetValue((uint32)hotThreadState.mThreadId, &threadInfo))
  4646. continue;
  4647. int tryStart = GetTickCount();
  4648. while ((hotThreadState.mRegisters.GetPC() >= jmpInstStart) && (hotThreadState.mRegisters.GetPC() < jmpInstEnd))
  4649. {
  4650. if (GetTickCount() - tryStart >= 8000)
  4651. {
  4652. Fail("Failed to hot replace method, can't move past prelude");
  4653. return false;
  4654. }
  4655. BfLogDbg("SetHotJump skipping through %p\n", hotThreadState.mRegisters.GetPC());
  4656. bool removedBreakpoint = false;
  4657. mActiveThread = threadInfo;
  4658. if ((mActiveThread->mStoppedAtAddress >= jmpInstStart) && (mActiveThread->mStoppedAtAddress < jmpInstEnd))
  4659. {
  4660. for (addr_target addr = jmpInstStart; addr < jmpInstEnd; addr++)
  4661. {
  4662. if (mPhysBreakpointAddrMap.ContainsKey(addr))
  4663. {
  4664. removedBreakpoint = true;
  4665. RemoveBreakpoint(addr);
  4666. }
  4667. }
  4668. }
  4669. RunState oldRunState = mRunState;
  4670. mRunState = RunState_HotStep;
  4671. if (mWantsDebugContinue)
  4672. {
  4673. mWantsDebugContinue = false;
  4674. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4675. mContinueEvent.Set();
  4676. }
  4677. BF_CONTEXT lcContext;
  4678. lcContext.ContextFlags = BF_CONTEXT_ALL;
  4679. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4680. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  4681. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  4682. ::ResumeThread(mActiveThread->mHThread);
  4683. BfLogDbg("ResumeThread %d\n", mActiveThread->mThreadId);
  4684. while (mRunState != RunState_Terminated)
  4685. {
  4686. mDebugManager->mCritSect.Unlock();
  4687. Sleep(0);
  4688. mDebugManager->mCritSect.Lock();
  4689. if (IsPaused())
  4690. break;
  4691. if (mWantsDebugContinue)
  4692. {
  4693. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4694. mWantsDebugContinue = false;
  4695. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4696. mContinueEvent.Set();
  4697. }
  4698. }
  4699. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4700. ::SuspendThread(mActiveThread->mHThread);
  4701. BfLogDbg("SuspendThread %d\n", mActiveThread->mThreadId);
  4702. mRunState = oldRunState;
  4703. if ((mRunState != RunState_Terminated) && (mRunState != RunState_Terminating))
  4704. {
  4705. if (!IsPaused())
  4706. {
  4707. BF_ASSERT(mWantsDebugContinue);
  4708. mWantsDebugContinue = false;
  4709. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4710. mContinueEvent.Set();
  4711. }
  4712. }
  4713. PopulateRegisters(&hotThreadState.mRegisters);
  4714. }
  4715. }
  4716. }
  4717. HotJumpOp jumpOp;
  4718. jumpOp.mOpCode = 0xE9;
  4719. jumpOp.mRelTarget = newTarget - oldSubprogram->mBlock.mLowPC - sizeof(HotJumpOp);
  4720. WriteMemory(oldSubprogram->mBlock.mLowPC, jumpOp);
  4721. ::FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)oldSubprogram->mBlock.mLowPC, sizeof(HotJumpOp));
  4722. return true;
  4723. }
  4724. DbgSubprogram* WinDebugger::TryFollowHotJump(DbgSubprogram* subprogram, addr_target addr)
  4725. {
  4726. if (subprogram->mHotReplaceKind != DbgSubprogram::HotReplaceKind_Replaced)
  4727. return subprogram;
  4728. if (addr != subprogram->mBlock.mLowPC)
  4729. return subprogram;
  4730. auto dbgModule = subprogram->mCompileUnit->mDbgModule;
  4731. HotJumpOp jumpOp = ReadMemory<HotJumpOp>(addr);
  4732. if (jumpOp.mOpCode != 0xE9)
  4733. return subprogram;
  4734. addr_target jumpAddr = addr + jumpOp.mRelTarget + sizeof(HotJumpOp);
  4735. auto jumpSubprogram = mDebugTarget->FindSubProgram(jumpAddr);
  4736. if (jumpSubprogram == NULL)
  4737. return subprogram;
  4738. return jumpSubprogram;
  4739. }
  4740. bool WinDebugger::ShouldShowStaticMember(DbgType* dbgType, DbgVariable* member)
  4741. {
  4742. // If locationData is non-null, that means it was added in addition to the static declaration in the CV type info,
  4743. // so only add the names from the type definition
  4744. auto flavor = dbgType->mCompileUnit->mDbgModule->mDbgFlavor;
  4745. return ((((dbgType->IsNamespace()) || (flavor != DbgFlavor_MS)) && ((member->mLocationData != NULL) || member->mIsConst)) ||
  4746. ((flavor == DbgFlavor_MS) && (member->mLocationData == NULL)));
  4747. }
  4748. String WinDebugger::GetMemberList(DbgType* dbgType, const StringImpl& expr, bool isPtr, bool isStatic, bool forceCast, bool isSplat, bool isReadOnly)
  4749. {
  4750. auto dbgModule = dbgType->GetDbgModule();
  4751. dbgType->PopulateType();
  4752. auto language = dbgType->GetLanguage();
  4753. if (!isStatic)
  4754. {
  4755. String retVal;
  4756. bool needsNewline = false;
  4757. bool isBfObject = false;
  4758. if (dbgType->IsBfObjectPtr())
  4759. {
  4760. isBfObject = true;
  4761. dbgType = dbgType->mTypeParam;
  4762. }
  4763. int baseIdx = 0;
  4764. for (auto baseTypeEntry : dbgType->mBaseTypes)
  4765. {
  4766. auto baseType = baseTypeEntry->mBaseType;
  4767. if ((baseType->mSize > 0) || (baseType->mTypeCode != DbgType_Struct) || (strcmp(baseType->mTypeName, "ValueType") != 0))
  4768. {
  4769. String baseTypeStr = baseType->ToStringRaw(language);
  4770. if (baseIdx > 0)
  4771. retVal += "\n";
  4772. if (isSplat)
  4773. retVal += "[base]\t((" + baseTypeStr + ")" + expr + "), nv";
  4774. else if (dbgType->WantsRefThis())
  4775. retVal += "[base]\t((" + baseTypeStr + ")this), nd, na, nv, this=" + expr;
  4776. else
  4777. retVal += "[base]\t((" + baseTypeStr + "*)this), nd, na, nv, this=" + expr;
  4778. if (isReadOnly)
  4779. retVal += ", ne";
  4780. }
  4781. needsNewline = true;
  4782. baseIdx++;
  4783. }
  4784. String thisExpr = expr;
  4785. String castString;
  4786. if (dbgType->IsBfObject())
  4787. {
  4788. auto ptrType = dbgType->GetDbgModule()->GetPointerType(dbgType);
  4789. castString = ptrType->ToStringRaw(language);
  4790. }
  4791. else
  4792. castString = dbgType->ToStringRaw(language);
  4793. bool hadStatics = false;
  4794. for (auto member : dbgType->mMemberList)
  4795. {
  4796. if (member->mMemberOffset < 0)
  4797. continue;
  4798. if (member->mIsStatic)
  4799. {
  4800. if (ShouldShowStaticMember(dbgType, member))
  4801. hadStatics = true;
  4802. }
  4803. else
  4804. {
  4805. bool ignoreMember = false;
  4806. if (member->mName != NULL)
  4807. {
  4808. if ((member->mName[0] == '?') ||
  4809. (member->mName[0] == '$') ||
  4810. (strncmp(member->mName, "_vptr$", 6) == 0))
  4811. ignoreMember = true;
  4812. }
  4813. if (!ignoreMember)
  4814. {
  4815. if (needsNewline)
  4816. retVal += "\n";
  4817. if (member->mName == NULL)
  4818. {
  4819. retVal += GetMemberList(member->mType, expr, isPtr, isStatic, forceCast, isSplat, isReadOnly);
  4820. }
  4821. else
  4822. {
  4823. retVal += String(member->mName);
  4824. if (isSplat)
  4825. {
  4826. retVal += "\t(" + thisExpr + ")." + String(member->mName);
  4827. // We don't want to rely on this being enforced here. For one, ref types shouldn't get ", ne" added,
  4828. // and this doesn't solve the issue of attempting to assign via the Immediate window
  4829. /*if (isReadOnly)
  4830. retVal += ", ne";*/
  4831. }
  4832. else
  4833. {
  4834. if (forceCast)
  4835. retVal += "\t((" + castString + ")this)." + String(member->mName);
  4836. else if ((member->mName[0] >= '0') && (member->mName[0] <= '9')) // Numbered tuple member?
  4837. retVal += "\tthis." + String(member->mName);
  4838. else
  4839. retVal += "\t" + String(member->mName);
  4840. retVal += ", this=" + thisExpr;
  4841. // if (isReadOnly)
  4842. // retVal += ", ne";
  4843. }
  4844. }
  4845. needsNewline = true;
  4846. }
  4847. }
  4848. }
  4849. if (hadStatics)
  4850. {
  4851. if (needsNewline)
  4852. retVal += "\n";
  4853. retVal += "Static values\t" + castString;
  4854. }
  4855. return retVal;
  4856. }
  4857. else
  4858. {
  4859. if (dbgType->IsBfObjectPtr())
  4860. dbgType = dbgType->mTypeParam;
  4861. String retVal;
  4862. String memberPrefix = expr;
  4863. bool needsNewline = false;
  4864. bool hadStatics = false;
  4865. for (auto member : dbgType->mMemberList)
  4866. {
  4867. if (member->mIsStatic)
  4868. {
  4869. if (ShouldShowStaticMember(dbgType, member))
  4870. {
  4871. if (needsNewline)
  4872. retVal += "\n";
  4873. retVal += String(member->mName) + "\t" + memberPrefix + "." + String(member->mName);
  4874. needsNewline = true;
  4875. }
  4876. }
  4877. }
  4878. return retVal;
  4879. }
  4880. return "";
  4881. }
  4882. bool WinDebugger::ParseFormatInfo(DbgModule* dbgModule, const StringImpl& formatInfoStr, DwFormatInfo* formatInfo, BfPassInstance* bfPassInstance, int* assignExprOffset, String* assignExprString, String* errorString, DbgTypedValue contextTypedValue)
  4883. {
  4884. String formatFlags = formatInfoStr;
  4885. if (assignExprOffset != NULL)
  4886. *assignExprOffset = -1;
  4887. while (formatFlags.length() > 0)
  4888. {
  4889. formatFlags = Trim(formatFlags);
  4890. if (formatFlags.IsEmpty())
  4891. break;
  4892. if (formatFlags[0] != ',')
  4893. {
  4894. return false;
  4895. }
  4896. else
  4897. {
  4898. int nextComma = formatFlags.IndexOf(',', 1);
  4899. int quotePos = formatFlags.IndexOf('"', 1);
  4900. if ((quotePos != -1) && (quotePos < nextComma))
  4901. {
  4902. int nextQuotePos = formatFlags.IndexOf('"', quotePos + 1);
  4903. if (nextQuotePos != -1)
  4904. nextComma = formatFlags.IndexOf(',', nextQuotePos + 1);
  4905. }
  4906. if (nextComma == -1)
  4907. nextComma = formatFlags.length();
  4908. String formatCmd = formatFlags.Substring(1, nextComma - 1);
  4909. formatCmd = Trim(formatCmd);
  4910. bool hadError = false;
  4911. if (strncmp(formatCmd.c_str(), "this=", 5) == 0)
  4912. {
  4913. formatCmd = formatFlags.Substring(1);
  4914. formatCmd = Trim(formatCmd);
  4915. String thisExpr = formatCmd.Substring(5);
  4916. if (thisExpr.empty())
  4917. break;
  4918. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, thisExpr, formatInfo);
  4919. formatInfo->mExplicitThis = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4920. if (dbgEvaluationContext.HadError())
  4921. {
  4922. if (errorString != NULL)
  4923. *errorString = dbgEvaluationContext.GetErrorStr();
  4924. return false;
  4925. }
  4926. formatFlags = thisExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4927. continue;
  4928. }
  4929. else if (strncmp(formatCmd.c_str(), "count=", 6) == 0)
  4930. {
  4931. formatCmd = formatFlags.Substring(1);
  4932. formatCmd = Trim(formatCmd);
  4933. String countExpr = formatCmd.Substring(6);
  4934. if (countExpr.empty())
  4935. break;
  4936. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4937. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4938. if ((countValue) && (countValue.mType->IsInteger()))
  4939. formatInfo->mOverrideCount = (intptr)countValue.GetInt64();
  4940. if (dbgEvaluationContext.HadError())
  4941. {
  4942. if (errorString != NULL)
  4943. *errorString = dbgEvaluationContext.GetErrorStr();
  4944. return false;
  4945. }
  4946. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4947. continue;
  4948. }
  4949. else if (strncmp(formatCmd.c_str(), "maxcount=", 9) == 0)
  4950. {
  4951. formatCmd = formatFlags.Substring(1);
  4952. formatCmd = Trim(formatCmd);
  4953. String countExpr = formatCmd.Substring(9);
  4954. if (countExpr.empty())
  4955. break;
  4956. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4957. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4958. if ((countValue) && (countValue.mType->IsInteger()))
  4959. formatInfo->mMaxCount = (intptr)countValue.GetInt64();
  4960. if (dbgEvaluationContext.HadError())
  4961. {
  4962. if (errorString != NULL)
  4963. *errorString = dbgEvaluationContext.GetErrorStr();
  4964. return false;
  4965. }
  4966. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4967. continue;
  4968. }
  4969. else if (strncmp(formatCmd.c_str(), "arraysize=", 10) == 0)
  4970. {
  4971. formatCmd = formatFlags.Substring(1);
  4972. formatCmd = Trim(formatCmd);
  4973. String countExpr = formatCmd.Substring(10);
  4974. if (countExpr.empty())
  4975. break;
  4976. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4977. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4978. if ((countValue) && (countValue.mType->IsInteger()))
  4979. formatInfo->mArrayLength = (intptr)countValue.GetInt64();
  4980. if (dbgEvaluationContext.HadError())
  4981. {
  4982. if (errorString != NULL)
  4983. *errorString = dbgEvaluationContext.GetErrorStr();
  4984. return false;
  4985. }
  4986. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4987. continue;
  4988. }
  4989. else if (strncmp(formatCmd.c_str(), "assign=", 7) == 0)
  4990. {
  4991. formatCmd = formatFlags.Substring(1);
  4992. formatCmd = Trim(formatCmd);
  4993. String assignExpr = formatCmd.Substring(7);
  4994. if (assignExpr.empty())
  4995. break;
  4996. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, assignExpr, formatInfo);
  4997. if (dbgEvaluationContext.HadError())
  4998. {
  4999. if (errorString != NULL)
  5000. *errorString = dbgEvaluationContext.GetErrorStr();
  5001. return false;
  5002. }
  5003. if (assignExprOffset != NULL)
  5004. {
  5005. //TODO: Keep track of the offset directly, this is a hack
  5006. *assignExprOffset = (int)formatInfoStr.IndexOf("assign=") + 7;
  5007. }
  5008. if (assignExprString != NULL)
  5009. *assignExprString = dbgEvaluationContext.mExprNode->ToString();
  5010. formatFlags = assignExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  5011. continue;
  5012. }
  5013. else if (strncmp(formatCmd.c_str(), "refid=", 6) == 0)
  5014. {
  5015. formatInfo->mReferenceId = formatCmd.Substring(6);
  5016. if ((formatInfo->mReferenceId.mLength >= 2) && (formatInfo->mReferenceId[0] == '\"'))
  5017. formatInfo->mReferenceId = formatInfo->mReferenceId.Substring(1, formatInfo->mReferenceId.length() - 2);
  5018. }
  5019. else if (strncmp(formatCmd.c_str(), "action=", 7) == 0)
  5020. {
  5021. formatInfo->mAction = formatCmd.Substring(7);
  5022. if ((formatInfo->mAction.mLength >= 2) && (formatInfo->mAction[0] == '\"'))
  5023. formatInfo->mAction = formatInfo->mReferenceId.Substring(1, formatInfo->mReferenceId.length() - 2);
  5024. }
  5025. else if (strncmp(formatCmd.c_str(), "_=", 2) == 0)
  5026. {
  5027. formatInfo->mSubjectExpr = formatCmd.Substring(2);
  5028. if ((formatInfo->mSubjectExpr.mLength >= 2) && (formatInfo->mSubjectExpr[0] == '\"'))
  5029. formatInfo->mSubjectExpr = formatInfo->mSubjectExpr.Substring(1, formatInfo->mSubjectExpr.length() - 2);
  5030. }
  5031. else if (strncmp(formatCmd.c_str(), "expectedType=", 13) == 0)
  5032. {
  5033. formatInfo->mExpectedType = formatCmd.Substring(13);
  5034. if ((formatInfo->mExpectedType.mLength >= 2) && (formatInfo->mExpectedType[0] == '\"'))
  5035. formatInfo->mExpectedType = formatInfo->mExpectedType.Substring(1, formatInfo->mExpectedType.length() - 2);
  5036. }
  5037. else if (strncmp(formatCmd.c_str(), "namespaceSearch=", 16) == 0)
  5038. {
  5039. formatInfo->mNamespaceSearch = formatCmd.Substring(16);
  5040. if ((formatInfo->mNamespaceSearch.mLength >= 2) && (formatInfo->mNamespaceSearch[0] == '\"'))
  5041. formatInfo->mNamespaceSearch = formatInfo->mNamespaceSearch.Substring(1, formatInfo->mNamespaceSearch.length() - 2);
  5042. }
  5043. else if (formatCmd == "d")
  5044. {
  5045. formatInfo->mDisplayType = DwDisplayType_Decimal;
  5046. }
  5047. else if (formatCmd == "x")
  5048. {
  5049. formatInfo->mDisplayType = DwDisplayType_HexLower;
  5050. }
  5051. else if (formatCmd == "X")
  5052. {
  5053. formatInfo->mDisplayType = DwDisplayType_HexUpper;
  5054. }
  5055. else if (formatCmd == "s")
  5056. {
  5057. formatInfo->mHidePointers = true;
  5058. formatInfo->mDisplayType = DwDisplayType_Ascii;
  5059. }
  5060. else if (formatCmd == "s8")
  5061. {
  5062. formatInfo->mHidePointers = true;
  5063. formatInfo->mDisplayType = DwDisplayType_Utf8;
  5064. }
  5065. else if (formatCmd == "s16")
  5066. {
  5067. formatInfo->mHidePointers = true;
  5068. formatInfo->mDisplayType = DwDisplayType_Utf16;
  5069. }
  5070. else if (formatCmd == "s32")
  5071. {
  5072. formatInfo->mHidePointers = true;
  5073. formatInfo->mDisplayType = DwDisplayType_Utf32;
  5074. }
  5075. else if (formatCmd == "nd")
  5076. {
  5077. formatInfo->mIgnoreDerivedClassInfo = true;
  5078. }
  5079. else if (formatCmd == "na")
  5080. {
  5081. formatInfo->mHidePointers = true;
  5082. }
  5083. else if (formatCmd == "nm")
  5084. {
  5085. formatInfo->mNoMembers = true;
  5086. }
  5087. else if (formatCmd == "ne")
  5088. {
  5089. formatInfo->mNoEdit = true;
  5090. }
  5091. else if (formatCmd == "nv")
  5092. {
  5093. formatInfo->mNoVisualizers = true;
  5094. }
  5095. else if (formatCmd == "rawStr")
  5096. {
  5097. formatInfo->mRawString = true;
  5098. }
  5099. else if (((!formatCmd.IsEmpty()) && ((formatCmd[0] >= '0') && (formatCmd[0] <= '9'))) ||
  5100. (formatCmd.StartsWith("(")))
  5101. {
  5102. String countExpr = formatCmd;
  5103. if (countExpr.empty())
  5104. break;
  5105. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  5106. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  5107. if ((countValue) && (countValue.mType->IsInteger()))
  5108. formatInfo->mArrayLength = (intptr)countValue.GetInt64();
  5109. if (dbgEvaluationContext.HadError())
  5110. {
  5111. if (errorString != NULL)
  5112. *errorString = dbgEvaluationContext.GetErrorStr();
  5113. return false;
  5114. }
  5115. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  5116. continue;
  5117. }
  5118. else
  5119. hadError = true;
  5120. if (hadError)
  5121. {
  5122. if (errorString != NULL)
  5123. *errorString = "Invalid format flags";
  5124. return false;
  5125. }
  5126. formatFlags = formatFlags.Substring(nextComma);
  5127. }
  5128. }
  5129. return true;
  5130. }
  5131. String WinDebugger::MaybeQuoteFormatInfoParam(const StringImpl& str)
  5132. {
  5133. bool needsQuote = false;
  5134. for (int i = 0; i < (int)str.length(); i++)
  5135. {
  5136. char c = str[i];
  5137. if (c == ',')
  5138. needsQuote = true;
  5139. }
  5140. if (!needsQuote)
  5141. return str;
  5142. String qStr = "\"";
  5143. qStr += str;
  5144. qStr += "\"";
  5145. return qStr;
  5146. }
  5147. DbgTypedValue WinDebugger::EvaluateInContext(DbgCompileUnit* dbgCompileUnit, const DbgTypedValue& contextTypedValue, const StringImpl& subExpr, DwFormatInfo* formatInfo, String* outReferenceId, String* outErrors)
  5148. {
  5149. DbgEvaluationContext dbgEvaluationContext(this, dbgCompileUnit->mDbgModule, subExpr, formatInfo, contextTypedValue);
  5150. if (dbgEvaluationContext.mDbgExprEvaluator == NULL)
  5151. return DbgTypedValue();
  5152. dbgEvaluationContext.mDbgExprEvaluator->mDbgCompileUnit = dbgCompileUnit;
  5153. if (formatInfo != NULL)
  5154. {
  5155. dbgEvaluationContext.mDbgExprEvaluator->mLanguage = formatInfo->mLanguage;
  5156. dbgEvaluationContext.mDbgExprEvaluator->mSubjectExpr = formatInfo->mSubjectExpr;
  5157. }
  5158. dbgEvaluationContext.mDbgExprEvaluator->mReferenceId = outReferenceId;
  5159. auto result = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  5160. if ((formatInfo != NULL) && (dbgEvaluationContext.mDbgExprEvaluator->mCountResultOverride != -1))
  5161. formatInfo->mOverrideCount = dbgEvaluationContext.mDbgExprEvaluator->mCountResultOverride;
  5162. if (dbgEvaluationContext.mPassInstance->HasFailed())
  5163. {
  5164. if (outErrors != NULL)
  5165. {
  5166. int errIdx = 0;
  5167. for (auto err : dbgEvaluationContext.mPassInstance->mErrors)
  5168. {
  5169. if (errIdx > 0)
  5170. (*outErrors) += "\n";
  5171. (*outErrors) += err->mError;
  5172. errIdx++;
  5173. }
  5174. }
  5175. return DbgTypedValue();
  5176. }
  5177. return result;
  5178. }
  5179. void WinDebugger::DbgVisFailed(DebugVisualizerEntry* debugVis, const StringImpl& evalString, const StringImpl& errors)
  5180. {
  5181. bool onlyMemError = errors.StartsWith("Failed to read") && !errors.Contains('\n');
  5182. if ((!debugVis->mShowedError) && (!onlyMemError))
  5183. {
  5184. debugVis->mShowedError = true;
  5185. String errStr = StrFormat("DbgVis '%s' failed while evaluating condition '%s'\n", debugVis->mName.c_str(), evalString.c_str());
  5186. String spacedErrors = errors;
  5187. spacedErrors.Insert(0, " ");
  5188. spacedErrors.Replace("\n", "\n ");
  5189. errStr += spacedErrors;
  5190. OutputMessage(errStr);
  5191. }
  5192. }
  5193. bool WinDebugger::EvalCondition(DebugVisualizerEntry* debugVis, DbgCompileUnit* dbgCompileUnit, DbgTypedValue typedVal, DwFormatInfo& formatInfo, const StringImpl& condition, const Array<String>& dbgVisWildcardCaptures, String& errorStr)
  5194. {
  5195. DwFormatInfo displayStrFormatInfo = formatInfo;
  5196. displayStrFormatInfo.mHidePointers = false;
  5197. displayStrFormatInfo.mRawString = false;
  5198. String errors;
  5199. const String conditionStr = mDebugManager->mDebugVisualizers->DoStringReplace(condition, dbgVisWildcardCaptures);
  5200. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, typedVal, conditionStr, &displayStrFormatInfo, NULL, &errors);
  5201. if ((!evalResult) || (!evalResult.mType->IsBoolean()))
  5202. {
  5203. if (formatInfo.mRawString)
  5204. return false;
  5205. errorStr += "<DbgVis Failed>";
  5206. DbgVisFailed(debugVis, conditionStr, errors);
  5207. return false;
  5208. }
  5209. return evalResult.mBool;
  5210. }
  5211. String WinDebugger::GetArrayItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgType* valueType, DbgTypedValue& curNode, int& count, String* outContinuationData)
  5212. {
  5213. DbgEvaluationContext conditionEvaluationContext(this, dbgCompileUnit, debugVis->mCondition);
  5214. String addrs;
  5215. bool checkLeft = true;
  5216. int usedCount = 0;
  5217. while (usedCount < count)
  5218. {
  5219. DbgTypedValue condVal = conditionEvaluationContext.EvaluateInContext(curNode);
  5220. if (!condVal)
  5221. break;
  5222. if (condVal.mBool)
  5223. {
  5224. auto val = curNode;
  5225. if (valueType == NULL)
  5226. {
  5227. String typeAddr = val.mType->ToStringRaw();
  5228. // RPad
  5229. typeAddr.Append(' ', sizeof(addr_target) * 2 - typeAddr.length());
  5230. addrs += typeAddr;
  5231. }
  5232. String addr = EncodeDataPtr(val.mPtr, false);
  5233. addrs += addr;
  5234. usedCount++;
  5235. }
  5236. curNode.mPtr += curNode.mType->mTypeParam->GetStride();
  5237. }
  5238. count = usedCount;
  5239. if (outContinuationData != NULL)
  5240. {
  5241. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(valueType, false) +
  5242. EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  5243. }
  5244. return addrs;
  5245. }
  5246. String WinDebugger::GetLinkedListItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, addr_target endNodePtr, DbgType* valueType, DbgTypedValue& curNode, int& count, String* outContinuationData)
  5247. {
  5248. DbgEvaluationContext nextEvaluationContext(this, dbgCompileUnit, debugVis->mNextPointer);
  5249. DbgEvaluationContext valueEvaluationContext(this, dbgCompileUnit, debugVis->mValuePointer);
  5250. String addrs;
  5251. bool checkLeft = true;
  5252. int mapIdx;
  5253. for (mapIdx = 0; mapIdx < count; mapIdx++)
  5254. {
  5255. if (curNode.mPtr == endNodePtr)
  5256. break;
  5257. DbgTypedValue val = valueEvaluationContext.EvaluateInContext(curNode);
  5258. if (!val)
  5259. break;
  5260. if (val.mPtr == 0)
  5261. break;
  5262. if (valueType == NULL)
  5263. {
  5264. String typeAddr = val.mType->ToStringRaw();
  5265. // RPad
  5266. typeAddr.Append(' ', sizeof(addr_target)*2 - typeAddr.length());
  5267. addrs += typeAddr;
  5268. }
  5269. String addr = EncodeDataPtr(val.mPtr, false);
  5270. addrs += addr;
  5271. curNode = nextEvaluationContext.EvaluateInContext(curNode);
  5272. }
  5273. count = mapIdx;
  5274. if (outContinuationData != NULL)
  5275. {
  5276. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(endNodePtr, false) + EncodeDataPtr(valueType, false) +
  5277. EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  5278. }
  5279. return addrs;
  5280. }
  5281. String WinDebugger::GetDictionaryItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgTypedValue dictValue, int bucketIdx, int nodeIdx, int& count, String* outContinuationData)
  5282. {
  5283. //DbgEvaluationContext bucketsEvaluationContext(this, dbgModule, debugVis->mBuckets);
  5284. DbgEvaluationContext nextEvaluationContext(this, dbgCompileUnit->mDbgModule, debugVis->mNextPointer);
  5285. DbgTypedValue bucketsPtr = EvaluateInContext(dbgCompileUnit, dictValue, debugVis->mBuckets);
  5286. DbgTypedValue entriesPtr = EvaluateInContext(dbgCompileUnit, dictValue, debugVis->mEntries);
  5287. if ((!bucketsPtr) || (!entriesPtr))
  5288. {
  5289. count = -1;
  5290. return "";
  5291. }
  5292. int entrySize = entriesPtr.mType->mTypeParam->GetStride();
  5293. int bucketIdxSize = bucketsPtr.mType->mTypeParam->GetStride();
  5294. String addrs;
  5295. bool checkLeft = true;
  5296. int encodeCount = 0;
  5297. while (encodeCount < count)
  5298. {
  5299. if (nodeIdx != -1)
  5300. {
  5301. DbgTypedValue entryValue;
  5302. entryValue.mSrcAddress = entriesPtr.mPtr + (nodeIdx * entrySize);
  5303. entryValue.mType = entriesPtr.mType->mTypeParam;
  5304. addrs += EncodeDataPtr(entryValue.mSrcAddress, false);
  5305. DbgTypedValue nextValue = nextEvaluationContext.EvaluateInContext(entryValue);
  5306. if ((!nextValue) || (!nextValue.mType->IsInteger()))
  5307. {
  5308. break;
  5309. }
  5310. nodeIdx = (int)nextValue.GetInt64();
  5311. encodeCount++;
  5312. }
  5313. else
  5314. {
  5315. if (bucketIdxSize == 4)
  5316. nodeIdx = ReadMemory<int>(bucketsPtr.mPtr + bucketIdx * sizeof(int32));
  5317. else
  5318. nodeIdx = (int)ReadMemory<int64>(bucketsPtr.mPtr + bucketIdx * sizeof(int64));
  5319. bucketIdx++;
  5320. }
  5321. }
  5322. count = encodeCount;
  5323. //count = mapIdx;
  5324. if (outContinuationData != NULL)
  5325. {
  5326. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(dictValue.mType, false) + EncodeDataPtr(dictValue.mSrcAddress, false) +
  5327. EncodeDataPtr((addr_target)bucketIdx, false) + EncodeDataPtr((addr_target)nodeIdx, false);
  5328. }
  5329. return addrs;
  5330. }
  5331. String WinDebugger::GetTreeItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, Array<addr_target>& parentList, DbgType*& valueType, DbgTypedValue& curNode, int count, String* outContinuationData)
  5332. {
  5333. DbgEvaluationContext leftEvaluationContext(this, dbgCompileUnit, debugVis->mLeftPointer);
  5334. DbgEvaluationContext rightEvaluationContext(this, dbgCompileUnit, debugVis->mRightPointer);
  5335. DbgEvaluationContext valueEvaluationContext(this, dbgCompileUnit, debugVis->mValuePointer);
  5336. DbgEvaluationContext conditionEvaluationContext(this, dbgCompileUnit, debugVis->mCondition);
  5337. String addrs;
  5338. bool checkLeft = true;
  5339. if ((curNode.mPtr & 2) != 0) // Flag from continuation
  5340. {
  5341. checkLeft = false;
  5342. curNode.mPtr &= (addr_target)~2;
  5343. }
  5344. HashSet<intptr> seenAddrs;
  5345. for (int mapIdx = 0; mapIdx < count; mapIdx++)
  5346. {
  5347. DbgTypedValue readNode;
  5348. while (true)
  5349. {
  5350. bool checkNode = (curNode.mPtr & 1) == 0;
  5351. readNode = curNode;
  5352. readNode.mPtr &= (addr_target)~1;
  5353. if (checkLeft)
  5354. {
  5355. DbgTypedValue leftValue = leftEvaluationContext.EvaluateInContext(readNode);
  5356. bool isEmpty = leftValue.mPtr == NULL;
  5357. if ((leftValue) && (conditionEvaluationContext.HasExpression()))
  5358. {
  5359. auto condValue = conditionEvaluationContext.EvaluateInContext(leftValue);
  5360. if (condValue)
  5361. isEmpty = !condValue.mBool;
  5362. }
  5363. if (isEmpty)
  5364. {
  5365. checkLeft = false;
  5366. break; // Handle node
  5367. }
  5368. parentList.push_back(curNode.mPtr);
  5369. curNode = leftValue;
  5370. }
  5371. else if (checkNode)
  5372. {
  5373. break; // Handle node
  5374. }
  5375. else
  5376. {
  5377. DbgTypedValue rightValue = rightEvaluationContext.EvaluateInContext(readNode);
  5378. bool isEmpty = rightValue.mPtr == NULL;
  5379. if ((rightValue) && (conditionEvaluationContext.HasExpression()))
  5380. {
  5381. auto condValue = conditionEvaluationContext.EvaluateInContext(rightValue);
  5382. if (condValue)
  5383. isEmpty = !condValue.mBool;
  5384. }
  5385. if (!isEmpty)
  5386. {
  5387. curNode = rightValue;
  5388. checkLeft = true;
  5389. }
  5390. else
  5391. {
  5392. if (parentList.size() == 0)
  5393. {
  5394. // Failed
  5395. break;
  5396. }
  5397. curNode.mPtr = parentList.back();
  5398. parentList.pop_back();
  5399. continue; // Don't check against seenAddrs
  5400. }
  5401. }
  5402. if (!seenAddrs.Add(curNode.mPtr))
  5403. {
  5404. // Failed!
  5405. return "";
  5406. }
  5407. }
  5408. DbgTypedValue val = valueEvaluationContext.EvaluateInContext(readNode);
  5409. if (valueType == NULL)
  5410. valueType = val.mType;
  5411. String addr = EncodeDataPtr(val.mPtr, false);
  5412. addrs += addr;
  5413. curNode.mPtr |= 1; // Node handled
  5414. }
  5415. if (!checkLeft)
  5416. curNode.mPtr |= 2;
  5417. if (outContinuationData != NULL)
  5418. {
  5419. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(valueType, false) + EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  5420. for (auto parent : parentList)
  5421. *outContinuationData += EncodeDataPtr(parent, false);
  5422. }
  5423. return addrs;
  5424. }
  5425. String WinDebugger::GetCollectionContinuation(const StringImpl& continuationData, int callStackIdx, int count)
  5426. {
  5427. DbgCompileUnit* dbgCompileUnit = GetCallStackCompileUnit(callStackIdx);;
  5428. if (!IsPaused())
  5429. return "";
  5430. const char* dataPtr = continuationData.c_str();
  5431. DebugVisualizerEntry* debugVis = (DebugVisualizerEntry*)DecodeLocalDataPtr(dataPtr);
  5432. if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_TreeItems)
  5433. {
  5434. DbgType* valueType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5435. DbgTypedValue curNode;
  5436. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5437. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5438. Array<addr_target> parentList;
  5439. String newContinuationData;
  5440. while (*dataPtr != 0)
  5441. parentList.push_back(DecodeTargetDataPtr(dataPtr));
  5442. String retVal = GetTreeItems(dbgCompileUnit, debugVis, parentList, valueType, curNode, count, &newContinuationData);
  5443. retVal += "\n" + newContinuationData;
  5444. return retVal;
  5445. }
  5446. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_LinkedList)
  5447. {
  5448. addr_target endNodePtr = DecodeTargetDataPtr(dataPtr);
  5449. DbgType* valueType = (DbgType*) DecodeLocalDataPtr(dataPtr);
  5450. DbgTypedValue curNode;
  5451. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5452. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5453. String newContinuationData;
  5454. if (count < 0)
  5455. count = 3;
  5456. String retVal = GetLinkedListItems(dbgCompileUnit, debugVis, endNodePtr, valueType, curNode, count, &newContinuationData);
  5457. retVal += "\n" + newContinuationData;
  5458. return retVal;
  5459. }
  5460. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Array)
  5461. {
  5462. DbgType* valueType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5463. DbgTypedValue curNode;
  5464. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5465. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5466. String newContinuationData;
  5467. if (count < 0)
  5468. count = 3;
  5469. String retVal = GetArrayItems(dbgCompileUnit, debugVis, valueType, curNode, count, &newContinuationData);
  5470. retVal += "\n" + newContinuationData;
  5471. return retVal;
  5472. }
  5473. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Dictionary)
  5474. {
  5475. DbgTypedValue dictValue;
  5476. dictValue.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5477. dictValue.mSrcAddress = DecodeTargetDataPtr(dataPtr);
  5478. int bucketIdx = (int)DecodeTargetDataPtr(dataPtr);
  5479. int nodeIdx = (int)DecodeTargetDataPtr(dataPtr);
  5480. String newContinuationData;
  5481. String retVal = GetDictionaryItems(dbgCompileUnit, debugVis, dictValue, bucketIdx, nodeIdx, count, &newContinuationData);
  5482. retVal += "\n" + newContinuationData;
  5483. return retVal;
  5484. }
  5485. return "";
  5486. }
  5487. template <typename T>
  5488. static String IntTypeToString(T val, const StringImpl& name, DwDisplayInfo* displayInfo, DwFormatInfo& formatInfo)
  5489. {
  5490. auto intDisplayType = displayInfo->mIntDisplayType;
  5491. if (formatInfo.mDisplayType == DwDisplayType_Decimal)
  5492. intDisplayType = DwIntDisplayType_Decimal;
  5493. else if (formatInfo.mDisplayType == DwDisplayType_HexUpper)
  5494. intDisplayType = DwIntDisplayType_HexadecimalUpper;
  5495. else if (formatInfo.mDisplayType == DwDisplayType_HexLower)
  5496. intDisplayType = DwIntDisplayType_HexadecimalLower;
  5497. if (intDisplayType == DwIntDisplayType_Binary)
  5498. {
  5499. String binary;
  5500. for (int i = 0; i < sizeof(T) * 8; i++)
  5501. {
  5502. if ((i != 0) && (i % 4 == 0))
  5503. binary = "'" + binary;
  5504. if ((i != 0) && (i % 16 == 0))
  5505. binary = "'" + binary;
  5506. binary = ((val & ((T)1 << i)) ? "1" : "0") + binary;
  5507. }
  5508. return StrFormat("0b'%s\n%s", binary.c_str(), name.c_str());
  5509. }
  5510. if (intDisplayType == DwIntDisplayType_Octal)
  5511. {
  5512. String format;
  5513. if (sizeof(T) == 8)
  5514. {
  5515. format = StrFormat("0o%%lo\n%s", name.c_str());
  5516. }
  5517. else
  5518. format = StrFormat("0o%%0%do\n%s", sizeof(val) * 2, name.c_str());
  5519. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5520. }
  5521. if (intDisplayType == DwIntDisplayType_HexadecimalUpper)
  5522. {
  5523. String format;
  5524. if (sizeof(T) == 8)
  5525. {
  5526. format = StrFormat("0x%%l@\n%s", name.c_str());
  5527. }
  5528. else
  5529. format = StrFormat("0x%%0%dX\n%s", sizeof(val) * 2, name.c_str());
  5530. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5531. }
  5532. if (intDisplayType == DwIntDisplayType_HexadecimalLower)
  5533. {
  5534. String format;
  5535. if (sizeof(T) == 8)
  5536. {
  5537. format = StrFormat("0x%%l@\n%s", name.c_str());
  5538. }
  5539. else
  5540. format = StrFormat("0x%%0%dx\n%s", sizeof(val) * 2, name.c_str());
  5541. return ToLower(StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val)));
  5542. }
  5543. if (std::is_unsigned<T>::value)
  5544. {
  5545. if (sizeof(T) == 8)
  5546. {
  5547. if (val > 0x7FFFFFFFF)
  5548. return StrFormat("%llu\n%s\n:editVal\t%lluUL", val, name.c_str(), val);
  5549. else
  5550. return StrFormat("%llu\n%s", val, name.c_str());
  5551. }
  5552. else
  5553. return StrFormat("%u\n%s", val, name.c_str());
  5554. }
  5555. else
  5556. {
  5557. if (sizeof(T) == 8)
  5558. {
  5559. if ((val > 0x7FFFFFFFF) || (val < -0x80000000LL))
  5560. return StrFormat("%lld\n%s\n:editVal\t%lldL", val, name.c_str(), val);
  5561. else
  5562. return StrFormat("%lld\n%s", val, name.c_str(), val);
  5563. }
  5564. else
  5565. return StrFormat("%d\n%s", val, name.c_str());
  5566. }
  5567. }
  5568. DwDisplayInfo* WinDebugger::GetDisplayInfo(const StringImpl& referenceId)
  5569. {
  5570. DwDisplayInfo* displayInfo = &mDebugManager->mDefaultDisplayInfo;
  5571. if (!referenceId.empty())
  5572. {
  5573. if (!mDebugManager->mDisplayInfos.TryGetValue(referenceId, &displayInfo))
  5574. {
  5575. int dollarIdx = referenceId.LastIndexOf('$');
  5576. if ((dollarIdx > 0) && (referenceId[dollarIdx - 1] == ']'))
  5577. {
  5578. // Try getting series displayinfo
  5579. mDebugManager->mDisplayInfos.TryGetValueWith(StringView(referenceId, 0, dollarIdx), &displayInfo);
  5580. }
  5581. }
  5582. }
  5583. return displayInfo;
  5584. }
  5585. static String WrapWithModifiers(const StringImpl& origName, DbgType* dbgType, DbgLanguage language)
  5586. {
  5587. if (language == DbgLanguage_Unknown)
  5588. language = dbgType->GetLanguage();
  5589. String name = origName;
  5590. while (true)
  5591. {
  5592. if (dbgType->mTypeCode == DbgType_Const)
  5593. {
  5594. if (language == DbgLanguage_Beef)
  5595. name = "readonly " + name;
  5596. else
  5597. name = "const " + name;
  5598. dbgType = dbgType->mTypeParam;
  5599. }
  5600. else if (dbgType->mTypeCode == DbgType_Volatile)
  5601. {
  5602. name = "volatile " + name;
  5603. dbgType = dbgType->mTypeParam;
  5604. }
  5605. else if (dbgType->mTypeCode == DbgType_TypeDef)
  5606. {
  5607. dbgType = dbgType->mTypeParam;
  5608. }
  5609. else if (dbgType->mTypeCode == DbgType_Ref)
  5610. {
  5611. if (language == DbgLanguage_Beef)
  5612. name = "ref " + name;
  5613. else
  5614. name = name + "&";
  5615. dbgType = dbgType->mTypeParam;
  5616. }
  5617. else if (dbgType->mTypeCode == DbgType_Bitfield)
  5618. {
  5619. return dbgType->ToString(language);
  5620. }
  5621. else
  5622. return name;
  5623. }
  5624. }
  5625. DebugVisualizerEntry* WinDebugger::FindVisualizerForType(DbgType* dbgType, Array<String>* wildcardCaptures)
  5626. {
  5627. auto entry = mDebugManager->mDebugVisualizers->FindEntryForType(dbgType->ToString(DbgLanguage_Unknown, true), dbgType->mCompileUnit->mDbgModule->mDbgFlavor, wildcardCaptures);
  5628. if (entry == NULL)
  5629. {
  5630. dbgType = dbgType->GetPrimaryType();
  5631. dbgType->PopulateType();
  5632. for (auto baseTypeEntry : dbgType->mBaseTypes)
  5633. {
  5634. entry = FindVisualizerForType(baseTypeEntry->mBaseType, wildcardCaptures);
  5635. if (entry != NULL)
  5636. break;
  5637. }
  5638. }
  5639. return entry;
  5640. }
  5641. #define GET_FROM(ptr, T) *((T*)(ptr += sizeof(T)) - 1)
  5642. String WinDebugger::ReadString(DbgTypeCode charType, intptr addr, bool isLocalAddr, intptr maxLength, DwFormatInfo& formatInfo, bool wantStringView)
  5643. {
  5644. int origMaxLength = maxLength;
  5645. if (addr == 0)
  5646. return "";
  5647. BP_ZONE("WinDebugger::ReadString");
  5648. String retVal = "\"";
  5649. bool wasTerminated = false;
  5650. String valString;
  5651. intptr maxShowSize = 255;
  5652. if (maxLength == -1)
  5653. maxLength = formatInfo.mOverrideCount;
  5654. else if (formatInfo.mOverrideCount != -1)
  5655. maxLength = BF_MIN(formatInfo.mOverrideCount, maxLength);
  5656. if (formatInfo.mMaxCount != -1)
  5657. maxLength = BF_MIN(formatInfo.mMaxCount, maxLength);
  5658. if (maxLength == -1)
  5659. maxLength = 8 * 1024 * 1024; // Is 8MB crazy?
  5660. if ((!formatInfo.mRawString) && (!wantStringView))
  5661. maxLength = BF_MIN(maxLength, maxShowSize);
  5662. if (wantStringView)
  5663. {
  5664. // Limit the original string view to 1MB, reevaluate on "More"
  5665. maxLength = BF_MIN(maxLength, 1024 * 1024);
  5666. }
  5667. //EnableMemCache();
  5668. bool readFailed = false;
  5669. intptr strPtr = addr;
  5670. int charLen = 1;
  5671. if ((charType == DbgType_SChar16) || (charType == DbgType_UChar16))
  5672. charLen = 2;
  5673. else if ((charType == DbgType_SChar32) || (charType == DbgType_UChar32))
  5674. charLen = 4;
  5675. bool isUTF8 = formatInfo.mDisplayType == DwDisplayType_Utf8;
  5676. int readSize = BF_MIN(1024, maxLength * charLen);
  5677. uint8 buf[1024];
  5678. uint8* bufPtr = NULL;
  5679. uint8* bufEnd = NULL;
  5680. bool hasHighAscii = false;
  5681. int i;
  5682. for (i = 0; i < maxLength; i++)
  5683. {
  5684. if (bufPtr >= bufEnd)
  5685. {
  5686. while (true)
  5687. {
  5688. if (readSize < charLen)
  5689. {
  5690. readFailed = true;
  5691. break;
  5692. }
  5693. if (ReadMemory(strPtr, readSize, buf, isLocalAddr))
  5694. break;
  5695. readSize /= 2;
  5696. }
  5697. if (readFailed)
  5698. break;
  5699. bufPtr = buf;
  5700. bufEnd = buf + readSize;
  5701. }
  5702. switch (charLen)
  5703. {
  5704. case 1:
  5705. {
  5706. char c = GET_FROM(bufPtr, char);
  5707. if ((c != 0) || (formatInfo.mOverrideCount != -1))
  5708. {
  5709. if ((uint8)c >= 0x80)
  5710. hasHighAscii = true;
  5711. valString.Append(c);
  5712. }
  5713. else
  5714. wasTerminated = true;
  5715. }
  5716. break;
  5717. case 2:
  5718. {
  5719. uint16 c16 = GET_FROM(bufPtr, uint16);
  5720. if ((c16 != 0) || (formatInfo.mOverrideCount != -1))
  5721. {
  5722. char str[8];
  5723. u8_toutf8(str, 8, c16);
  5724. valString += str;
  5725. }
  5726. else
  5727. wasTerminated = true;
  5728. }
  5729. break;
  5730. case 4:
  5731. {
  5732. uint32 c32 = GET_FROM(bufPtr, uint32);
  5733. if ((c32 != 0) || (formatInfo.mOverrideCount != -1))
  5734. {
  5735. char str[8];
  5736. u8_toutf8(str, 8, c32);
  5737. valString += str;
  5738. }
  5739. else
  5740. wasTerminated = true;
  5741. }
  5742. break;
  5743. }
  5744. if ((wasTerminated) && (formatInfo.mOverrideCount != -1))
  5745. {
  5746. valString += '\x00';
  5747. wasTerminated = false;
  5748. }
  5749. if ((wasTerminated) || (readFailed))
  5750. {
  5751. break;
  5752. }
  5753. strPtr += charLen;
  5754. }
  5755. //DisableMemCache();
  5756. if (formatInfo.mOverrideCount != -1)
  5757. {
  5758. if (i == formatInfo.mOverrideCount)
  5759. wasTerminated = true;
  5760. }
  5761. if (strPtr == addr + origMaxLength)
  5762. wasTerminated = true;
  5763. if (valString.length() == formatInfo.mOverrideCount)
  5764. wasTerminated = true;
  5765. // if (formatInfo.mDisplayType == DwDisplayType_Ascii)
  5766. // {
  5767. // // Our encoding for retVal is already assumed to be UTF8, so the special case here actually Ascii
  5768. // valString = UTF8Encode(ToWString(valString));
  5769. // }
  5770. if ((formatInfo.mRawString) || (wantStringView))
  5771. {
  5772. if ((formatInfo.mDisplayType == DwDisplayType_Utf8) || (!hasHighAscii))
  5773. return valString;
  5774. String utf8Str;
  5775. for (int i = 0; i < (int)valString.length(); i++)
  5776. {
  5777. char c = valString[i];
  5778. if ((uint8)c >= 0x80)
  5779. {
  5780. utf8Str += (char)(0xC0 | (((uint8)c & 0xFF) >> 6));
  5781. utf8Str += (char)(0x80 | ((uint8)c & 0x3F));
  5782. }
  5783. else
  5784. utf8Str += c;
  5785. }
  5786. return utf8Str;
  5787. }
  5788. if ((readFailed) && (valString.IsEmpty()))
  5789. return "< Failed to read string >";
  5790. retVal += SlashString(valString, true, true, formatInfo.mLanguage == DbgLanguage_Beef);
  5791. // We could go over 'maxShowSize' if we have a lot of slashed chars. An uninitialized string can be filled with '\xcc' chars
  5792. if ((!formatInfo.mRawString) && (!wantStringView) && ((int)retVal.length() > maxShowSize))
  5793. {
  5794. retVal = retVal.Substring(0, maxShowSize);
  5795. wasTerminated = false;
  5796. }
  5797. if (wasTerminated)
  5798. retVal += "\"";
  5799. else
  5800. retVal += "...";
  5801. return retVal;
  5802. }
  5803. bool WinDebugger::ProcessEvalString(DbgCompileUnit* dbgCompileUnit, DbgTypedValue useTypedValue, String& evalStr, String& displayString, DwFormatInfo& formatInfo, DebugVisualizerEntry* debugVis, bool limitLength)
  5804. {
  5805. bool success = true;
  5806. for (int i = 0; i < (int)evalStr.length(); i++)
  5807. {
  5808. char c = evalStr[i];
  5809. char nextC = 0;
  5810. if (i < (int)evalStr.length() - 1)
  5811. nextC = evalStr[i + 1];
  5812. if ((c == '{') && (nextC != '{'))
  5813. {
  5814. // Evaluate
  5815. int endIdx = i;
  5816. for (; endIdx < (int)evalStr.length(); endIdx++)
  5817. {
  5818. //TODO: Do better parsing - this paren could be inside a string, for example
  5819. if (evalStr[endIdx] == '}')
  5820. break;
  5821. }
  5822. DwFormatInfo displayStrFormatInfo = formatInfo;
  5823. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + (int)displayString.length();
  5824. displayStrFormatInfo.mHidePointers = false;
  5825. if ((limitLength) && (displayStrFormatInfo.mTotalSummaryLength > 255))
  5826. {
  5827. displayString += "...";
  5828. }
  5829. else
  5830. {
  5831. String evalString = evalStr.Substring(i + 1, endIdx - i - 1);
  5832. String errors;
  5833. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, useTypedValue, evalString, &displayStrFormatInfo, NULL, &errors);
  5834. if (evalResult)
  5835. {
  5836. if (displayStrFormatInfo.mNoEdit)
  5837. formatInfo.mNoEdit = true;
  5838. String result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  5839. if ((formatInfo.mRawString) && (limitLength))
  5840. {
  5841. displayString = result;
  5842. return success;
  5843. }
  5844. if (displayStrFormatInfo.mRawString)
  5845. {
  5846. displayString += result;
  5847. }
  5848. else
  5849. {
  5850. int crPos = result.IndexOf('\n');
  5851. if (crPos != -1)
  5852. displayString += result.Substring(0, crPos);
  5853. else
  5854. displayString += result;
  5855. }
  5856. }
  5857. else if (debugVis != NULL)
  5858. {
  5859. success = false;
  5860. displayString += "<DbgVis Failed>";
  5861. DbgVisFailed(debugVis, evalString, errors);
  5862. }
  5863. else
  5864. {
  5865. success = false;
  5866. displayString += "<Eval Failed>";
  5867. }
  5868. }
  5869. i = endIdx;
  5870. continue;
  5871. }
  5872. else if ((c == '{') && (nextC == '{'))
  5873. {
  5874. // Skip next paren
  5875. i++;
  5876. }
  5877. else if ((c == '}') && (nextC == '}'))
  5878. {
  5879. // Skip next paren
  5880. i++;
  5881. }
  5882. displayString += c;
  5883. }
  5884. return success;
  5885. }
  5886. static bool IsNormalChar(uint32 c)
  5887. {
  5888. return (c < 0x80);
  5889. }
  5890. String WinDebugger::DbgTypedValueToString(const DbgTypedValue& origTypedValue, const StringImpl& expr, DwFormatInfo& formatInfo, DbgExprEvaluator* optEvaluator, bool fullPrecision)
  5891. {
  5892. BP_ZONE("WinDebugger::DbgTypedValueToString");
  5893. DbgTypedValue typedValue = origTypedValue;
  5894. auto dbgCompileUnit = typedValue.mType->mCompileUnit;
  5895. auto dbgModule = typedValue.mType->GetDbgModule();
  5896. auto language = origTypedValue.mType->GetLanguage();
  5897. if (language == DbgLanguage_Unknown)
  5898. language = formatInfo.mLanguage;
  5899. formatInfo.mLanguage = language;
  5900. bool isBeef = language == DbgLanguage_Beef;
  5901. char str[32];
  5902. bool readFailed = false;
  5903. bool isCompositeType = false;
  5904. bool isSizedArray = false;
  5905. bool isEnum = false;
  5906. int64 enumVal = 0;
  5907. String result;
  5908. String stringViewData;
  5909. DwDisplayInfo* displayInfo = GetDisplayInfo(formatInfo.mReferenceId);
  5910. bool wantStringView = (displayInfo->mFormatStr == "str") && (formatInfo.mAllowStringView);
  5911. DbgType* origValueType = typedValue.mType;
  5912. bool origHadRef = false;
  5913. DbgType* dwValueType = typedValue.mType->RemoveModifiers(&origHadRef);
  5914. if (dwValueType == NULL)
  5915. dwValueType = dbgModule->GetPrimitiveType(DbgType_Void, language);
  5916. else
  5917. dwValueType = dwValueType->GetPrimaryType();
  5918. if (dwValueType->mTypeCode == DbgType_TypeDef)
  5919. {
  5920. DbgTypedValue realTypedVal = typedValue;
  5921. realTypedVal.mType = dwValueType->mTypeParam;
  5922. return DbgTypedValueToString(realTypedVal, expr, formatInfo, optEvaluator);
  5923. }
  5924. if (formatInfo.mRawString)
  5925. {
  5926. if ((dwValueType->mTypeCode != DbgType_Struct) && (dwValueType->mTypeCode != DbgType_Class) && (dwValueType->mTypeCode != DbgType_Ptr) && (dwValueType->mTypeCode != DbgType_SizedArray))
  5927. return "";
  5928. }
  5929. auto _ShowArraySummary = [&](String& retVal, addr_target ptrVal, int64 arraySize, DbgType* innerType)
  5930. {
  5931. String displayString;
  5932. displayString += "{";
  5933. for (int idx = 0; idx < arraySize; idx++)
  5934. {
  5935. if (formatInfo.mTotalSummaryLength + retVal.length() + displayString.length() > 255)
  5936. {
  5937. displayString += "...";
  5938. break;
  5939. }
  5940. if ((idx != 0) && (!displayString.EndsWith('{')))
  5941. displayString += ", ";
  5942. DwFormatInfo displayStrFormatInfo = formatInfo;
  5943. displayStrFormatInfo.mExpandItemDepth = 1;
  5944. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + retVal.length() + displayString.length();
  5945. displayStrFormatInfo.mHidePointers = false;
  5946. displayStrFormatInfo.mArrayLength = -1;
  5947. // Why did we have this "na" on here? It made "void*[3]" type things show up as "{,,}"
  5948. //String evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + StrFormat(")[%d], na", idx);
  5949. String evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + StrFormat(")[%lld]", idx);
  5950. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, typedValue, evalStr, &displayStrFormatInfo);
  5951. String result;
  5952. if (evalResult)
  5953. {
  5954. result = DbgTypedValueToString(evalResult, evalStr, displayStrFormatInfo, NULL);
  5955. int crPos = result.IndexOf('\n');
  5956. if (crPos != -1)
  5957. result.RemoveToEnd(crPos);
  5958. }
  5959. else
  5960. result = "???";
  5961. displayString += result;
  5962. }
  5963. displayString += "}";
  5964. retVal += displayString;
  5965. };
  5966. if (formatInfo.mArrayLength != -1)
  5967. {
  5968. if (formatInfo.mRawString)
  5969. return "";
  5970. if (dwValueType->IsPointer())
  5971. {
  5972. String retVal;
  5973. addr_target ptrVal = (addr_target)typedValue.mPtr;
  5974. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  5975. {
  5976. retVal = EncodeDataPtr(ptrVal, true) + " ";
  5977. retVal += dwValueType->mTypeParam->ToString(language);
  5978. retVal += StrFormat("[%lld] ", (int64)formatInfo.mArrayLength);
  5979. }
  5980. _ShowArraySummary(retVal, ptrVal, formatInfo.mArrayLength, dwValueType->mTypeParam);
  5981. String idxStr = "[{0}]";
  5982. DbgType* innerType = dwValueType->mTypeParam;
  5983. retVal += "\n" + dwValueType->ToString(language);
  5984. String evalStr = "*((" + typedValue.mType->ToStringRaw(language) + ")" + EncodeDataPtr(ptrVal, true) + " + {0})";
  5985. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, (int)BF_MAX(formatInfo.mArrayLength, 0), 10000) +
  5986. "\t" + idxStr + "\t" + evalStr;
  5987. return retVal;
  5988. }
  5989. else
  5990. {
  5991. DwFormatInfo newFormatInfo = formatInfo;
  5992. newFormatInfo.mArrayLength = -1;
  5993. String retVal = DbgTypedValueToString(typedValue, expr, newFormatInfo, optEvaluator);
  5994. int crPos = (int)retVal.IndexOf('\n');
  5995. if (crPos != -1)
  5996. retVal = "!Array length flag not valid with this type" + retVal.Substring(crPos);
  5997. return retVal;
  5998. }
  5999. }
  6000. switch (dwValueType->mTypeCode)
  6001. {
  6002. case DbgType_Void:
  6003. return "\nvoid";
  6004. case DbgType_Bool:
  6005. {
  6006. if (typedValue.mUInt8 == 0)
  6007. return "false\n" + WrapWithModifiers("bool", origValueType, language);
  6008. else if (typedValue.mUInt8 == 1)
  6009. return "true\n" + WrapWithModifiers("bool", origValueType, language);
  6010. else
  6011. return StrFormat("true (%d)\n", typedValue.mUInt8) + WrapWithModifiers("bool", origValueType, language);
  6012. }
  6013. break;
  6014. case DbgType_UChar:
  6015. if (language != DbgLanguage_Beef)
  6016. return IntTypeToString<uint8>(typedValue.mUInt8, WrapWithModifiers("uint8_t", origValueType, language), displayInfo, formatInfo);
  6017. case DbgType_SChar:
  6018. {
  6019. if (typedValue.mInt8 != 0)
  6020. {
  6021. char str[2] = {(char)typedValue.mInt8};
  6022. result = SlashString(str, formatInfo.mDisplayType == DwDisplayType_Utf8, true);
  6023. if (!IsNormalChar(typedValue.mUInt8))
  6024. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt8);
  6025. else
  6026. result = StrFormat("'%s'\n", result.c_str());
  6027. }
  6028. else
  6029. result = "'\\0'\n";
  6030. return result + WrapWithModifiers("char", origValueType, language);
  6031. }
  6032. break;
  6033. case DbgType_UChar16:
  6034. if (language != DbgLanguage_Beef)
  6035. return IntTypeToString<int16>(typedValue.mUInt8, WrapWithModifiers("uint16_t", origValueType, language), displayInfo, formatInfo);
  6036. case DbgType_SChar16:
  6037. {
  6038. if (typedValue.mInt16 != 0)
  6039. {
  6040. u8_toutf8(str, 8, typedValue.mUInt32);
  6041. result = SlashString(str, true, true);
  6042. if (!IsNormalChar(typedValue.mUInt32))
  6043. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt16);
  6044. else
  6045. result = StrFormat("'%s'\n", result.c_str());
  6046. }
  6047. else
  6048. result = "'\\0'\n";
  6049. return result + WrapWithModifiers(isBeef ? "char16" : "int16_t", origValueType, language);
  6050. }
  6051. break;
  6052. case DbgType_UChar32:
  6053. case DbgType_SChar32:
  6054. {
  6055. if (typedValue.mInt32 != 0)
  6056. {
  6057. u8_toutf8(str, 8, typedValue.mUInt32);
  6058. result = SlashString(str, true, true);
  6059. if (!IsNormalChar(typedValue.mUInt32))
  6060. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt32);
  6061. else
  6062. result = StrFormat("'%s'\n", result.c_str());
  6063. }
  6064. else
  6065. result = "'\\0'\n";
  6066. return result + WrapWithModifiers(isBeef ? "char32" : "int32_t", origValueType, language);
  6067. }
  6068. break;
  6069. case DbgType_i8:
  6070. return IntTypeToString<int8>(typedValue.mInt8, WrapWithModifiers(isBeef ? "int8" : "int8_t", origValueType, language), displayInfo, formatInfo);
  6071. case DbgType_u8:
  6072. return IntTypeToString<uint8>(typedValue.mUInt8, WrapWithModifiers(isBeef ? "uint8" : "uint8_t", origValueType, language), displayInfo, formatInfo);
  6073. case DbgType_i16:
  6074. return IntTypeToString<int16>(typedValue.mInt16, WrapWithModifiers(isBeef ? "int16" : "int16_t", origValueType, language), displayInfo, formatInfo);
  6075. case DbgType_u16:
  6076. return IntTypeToString<uint16>(typedValue.mUInt16, WrapWithModifiers(isBeef ? "uint16" : "uint16_t", origValueType, language), displayInfo, formatInfo);
  6077. case DbgType_i32:
  6078. return IntTypeToString<int32>(typedValue.mInt32, WrapWithModifiers(isBeef ? "int32" : "int32_t", origValueType, language), displayInfo, formatInfo);
  6079. case DbgType_u32:
  6080. return IntTypeToString<uint32>(typedValue.mUInt32, WrapWithModifiers(isBeef ? "uint32" : "uint32_t", origValueType, language), displayInfo, formatInfo);
  6081. case DbgType_i64:
  6082. return IntTypeToString<int64>(typedValue.mInt64, WrapWithModifiers(isBeef ? "int64" : "int64_t", origValueType, language), displayInfo, formatInfo);
  6083. case DbgType_u64:
  6084. return IntTypeToString<uint64>(typedValue.mUInt64, WrapWithModifiers(isBeef ? "uint64" : "uint64_t", origValueType, language), displayInfo, formatInfo);
  6085. case DbgType_RegGroup:
  6086. {
  6087. if ((typedValue.mRegNum >= CPUReg_M128_XMMREG_FIRST) && (typedValue.mRegNum <= CPUReg_M128_XMMREG_LAST))
  6088. {
  6089. int callStackIdx = formatInfo.mCallStackIdx;
  6090. FixCallStackIdx(callStackIdx);
  6091. UpdateRegisterUsage(callStackIdx);
  6092. WdStackFrame* wdStackFrame = mCallStack[callStackIdx];
  6093. RegForm regForm = RegForm_Unknown;
  6094. if (typedValue.mRegNum < (int)wdStackFrame->mRegForms.size())
  6095. regForm = wdStackFrame->mRegForms[typedValue.mRegNum];
  6096. int xmmMajor = typedValue.mRegNum - CPUReg_M128_XMMREG_FIRST;
  6097. String headerStr;
  6098. String xmmType = "__m128";
  6099. int xmmCount = 4;
  6100. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2) ||
  6101. (regForm == RegForm_Long) || (regForm == RegForm_Long2) ||
  6102. (regForm == RegForm_ULong) || (regForm == RegForm_ULong2))
  6103. xmmCount = 2;
  6104. //TODO: add byte, short, int, etc...
  6105. if (optEvaluator)
  6106. {
  6107. DwMmDisplayType mmDwMmDisplayType = displayInfo->mMmDisplayType;
  6108. if (mmDwMmDisplayType == DwMmDisplayType_Default)
  6109. {
  6110. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2))
  6111. mmDwMmDisplayType = DwMmDisplayType_Double;
  6112. else if (regForm == RegForm_Int4)
  6113. mmDwMmDisplayType = DwMmDisplayType_Int32;
  6114. }
  6115. if (mmDwMmDisplayType == DwMmDisplayType_Double)
  6116. {
  6117. xmmType = "__m128d";
  6118. xmmCount = 2;
  6119. double xmmRegVals[2];
  6120. CPURegisters* regs = optEvaluator->GetRegisters();
  6121. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  6122. {
  6123. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  6124. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_Double);
  6125. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  6126. xmmRegVals[xmmMinor] = xmmReg.mDouble;
  6127. }
  6128. headerStr = StrFormat("(%f, %f)", xmmRegVals[0], xmmRegVals[1]);
  6129. }
  6130. else if (mmDwMmDisplayType == DwMmDisplayType_UInt8)
  6131. {
  6132. int xmmRegVals[4];
  6133. xmmCount = 16;
  6134. CPURegisters* regs = optEvaluator->GetRegisters();
  6135. for (int xmmMinor = 0; xmmMinor < BF_ARRAY_COUNT(xmmRegVals); ++xmmMinor)
  6136. {
  6137. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  6138. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i32);
  6139. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  6140. xmmRegVals[xmmMinor] = xmmReg.mInt32;
  6141. }
  6142. headerStr = StrFormat("(%d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d)",
  6143. xmmRegVals[0] & 0xFF, (xmmRegVals[0] >> 8) & 0xFF, (xmmRegVals[0] >> 16) & 0xFF, (xmmRegVals[0] >> 24) & 0xFF,
  6144. xmmRegVals[1] & 0xFF, (xmmRegVals[1] >> 8) & 0xFF, (xmmRegVals[1] >> 16) & 0xFF, (xmmRegVals[1] >> 24) & 0xFF,
  6145. xmmRegVals[2] & 0xFF, (xmmRegVals[2] >> 8) & 0xFF, (xmmRegVals[2] >> 16) & 0xFF, (xmmRegVals[2] >> 24) & 0xFF,
  6146. xmmRegVals[3] & 0xFF, (xmmRegVals[3] >> 8) & 0xFF, (xmmRegVals[3] >> 16) & 0xFF, (xmmRegVals[3] >> 24) & 0xFF);
  6147. }
  6148. else if (mmDwMmDisplayType == DwMmDisplayType_Int16)
  6149. {
  6150. int xmmRegVals[4];
  6151. xmmCount = 8;
  6152. CPURegisters* regs = optEvaluator->GetRegisters();
  6153. for (int xmmMinor = 0; xmmMinor < BF_ARRAY_COUNT(xmmRegVals); ++xmmMinor)
  6154. {
  6155. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  6156. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i32);
  6157. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  6158. xmmRegVals[xmmMinor] = xmmReg.mInt32;
  6159. }
  6160. headerStr = StrFormat("(%d, %d, %d, %d, %d, %d, %d, %d)",
  6161. xmmRegVals[0] & 0xFFFF, (xmmRegVals[0] >> 16) & 0xFFFF,
  6162. xmmRegVals[1] & 0xFFFF, (xmmRegVals[1] >> 16) & 0xFFFF,
  6163. xmmRegVals[2] & 0xFFFF, (xmmRegVals[2] >> 16) & 0xFFFF,
  6164. xmmRegVals[3] & 0xFFFF, (xmmRegVals[3] >> 16) & 0xFFFF);
  6165. }
  6166. else if (mmDwMmDisplayType == DwMmDisplayType_Int32)
  6167. {
  6168. int xmmRegVals[4];
  6169. xmmCount = 4;
  6170. CPURegisters* regs = optEvaluator->GetRegisters();
  6171. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  6172. {
  6173. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  6174. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i32);
  6175. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  6176. xmmRegVals[xmmMinor] = xmmReg.mInt32;
  6177. }
  6178. headerStr = StrFormat("(%d, %d, %d, %d)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  6179. }
  6180. else if (mmDwMmDisplayType == DwMmDisplayType_Int64)
  6181. {
  6182. int64 xmmRegVals[2];
  6183. xmmCount = 2;
  6184. CPURegisters* regs = optEvaluator->GetRegisters();
  6185. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  6186. {
  6187. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  6188. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i64);
  6189. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  6190. xmmRegVals[xmmMinor] = xmmReg.mInt64;
  6191. }
  6192. headerStr = StrFormat("(%lld, %lld)", xmmRegVals[0], xmmRegVals[1]);
  6193. }
  6194. else // float
  6195. {
  6196. float xmmRegVals[4];
  6197. xmmCount = 4;
  6198. CPURegisters* regs = optEvaluator->GetRegisters();
  6199. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  6200. {
  6201. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  6202. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_Single);
  6203. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  6204. xmmRegVals[xmmMinor] = xmmReg.mSingle;
  6205. }
  6206. headerStr = StrFormat("(%f, %f, %f, %f)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  6207. }
  6208. }
  6209. else
  6210. {
  6211. headerStr = StrFormat("XMM%d", xmmMajor);
  6212. }
  6213. result = headerStr + "\n" + xmmType;
  6214. for (int i = 0; i < xmmCount; i++)
  6215. {
  6216. if (xmmCount == 16)
  6217. result += WrapWithModifiers(StrFormat("\n[%d]\t(uint8)($xmm%d_%d >> %d)", i, xmmMajor, i / 4, (i % 4)*8), origValueType, language);
  6218. else if (xmmCount == 8)
  6219. result += WrapWithModifiers(StrFormat("\n[%d]\t(int16)($xmm%d_%d >> %d)", i, xmmMajor, i / 2, (i % 2)*8), origValueType, language);
  6220. else
  6221. result += WrapWithModifiers(StrFormat("\n[%d]\t$xmm%d_%d", i, xmmMajor, i), origValueType, language);
  6222. }
  6223. return result;
  6224. }
  6225. else
  6226. {
  6227. switch (typedValue.mRegNum)
  6228. {
  6229. case CPUReg_CAT_ALLREGS:
  6230. {
  6231. return "ALLREGS\n__allregs\niregs\t$iregs\nflags\t$flags\nfpregs\t$fpregs\nmmregs\t$mmregs\nxmmregs\t$xmmregs";
  6232. }
  6233. break;
  6234. case CPUReg_CAT_IREGS:
  6235. {
  6236. #ifdef BF_DBG_32
  6237. String headerStr;
  6238. if (optEvaluator)
  6239. {
  6240. CPURegisters* regs = optEvaluator->GetRegisters();
  6241. 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)",
  6242. (uint32)regs->mIntRegs.eax, (uint32)regs->mIntRegs.ebx, (uint32)regs->mIntRegs.ecx, (uint32)regs->mIntRegs.edx,
  6243. (uint32)regs->mIntRegs.esi, (uint32)regs->mIntRegs.edi, (uint32)regs->mIntRegs.esp, (uint32)regs->mIntRegs.ebp,
  6244. (uint32)regs->mIntRegs.eip, (uint32)regs->mIntRegs.efl);
  6245. }
  6246. else
  6247. {
  6248. headerStr = "IREGS";
  6249. }
  6250. 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());
  6251. #else
  6252. String headerStr;
  6253. if (optEvaluator)
  6254. {
  6255. CPURegisters* regs = optEvaluator->GetRegisters();
  6256. 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)",
  6257. (uint64)regs->mIntRegs.rax, (uint64)regs->mIntRegs.rbx, (uint64)regs->mIntRegs.rcx, (uint64)regs->mIntRegs.rdx,
  6258. (uint64)regs->mIntRegs.rsi, (uint64)regs->mIntRegs.rdi, (uint64)regs->mIntRegs.rsp, (uint64)regs->mIntRegs.rbp,
  6259. (uint64)regs->mIntRegs.rip,
  6260. (uint64)regs->mIntRegs.r8, (uint64)regs->mIntRegs.r9, (uint64)regs->mIntRegs.r10, (uint64)regs->mIntRegs.r11,
  6261. (uint64)regs->mIntRegs.r12, (uint64)regs->mIntRegs.r13, (uint64)regs->mIntRegs.r14, (uint64)regs->mIntRegs.r15,
  6262. (uint32)regs->mIntRegs.efl);
  6263. }
  6264. else
  6265. {
  6266. headerStr = "IREGS";
  6267. }
  6268. 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());
  6269. #endif
  6270. }
  6271. break;
  6272. case CPUReg_CAT_FPREGS:
  6273. {
  6274. String headerStr;
  6275. if (optEvaluator)
  6276. {
  6277. CPURegisters* regs = optEvaluator->GetRegisters();
  6278. headerStr = "(";
  6279. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6280. {
  6281. if (i)
  6282. headerStr += ", ";
  6283. double val = ConvertFloat80ToDouble(regs->mFpMmRegsArray[i].fp.fp80);
  6284. headerStr += StrFormat("%f", val);
  6285. }
  6286. headerStr += ")";
  6287. }
  6288. else
  6289. {
  6290. headerStr = "FPREGS";
  6291. }
  6292. result = StrFormat("%s\n__fpregs", headerStr.c_str());
  6293. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6294. result += StrFormat("\n[%d]\t$st%d", i, i);
  6295. return result;
  6296. }
  6297. break;
  6298. case CPUReg_CAT_MMREGS:
  6299. {
  6300. String headerStr;
  6301. if (optEvaluator)
  6302. {
  6303. CPURegisters* regs = optEvaluator->GetRegisters();
  6304. headerStr = "(";
  6305. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6306. {
  6307. if (i)
  6308. headerStr += ", ";
  6309. uint64 val = regs->mFpMmRegsArray[i].mm;
  6310. headerStr += StrFormat("0x%016llx", val);
  6311. }
  6312. headerStr += ")";
  6313. }
  6314. else
  6315. {
  6316. headerStr = "MMREGS";
  6317. }
  6318. result = StrFormat("%s\n__mmregs", headerStr.c_str());
  6319. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6320. result += StrFormat("\n[%d]\t$mm%d", i, i);
  6321. return result;
  6322. }
  6323. break;
  6324. case CPUReg_CAT_XMMREGS:
  6325. {
  6326. String headerStr = StrFormat("XMMREGS[%d]", CPURegisters::kNumXmmRegs); // these are too big to put a useful header for the entire category
  6327. result = StrFormat("%s\n__xmmregs", headerStr.c_str());
  6328. for (int i = 0; i < CPURegisters::kNumXmmRegs; ++i)
  6329. result += StrFormat("\n[%d]\t$xmm%d", i, i);
  6330. return result;
  6331. }
  6332. break;
  6333. case CPUReg_CAT_FLAGS:
  6334. {
  6335. String headerStr;
  6336. if (optEvaluator)
  6337. {
  6338. CPURegisters* regs = optEvaluator->GetRegisters();
  6339. #ifdef BF_DBG_32
  6340. #define FLAGVAR(abbr, name) int flag##abbr = ((regs->mIntRegs.efl & ((uint64)1 << CPURegisters::GetFlagBitForRegister(X86Reg_FLAG_##abbr##_##name))) != 0) ? 1 : 0
  6341. FLAGVAR(CF, CARRY);
  6342. FLAGVAR(PF, PARITY);
  6343. FLAGVAR(AF, ADJUST);
  6344. FLAGVAR(ZF, ZERO);
  6345. FLAGVAR(SF, SIGN);
  6346. FLAGVAR(IF, INTERRUPT);
  6347. FLAGVAR(DF, DIRECTION);
  6348. FLAGVAR(OF, OVERFLOW);
  6349. #undef FLAGVAR
  6350. #else
  6351. #define FLAGVAR(abbr, name) int flag##abbr = ((regs->mIntRegs.efl & ((uint64)1 << CPURegisters::GetFlagBitForRegister(X64Reg_FLAG_##abbr##_##name))) != 0) ? 1 : 0
  6352. FLAGVAR(CF, CARRY);
  6353. FLAGVAR(PF, PARITY);
  6354. FLAGVAR(AF, ADJUST);
  6355. FLAGVAR(ZF, ZERO);
  6356. FLAGVAR(SF, SIGN);
  6357. FLAGVAR(IF, INTERRUPT);
  6358. FLAGVAR(DF, DIRECTION);
  6359. FLAGVAR(OF, OVERFLOW);
  6360. #undef FLAGVAR
  6361. #endif
  6362. headerStr = StrFormat("(CF=%d, PF=%d, AF=%d, ZF=%d, SF=%d, IF=%d, DF=%d, OF=%d)",
  6363. flagCF, flagPF, flagAF, flagZF, flagSF, flagIF, flagDF, flagOF);
  6364. }
  6365. else
  6366. {
  6367. headerStr = "FLAGS";
  6368. }
  6369. 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",
  6370. headerStr.c_str());
  6371. }
  6372. break;
  6373. default:
  6374. BF_ASSERT(false && "unknown category register");
  6375. return "UNKNOWNCATEGORY\n__unknown\n";
  6376. }
  6377. }
  6378. }
  6379. break;
  6380. case DbgType_Single:
  6381. {
  6382. DwFloatDisplayType floatDisplayType = displayInfo->mFloatDisplayType;
  6383. if (floatDisplayType == DwFloatDisplayType_Default)
  6384. floatDisplayType = DwFloatDisplayType_Minimal;
  6385. if (floatDisplayType == DwFloatDisplayType_Minimal)
  6386. ExactMinimalFloatToStr(typedValue.mSingle, str);
  6387. else if (floatDisplayType == DwFloatDisplayType_Full)
  6388. sprintf(str, "%1.9g", typedValue.mSingle);
  6389. else if (floatDisplayType == DwFloatDisplayType_HexUpper)
  6390. sprintf(str, "0x%04X", typedValue.mUInt32);
  6391. else //if (floatDisplayType == DwFloatDisplayType_HexLower)
  6392. sprintf(str, "0x%04x", typedValue.mUInt32);
  6393. return StrFormat("%s\n%s", str, WrapWithModifiers("float", origValueType, language).c_str());
  6394. }
  6395. case DbgType_Double:
  6396. {
  6397. DwFloatDisplayType floatDisplayType = displayInfo->mFloatDisplayType;
  6398. if (floatDisplayType == DwFloatDisplayType_Default)
  6399. floatDisplayType = DwFloatDisplayType_Minimal;
  6400. if (floatDisplayType == DwFloatDisplayType_Minimal)
  6401. ExactMinimalDoubleToStr(typedValue.mDouble, str);
  6402. else if (floatDisplayType == DwFloatDisplayType_Full)
  6403. sprintf(str, "%1.17g", typedValue.mDouble);
  6404. else if (floatDisplayType == DwFloatDisplayType_HexUpper)
  6405. sprintf(str, "0x%08llX", typedValue.mUInt64);
  6406. else //if (floatDisplayType == DwFloatDisplayType_HexLower)
  6407. sprintf(str, "0x%08llx", typedValue.mUInt64);
  6408. return StrFormat("%s\n%s", str, WrapWithModifiers("double", origValueType, language).c_str());
  6409. }
  6410. case DbgType_Subroutine:
  6411. if (typedValue.mCharPtr != NULL)
  6412. return StrFormat("%s\nfunc", typedValue.mCharPtr);
  6413. else
  6414. return "\nfunc";
  6415. case DbgType_RawText:
  6416. return StrFormat("%s\nrawtext", typedValue.mCharPtr);
  6417. case DbgType_Ptr:
  6418. {
  6419. addr_target ptrVal = (addr_target)typedValue.mPtr;
  6420. String retVal;
  6421. DbgType* innerType = dwValueType->mTypeParam;
  6422. if (innerType == NULL)
  6423. return EncodeDataPtr(ptrVal, true) + "\nvoid*";
  6424. bool isChar = false;
  6425. DbgType* unmodInnerType = innerType->RemoveModifiers();
  6426. if (unmodInnerType != NULL)
  6427. {
  6428. if (language == DbgLanguage_Beef)
  6429. {
  6430. if ((unmodInnerType->mTypeCode == DbgType_UChar) ||
  6431. (unmodInnerType->mTypeCode == DbgType_UChar16) ||
  6432. (unmodInnerType->mTypeCode == DbgType_UChar32))
  6433. isChar = true;
  6434. }
  6435. else
  6436. {
  6437. if ((unmodInnerType->mTypeCode == DbgType_SChar) ||
  6438. (unmodInnerType->mTypeCode == DbgType_SChar16) ||
  6439. (unmodInnerType->mTypeCode == DbgType_SChar32))
  6440. isChar = true;
  6441. }
  6442. }
  6443. if ((isChar) && (formatInfo.mArrayLength == -1))
  6444. {
  6445. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6446. retVal = EncodeDataPtr(ptrVal, true);
  6447. int strLen = formatInfo.mOverrideCount;
  6448. if (typedValue.mIsLiteral)
  6449. {
  6450. if (strLen == -1)
  6451. strLen = 0x7FFFFFFF;
  6452. if (typedValue.mDataLen > 0)
  6453. strLen = BF_MIN(strLen, typedValue.mDataLen);
  6454. else
  6455. strLen = BF_MIN(strLen, strlen(typedValue.mCharPtr));
  6456. }
  6457. SetAndRestoreValue<intptr> prevOverrideLen(formatInfo.mOverrideCount, strLen);
  6458. String strResult = ReadString(unmodInnerType->mTypeCode, typedValue.mLocalIntPtr, typedValue.mIsLiteral, strLen, formatInfo, wantStringView);
  6459. if (formatInfo.mRawString)
  6460. return strResult;
  6461. if (!strResult.IsEmpty())
  6462. {
  6463. if (!retVal.IsEmpty())
  6464. retVal += " ";
  6465. if (!wantStringView)
  6466. retVal += strResult;
  6467. }
  6468. retVal += "\n" + origValueType->ToString(language);
  6469. retVal += "\n:stringView";
  6470. if (wantStringView)
  6471. {
  6472. retVal += "\t";
  6473. retVal += SlashString(strResult, false, false, true);
  6474. }
  6475. return retVal;
  6476. }
  6477. else if ((unmodInnerType != NULL) &&
  6478. ((unmodInnerType->mTypeCode == DbgType_Class) || (unmodInnerType->mTypeCode == DbgType_Struct) || (unmodInnerType->mTypeCode == DbgType_Union)))
  6479. {
  6480. isCompositeType = true;
  6481. }
  6482. else if ((unmodInnerType != NULL) && (unmodInnerType->mTypeCode == DbgType_SizedArray))
  6483. {
  6484. isSizedArray = true;
  6485. }
  6486. else if (unmodInnerType->mTypeCode == DbgType_Subroutine)
  6487. {
  6488. if (formatInfo.mRawString)
  6489. return "";
  6490. addr_target funcPtr = (addr_target)typedValue.mPtr;
  6491. String retVal;
  6492. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6493. retVal = EncodeDataPtr(funcPtr, true);
  6494. String symbolName;
  6495. addr_target offset;
  6496. DbgModule* dwarf;
  6497. static String demangledName;
  6498. auto subProgram = mDebugTarget->FindSubProgram(funcPtr);
  6499. if (subProgram != NULL)
  6500. {
  6501. demangledName = subProgram->ToString();
  6502. }
  6503. else if (mDebugTarget->FindSymbolAt(funcPtr, &symbolName, &offset, &dwarf))
  6504. {
  6505. demangledName = BfDemangler::Demangle(symbolName, language);
  6506. if (offset != 0)
  6507. demangledName += StrFormat("+%d", offset);
  6508. }
  6509. else
  6510. {
  6511. auto dbgModule = mDebugTarget->FindDbgModuleForAddress(funcPtr);
  6512. if (dbgModule != NULL)
  6513. demangledName += dbgModule->GetLinkedModule()->mDisplayName + "!";
  6514. demangledName += StrFormat("0x%@", funcPtr);
  6515. }
  6516. retVal += " {";
  6517. retVal += demangledName;
  6518. retVal += "}";
  6519. retVal += "\n" + origValueType->ToString(language);
  6520. return retVal;
  6521. }
  6522. else if (unmodInnerType->mTypeCode == DbgType_Void)
  6523. {
  6524. if (formatInfo.mRawString)
  6525. return "";
  6526. addr_target ptr = (addr_target)typedValue.mPtr;
  6527. String symbolName;
  6528. addr_target offset;
  6529. DbgModule* dwarf;
  6530. String demangledName;
  6531. retVal += demangledName = StrFormat("0x%@", ptr);
  6532. if (mDebugTarget->FindSymbolAt(ptr, &symbolName, &offset, &dwarf))
  6533. {
  6534. if (offset == 0)
  6535. {
  6536. retVal += " {";
  6537. retVal += BfDemangler::Demangle(symbolName, language);
  6538. retVal += "}";
  6539. }
  6540. }
  6541. retVal += "\n" + origValueType->ToString(language);
  6542. return retVal;
  6543. }
  6544. else
  6545. {
  6546. if (formatInfo.mRawString)
  6547. return "";
  6548. addr_target ptrVal = (addr_target)typedValue.mPtr;
  6549. String retVal;
  6550. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6551. retVal = EncodeDataPtr(ptrVal, true);
  6552. if (ptrVal != 0)
  6553. {
  6554. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, NULL, -1, -1);
  6555. DbgTypedValue innerTypedVal = dbgExprEvaluator.ReadTypedValue(NULL, innerType, typedValue.mPtr, DbgAddrType_Target);
  6556. if (innerTypedVal)
  6557. {
  6558. DwFormatInfo defaultFormatInfo;
  6559. defaultFormatInfo.mLanguage = formatInfo.mLanguage;
  6560. defaultFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + 2; // Take into accout the necessary {}'s
  6561. defaultFormatInfo.mExpandItemDepth++;
  6562. String innerStr = DbgTypedValueToString(innerTypedVal, "", defaultFormatInfo, &dbgExprEvaluator);
  6563. int crIdx = innerStr.IndexOf('\n');
  6564. if (crIdx != -1)
  6565. {
  6566. String innerDataStr = innerStr.Substring(0, crIdx);
  6567. if (!innerDataStr.empty())
  6568. {
  6569. if (!retVal.empty())
  6570. retVal += " ";
  6571. retVal += "{" + innerDataStr + "}";
  6572. }
  6573. }
  6574. else
  6575. {
  6576. retVal += "{ ??? }";
  6577. }
  6578. }
  6579. }
  6580. retVal += "\n" + origValueType->ToString(language);
  6581. innerType->PopulateType();
  6582. if ((ptrVal != 0) &&
  6583. ((!innerType->mMemberList.IsEmpty()) || (innerType->mSize > 0) || (innerType->mTypeParam != NULL)))
  6584. {
  6585. String ptrDataStr = StrFormat("(%s)", dwValueType->ToStringRaw(language).c_str()) + EncodeDataPtr(typedValue.mPtr, true);
  6586. retVal += "\n*\t";
  6587. // Why did we have this? It messed up a pointer to sized array
  6588. /*if (language == DbgLanguage_Beef)
  6589. retVal += "this";
  6590. else*/
  6591. retVal += "*this";
  6592. if (!formatInfo.mReferenceId.empty())
  6593. retVal += ", refid=" + MaybeQuoteFormatInfoParam(formatInfo.mReferenceId);
  6594. retVal += ", this=" + ptrDataStr;
  6595. }
  6596. return retVal;
  6597. }
  6598. break;
  6599. }
  6600. case DbgType_Union:
  6601. case DbgType_Class:
  6602. case DbgType_Struct:
  6603. isCompositeType = true;
  6604. break;
  6605. case DbgType_Enum:
  6606. enumVal = typedValue.GetInt64();
  6607. isEnum = true;
  6608. break;
  6609. case DbgType_SizedArray:
  6610. {
  6611. isSizedArray = true;
  6612. }
  6613. break;
  6614. default:
  6615. break;
  6616. }
  6617. if (isSizedArray)
  6618. {
  6619. String retVal;
  6620. addr_target ptrVal = 0;
  6621. DbgType* arrayType = dwValueType;
  6622. DbgType* innerType = dwValueType->mTypeParam;
  6623. if (dwValueType->mTypeCode == DbgType_SizedArray)
  6624. {
  6625. ptrVal = (addr_target)typedValue.mSrcAddress;
  6626. }
  6627. else
  6628. {
  6629. BF_ASSERT(dwValueType->mTypeCode == DbgType_Ptr);
  6630. arrayType = innerType;
  6631. innerType = arrayType->mTypeParam;
  6632. ptrVal = typedValue.mPtr;
  6633. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6634. retVal = EncodeDataPtr(ptrVal, true) + " ";
  6635. }
  6636. if (ptrVal == 0)
  6637. ptrVal = typedValue.mPtr;
  6638. intptr arraySize = 0;
  6639. intptr innerSize = innerType->GetStride();
  6640. if (innerSize > 0)
  6641. arraySize = arrayType->GetStride() / innerSize;
  6642. else
  6643. {
  6644. // Failure!
  6645. }
  6646. String idxStr = "[{0}]";
  6647. if (innerType->IsChar(language))
  6648. {
  6649. String strVal = ReadString(innerType->mTypeCode, typedValue.mSrcAddress, false, arraySize, formatInfo, false);
  6650. if (formatInfo.mRawString)
  6651. return strVal;
  6652. retVal += strVal;
  6653. }
  6654. else
  6655. {
  6656. if (formatInfo.mRawString)
  6657. return "";
  6658. _ShowArraySummary(retVal, ptrVal, arraySize, innerType);
  6659. }
  6660. retVal += "\n" + origValueType->ToString(language);
  6661. String referenceId = dwValueType->ToString(language);
  6662. String evalStr;
  6663. // Why did we have the "na"? Do we not want to show addresses for all members?
  6664. evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + ")[{0}], refid=" + MaybeQuoteFormatInfoParam(referenceId + ".[]");
  6665. if (typedValue.mIsReadOnly)
  6666. evalStr += ", ne";
  6667. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, (int)BF_MAX(arraySize, 0), 10000) +
  6668. "\t" + idxStr + "\t" + evalStr;
  6669. return retVal;
  6670. }
  6671. dwValueType->PopulateType();
  6672. if (isEnum)
  6673. {
  6674. String retVal;
  6675. int64 bitsLeft = enumVal;
  6676. int valueCount = 0;
  6677. String editVal;
  6678. dwValueType = dwValueType->GetPrimaryType();
  6679. dwValueType->PopulateType();
  6680. while ((bitsLeft != 0) || (valueCount == 0))
  6681. {
  6682. DbgVariable* bestMatch = NULL;
  6683. for (auto member : dwValueType->mMemberList)
  6684. {
  6685. if (member->mConstValue == bitsLeft)
  6686. {
  6687. bestMatch = member;
  6688. break;
  6689. }
  6690. }
  6691. if (bestMatch == NULL)
  6692. {
  6693. for (auto member : dwValueType->mMemberList)
  6694. {
  6695. if ((member->mConstValue != 0) &&
  6696. ((member->mConstValue & bitsLeft) == member->mConstValue))
  6697. {
  6698. bestMatch = member;
  6699. break;
  6700. }
  6701. }
  6702. }
  6703. if (bestMatch == NULL)
  6704. break;
  6705. if (valueCount > 0)
  6706. {
  6707. retVal += " | ";
  6708. if (language == DbgLanguage_C)
  6709. editVal += " | ";
  6710. }
  6711. if (language == DbgLanguage_Beef)
  6712. retVal += ".";
  6713. retVal += bestMatch->mName;
  6714. if (language == DbgLanguage_C)
  6715. {
  6716. if (dwValueType->mParent != NULL)
  6717. {
  6718. editVal += dwValueType->mParent->ToString(language);
  6719. editVal += "::";
  6720. }
  6721. editVal += bestMatch->mName;
  6722. }
  6723. valueCount++;
  6724. bitsLeft &= ~bestMatch->mConstValue;
  6725. }
  6726. if ((valueCount == 0) || (bitsLeft != 0))
  6727. {
  6728. if (valueCount > 0)
  6729. retVal += " | ";
  6730. retVal += StrFormat("%lld", bitsLeft);
  6731. if (language == DbgLanguage_C)
  6732. {
  6733. if (valueCount > 0)
  6734. editVal += " | ";
  6735. editVal += StrFormat("%lld", bitsLeft);
  6736. }
  6737. }
  6738. retVal += "\n" + origValueType->ToString();
  6739. if (language == DbgLanguage_C)
  6740. {
  6741. retVal += "\n:editVal\t";
  6742. retVal += editVal;
  6743. }
  6744. retVal += "\n:canEdit";
  6745. return retVal;
  6746. }
  6747. else if (isCompositeType)
  6748. {
  6749. addr_target ptrVal;
  6750. if (dwValueType->IsPointer())
  6751. ptrVal = (addr_target)typedValue.mPtr;
  6752. else
  6753. ptrVal = (addr_target)typedValue.mSrcAddress;
  6754. String retVal;
  6755. if ((!typedValue.mIsLiteral) && (dwValueType->IsPointer()) &&
  6756. ((!formatInfo.mHidePointers) || (ptrVal == 0)))
  6757. retVal = EncodeDataPtr(ptrVal, true);
  6758. DbgType* innerType = dwValueType;
  6759. bool wasPtr = false;
  6760. if (innerType->mTypeCode == DbgType_Ptr)
  6761. {
  6762. wasPtr = true;
  6763. innerType = dwValueType->mTypeParam;
  6764. innerType = innerType->RemoveModifiers();
  6765. }
  6766. innerType = innerType->GetPrimaryType();
  6767. addr_target dataPtr = wasPtr ? typedValue.mPtr : typedValue.mSrcAddress;
  6768. DbgType* actualType = NULL;
  6769. bool useActualRawType = false;
  6770. bool isBfObject = innerType->IsBfObject();
  6771. bool hasCPPVTable = false;
  6772. if (!isBfObject)
  6773. hasCPPVTable = innerType->HasCPPVTable();
  6774. int bfObjectFlags = 0;
  6775. addr_target classVDataPtr = 0;
  6776. bool isAppendBfObject = false;
  6777. bool isStackBfObject = false;
  6778. bool isDeletedBfObject = false;
  6779. bool isCompositeWithoutAddress = false;
  6780. if (innerType->IsBfPayloadEnum())
  6781. {
  6782. if (formatInfo.mRawString)
  6783. return "";
  6784. auto tagMember = innerType->mMemberList.mTail;
  6785. int tagIdx = 0;
  6786. if (dataPtr == -1)
  6787. {
  6788. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, "(int)" + expr, &formatInfo);
  6789. auto dscValue = dbgEvaluationContext.EvaluateInContext(DbgTypedValue());
  6790. tagIdx = dscValue.mInt32;
  6791. }
  6792. else if (!ReadMemory((intptr)ptrVal + tagMember->mMemberOffset, tagMember->mType->mSize, (void*)&tagIdx))
  6793. {
  6794. return StrFormat("!Failed to read from 0x%@", ptrVal);
  6795. }
  6796. char findStr[16];
  6797. findStr[0] = '_';
  6798. itoa(tagIdx, findStr + 1, 10);
  6799. int len = strlen(findStr);
  6800. findStr[len] = '_';
  6801. len++;
  6802. if (!retVal.empty())
  6803. retVal += " ";
  6804. int startIdx = 0;
  6805. for (auto member : innerType->mMemberList)
  6806. {
  6807. if (strncmp(member->mName, findStr, len) == 0)
  6808. {
  6809. retVal += ".";
  6810. retVal += member->mName + len;
  6811. String tupleExpr;
  6812. DbgTypedValue tupleVal;
  6813. if (dataPtr == -1)
  6814. {
  6815. tupleVal.mSrcAddress = -1;
  6816. tupleVal.mType = member->mType;
  6817. //tupleExpr = "$" + expr + "$u";
  6818. tupleVal.mVariable = typedValue.mVariable;
  6819. tupleExpr = "(" + member->mType->ToStringRaw() + ")(" + expr + ")";
  6820. }
  6821. else
  6822. {
  6823. tupleVal.mType = member->mType;
  6824. tupleVal.mSrcAddress = ptrVal;
  6825. }
  6826. DwFormatInfo displayStrFormatInfo = formatInfo;
  6827. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + (int)retVal.length();
  6828. displayStrFormatInfo.mExpandItemDepth++;
  6829. displayStrFormatInfo.mHidePointers = false;
  6830. retVal += DbgTypedValueToString(tupleVal, tupleExpr, displayStrFormatInfo, NULL);
  6831. int idx = (int)retVal.IndexOf('\n');
  6832. if (idx != -1)
  6833. {
  6834. if ((idx > 2) && (strncmp(retVal.c_str() + idx - 2, "()", 2) == 0))
  6835. {
  6836. // Take off a terminating "()" on the value, if there is one
  6837. retVal.Remove(idx - 2, 2);
  6838. }
  6839. String typeName = innerType->ToString(DbgLanguage_Unknown, true);
  6840. typeName += " ";
  6841. retVal.Insert(idx + 1, typeName);
  6842. }
  6843. return retVal;
  6844. }
  6845. }
  6846. }
  6847. if (isBfObject)
  6848. {
  6849. classVDataPtr = ReadMemory<addr_target>(ptrVal);
  6850. mDebugTarget->GetCompilerSettings();
  6851. if (mDebugTarget->mBfObjectHasFlags)
  6852. {
  6853. bfObjectFlags = ((int)classVDataPtr) & 0xFF;
  6854. if ((bfObjectFlags & BfObjectFlag_Deleted) != 0)
  6855. isDeletedBfObject = true;
  6856. if ((bfObjectFlags & BfObjectFlag_AppendAlloc) != 0)
  6857. isAppendBfObject = true;
  6858. if ((bfObjectFlags & (BfObjectFlag_StackAlloc | BfObjectFlag_Allocated)) == BfObjectFlag_StackAlloc)
  6859. isStackBfObject = true;
  6860. classVDataPtr &= ~0xFF;
  6861. }
  6862. }
  6863. if (!formatInfo.mIgnoreDerivedClassInfo)
  6864. {
  6865. if (isBfObject)
  6866. {
  6867. dbgModule->ParseSymbolData();
  6868. String symbolName;
  6869. addr_target symOffset;
  6870. if ((mDebugTarget->FindSymbolAt(classVDataPtr, &symbolName, &symOffset)) && (symOffset < 0x100))
  6871. {
  6872. String mangledClassName;
  6873. const char* symEnd = "sBfClassVData";
  6874. int symEndLen = strlen(symEnd);
  6875. if (((int)symbolName.length() > symEndLen) && (strstr(symbolName.c_str(), symEnd) != NULL))
  6876. mangledClassName = symbolName;
  6877. // If we have flags then we may be pointing past the _typeData, actually. We could fix this by masking out
  6878. // the flags area, but we need to be sure we are running a build that supports flags
  6879. symEnd = "sBfTypeData";
  6880. symEndLen = strlen(symEnd);
  6881. if (((int) symbolName.length() > symEndLen) && (strstr(symbolName.c_str(), symEnd) != NULL))
  6882. mangledClassName = symbolName;
  6883. if (mangledClassName.length() > 0)
  6884. {
  6885. String className = BfDemangler::Demangle(mangledClassName, innerType->GetLanguage(), BfDemangler::Flag_RawDemangle);
  6886. for (int i = 0; i < className.length() - 3; i++)
  6887. {
  6888. if ((className[i] == 'b') &&
  6889. (className[i + 1] == 'f') &&
  6890. (className[i + 2] == '.'))
  6891. {
  6892. bool matches;
  6893. if (i == 0)
  6894. matches = true;
  6895. else
  6896. {
  6897. char prevC = className[i - 1];
  6898. if ((prevC == ' ') ||
  6899. (prevC == ',') ||
  6900. (prevC == '<'))
  6901. {
  6902. matches = true;
  6903. }
  6904. }
  6905. if (matches)
  6906. className.Remove(i, 3);
  6907. }
  6908. }
  6909. int lastDot = (int)className.LastIndexOf('.');
  6910. if (lastDot > 0)
  6911. className = className.Substring(0, lastDot);
  6912. const char* arrPrefix = "System.Array1<";
  6913. if (strncmp(className.c_str(), arrPrefix, strlen(arrPrefix)) == 0)
  6914. {
  6915. className = className.Substring(strlen(arrPrefix), className.length() - strlen(arrPrefix) - 1);
  6916. className += "[]";
  6917. }
  6918. auto typeEntry = dbgModule->GetLinkedModule()->mTypeMap.Find(className.c_str(), DbgLanguage_BeefUnfixed);
  6919. if (typeEntry != NULL)
  6920. {
  6921. actualType = typeEntry->mValue;
  6922. if (!actualType->IsBfObject())
  6923. {
  6924. if (actualType->mTypeCode == DbgType_Ptr)
  6925. {
  6926. actualType = actualType->mTypeParam;
  6927. }
  6928. }
  6929. }
  6930. }
  6931. }
  6932. }
  6933. else if (hasCPPVTable)
  6934. {
  6935. dbgModule->ParseSymbolData();
  6936. addr_target classVDataPtr = ReadMemory<addr_target>(ptrVal);
  6937. String symbolName;
  6938. addr_target offset = 0;
  6939. if (mDebugTarget->FindSymbolAt(classVDataPtr, &symbolName, &offset, NULL))
  6940. {
  6941. // On GNU, vtable indices can "go negative" for things like RTTI and virtual inheritance, so
  6942. // we can't rely on an exact vtable address lookup
  6943. if (offset < 0x200)
  6944. {
  6945. DbgLanguage lang = innerType->GetLanguage();
  6946. const char* symStart = (innerType->mCompileUnit->mDbgModule->mDbgFlavor == DbgFlavor_GNU) ? "_ZTV" : "??_7";
  6947. if (strncmp(symbolName.c_str(), symStart, strlen(symStart)) == 0)
  6948. {
  6949. //String mangledClassName = symbolName.Substring(1);
  6950. String className = BfDemangler::Demangle(symbolName, lang);
  6951. int vtableNameIdx = (int)className.IndexOf("::`vftable'");
  6952. if (vtableNameIdx != -1)
  6953. className = className.Substring(0, vtableNameIdx);
  6954. auto typeEntry = dbgModule->mTypeMap.Find(className.c_str(), DbgLanguage_C);
  6955. if (typeEntry != NULL)
  6956. {
  6957. actualType = typeEntry->mValue;
  6958. if ((int)className.IndexOf('<') != -1)
  6959. useActualRawType = true;
  6960. int thisOffset = 0;
  6961. if (!DbgExprEvaluator::TypeIsSubTypeOf(actualType, innerType, &thisOffset))
  6962. {
  6963. // This catches virtual inheritance cases where we can't downcast
  6964. actualType = NULL;
  6965. }
  6966. }
  6967. }
  6968. }
  6969. }
  6970. }
  6971. }
  6972. DbgType* displayType = origValueType;
  6973. String displayString;
  6974. bool wantsCustomExpandedItems = false;
  6975. DebugVisualizerEntry* debugVis = NULL;
  6976. Array<String> dbgVisWildcardCaptures;
  6977. DbgType* dwUseType = (actualType != NULL) ? actualType : innerType;
  6978. //auto ptrDataType = dwValueType;
  6979. //TODO: Changed this from the above to account for COFF types where 'this' is always a fwd reference, does this cause any issues?
  6980. auto ptrDataType = innerType;
  6981. String ptrDataStr;
  6982. if (/*(!innerType->IsBfObject()) &&*/ (!ptrDataType->IsPointer()))
  6983. {
  6984. if ((dataPtr != 0) || (ptrDataType->GetByteCount() > sizeof(addr_target)))
  6985. {
  6986. bool wantsRefThis = ptrDataType->WantsRefThis();
  6987. ptrDataType = ptrDataType->GetDbgModule()->GetPointerType(ptrDataType);
  6988. if (wantsRefThis)
  6989. ptrDataStr += "*";
  6990. }
  6991. else
  6992. {
  6993. // Data is inline - must be int-sized or less
  6994. isCompositeWithoutAddress = true;
  6995. dataPtr = typedValue.mPtr;
  6996. }
  6997. }
  6998. String ptrDataTypeStr = ptrDataType->ToStringRaw();
  6999. ptrDataStr += StrFormat("(%s)", ptrDataTypeStr.c_str()) + EncodeDataPtr(dataPtr, true);
  7000. DbgType* dwUsePtrType = dwUseType;
  7001. String ptrUseDataStr;
  7002. if (!dwUsePtrType->IsPointer())
  7003. {
  7004. bool wantsRefThis = dwUsePtrType->WantsRefThis();
  7005. dwUsePtrType = dwUsePtrType->GetDbgModule()->GetPointerType(dwUsePtrType);
  7006. if (wantsRefThis)
  7007. ptrUseDataStr += "*";
  7008. }
  7009. String ptrUseDataTypeStr = dwUsePtrType->ToStringRaw();
  7010. ptrUseDataStr += StrFormat("(%s)", ptrUseDataTypeStr.c_str()) + EncodeDataPtr(dataPtr, true);
  7011. if ((origTypedValue.mSrcAddress == -1) && (origTypedValue.mVariable != NULL))
  7012. {
  7013. ptrDataStr = origTypedValue.mVariable->mName;
  7014. if (!origTypedValue.mType->RemoveModifiers()->Equals(origTypedValue.mVariable->mType->RemoveModifiers()))
  7015. {
  7016. //ptrDataStr = StrFormat("(%s)%s", origTypedValue.mType->ToString().c_str(), origTypedValue.mVariable->mName);
  7017. ptrDataStr = expr;
  7018. }
  7019. ptrUseDataStr = ptrDataStr;
  7020. }
  7021. bool isNull = wasPtr && (dataPtr == 0);
  7022. bool isBadSrc = !wasPtr && (dataPtr == 0) && (!dwValueType->IsValuelessType());
  7023. if ((ptrVal == 0) && (dwValueType->IsTypedPrimitive()))
  7024. {
  7025. DbgTypedValue rawVal;
  7026. rawVal.mInt64 = origTypedValue.mInt64;
  7027. rawVal.mType = dwValueType->GetRootBaseType();
  7028. ptrDataStr = "(" + dwUseType->ToStringRaw() + ")";
  7029. ptrDataStr += DbgTypedValueToString(rawVal, expr, formatInfo, optEvaluator, fullPrecision);
  7030. int editValIdx = ptrDataStr.IndexOf(":editVal");
  7031. if (editValIdx != -1)
  7032. ptrDataStr.Remove(0, editValIdx + 9);
  7033. int crPos = (int)ptrDataStr.IndexOf('\n');
  7034. if (crPos != -1)
  7035. ptrDataStr.RemoveToEnd(crPos);
  7036. ptrUseDataStr = ptrDataStr;
  7037. if ((origTypedValue.mRegNum != -1) && (!expr.IsEmpty()) && (!formatInfo.mExplicitThis))
  7038. {
  7039. // There's no address, use direct local identifier
  7040. ptrDataStr = expr;
  7041. ptrUseDataStr = expr;
  7042. }
  7043. // This keeps 'function' types from showing null as "<null parent>"
  7044. isBadSrc = false;
  7045. }
  7046. else if ((ptrVal == 0) && (dwValueType->IsCompositeType()))
  7047. {
  7048. }
  7049. DbgTypedValue useTypedValue = typedValue;
  7050. if ((origHadRef) || ((typedValue.mType->HasPointer()) && (!dwUseType->HasPointer())))
  7051. {
  7052. useTypedValue.mSrcAddress = useTypedValue.mPtr;
  7053. useTypedValue.mPtr = 0;
  7054. if (dwUseType->IsTypedPrimitive())
  7055. {
  7056. int byteCount = dwUseType->GetByteCount();
  7057. if (byteCount <= sizeof(intptr))
  7058. {
  7059. ReadMemory(useTypedValue.mSrcAddress, byteCount, &useTypedValue.mPtr);
  7060. }
  7061. }
  7062. }
  7063. useTypedValue.mType = dwUseType;
  7064. if ((!formatInfo.mNoVisualizers) && (!isNull) && (!isBadSrc))
  7065. {
  7066. if (language == DbgLanguage_Beef)
  7067. dwUseType->FixName();
  7068. debugVis = FindVisualizerForType(dwUseType, &dbgVisWildcardCaptures);
  7069. }
  7070. bool hadCustomDisplayString = false;
  7071. if (debugVis != NULL)
  7072. {
  7073. auto& displayStringList = (formatInfo.mRawString || wantStringView) ? debugVis->mStringViews : debugVis->mDisplayStrings;
  7074. for (auto displayEntry : displayStringList)
  7075. {
  7076. if (!displayEntry->mCondition.empty())
  7077. {
  7078. if (!EvalCondition(debugVis, dbgCompileUnit, useTypedValue, formatInfo, displayEntry->mCondition, dbgVisWildcardCaptures, displayString))
  7079. continue;
  7080. }
  7081. hadCustomDisplayString = true;
  7082. String displayStr = mDebugManager->mDebugVisualizers->DoStringReplace(displayEntry->mString, dbgVisWildcardCaptures);
  7083. if (displayString.length() > 0)
  7084. displayString += " ";
  7085. if (wantStringView)
  7086. {
  7087. DwFormatInfo strFormatInfo = formatInfo;
  7088. strFormatInfo.mRawString = true;
  7089. ProcessEvalString(dbgCompileUnit, useTypedValue, displayStr, stringViewData, strFormatInfo, debugVis, true);
  7090. }
  7091. else
  7092. ProcessEvalString(dbgCompileUnit, useTypedValue, displayStr, displayString, formatInfo, debugVis, true);
  7093. if (formatInfo.mRawString)
  7094. return displayString;
  7095. break;
  7096. }
  7097. if ((!debugVis->mExpandItems.empty()) || (debugVis->mCollectionType != DebugVisualizerEntry::CollectionType_None))
  7098. {
  7099. wantsCustomExpandedItems = true;
  7100. }
  7101. }
  7102. if (formatInfo.mRawString)
  7103. return "";
  7104. bool isTuple = (dwUseType->mName != NULL) && (dwUseType->mName[0] == '(') && (language == DbgLanguage_Beef);
  7105. if (isBadSrc)
  7106. {
  7107. displayString += "<null parent>";
  7108. }
  7109. else if ((!isNull) && (!formatInfo.mNoVisualizers) && (!hadCustomDisplayString))
  7110. {
  7111. // Create our own custom display
  7112. String firstRet;
  7113. String bigRet = isTuple ? "(" : "{ ";
  7114. int memberIdx = 0;
  7115. DbgType* summaryType = dwUseType;
  7116. bool summaryDone = false;
  7117. bool truncatedMemberList = false;
  7118. DbgTypedValue summaryTypedValue = useTypedValue;
  7119. String summaryDataStr = ptrDataStr;
  7120. String splatStr;
  7121. if (dataPtr == -1)
  7122. splatStr = expr;
  7123. while (summaryType != NULL)
  7124. {
  7125. summaryType->PopulateType();
  7126. if ((summaryType->IsTypedPrimitive()) &&
  7127. ((summaryType->mBaseTypes.IsEmpty()) || (!summaryType->mBaseTypes.front()->mBaseType->IsTypedPrimitive())))
  7128. {
  7129. if (formatInfo.mTotalSummaryLength + (int)displayString.length() > 255)
  7130. {
  7131. truncatedMemberList = true;
  7132. summaryDone = true;
  7133. bigRet += "...";
  7134. }
  7135. else
  7136. {
  7137. DwFormatInfo displayStrFormatInfo = formatInfo;
  7138. displayStrFormatInfo.mExpandItemDepth = 1;
  7139. displayStrFormatInfo.mTotalSummaryLength += (int)displayString.length();
  7140. displayStrFormatInfo.mHidePointers = false;
  7141. DbgType* primType = summaryType->mTypeParam;
  7142. String result;
  7143. if (primType->IsInteger())
  7144. formatInfo.mTypeKindFlags = (DbgTypeKindFlags)(formatInfo.mTypeKindFlags | DbgTypeKindFlag_Int);
  7145. if ((dataPtr != 0) && (dataPtr != -1))
  7146. {
  7147. String evalString = "(" + primType->ToString() + ")" + ptrDataStr;
  7148. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, origTypedValue, evalString, &displayStrFormatInfo);
  7149. if (evalResult)
  7150. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  7151. }
  7152. else
  7153. {
  7154. DbgTypedValue evalResult = origTypedValue;
  7155. evalResult.mType = primType;
  7156. String evalString = "(" + primType->ToString() + ")" + expr;
  7157. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  7158. }
  7159. if (formatInfo.mRawString)
  7160. return result;
  7161. int crPos = result.IndexOf('\n');
  7162. if (crPos != -1)
  7163. result.RemoveToEnd(crPos);
  7164. if (memberIdx == 0)
  7165. firstRet = result;
  7166. bigRet += result;
  7167. memberIdx++;
  7168. }
  7169. }
  7170. for (auto member : summaryType->mMemberList)
  7171. {
  7172. if (!member->mIsStatic)
  7173. {
  7174. if (formatInfo.mTotalSummaryLength + retVal.length() + bigRet.length() > 255)
  7175. {
  7176. truncatedMemberList = true;
  7177. summaryDone = true;
  7178. bigRet += "...";
  7179. break;
  7180. }
  7181. if (member->mName != NULL)
  7182. {
  7183. if (member->mName[0] == '$')
  7184. continue;
  7185. if (!isdigit(*member->mName))
  7186. {
  7187. if (memberIdx != 0)
  7188. bigRet += isTuple ? ", " : " ";
  7189. if ((!isTuple) || (member->mName[0] != '_'))
  7190. {
  7191. bigRet += String(member->mName);
  7192. bigRet += isTuple ? ":" : "=";
  7193. }
  7194. }
  7195. else
  7196. {
  7197. if (memberIdx != 0)
  7198. bigRet += ", ";
  7199. }
  7200. DwFormatInfo displayStrFormatInfo = formatInfo;
  7201. displayStrFormatInfo.mExpandItemDepth = 1;
  7202. displayStrFormatInfo.mHidePointers = false;
  7203. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + retVal.length() + bigRet.length();
  7204. String evalString;
  7205. if (dataPtr != -1)
  7206. {
  7207. if ((member->mName[0] >= '0') && (member->mName[0] <= '9'))
  7208. evalString += "this.";
  7209. evalString += String(member->mName); // +", this=" + summaryDataStr;
  7210. }
  7211. else
  7212. {
  7213. evalString = "(";
  7214. evalString += splatStr;
  7215. evalString += ").";
  7216. evalString += member->mName;
  7217. }
  7218. String referenceId;
  7219. String result;
  7220. if (!member->mType->IsValuelessType())
  7221. {
  7222. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, summaryTypedValue, evalString, &displayStrFormatInfo, &referenceId);
  7223. if (evalResult)
  7224. {
  7225. displayStrFormatInfo.mReferenceId = referenceId;
  7226. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  7227. int crPos = result.IndexOf('\n');
  7228. if (crPos != -1)
  7229. result.RemoveToEnd(crPos);
  7230. }
  7231. else
  7232. result = "???";
  7233. }
  7234. if (member->mType->IsInteger())
  7235. formatInfo.mTypeKindFlags = (DbgTypeKindFlags)(formatInfo.mTypeKindFlags | DbgTypeKindFlag_Int);
  7236. if (formatInfo.mRawString)
  7237. return result;
  7238. if (memberIdx == 0)
  7239. firstRet = result;
  7240. bigRet += result;
  7241. //formatInfo.mEmbeddedDisplayCount = displayStrFormatInfo.mEmbeddedDisplayCount;
  7242. memberIdx++;
  7243. }
  7244. else
  7245. {
  7246. //TODO: Handle C++ unions?
  7247. }
  7248. }
  7249. }
  7250. if (truncatedMemberList)
  7251. break;
  7252. // Find first base class with members
  7253. DbgType* nextSummaryType = NULL;
  7254. for (auto checkBase : summaryType->mBaseTypes)
  7255. {
  7256. auto checkBaseType = checkBase->mBaseType;
  7257. checkBaseType = checkBaseType->GetPrimaryType();
  7258. checkBaseType->PopulateType();
  7259. if ((checkBaseType->GetByteCount() > 0) || (checkBaseType->IsPrimitiveType()))
  7260. {
  7261. if (!splatStr.empty())
  7262. {
  7263. splatStr = "(" + checkBaseType->ToString() + ")" + splatStr;
  7264. }
  7265. else
  7266. {
  7267. summaryTypedValue.mType = checkBaseType;
  7268. }
  7269. nextSummaryType = checkBaseType;
  7270. break;
  7271. }
  7272. }
  7273. summaryType = nextSummaryType;
  7274. if (summaryType == NULL)
  7275. break;
  7276. // Don't add the Object members
  7277. if ((summaryType->GetBaseType() == NULL) && (summaryType->IsBfObject()))
  7278. break;
  7279. // If we don't have many members then find a base class with some members to show
  7280. if ((memberIdx != 0) && (displayString.length() >= 255))
  7281. {
  7282. truncatedMemberList = true;
  7283. bigRet += "...";
  7284. break;
  7285. }
  7286. }
  7287. bigRet += isTuple ? ")" : " }";
  7288. if (displayString.length() > 0)
  7289. displayString += " ";
  7290. if ((memberIdx == 1) && (!truncatedMemberList) && (firstRet.IndexOf('{') == -1) && (!isTuple))
  7291. displayString += "{ " + firstRet + " }";
  7292. else
  7293. displayString += bigRet;
  7294. }
  7295. DbgType* memberListType = actualType;
  7296. bool memberListForceCast = false;
  7297. if (actualType != NULL)
  7298. {
  7299. String valTypeName = displayType->ToString();
  7300. String actualTypeName = actualType->ToString(DbgLanguage_Unknown, true);
  7301. String actualUseTypeName = actualTypeName;
  7302. if ((int)actualTypeName.IndexOf('^') != -1)
  7303. useActualRawType = true;
  7304. if (useActualRawType)
  7305. actualUseTypeName = actualType->ToStringRaw();
  7306. if (displayString.empty())
  7307. {
  7308. // Nothing to display
  7309. }
  7310. else
  7311. {
  7312. if (!retVal.empty())
  7313. retVal += " ";
  7314. retVal += displayString;
  7315. }
  7316. retVal += "\n" + valTypeName;
  7317. if ((innerType->IsBaseBfObject()) || (innerType->IsInterface()))
  7318. {
  7319. if (actualType != innerType)
  7320. {
  7321. retVal += " {" + actualTypeName + "}";
  7322. memberListForceCast = true;
  7323. }
  7324. }
  7325. else
  7326. {
  7327. if (actualType != innerType)
  7328. {
  7329. retVal += " {" + actualTypeName + "}";
  7330. retVal += "\n";
  7331. if (!wantsCustomExpandedItems)
  7332. {
  7333. retVal += "[" + actualTypeName + "]\t((" + actualUseTypeName;
  7334. if (!actualType->IsBfObject())
  7335. retVal += "*";
  7336. retVal += ")this), nd, na, nv, this=" + ptrDataStr;
  7337. memberListType = innerType;
  7338. }
  7339. }
  7340. }
  7341. }
  7342. else
  7343. {
  7344. if ((formatInfo.mHidePointers) && (formatInfo.mIgnoreDerivedClassInfo))
  7345. {
  7346. displayType = innerType;
  7347. if (displayString.empty())
  7348. retVal += displayType->ToString(DbgLanguage_Unknown, true);
  7349. }
  7350. if (!displayString.empty())
  7351. {
  7352. if (!retVal.empty())
  7353. retVal += " ";
  7354. retVal += displayString;
  7355. }
  7356. else
  7357. {
  7358. if (formatInfo.mRawString)
  7359. return "";
  7360. }
  7361. retVal += "\n" + displayType->ToString(DbgLanguage_Unknown, true);
  7362. memberListType = innerType;
  7363. }
  7364. if ((isBfObject) && (mDebugTarget->mBfObjectHasFlags) && (!formatInfo.mNoVisualizers) && (!formatInfo.mRawString))
  7365. {
  7366. int stackTraceLen = 1;
  7367. addr_target stackTraceAddr = ptrVal + sizeof(addr_target);
  7368. if ((bfObjectFlags & BfObjectFlag_AllocInfo) != 0)
  7369. {
  7370. addr_target objectSize = ReadMemory<addr_target>(ptrVal + sizeof(addr_target));
  7371. addr_target largeAllocInfo = ReadMemory<addr_target>(ptrVal + objectSize);
  7372. stackTraceLen = (largeAllocInfo >> 8) & 0xFFFF;
  7373. stackTraceAddr = ptrVal + objectSize + sizeof(addr_target);
  7374. }
  7375. else if ((bfObjectFlags & BfObjectFlag_AllocInfo_Short) != 0)
  7376. {
  7377. addr_target dbgAllocInfo = ReadMemory<addr_target>(ptrVal + sizeof(addr_target));
  7378. stackTraceLen = dbgAllocInfo & 0xFF;
  7379. stackTraceAddr = ptrVal + (dbgAllocInfo >> 16);
  7380. }
  7381. retVal += StrFormat("\n[AllocStackTrace]\t(System.CallStackList)%s, count=%d, na", EncodeDataPtr(stackTraceAddr, true).c_str(), stackTraceLen);
  7382. }
  7383. retVal += StrFormat("\n:language\t%d", language);
  7384. if (formatInfo.mNoMembers)
  7385. {
  7386. //
  7387. }
  7388. else if (wantsCustomExpandedItems)
  7389. {
  7390. HandleCustomExpandedItems(retVal, dbgCompileUnit, debugVis, dwUseType, dwValueType, ptrUseDataStr, ptrDataStr, useTypedValue, dbgVisWildcardCaptures, formatInfo);
  7391. }
  7392. else if ((!isNull) && (!isBadSrc))
  7393. {
  7394. if (dataPtr == -1)
  7395. {
  7396. //String splatName = ((origTypedValue.mSrcAddress == -1) && (origTypedValue.mVariable != NULL)) ? origTypedValue.mVariable->mName : expr;
  7397. String splatName = expr;
  7398. retVal += "\n" + GetMemberList(memberListType, splatName, wasPtr, false, false, true, origTypedValue.mIsReadOnly);
  7399. }
  7400. else
  7401. {
  7402. retVal += "\n" + GetMemberList(memberListType, ptrDataStr, wasPtr, false, memberListForceCast, isCompositeWithoutAddress, origTypedValue.mIsReadOnly);
  7403. }
  7404. }
  7405. if (formatInfo.mExpandItemDepth > 0)
  7406. return retVal;
  7407. if (isAppendBfObject)
  7408. retVal += "\n:appendAlloc";
  7409. if (isStackBfObject)
  7410. retVal += "\n:stack";
  7411. if (isDeletedBfObject)
  7412. retVal += "\n:deleted";
  7413. if (!formatInfo.mAction.IsEmpty())
  7414. {
  7415. retVal += "\n:action\t";
  7416. retVal += formatInfo.mAction;
  7417. }
  7418. else if ((debugVis != NULL) && (!debugVis->mAction.empty()))
  7419. {
  7420. String rawActionStr = mDebugManager->mDebugVisualizers->DoStringReplace(debugVis->mAction, dbgVisWildcardCaptures);
  7421. String actionStr;
  7422. ProcessEvalString(dbgCompileUnit, useTypedValue, rawActionStr, actionStr, formatInfo, debugVis, true);
  7423. retVal += "\n:action\t" + actionStr;
  7424. }
  7425. if ((!typedValue.mIsLiteral) && (dwValueType->IsPointer()))
  7426. {
  7427. retVal += "\n:editVal\t" + EncodeDataPtr(ptrVal, true);
  7428. }
  7429. if (((debugVis != NULL) && (!debugVis->mStringViews.IsEmpty())) || (wantStringView))
  7430. retVal += "\n:stringView";
  7431. if (wantStringView)
  7432. {
  7433. retVal += "\t";
  7434. retVal += SlashString(stringViewData, false, false, true);
  7435. }
  7436. return retVal;
  7437. }
  7438. return "Unknown Type\n" + origValueType->ToString();
  7439. }
  7440. void WinDebugger::HandleCustomExpandedItems(String& retVal, DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgType* dwUseType, DbgType* dwValueType, String& ptrUseDataStr, String& ptrDataStr, DbgTypedValue useTypedValue, Array<String>& dbgVisWildcardCaptures, DwFormatInfo& formatInfo)
  7441. {
  7442. auto debugVisualizers = mDebugManager->mDebugVisualizers;
  7443. auto dbgModule = dbgCompileUnit->mDbgModule;
  7444. if (formatInfo.mExpandItemDepth > 10) // Avoid crashing on circular ExpandItems
  7445. return;
  7446. auto language = formatInfo.mLanguage;
  7447. bool isReadOnly = false;
  7448. if (useTypedValue.mIsReadOnly)
  7449. isReadOnly = true;
  7450. for (auto entry : debugVis->mExpandItems)
  7451. {
  7452. if (!entry->mCondition.empty())
  7453. {
  7454. String error;
  7455. if (!EvalCondition(debugVis, dbgCompileUnit, useTypedValue, formatInfo, entry->mCondition, dbgVisWildcardCaptures, error))
  7456. {
  7457. if (!error.empty())
  7458. retVal += "\n" + entry->mName + "\t@!<DbgVis Failed>@!";
  7459. continue;
  7460. }
  7461. }
  7462. String replacedStr = debugVisualizers->DoStringReplace(entry->mValue, dbgVisWildcardCaptures);
  7463. retVal += "\n" + entry->mName + "\t" + replacedStr + ", this=(" + ptrUseDataStr + ")";
  7464. }
  7465. String referenceId = dwUseType->ToString();
  7466. if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_ExpandedItem)
  7467. {
  7468. DbgTypedValue itemValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7469. if (itemValue)
  7470. {
  7471. DwFormatInfo itemFormatInfo = formatInfo;
  7472. itemFormatInfo.mExpandItemDepth++;
  7473. String itemRetVal = DbgTypedValueToString(itemValue, "", itemFormatInfo, NULL);
  7474. int crIdx = (int)itemRetVal.IndexOf('\n');
  7475. if (crIdx != -1)
  7476. {
  7477. crIdx = (int)itemRetVal.IndexOf('\n', crIdx + 1);
  7478. if (crIdx != -1)
  7479. retVal += itemRetVal.Substring(crIdx);
  7480. }
  7481. }
  7482. }
  7483. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Array)
  7484. {
  7485. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7486. Array<int> lowerDimSizes;
  7487. for (auto lowerDim : debugVis->mLowerDimSizes)
  7488. {
  7489. DbgTypedValue lowerDimValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(lowerDim, dbgVisWildcardCaptures), &formatInfo);
  7490. int dimSize = 0;
  7491. if ((lowerDimValue) && (lowerDimValue.mType->IsInteger()))
  7492. dimSize = (int)lowerDimValue.GetInt64();
  7493. dimSize = BF_MAX(dimSize, 1);
  7494. lowerDimSizes.push_back(dimSize);
  7495. }
  7496. if ((sizeValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7497. {
  7498. if (!debugVis->mCondition.IsEmpty())
  7499. {
  7500. int size = (int)sizeValue.GetInt64();
  7501. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7502. DbgTypedValue curNode = headPointer;
  7503. Array<addr_target> parentList;
  7504. String continuationData;
  7505. int totalSize = 2;
  7506. auto valueType = headPointer.mType;
  7507. String addrs = GetArrayItems(dbgCompileUnit, debugVis, valueType, headPointer, totalSize, &continuationData);
  7508. String firstAddr;
  7509. String secondAddr;
  7510. bool hasSecondAddr = valueType == NULL;
  7511. if (addrs.length() > 0)
  7512. {
  7513. const char* addrsPtr = addrs.c_str();
  7514. firstAddr = addrs.Substring(0, sizeof(addr_target) * 2);
  7515. if (hasSecondAddr)
  7516. secondAddr = addrs.Substring(sizeof(addr_target) * 2, sizeof(addr_target) * 2);
  7517. }
  7518. String evalStr;
  7519. if (valueType != NULL)
  7520. {
  7521. evalStr = "(" + valueType->ToStringRaw();
  7522. if (!valueType->IsPointer())
  7523. evalStr += "*";
  7524. evalStr += ")0x{1}";
  7525. }
  7526. else
  7527. {
  7528. evalStr += "({1})0x{2}";
  7529. }
  7530. if (!debugVis->mShowElementAddrs)
  7531. evalStr.Insert(0, "*");
  7532. if (addrs.length() > 0)
  7533. {
  7534. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7535. if (isReadOnly)
  7536. evalStr += ", ne";
  7537. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, BF_MAX(size, 0), 10000) +
  7538. "\t[{0}]\t" + evalStr + "\t" + firstAddr;
  7539. if (hasSecondAddr)
  7540. retVal += "\t" + secondAddr;
  7541. if (size != 0)
  7542. {
  7543. retVal += "\n:addrs\t" + addrs;
  7544. if (valueType == NULL)
  7545. retVal += "\n:addrsEntrySize\t2";
  7546. if (continuationData.length() > 0)
  7547. retVal += "\n:continuation\t" + continuationData;
  7548. }
  7549. }
  7550. }
  7551. else if (lowerDimSizes.size() == 1)
  7552. {
  7553. int dimSize1 = lowerDimSizes[0];
  7554. String evalStr = "(" + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7555. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7556. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7557. if (isReadOnly)
  7558. evalStr += ", ne";
  7559. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, sizeValue.GetInt64() / dimSize1, 50000) +
  7560. "\t[{0}]\t" + evalStr;
  7561. }
  7562. else if (lowerDimSizes.size() == 2)
  7563. {
  7564. int dimSize1 = lowerDimSizes[0];
  7565. int dimSize2 = lowerDimSizes[1];
  7566. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7567. if ((headPointer.mType != NULL) && (headPointer.mType->IsPointer()))
  7568. {
  7569. String evalStr = StrFormat("((%s[%d]*)", headPointer.mType->mTypeParam->ToStringRaw(language).c_str(), dimSize2) + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7570. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7571. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7572. if (isReadOnly)
  7573. evalStr += ", ne";
  7574. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, sizeValue.GetInt64() / dimSize1 / dimSize2, 50000) +
  7575. "\t[{0}]\t" + evalStr;
  7576. }
  7577. }
  7578. else if (lowerDimSizes.size() == 3)
  7579. {
  7580. int dimSize1 = lowerDimSizes[0];
  7581. int dimSize2 = lowerDimSizes[1];
  7582. int dimSize3 = lowerDimSizes[2];
  7583. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7584. if ((headPointer.mType != NULL) && (headPointer.mType->IsPointer()))
  7585. {
  7586. String evalStr = StrFormat("((%s[%d][%d]*)", headPointer.mType->mTypeParam->ToStringRaw(language).c_str(), dimSize2, dimSize3) + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7587. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7588. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7589. if (isReadOnly)
  7590. evalStr += ", ne";
  7591. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, sizeValue.GetInt64() / dimSize1 / dimSize2 / dimSize3, 50000) +
  7592. "\t[{0}]\t" + evalStr;
  7593. }
  7594. }
  7595. else
  7596. {
  7597. String evalStr = "*(" + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) + " + {0}), this=" + ptrUseDataStr;
  7598. evalStr += ", refid=\"" + referenceId + ".[]${0}\"";
  7599. if (isReadOnly)
  7600. evalStr += ", ne";
  7601. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, sizeValue.GetInt64(), 50000) +
  7602. "\t[{0}]\t" + evalStr;
  7603. }
  7604. }
  7605. }
  7606. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_IndexItems)
  7607. {
  7608. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7609. if ((sizeValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7610. {
  7611. String evalStr = debugVis->mValuePointer + ", this=" + ptrUseDataStr;
  7612. evalStr.Replace("$i", "{0}");
  7613. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7614. if (isReadOnly)
  7615. evalStr += ", ne";
  7616. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, sizeValue.GetInt64(), 50000) +
  7617. "\t[{0}]\t" + evalStr;
  7618. }
  7619. }
  7620. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_LinkedList)
  7621. {
  7622. DbgType* valueType = NULL;
  7623. if (!debugVis->mValueType.empty())
  7624. {
  7625. valueType = dbgModule->FindType(debugVisualizers->DoStringReplace(debugVis->mValueType, dbgVisWildcardCaptures), dwValueType);
  7626. if (valueType != NULL)
  7627. valueType = valueType->ResolveTypeDef();
  7628. }
  7629. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mHeadPointer, dbgVisWildcardCaptures), &formatInfo);
  7630. if (headPointer)
  7631. {
  7632. DbgTypedValue endPointer;
  7633. if (!debugVis->mEndPointer.empty())
  7634. endPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mEndPointer, dbgVisWildcardCaptures), &formatInfo);
  7635. DbgTypedValue nextPointer = EvaluateInContext(dbgCompileUnit, headPointer, debugVisualizers->DoStringReplace(debugVis->mNextPointer, dbgVisWildcardCaptures), &formatInfo);
  7636. int size = -1;
  7637. if (!debugVis->mSize.empty())
  7638. {
  7639. auto sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7640. if (sizeValue)
  7641. size = (int)sizeValue.GetInt64();
  7642. }
  7643. DbgTypedValue curNode = headPointer;
  7644. Array<addr_target> parentList;
  7645. String continuationData;
  7646. int totalSize = 2;
  7647. String addrs = GetLinkedListItems(dbgCompileUnit, debugVis, endPointer.mPtr, valueType, curNode, totalSize, &continuationData);
  7648. String firstAddr;
  7649. String secondAddr;
  7650. bool hasSecondAddr = valueType == NULL;
  7651. if (addrs.length() > 0)
  7652. {
  7653. const char* addrsPtr = addrs.c_str();
  7654. firstAddr = addrs.Substring(0, sizeof(addr_target)*2);
  7655. if (hasSecondAddr)
  7656. secondAddr = addrs.Substring(sizeof(addr_target)*2, sizeof(addr_target)*2);
  7657. }
  7658. String evalStr;
  7659. if (valueType != NULL)
  7660. {
  7661. evalStr = "(" + valueType->ToStringRaw();
  7662. if (!valueType->IsPointer())
  7663. evalStr += "*";
  7664. evalStr += ")0x{1}";
  7665. }
  7666. else
  7667. {
  7668. evalStr += "({1})0x{2}";
  7669. }
  7670. if (!debugVis->mShowElementAddrs)
  7671. evalStr.Insert(0, "*");
  7672. if (addrs.length() > 0)
  7673. {
  7674. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7675. if (isReadOnly)
  7676. evalStr += ", ne";
  7677. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, size, 10000) +
  7678. "\t[{0}]\t" + evalStr + "\t" + firstAddr;
  7679. if (hasSecondAddr)
  7680. retVal += "\t" + secondAddr;
  7681. if (size != 0)
  7682. {
  7683. retVal += "\n:addrs\t" + addrs;
  7684. if (valueType == NULL)
  7685. retVal += "\n:addrsEntrySize\t2";
  7686. if (continuationData.length() > 0)
  7687. retVal += "\n:continuation\t" + continuationData;
  7688. }
  7689. }
  7690. }
  7691. }
  7692. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_TreeItems)
  7693. {
  7694. DbgType* valueType = NULL;
  7695. if (!debugVis->mValueType.empty())
  7696. {
  7697. valueType = dbgModule->FindType(debugVisualizers->DoStringReplace(debugVis->mValueType, dbgVisWildcardCaptures), dwValueType);
  7698. if (valueType != NULL)
  7699. valueType = valueType->ResolveTypeDef();
  7700. }
  7701. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7702. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mHeadPointer, dbgVisWildcardCaptures), &formatInfo);
  7703. if (sizeValue)
  7704. sizeValue.mType = sizeValue.mType->RemoveModifiers();
  7705. if ((sizeValue) && (headPointer) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7706. {
  7707. DbgTypedValue curNode = headPointer;
  7708. Array<addr_target> parentList;
  7709. String continuationData;
  7710. int getItemCount = (int)BF_MIN(sizeValue.GetInt64(), 32LL);
  7711. String addrs = GetTreeItems(dbgCompileUnit, debugVis, parentList, valueType, curNode, getItemCount, &continuationData);
  7712. addr_target firstAddr = 0;
  7713. addr_target secondAddr = 0;
  7714. bool hasSecondAddr = valueType == NULL;
  7715. if (addrs.length() > 0)
  7716. {
  7717. const char* addrsPtr = addrs.c_str();
  7718. firstAddr = DecodeTargetDataPtr(addrsPtr);
  7719. if (hasSecondAddr)
  7720. secondAddr = DecodeTargetDataPtr(addrsPtr);
  7721. }
  7722. String evalStr;
  7723. if (valueType != NULL)
  7724. {
  7725. evalStr = "*(" + valueType->ToStringRaw();
  7726. if (!valueType->IsPointer())
  7727. evalStr += "*";
  7728. evalStr += ")0x{1}";
  7729. }
  7730. else
  7731. {
  7732. evalStr += "*(_T_{1}*)0x{2}";
  7733. }
  7734. int size = (int)sizeValue.GetInt64();
  7735. if (addrs.length() == 0)
  7736. {
  7737. evalStr = ""; // Failed
  7738. }
  7739. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7740. if (isReadOnly)
  7741. evalStr += ", ne";
  7742. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, size, 10000) +
  7743. "\t[{0}]\t" + evalStr + "\t" + EncodeDataPtr(firstAddr, false);
  7744. if (hasSecondAddr)
  7745. retVal += "\t" + EncodeDataPtr(secondAddr, false);
  7746. if (addrs.length() > 0)
  7747. {
  7748. retVal += "\n:addrs\t" + addrs;
  7749. if (continuationData.length() > 0)
  7750. retVal += "\n:continuation\t" + continuationData;
  7751. }
  7752. }
  7753. }
  7754. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Dictionary)
  7755. {
  7756. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7757. DbgTypedValue entriesPtrValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mEntries, dbgVisWildcardCaptures), &formatInfo);
  7758. if (sizeValue)
  7759. sizeValue.mType = sizeValue.mType->RemoveModifiers();
  7760. if ((sizeValue) && (entriesPtrValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7761. {
  7762. String continuationData;
  7763. DbgType* valueType = entriesPtrValue.mType;
  7764. int getItemCount = (int)std::min(sizeValue.GetInt64(), 2LL);
  7765. DbgType* useTypedValType = useTypedValue.mType;
  7766. addr_target useTypedValPtr = useTypedValue.mPtr;
  7767. addr_target useTypedValAddr = useTypedValue.mSrcAddress;
  7768. String addrs = GetDictionaryItems(dbgCompileUnit, debugVis, useTypedValue, 0, -1, getItemCount, &continuationData);
  7769. addr_target firstAddr = 0;
  7770. if (addrs.length() > 0)
  7771. {
  7772. const char* addrsPtr = addrs.c_str();
  7773. firstAddr = DecodeTargetDataPtr(addrsPtr);
  7774. }
  7775. String evalStr = "((" + valueType->ToStringRaw() + ")0x{1}), na";
  7776. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7777. if (isReadOnly)
  7778. evalStr += ", ne";
  7779. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64(), 10000) +
  7780. "\t[{0}]\t" + evalStr + "\t" + EncodeDataPtr(firstAddr, false);
  7781. if (addrs.length() > 0)
  7782. {
  7783. retVal += "\n:addrs\t" + addrs;
  7784. if (continuationData.length() > 0)
  7785. retVal += "\n:continuation\t" + continuationData;
  7786. }
  7787. }
  7788. }
  7789. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_CallStackList)
  7790. {
  7791. int size = 0;
  7792. String addrs;
  7793. String firstVal;
  7794. auto ptr = useTypedValue.mPtr;
  7795. for (int i = 0; i < formatInfo.mOverrideCount; i++)
  7796. {
  7797. auto funcAddr = ReadMemory<addr_target>(ptr + i * sizeof(addr_target));
  7798. auto srcFuncAddr = funcAddr;
  7799. addrs += EncodeDataPtr(funcAddr - 1, false);
  7800. if (i == 0)
  7801. firstVal = addrs;
  7802. addrs += EncodeDataPtr((addr_target)0, false);
  7803. size++;
  7804. int inlineIdx = 0;
  7805. auto subProgram = mDebugTarget->FindSubProgram(funcAddr - 1, DbgOnDemandKind_LocalOnly);
  7806. while (subProgram != NULL)
  7807. {
  7808. if (subProgram->mInlineeInfo == NULL)
  7809. break;
  7810. auto prevFuncAddr = subProgram->mBlock.mLowPC;
  7811. subProgram = subProgram->mInlineeInfo->mInlineParent;
  7812. addrs += EncodeDataPtr(subProgram->mBlock.mLowPC + 1, false);
  7813. addrs += EncodeDataPtr(prevFuncAddr, false);
  7814. size++;
  7815. inlineIdx++;
  7816. }
  7817. }
  7818. String evalStr = "(System.CallStackAddr)0x{1}";
  7819. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7820. evalStr += ", ne";
  7821. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, size, 10000) +
  7822. "\t[{0}]\t" + evalStr + ", action=ShowCodeAddr {1} {2}\t" + firstVal + "\t" + EncodeDataPtr((addr_target)0, false);
  7823. retVal += "\n:addrs\t" + addrs;
  7824. retVal += "\n:addrsEntrySize\t2";
  7825. return;
  7826. }
  7827. if (formatInfo.mExpandItemDepth == 0)
  7828. {
  7829. //retVal += "\n[Raw View]\tthis, this=" + ptrDataStr + ", nv";
  7830. retVal += "\n[Raw View]\t" + ptrDataStr + ", nv";
  7831. }
  7832. }
  7833. bool WinDebugger::IsPaused()
  7834. {
  7835. return (mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint) || (mRunState == RunState_Exception) || (mRunState == RunState_DebugEval_Done);
  7836. }
  7837. DbgTypedValue WinDebugger::GetRegister(const StringImpl& regName, DbgLanguage language, CPURegisters* registers, Array<RegForm>* regForms)
  7838. {
  7839. int regNum = -1;
  7840. String lwrRegName(regName);
  7841. _strlwr((char*)lwrRegName.c_str());
  7842. // int regs
  7843. #ifdef BF_DBG_32
  7844. DbgTypeCode regType = DbgType_i32;
  7845. if (lwrRegName == "eax")
  7846. regNum = X86Reg_EAX;
  7847. else if (lwrRegName == "ecx")
  7848. regNum = X86Reg_ECX;
  7849. else if (lwrRegName == "edx")
  7850. regNum = X86Reg_EDX;
  7851. else if (lwrRegName == "ebx")
  7852. regNum = X86Reg_EBX;
  7853. else if (lwrRegName == "esp")
  7854. regNum = X86Reg_ESP;
  7855. else if (lwrRegName == "ebp")
  7856. regNum = X86Reg_EBP;
  7857. else if (lwrRegName == "esi")
  7858. regNum = X86Reg_ESI;
  7859. else if (lwrRegName == "edi")
  7860. regNum = X86Reg_EDI;
  7861. else if (lwrRegName == "eip")
  7862. regNum = X86Reg_EIP;
  7863. else if (lwrRegName == "efl")
  7864. regNum = X86Reg_EFL;
  7865. #else
  7866. DbgTypeCode regType = DbgType_i64;
  7867. if (lwrRegName == "rax")
  7868. regNum = X64Reg_RAX;
  7869. else if (lwrRegName == "rcx")
  7870. regNum = X64Reg_RCX;
  7871. else if (lwrRegName == "rdx")
  7872. regNum = X64Reg_RDX;
  7873. else if (lwrRegName == "rbx")
  7874. regNum = X64Reg_RBX;
  7875. else if (lwrRegName == "rsp")
  7876. regNum = X64Reg_RSP;
  7877. else if (lwrRegName == "rbp")
  7878. regNum = X64Reg_RBP;
  7879. else if (lwrRegName == "rsi")
  7880. regNum = X64Reg_RSI;
  7881. else if (lwrRegName == "rdi")
  7882. regNum = X64Reg_RDI;
  7883. else if (lwrRegName == "rip")
  7884. regNum = X64Reg_RIP;
  7885. else if (lwrRegName == "r8")
  7886. regNum = X64Reg_R8;
  7887. else if (lwrRegName == "r9")
  7888. regNum = X64Reg_R9;
  7889. else if (lwrRegName == "r10")
  7890. regNum = X64Reg_R10;
  7891. else if (lwrRegName == "r11")
  7892. regNum = X64Reg_R11;
  7893. else if (lwrRegName == "r12")
  7894. regNum = X64Reg_R12;
  7895. else if (lwrRegName == "r13")
  7896. regNum = X64Reg_R13;
  7897. else if (lwrRegName == "r14")
  7898. regNum = X64Reg_R14;
  7899. else if (lwrRegName == "r15")
  7900. regNum = X64Reg_R15;
  7901. else
  7902. {
  7903. regType = DbgType_i32;
  7904. if (lwrRegName == "eax")
  7905. regNum = X64Reg_RAX;
  7906. else if (lwrRegName == "ecx")
  7907. regNum = X64Reg_RCX;
  7908. else if (lwrRegName == "edx")
  7909. regNum = X64Reg_RDX;
  7910. else if (lwrRegName == "ebx")
  7911. regNum = X64Reg_RBX;
  7912. else if (lwrRegName == "efl")
  7913. regNum = X64Reg_EFL;
  7914. else if (lwrRegName == "esi")
  7915. regNum = X64Reg_RSI;
  7916. else if (lwrRegName == "edi")
  7917. regNum = X64Reg_RDI;
  7918. else if (lwrRegName == "r8d")
  7919. regNum = X64Reg_R8;
  7920. else if (lwrRegName == "r9d")
  7921. regNum = X64Reg_R9;
  7922. else if (lwrRegName == "r10d")
  7923. regNum = X64Reg_R10;
  7924. else if (lwrRegName == "r11d")
  7925. regNum = X64Reg_R11;
  7926. else if (lwrRegName == "r12d")
  7927. regNum = X64Reg_R12;
  7928. else if (lwrRegName == "r13d")
  7929. regNum = X64Reg_R13;
  7930. else if (lwrRegName == "r14d")
  7931. regNum = X64Reg_R14;
  7932. else if (lwrRegName == "r15d")
  7933. regNum = X64Reg_R15;
  7934. else
  7935. {
  7936. regType = DbgType_i16;
  7937. if (lwrRegName == "ax")
  7938. regNum = X64Reg_RAX;
  7939. else if (lwrRegName == "cx")
  7940. regNum = X64Reg_RCX;
  7941. else if (lwrRegName == "dx")
  7942. regNum = X64Reg_RDX;
  7943. else if (lwrRegName == "bx")
  7944. regNum = X64Reg_RBX;
  7945. else if (lwrRegName == "si")
  7946. regNum = X64Reg_RSI;
  7947. else if (lwrRegName == "di")
  7948. regNum = X64Reg_RDI;
  7949. else if (lwrRegName == "r8w")
  7950. regNum = X64Reg_R8;
  7951. else if (lwrRegName == "r9w")
  7952. regNum = X64Reg_R9;
  7953. else if (lwrRegName == "r10w")
  7954. regNum = X64Reg_R10;
  7955. else if (lwrRegName == "r11w")
  7956. regNum = X64Reg_R11;
  7957. else if (lwrRegName == "r12w")
  7958. regNum = X64Reg_R12;
  7959. else if (lwrRegName == "r13w")
  7960. regNum = X64Reg_R13;
  7961. else if (lwrRegName == "r14w")
  7962. regNum = X64Reg_R14;
  7963. else if (lwrRegName == "r15w")
  7964. regNum = X64Reg_R15;
  7965. else
  7966. {
  7967. regType = DbgType_i8;
  7968. if (lwrRegName == "al")
  7969. regNum = X64Reg_RAX;
  7970. else if (lwrRegName == "cl")
  7971. regNum = X64Reg_RCX;
  7972. else if (lwrRegName == "dl")
  7973. regNum = X64Reg_RDX;
  7974. else if (lwrRegName == "bl")
  7975. regNum = X64Reg_RBX;
  7976. else if (lwrRegName == "sil")
  7977. regNum = X64Reg_RSI;
  7978. else if (lwrRegName == "dil")
  7979. regNum = X64Reg_RDI;
  7980. else if (lwrRegName == "r8b")
  7981. regNum = X64Reg_R8;
  7982. else if (lwrRegName == "r9b")
  7983. regNum = X64Reg_R9;
  7984. else if (lwrRegName == "r10b")
  7985. regNum = X64Reg_R10;
  7986. else if (lwrRegName == "r11b")
  7987. regNum = X64Reg_R11;
  7988. else if (lwrRegName == "r12b")
  7989. regNum = X64Reg_R12;
  7990. else if (lwrRegName == "r13b")
  7991. regNum = X64Reg_R13;
  7992. else if (lwrRegName == "r14b")
  7993. regNum = X64Reg_R14;
  7994. else if (lwrRegName == "r15b")
  7995. regNum = X64Reg_R15;
  7996. }
  7997. }
  7998. }
  7999. #endif
  8000. auto dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  8001. if (regNum != -1)
  8002. {
  8003. DbgTypedValue typedVal;
  8004. typedVal.mType = dbgModule->GetPrimitiveType(regType, language);
  8005. typedVal.mInt64 = registers->mIntRegsArray[regNum];
  8006. typedVal.mRegNum = regNum;
  8007. return typedVal;
  8008. }
  8009. // st regs
  8010. if ((lwrRegName.length() == 3) && (lwrRegName[0] == 's') && (lwrRegName[1] == 't') && (lwrRegName[2] >= '0') && (lwrRegName[2] <= '7'))
  8011. {
  8012. regNum = CPUReg_FPSTREG_FIRST + (lwrRegName[2] - '0');
  8013. }
  8014. if (regNum != -1)
  8015. {
  8016. DbgTypedValue typedVal;
  8017. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Double, language);
  8018. typedVal.mDouble = ConvertFloat80ToDouble(registers->mFpMmRegsArray[regNum - CPUReg_FPSTREG_FIRST].fp.fp80);
  8019. typedVal.mRegNum = regNum;
  8020. return typedVal;
  8021. }
  8022. // mm regs
  8023. if ((lwrRegName.length() == 3) && (lwrRegName[0] == 'm') && (lwrRegName[1] == 'm') && (lwrRegName[2] >= '0') && (lwrRegName[2] <= '7'))
  8024. {
  8025. regNum = CPUReg_MMREG_FIRST + (lwrRegName[2] - '0');
  8026. }
  8027. if (regNum != -1)
  8028. {
  8029. DbgTypedValue typedVal;
  8030. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_i64, language);
  8031. typedVal.mInt64 = registers->mFpMmRegsArray[regNum - CPUReg_MMREG_FIRST].mm;
  8032. typedVal.mRegNum = regNum;
  8033. return typedVal;
  8034. }
  8035. // xmm regs
  8036. #ifdef BF_DBG_32
  8037. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '7') &&
  8038. (lwrRegName[4] == '_') && (lwrRegName[5] >= '0') && (lwrRegName[5] <= '3'))
  8039. {
  8040. regNum = CPUReg_XMMREG_FIRST + ((lwrRegName[3] - '0') * 4) + (lwrRegName[5] - '0');
  8041. }
  8042. #else
  8043. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '9') &&
  8044. (lwrRegName[4] == '_') && (lwrRegName[5] >= '0') && (lwrRegName[5] <= '3'))
  8045. {
  8046. regNum = CPUReg_XMMREG_FIRST + ((lwrRegName[3] - '0') * 4) + (lwrRegName[5] - '0');
  8047. }
  8048. if ((lwrRegName.length() == 7) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] == '1') && (lwrRegName[4] >= '0') && (lwrRegName[4] <= '9') &&
  8049. (lwrRegName[5] == '_') && (lwrRegName[6] >= '0') && (lwrRegName[6] <= '3'))
  8050. {
  8051. regNum = CPUReg_XMMREG_FIRST + ((10 + (lwrRegName[4] - '0')) * 4) + (lwrRegName[6] - '0');
  8052. }
  8053. #endif
  8054. if (regNum != -1)
  8055. {
  8056. int xmmMajor = (regNum - CPUReg_XMMREG_FIRST) >> 2;
  8057. int xmmMinor = (regNum - CPUReg_XMMREG_FIRST) & 3;
  8058. DwMmDisplayType mmDisplayType = GetDisplayInfo(StrFormat("$XMM%d", xmmMajor))->mMmDisplayType;
  8059. RegForm regForm = RegForm_Unknown;
  8060. if (regForms != NULL)
  8061. {
  8062. int regFormIdx = CPUReg_M128_XMMREG_FIRST + xmmMajor;
  8063. if (regFormIdx < (int)regForms->size())
  8064. regForm = (*regForms)[regFormIdx];
  8065. }
  8066. if (mmDisplayType == DwMmDisplayType_Default)
  8067. {
  8068. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2))
  8069. mmDisplayType = DwMmDisplayType_Double;
  8070. else if (regForm == RegForm_Int4)
  8071. mmDisplayType = DwMmDisplayType_Int32;
  8072. }
  8073. //TODO: Add int types
  8074. if (mmDisplayType == DwMmDisplayType_Double)
  8075. {
  8076. DbgTypedValue typedVal;
  8077. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Double, language);
  8078. typedVal.mDouble = registers->mXmmDRegsArray[xmmMajor].d[xmmMinor];
  8079. typedVal.mRegNum = regNum;
  8080. return typedVal;
  8081. }
  8082. else if ((mmDisplayType == DwMmDisplayType_UInt8) || (mmDisplayType == DwMmDisplayType_Int16) || (mmDisplayType == DwMmDisplayType_Int32))
  8083. {
  8084. DbgTypedValue typedVal;
  8085. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_i32, language);
  8086. typedVal.mInt32 = registers->mXmmI32RegsARray[xmmMajor].i[xmmMinor];
  8087. typedVal.mRegNum = regNum;
  8088. return typedVal;
  8089. }
  8090. else if (mmDisplayType == DwMmDisplayType_Int64)
  8091. {
  8092. DbgTypedValue typedVal;
  8093. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_i64, language);
  8094. typedVal.mInt64 = registers->mXmmI64RegsARray[xmmMajor].i[xmmMinor];
  8095. typedVal.mRegNum = regNum;
  8096. return typedVal;
  8097. }
  8098. DbgTypedValue typedVal;
  8099. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Single, language);
  8100. typedVal.mSingle = registers->mXmmRegsArray[xmmMajor].f[xmmMinor];
  8101. typedVal.mRegNum = regNum;
  8102. return typedVal;
  8103. }
  8104. #ifdef BF_DBG_32
  8105. if ((lwrRegName.length() == 4) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '7'))
  8106. {
  8107. regNum = CPUReg_M128_XMMREG_FIRST + (lwrRegName[3] - '0');
  8108. }
  8109. #else
  8110. if ((lwrRegName.length() == 4) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '9'))
  8111. {
  8112. regNum = CPUReg_M128_XMMREG_FIRST + (lwrRegName[3] - '0');
  8113. }
  8114. if ((lwrRegName.length() == 5) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] == '1') && (lwrRegName[4] >= '0') && (lwrRegName[4] <= '5'))
  8115. {
  8116. regNum = CPUReg_M128_XMMREG_FIRST + 10 + (lwrRegName[4] - '0');
  8117. }
  8118. #endif
  8119. if (regNum != -1)
  8120. {
  8121. DbgTypedValue typedVal;
  8122. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_RegGroup, language);
  8123. 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)
  8124. typedVal.mRegNum = regNum;
  8125. return typedVal;
  8126. }
  8127. // flags
  8128. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'f') && (lwrRegName[1] == 'l') && (lwrRegName[2] == 'a') && (lwrRegName[3] == 'g') && (lwrRegName[5] == 'f'))
  8129. {
  8130. switch(lwrRegName[4])
  8131. {
  8132. case 'c': regNum = CPUReg_FLAG_CF_CARRY; break;
  8133. case 'p': regNum = CPUReg_FLAG_PF_PARITY; break;
  8134. case 'a': regNum = CPUReg_FLAG_AF_ADJUST; break;
  8135. case 'z': regNum = CPUReg_FLAG_ZF_ZERO; break;
  8136. case 's': regNum = CPUReg_FLAG_SF_SIGN; break;
  8137. case 'i': regNum = CPUReg_FLAG_IF_INTERRUPT; break;
  8138. case 'd': regNum = CPUReg_FLAG_DF_DIRECTION; break;
  8139. case 'o': regNum = CPUReg_FLAG_OF_OVERFLOW; break;
  8140. default: break;
  8141. }
  8142. }
  8143. if (regNum != -1)
  8144. {
  8145. int flagBit = CPURegisters::GetFlagBitForRegister(regNum);
  8146. BF_ASSERT(flagBit >= 0);
  8147. DbgTypedValue typedVal;
  8148. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Bool, language);
  8149. typedVal.mBool = (registers->mIntRegs.efl & ((uint64)1 << flagBit)) != 0;
  8150. typedVal.mRegNum = regNum;
  8151. return typedVal;
  8152. }
  8153. // categories
  8154. if (lwrRegName == "allregs")
  8155. regNum = CPUReg_CAT_ALLREGS;
  8156. else if (lwrRegName == "iregs")
  8157. regNum = CPUReg_CAT_IREGS;
  8158. else if (lwrRegName == "fpregs")
  8159. regNum = CPUReg_CAT_FPREGS;
  8160. else if (lwrRegName == "mmregs")
  8161. regNum = CPUReg_CAT_MMREGS;
  8162. else if (lwrRegName == "xmmregs")
  8163. regNum = CPUReg_CAT_XMMREGS;
  8164. else if (lwrRegName == "flags")
  8165. regNum = CPUReg_CAT_FLAGS;
  8166. if (regNum != -1)
  8167. {
  8168. DbgTypedValue typedVal;
  8169. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_RegGroup, language);
  8170. 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)
  8171. typedVal.mRegNum = regNum;
  8172. return typedVal;
  8173. }
  8174. return DbgTypedValue();
  8175. }
  8176. DbgModule* WinDebugger::GetCallStackDbgModule(int callStackIdx)
  8177. {
  8178. if ((mRunState == RunState_NotStarted) || (!IsPaused()))
  8179. return mEmptyDebugTarget->GetMainDbgModule();
  8180. if (callStackIdx == -1)
  8181. return mDebugTarget->GetMainDbgModule();
  8182. FixCallStackIdx(callStackIdx);
  8183. if (callStackIdx >= mCallStack.size())
  8184. return mDebugTarget->GetMainDbgModule();
  8185. UpdateCallStackMethod(callStackIdx);
  8186. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  8187. if (subProgram != NULL)
  8188. return subProgram->mCompileUnit->mDbgModule;
  8189. auto dbgModule = mDebugTarget->FindDbgModuleForAddress(mCallStack[callStackIdx]->mRegisters.GetPC());
  8190. if (dbgModule != NULL)
  8191. return dbgModule;
  8192. return mDebugTarget->GetMainDbgModule();
  8193. }
  8194. DbgSubprogram* WinDebugger::GetCallStackSubprogram(int callStackIdx)
  8195. {
  8196. if ((IsInRunState()) || (mRunState == RunState_NotStarted) || (callStackIdx == -1))
  8197. return NULL;
  8198. if (callStackIdx >= (int)mCallStack.size())
  8199. UpdateCallStack();
  8200. if (mCallStack.IsEmpty())
  8201. return NULL;
  8202. if (callStackIdx >= (int)mCallStack.size())
  8203. callStackIdx = 0;
  8204. UpdateCallStackMethod(callStackIdx);
  8205. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  8206. return subProgram;
  8207. }
  8208. DbgCompileUnit* WinDebugger::GetCallStackCompileUnit(int callStackIdx)
  8209. {
  8210. if ((IsInRunState()) || (mRunState == RunState_NotStarted) || (callStackIdx == -1))
  8211. return NULL;
  8212. if (callStackIdx >= (int)mCallStack.size())
  8213. UpdateCallStack();
  8214. if (mCallStack.IsEmpty())
  8215. return NULL;
  8216. if (callStackIdx >= (int)mCallStack.size())
  8217. callStackIdx = 0;
  8218. UpdateCallStackMethod(callStackIdx);
  8219. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  8220. if (subProgram == NULL)
  8221. return NULL;
  8222. return subProgram->mCompileUnit;
  8223. }
  8224. String WinDebugger::EvaluateContinue(DbgPendingExpr* pendingExpr, BfPassInstance& bfPassInstance)
  8225. {
  8226. DbgModule* dbgModule = NULL;
  8227. DbgCompileUnit* dbgCompileUnit = NULL;
  8228. if (pendingExpr->mThreadId == -1)
  8229. {
  8230. if ((pendingExpr->mFormatInfo.mLanguage == DbgLanguage_Beef) && (mDebugTarget != NULL) && (mDebugTarget->mTargetBinary != NULL))
  8231. dbgModule = mDebugTarget->mTargetBinary;
  8232. else
  8233. dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  8234. }
  8235. else
  8236. {
  8237. dbgModule = GetCallStackDbgModule(pendingExpr->mCallStackIdx);
  8238. if ((dbgModule != NULL) &&(!dbgModule->mDebugTarget->mIsEmpty))
  8239. dbgCompileUnit = GetCallStackCompileUnit(pendingExpr->mCallStackIdx);
  8240. }
  8241. if (dbgModule == NULL)
  8242. dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  8243. if (!pendingExpr->mException.empty())
  8244. {
  8245. RestoreAllRegisters();
  8246. return "!" + pendingExpr->mException;
  8247. }
  8248. DwAutoComplete autoComplete;
  8249. if (bfPassInstance.HasFailed())
  8250. {
  8251. // Don't allow pending calls if we've already failed in the calling Evaluate()
  8252. pendingExpr->mExpressionFlags = (DwEvalExpressionFlags)(pendingExpr->mExpressionFlags & ~DwEvalExpressionFlag_AllowCalls);
  8253. }
  8254. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, pendingExpr->mCallStackIdx, pendingExpr->mCursorPos);
  8255. if (!pendingExpr->mFormatInfo.mStackSearchStr.IsEmpty())
  8256. {
  8257. dbgExprEvaluator.mStackSearch = new DbgStackSearch();
  8258. dbgExprEvaluator.mStackSearch->mSearchStr = pendingExpr->mFormatInfo.mStackSearchStr;
  8259. }
  8260. dbgExprEvaluator.mLanguage = pendingExpr->mFormatInfo.mLanguage;
  8261. dbgExprEvaluator.mReferenceId = &pendingExpr->mReferenceId;
  8262. dbgExprEvaluator.mExpressionFlags = pendingExpr->mExpressionFlags;
  8263. dbgExprEvaluator.mExplicitThis = pendingExpr->mFormatInfo.mExplicitThis;
  8264. dbgExprEvaluator.mSubjectExpr = pendingExpr->mFormatInfo.mSubjectExpr;
  8265. dbgExprEvaluator.mNamespaceSearchStr = pendingExpr->mFormatInfo.mNamespaceSearch;
  8266. dbgExprEvaluator.mExpectingTypeName = pendingExpr->mFormatInfo.mExpectedType;
  8267. dbgExprEvaluator.mCallResults = &pendingExpr->mCallResults;
  8268. if ((pendingExpr->mExpressionFlags & DwEvalExpressionFlag_ValidateOnly) != 0)
  8269. {
  8270. dbgExprEvaluator.mValidateOnly = true;
  8271. }
  8272. if (pendingExpr->mCursorPos != -1)
  8273. {
  8274. dbgExprEvaluator.mAutoComplete = &autoComplete;
  8275. }
  8276. dbgExprEvaluator.mDbgCompileUnit = dbgCompileUnit;
  8277. DbgTypedValue exprResult;
  8278. if (pendingExpr->mExplitType != NULL)
  8279. {
  8280. exprResult.mHasNoValue = true;
  8281. exprResult.mType = pendingExpr->mExplitType;
  8282. }
  8283. else if (pendingExpr->mExprNode != NULL)
  8284. {
  8285. exprResult = dbgExprEvaluator.Resolve(pendingExpr->mExprNode);
  8286. }
  8287. if (dbgExprEvaluator.mCreatedPendingCall)
  8288. {
  8289. BF_ASSERT(mRunState == RunState_DebugEval);
  8290. //ContinueDebugEvent();
  8291. return "!pending";
  8292. }
  8293. if (dbgExprEvaluator.mCountResultOverride != -1)
  8294. pendingExpr->mFormatInfo.mOverrideCount = dbgExprEvaluator.mCountResultOverride;
  8295. String val;
  8296. if (bfPassInstance.HasFailed())
  8297. {
  8298. BfLogDbgExpr("Evaluate Failed: %s\n", bfPassInstance.mErrors[0]->mError.c_str());
  8299. val = StrFormat("!%d\t%d\t%s", bfPassInstance.mErrors[0]->GetSrcStart(), bfPassInstance.mErrors[0]->GetSrcLength(), bfPassInstance.mErrors[0]->mError.c_str());
  8300. }
  8301. else if (dbgExprEvaluator.mBlockedSideEffects)
  8302. {
  8303. BfLogDbgExpr("Evaluate blocked side effects\n");
  8304. val = "!sideeffects";
  8305. }
  8306. else if (!exprResult)
  8307. {
  8308. if (exprResult.mType != NULL)
  8309. {
  8310. BfLogDbgExpr("Evaluate success\n");
  8311. String typeName = exprResult.mType->ToString();
  8312. DbgType* rawType = exprResult.mType;
  8313. if (rawType->IsBfObjectPtr())
  8314. rawType = rawType->mTypeParam;
  8315. String typeNameRaw = rawType->ToStringRaw();
  8316. val = typeName + "\n" + typeName;
  8317. val += "\n" + GetMemberList(exprResult.mType, typeNameRaw, false, true, false, false, exprResult.mIsReadOnly);
  8318. if (exprResult.mType->mTypeCode == DbgType_Namespace)
  8319. {
  8320. val += "\n:type\tnamespace";
  8321. }
  8322. else
  8323. {
  8324. auto type = exprResult.mType;
  8325. if (type->IsPointer())
  8326. type = type->mTypeParam;
  8327. if (type->IsBfObject())
  8328. val += "\n:type\tclass";
  8329. else
  8330. val += "\n:type\tvaluetype";
  8331. }
  8332. if (!pendingExpr->mReferenceId.empty())
  8333. val += "\n:referenceId\t" + pendingExpr->mReferenceId;
  8334. }
  8335. else
  8336. val = "!";
  8337. }
  8338. else if ((pendingExpr->mExpressionFlags & (DwEvalExpressionFlag_MemoryAddress)) != 0)
  8339. {
  8340. DbgType* resultType = exprResult.mType->RemoveModifiers();
  8341. if ((resultType->IsInteger()) || (resultType->IsPointerOrRef()))
  8342. {
  8343. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", 0);
  8344. }
  8345. else
  8346. {
  8347. if (exprResult.mSrcAddress != 0)
  8348. val = StrFormat("!Type '%s' is invalid. A pointer or address value is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  8349. else
  8350. val = StrFormat("!Type '%s' is invalid. A pointer or address value is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  8351. }
  8352. }
  8353. else if ((pendingExpr->mExpressionFlags & (DwEvalExpressionFlag_MemoryWatch)) != 0)
  8354. {
  8355. DbgType* resultType = exprResult.mType->RemoveModifiers();
  8356. bool isMemoryWatch = (pendingExpr->mExpressionFlags & DwEvalExpressionFlag_MemoryWatch) != 0;
  8357. if (!resultType->IsPointerOrRef())
  8358. {
  8359. if (exprResult.mSrcAddress != 0)
  8360. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  8361. else
  8362. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  8363. }
  8364. else
  8365. {
  8366. auto innerType = resultType->mTypeParam;
  8367. int byteCount = innerType->GetByteCount();
  8368. if (pendingExpr->mFormatInfo.mArrayLength != -1)
  8369. byteCount *= pendingExpr->mFormatInfo.mArrayLength;
  8370. if (byteCount == 0)
  8371. {
  8372. 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());
  8373. }
  8374. #ifdef BF_DBG_32
  8375. else if ((isMemoryWatch) && (!IsMemoryBreakpointSizeValid(exprResult.mPtr, byteCount)))
  8376. {
  8377. if (innerType->mSize > 16)
  8378. 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);
  8379. else if (!IsMemoryBreakpointSizeValid(0, byteCount))
  8380. 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);
  8381. else
  8382. 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);
  8383. }
  8384. #else
  8385. else if ((isMemoryWatch) && (!IsMemoryBreakpointSizeValid(exprResult.mPtr, byteCount)))
  8386. {
  8387. if (innerType->mSize > 32)
  8388. 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);
  8389. else if (!IsMemoryBreakpointSizeValid(0, byteCount))
  8390. 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);
  8391. else
  8392. 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);
  8393. }
  8394. #endif
  8395. else
  8396. {
  8397. auto language = dbgExprEvaluator.GetLanguage();
  8398. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", byteCount) + "\n" + StrFormat("%d\t", language) + innerType->ToStringRaw(language);
  8399. }
  8400. }
  8401. }
  8402. else
  8403. {
  8404. if (pendingExpr->mFormatInfo.mNoEdit)
  8405. exprResult.mIsReadOnly = true;
  8406. if (!pendingExpr->mReferenceId.empty())
  8407. pendingExpr->mFormatInfo.mReferenceId = pendingExpr->mReferenceId;
  8408. val = DbgTypedValueToString(exprResult, pendingExpr->mExprNode->ToString(), pendingExpr->mFormatInfo, &dbgExprEvaluator, (pendingExpr->mExpressionFlags & DwEvalExpressionFlag_FullPrecision) != 0);
  8409. if ((!val.empty()) && (val[0] == '!'))
  8410. return val;
  8411. if (pendingExpr->mFormatInfo.mRawString)
  8412. return val;
  8413. if (exprResult.mIsLiteral)
  8414. val += "\n:literal";
  8415. if (bfPassInstance.HasMessages())
  8416. {
  8417. for (auto error : bfPassInstance.mErrors)
  8418. {
  8419. if (error->mIsWarning)
  8420. {
  8421. val += "\n:warn\t";
  8422. val += error->mError;
  8423. }
  8424. }
  8425. }
  8426. if (!pendingExpr->mFormatInfo.mReferenceId.empty())
  8427. val += "\n:referenceId\t" + pendingExpr->mFormatInfo.mReferenceId;
  8428. auto breakAddress = exprResult.mSrcAddress;
  8429. int breakSize = exprResult.mType->GetByteCount();
  8430. if (exprResult.mType->IsRef())
  8431. breakSize = exprResult.mType->mTypeParam->GetByteCount();
  8432. if ((breakAddress != 0) && (HasMemoryBreakpoint(breakAddress, breakSize)))
  8433. val += StrFormat("\n:break\t%@", breakAddress);
  8434. auto checkType = exprResult.mType->RemoveModifiers();
  8435. if (checkType->IsBfObjectPtr())
  8436. val += "\n:type\tobject";
  8437. else if ((checkType->IsPointer()) || (checkType->mTypeCode == DbgType_Subroutine))
  8438. val += "\n:type\tpointer";
  8439. else if (checkType->IsInteger())
  8440. val += "\n:type\tint";
  8441. else if (checkType->IsFloat())
  8442. val += "\n:type\tfloat";
  8443. else if ((exprResult.mRegNum >= X64Reg_M128_XMM0) && (exprResult.mRegNum <= X64Reg_M128_XMM15))
  8444. val += "\n:type\tmm128";
  8445. else
  8446. val += "\n:type\tvaluetype";
  8447. if ((pendingExpr->mFormatInfo.mTypeKindFlags & DbgTypeKindFlag_Int) != 0)
  8448. val += "\n:type\tint";
  8449. if (dbgExprEvaluator.mHadSideEffects)
  8450. val += "\n:sideeffects";
  8451. if ((dbgExprEvaluator.mStackSearch != NULL) && (dbgExprEvaluator.mStackSearch->mStartingStackIdx != dbgExprEvaluator.mCallStackIdx))
  8452. val += StrFormat("\n:stackIdx\t%d", dbgExprEvaluator.mCallStackIdx);
  8453. auto underlyingType = exprResult.mType->RemoveModifiers();
  8454. bool canEdit = true;
  8455. if (pendingExpr->mFormatInfo.mLanguage == DbgLanguage_Beef)
  8456. {
  8457. if (exprResult.mType->IsConst())
  8458. canEdit = false;
  8459. }
  8460. if (pendingExpr->mFormatInfo.mNoEdit)
  8461. canEdit = false;
  8462. if (exprResult.mIsReadOnly)
  8463. canEdit = false;
  8464. const char* langStr = (pendingExpr->mFormatInfo.mLanguage == DbgLanguage_Beef) ? "@Beef:" : "@C:";
  8465. if (exprResult.mSrcAddress != 0)
  8466. {
  8467. val += StrFormat("\n:addrValueExpr\t%s(%s*)", langStr, exprResult.mType->ToString(pendingExpr->mFormatInfo.mLanguage).c_str());
  8468. val += EncodeDataPtr(exprResult.mSrcAddress, true);
  8469. }
  8470. if (exprResult.mType->IsPointerOrRef())
  8471. {
  8472. auto underlyingType = exprResult.mType->mTypeParam;
  8473. if (underlyingType != NULL)
  8474. {
  8475. val += StrFormat("\n:pointeeExpr\t%s(%s%s)", langStr, underlyingType->ToString(pendingExpr->mFormatInfo.mLanguage).c_str(),
  8476. underlyingType->IsBfObject() ? "" : "*");
  8477. val += EncodeDataPtr(exprResult.mPtr, true);
  8478. }
  8479. val += "\n:pointer\t" + EncodeDataPtr(exprResult.mPtr, true);
  8480. }
  8481. if (val[0] == '!')
  8482. {
  8483. // Already has an error embedded, can't edit
  8484. }
  8485. else if ((exprResult.mSrcAddress != 0) && (underlyingType->mTypeCode >= DbgType_i8) && (underlyingType->mTypeCode <= DbgType_Ptr) &&
  8486. (underlyingType->mTypeCode != DbgType_Class) && (underlyingType->mTypeCode != DbgType_Struct))
  8487. {
  8488. if (canEdit)
  8489. val += "\n:canEdit";
  8490. if (exprResult.mType->mTypeCode == DbgType_Ptr)
  8491. {
  8492. val += "\n:editVal\t" + EncodeDataPtr(exprResult.mPtr, true);
  8493. }
  8494. }
  8495. else if ((underlyingType->IsStruct()) && (exprResult.mSrcAddress != 0) && (underlyingType->IsTypedPrimitive()))
  8496. {
  8497. auto primType = underlyingType->GetRootBaseType();
  8498. DbgTypedValue primVal = dbgExprEvaluator.ReadTypedValue(NULL, primType, exprResult.mSrcAddress, DbgAddrType_Target);
  8499. String primResult = DbgTypedValueToString(primVal, "", pendingExpr->mFormatInfo, NULL);
  8500. int crPos = (int)primResult.IndexOf('\n');
  8501. if (crPos != -1)
  8502. primResult.RemoveToEnd(crPos);
  8503. if (canEdit)
  8504. val += "\n:canEdit";
  8505. val += "\n:editVal\t" + primResult;
  8506. }
  8507. else if (exprResult.mRegNum >= 0)
  8508. {
  8509. bool isPseudoReg = ( ((exprResult.mRegNum >= X86Reg_M128_XMMREG_FIRST) && (exprResult.mRegNum <= X86Reg_M128_XMMREG_LAST))
  8510. || ((exprResult.mRegNum >= X86Reg_CAT_FIRST) && (exprResult.mRegNum <= X86Reg_CAT_LAST)) );
  8511. if (!isPseudoReg)
  8512. {
  8513. if (canEdit)
  8514. val += "\n:canEdit";
  8515. if (exprResult.mType->mTypeCode == DbgType_Ptr)
  8516. {
  8517. val += "\n:editVal\t" + EncodeDataPtr(exprResult.mPtr, true);
  8518. }
  8519. }
  8520. }
  8521. }
  8522. if (pendingExpr->mFormatInfo.mRawString)
  8523. return "";
  8524. if (val[0] != '!')
  8525. {
  8526. if (pendingExpr->mUsedSpecifiedLock)
  8527. val += "\n:usedLock";
  8528. if (pendingExpr->mStackIdxOverride != -1)
  8529. val += StrFormat("\n:stackIdx\t%d", pendingExpr->mStackIdxOverride);
  8530. }
  8531. if (pendingExpr->mCursorPos != -1)
  8532. val += GetAutocompleteOutput(autoComplete);
  8533. return val;
  8534. }
  8535. String WinDebugger::EvaluateContinue()
  8536. {
  8537. BP_ZONE("WinDebugger::EvaluateContinue");
  8538. AutoCrit autoCrit(mDebugManager->mCritSect);
  8539. if (mDebugPendingExpr == NULL)
  8540. return "!Evaluation canceled";
  8541. if (!IsPaused())
  8542. return "!Not paused";
  8543. if (mRunState == RunState_DebugEval_Done)
  8544. mRunState = RunState_Paused;
  8545. BfPassInstance bfPassInstance(mBfSystem);
  8546. String result = EvaluateContinue(mDebugPendingExpr, bfPassInstance);
  8547. if (result != "!pending")
  8548. {
  8549. BfLogDbg("EvaluateContinue finishing pending expr in thread %d\n", mDebugEvalThreadInfo.mThreadId);
  8550. CleanupDebugEval();
  8551. }
  8552. return result;
  8553. }
  8554. void WinDebugger::EvaluateContinueKeep()
  8555. {
  8556. if (mDebugPendingExpr != NULL)
  8557. mDebugPendingExpr->mIdleTicks = 0;
  8558. }
  8559. static void PdbTestFile(WinDebugger* debugger, const StringImpl& path)
  8560. {
  8561. if (!path.EndsWith(".PDB", StringImpl::CompareKind_OrdinalIgnoreCase))
  8562. return;
  8563. OutputDebugStrF("Testing %s\n", path.c_str());
  8564. COFF coffFile(debugger->mDebugTarget);
  8565. uint8 wantGuid[16] = { 0 };
  8566. if (!coffFile.TryLoadPDB(path, wantGuid, -1))
  8567. return;
  8568. if (!coffFile.mIs64Bit)
  8569. return;
  8570. coffFile.ParseTypeData();
  8571. coffFile.ParseSymbolData();
  8572. coffFile.ParseGlobalsData();
  8573. for (int i = 0; i < coffFile.mTypes.mSize; i++)
  8574. coffFile.mTypes[i]->PopulateType();
  8575. for (int i = 0; i < coffFile.mCvModuleInfo.mSize; i++)
  8576. coffFile.ParseCompileUnit(i);
  8577. }
  8578. static void PdbTest(WinDebugger* debugger, const StringImpl& path)
  8579. {
  8580. for (auto& fileEntry : FileEnumerator(path, FileEnumerator::Flags_Files))
  8581. {
  8582. String filePath = fileEntry.GetFilePath();
  8583. PdbTestFile(debugger, filePath);
  8584. }
  8585. for (auto& fileEntry : FileEnumerator(path, FileEnumerator::Flags_Directories))
  8586. {
  8587. String childPath = fileEntry.GetFilePath();
  8588. String dirName;
  8589. dirName = GetFileName(childPath);
  8590. PdbTest(debugger, childPath);
  8591. }
  8592. }
  8593. String WinDebugger::Evaluate(const StringImpl& expr, DwFormatInfo formatInfo, int callStackIdx, int cursorPos, int language, DwEvalExpressionFlags expressionFlags)
  8594. {
  8595. BP_ZONE_F("WinDebugger::Evaluate %s", BP_DYN_STR(expr.c_str()));
  8596. AutoCrit autoCrit(mDebugManager->mCritSect);
  8597. if ((expressionFlags & DwEvalExpressionFlag_Symbol) != 0)
  8598. {
  8599. DwAutoComplete autoComplete;
  8600. String retVal;
  8601. retVal += GetAutocompleteOutput(autoComplete);
  8602. return retVal;
  8603. }
  8604. UpdateCallStackMethod(callStackIdx);
  8605. BfLogDbgExpr("Evaluate %s in thread %d\n", expr.c_str(), (mActiveThread != NULL) ? mActiveThread->mThreadId : 0);
  8606. if (language != -1)
  8607. formatInfo.mLanguage = (DbgLanguage)language;
  8608. auto activeThread = mActiveThread;
  8609. if ((!IsPaused()) && (mRunState != RunState_NotStarted) && (mRunState != RunState_DebugEval))
  8610. {
  8611. activeThread = NULL;
  8612. callStackIdx = -1;
  8613. }
  8614. if (mDebugPendingExpr != NULL)
  8615. {
  8616. // We already have a pending call
  8617. expressionFlags = (DwEvalExpressionFlags)(expressionFlags & ~DwEvalExpressionFlag_AllowCalls);
  8618. }
  8619. if ((expressionFlags & DwEvalExpressionFlag_RawStr) != 0)
  8620. {
  8621. formatInfo.mRawString = true;
  8622. }
  8623. if ((expressionFlags & DwEvalExpressionFlag_AllowStringView) != 0)
  8624. {
  8625. formatInfo.mAllowStringView = true;
  8626. }
  8627. auto terminatedExpr = expr + ";";
  8628. auto prevActiveThread = mActiveThread;
  8629. bool restoreActiveThread = false;
  8630. defer(
  8631. {
  8632. if (restoreActiveThread)
  8633. SetActiveThread(prevActiveThread->mThreadId);
  8634. });
  8635. bool usedSpecifiedLock = false;
  8636. int stackIdxOverride = -1;
  8637. if (terminatedExpr.StartsWith('{'))
  8638. {
  8639. String locString;
  8640. int closeIdx = terminatedExpr.IndexOf('}');
  8641. if (closeIdx != -1)
  8642. locString = terminatedExpr.Substring(1, closeIdx - 1);
  8643. for (int i = 0; i <= closeIdx; i++)
  8644. terminatedExpr[i] = ' ';
  8645. locString.Trim();
  8646. if (locString.StartsWith("Thread:", StringImpl::CompareKind_OrdinalIgnoreCase))
  8647. {
  8648. bool foundLockMatch = true;
  8649. locString.Remove(0, 7);
  8650. char* endPtr = NULL;
  8651. int64 threadId = (int64)strtoll(locString.c_str(), &endPtr, 10);
  8652. if (endPtr != NULL)
  8653. {
  8654. locString.Remove(0, endPtr - locString.c_str());
  8655. locString.Trim();
  8656. if (locString.StartsWith("SP:", StringImpl::CompareKind_OrdinalIgnoreCase))
  8657. {
  8658. locString.Remove(0, 3);
  8659. char* endPtr = NULL;
  8660. uint64 sp = (uint64)strtoll(locString.c_str(), &endPtr, 16);
  8661. if (endPtr != NULL)
  8662. {
  8663. locString.Remove(0, endPtr - locString.c_str());
  8664. locString.Trim();
  8665. if (locString.StartsWith("Func:", StringImpl::CompareKind_OrdinalIgnoreCase))
  8666. {
  8667. locString.Remove(0, 5);
  8668. char* endPtr = NULL;
  8669. int64 funcAddr = (int64)strtoll(locString.c_str(), &endPtr, 16);
  8670. if (endPtr != NULL)
  8671. {
  8672. // Actually do it
  8673. if ((mActiveThread != NULL) && (mActiveThread->mThreadId != threadId))
  8674. restoreActiveThread = true;
  8675. if ((mActiveThread == NULL) || (mActiveThread->mThreadId != threadId))
  8676. SetActiveThread(threadId);
  8677. if ((mActiveThread != NULL) && (mActiveThread->mThreadId == threadId))
  8678. {
  8679. int foundStackIdx = -1;
  8680. int checkStackIdx = 0;
  8681. while (true)
  8682. {
  8683. if (checkStackIdx >= mCallStack.mSize)
  8684. UpdateCallStack();
  8685. if (checkStackIdx >= mCallStack.mSize)
  8686. break;
  8687. auto stackFrame = mCallStack[checkStackIdx];
  8688. if (stackFrame->mRegisters.GetSP() == sp)
  8689. {
  8690. foundStackIdx = checkStackIdx;
  8691. break;
  8692. }
  8693. if (stackFrame->mRegisters.GetSP() > sp)
  8694. {
  8695. foundStackIdx = checkStackIdx - 1;
  8696. break;
  8697. }
  8698. checkStackIdx++;
  8699. }
  8700. if (foundStackIdx != -1)
  8701. {
  8702. UpdateCallStackMethod(foundStackIdx);
  8703. auto stackFrame = mCallStack[foundStackIdx];
  8704. if ((stackFrame->mSubProgram != NULL) && ((int64)stackFrame->mSubProgram->mBlock.mLowPC == funcAddr))
  8705. {
  8706. if ((callStackIdx != foundStackIdx) || (mActiveThread != prevActiveThread))
  8707. usedSpecifiedLock = true;
  8708. callStackIdx = foundStackIdx;
  8709. foundLockMatch = true;
  8710. }
  8711. }
  8712. }
  8713. }
  8714. }
  8715. }
  8716. }
  8717. }
  8718. if (!foundLockMatch)
  8719. return "!Locked stack frame not found";
  8720. bool doClear = false;
  8721. for (int i = closeIdx; i < terminatedExpr.mLength; i++)
  8722. {
  8723. char c = terminatedExpr[i];
  8724. if (doClear)
  8725. {
  8726. terminatedExpr[i] = ' ';
  8727. if (c == '}')
  8728. break;
  8729. }
  8730. else
  8731. {
  8732. if (c == '{')
  8733. {
  8734. int endIdx = terminatedExpr.IndexOf('}');
  8735. if (endIdx == -1)
  8736. break;
  8737. terminatedExpr[i] = ' ';
  8738. doClear = true;
  8739. }
  8740. else if (!::isspace((uint8)c))
  8741. break;
  8742. }
  8743. }
  8744. }
  8745. else if (!locString.IsEmpty())
  8746. {
  8747. const char* checkPtr = locString.c_str();
  8748. if ((*checkPtr == '^') || (*checkPtr == '@'))
  8749. checkPtr++;
  8750. char* endPtr = NULL;
  8751. int useCallStackIdx = strtol(checkPtr, &endPtr, 10);
  8752. if (endPtr == locString.c_str() + locString.length())
  8753. {
  8754. if (locString[0] == '@')
  8755. callStackIdx = useCallStackIdx;
  8756. else
  8757. callStackIdx += useCallStackIdx;
  8758. stackIdxOverride = callStackIdx;
  8759. }
  8760. else
  8761. {
  8762. formatInfo.mStackSearchStr = locString;
  8763. }
  8764. }
  8765. }
  8766. auto dbgModule = GetCallStackDbgModule(callStackIdx);
  8767. auto dbgSubprogram = GetCallStackSubprogram(callStackIdx);
  8768. DbgCompileUnit* dbgCompileUnit = NULL;
  8769. if (dbgSubprogram != NULL)
  8770. dbgCompileUnit = dbgSubprogram->mCompileUnit;
  8771. if ((expr.length() > 0) && (expr[0] == '!'))
  8772. {
  8773. if (expr.StartsWith("!step "))
  8774. {
  8775. expressionFlags = (DwEvalExpressionFlags)(expressionFlags | DwEvalExpressionFlag_StepIntoCalls);
  8776. for (int i = 0; i < 5; i++)
  8777. terminatedExpr[i] = ' ';
  8778. }
  8779. else
  8780. {
  8781. String cmd = expr;
  8782. int commaPos = (int)cmd.IndexOf(',');
  8783. if (commaPos != -1)
  8784. cmd.RemoveToEnd(commaPos);
  8785. if (cmd == "!info")
  8786. {
  8787. OutputMessage(StrFormat("Module: %s\n", dbgModule->mDisplayName.c_str()));
  8788. if (dbgSubprogram == NULL)
  8789. {
  8790. //
  8791. }
  8792. else if (dbgSubprogram->mLinkName != NULL)
  8793. {
  8794. OutputMessage(StrFormat("Link Name: %s\n", dbgSubprogram->mLinkName));
  8795. }
  8796. else
  8797. {
  8798. String outSymbol;
  8799. if (mDebugTarget->FindSymbolAt(dbgSubprogram->mBlock.mLowPC, &outSymbol))
  8800. {
  8801. OutputMessage(StrFormat("Link Name: %s\n", outSymbol.c_str()));
  8802. }
  8803. }
  8804. return "";
  8805. }
  8806. else if (cmd == "!dbg")
  8807. {
  8808. mDbgBreak = true;
  8809. return "";
  8810. }
  8811. else if (cmd == "!pdbtest")
  8812. {
  8813. PdbTest(this, "c:\\");
  8814. }
  8815. else if (cmd.StartsWith("!pdbtest "))
  8816. PdbTestFile(this, cmd.Substring(9));
  8817. }
  8818. }
  8819. bool valIsAddr = false;
  8820. BfParser* parser = new BfParser(mBfSystem);
  8821. parser->mCompatMode = true;
  8822. BfPassInstance bfPassInstance(mBfSystem);
  8823. if ((terminatedExpr.length() > 2) && (terminatedExpr[0] == '@'))
  8824. {
  8825. if (terminatedExpr[1] == '!') // Return string as error
  8826. {
  8827. int errorEnd = (int)terminatedExpr.IndexOf("@!", 2);
  8828. if (errorEnd != -1)
  8829. return terminatedExpr.Substring(1, errorEnd - 1);
  8830. else
  8831. return terminatedExpr.Substring(1);
  8832. }
  8833. else if (terminatedExpr[1] == '>') // Return string as text
  8834. {
  8835. int errorEnd = (int)terminatedExpr.IndexOf("@>", 2);
  8836. if (errorEnd != -1)
  8837. return terminatedExpr.Substring(2, errorEnd - 1);
  8838. else
  8839. return terminatedExpr.Substring(2);
  8840. }
  8841. else // Look for "@:" or "@Beef:" style
  8842. {
  8843. int colonIdx = terminatedExpr.IndexOf(':');
  8844. if (colonIdx > 0)
  8845. {
  8846. bool isValid = true;
  8847. DbgLanguage language = DbgLanguage_Unknown;
  8848. String lang = terminatedExpr.Substring(1, colonIdx - 1);
  8849. lang = ToUpper(lang);
  8850. if ((lang == "") || (lang == "BEEF"))
  8851. {
  8852. language = DbgLanguage_Beef;
  8853. }
  8854. else if (lang == "C")
  8855. {
  8856. language = DbgLanguage_C;
  8857. }
  8858. if (language != DbgLanguage_Unknown)
  8859. {
  8860. for (int i = 0; i < colonIdx + 1; i++)
  8861. terminatedExpr[i] = ' ';
  8862. DbgLanguage curLanguage = DbgLanguage_Unknown;
  8863. if (dbgSubprogram != NULL)
  8864. curLanguage = dbgSubprogram->GetLanguage();
  8865. if (language != curLanguage)
  8866. {
  8867. dbgModule = mDebugTarget->mTargetBinary;
  8868. dbgSubprogram = NULL;
  8869. formatInfo.mLanguage = language;
  8870. callStackIdx = -1;
  8871. }
  8872. }
  8873. }
  8874. }
  8875. }
  8876. parser->SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  8877. parser->Parse(&bfPassInstance);
  8878. BfReducer bfReducer;
  8879. bfReducer.mAlloc = parser->mAlloc;
  8880. bfReducer.mSystem = mBfSystem;
  8881. bfReducer.mPassInstance = &bfPassInstance;
  8882. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser->mRootNode);
  8883. bfReducer.mVisitorPos.MoveNext();
  8884. bfReducer.mCompatMode = parser->mCompatMode;
  8885. bfReducer.mSource = parser;
  8886. auto exprNode = bfReducer.CreateExpression(parser->mRootNode->mChildArr.GetAs<BfAstNode*>(0));
  8887. parser->Close();
  8888. formatInfo.mCallStackIdx = callStackIdx;
  8889. if ((formatInfo.mLanguage == DbgLanguage_Unknown) && (dbgSubprogram != NULL))
  8890. formatInfo.mLanguage = dbgSubprogram->GetLanguage();
  8891. DbgPendingExpr* pendingExpr = new DbgPendingExpr();
  8892. if (activeThread != NULL)
  8893. pendingExpr->mThreadId = activeThread->mThreadId;
  8894. pendingExpr->mParser = parser;
  8895. pendingExpr->mCallStackIdx = callStackIdx;
  8896. pendingExpr->mCursorPos = cursorPos;
  8897. pendingExpr->mExpressionFlags = expressionFlags;
  8898. pendingExpr->mExprNode = exprNode;
  8899. DbgType* explicitType = NULL;
  8900. String formatFlags;
  8901. String assignExpr;
  8902. int assignExprOffset = -1;
  8903. if ((exprNode != NULL) && (exprNode->GetSrcEnd() < (int)expr.length()))
  8904. {
  8905. int formatOffset = exprNode->GetSrcEnd();
  8906. while (formatOffset < (int)expr.length())
  8907. {
  8908. char c = expr[formatOffset];
  8909. if (c == ' ')
  8910. formatOffset++;
  8911. else
  8912. break;
  8913. }
  8914. formatFlags = Trim(expr.Substring(formatOffset));
  8915. bool isComplexType = false;
  8916. for (char c : formatFlags)
  8917. if (c == '>')
  8918. isComplexType = true;
  8919. if (isComplexType)
  8920. {
  8921. explicitType = dbgModule->FindType(expr);
  8922. }
  8923. if ((explicitType == NULL) && (formatFlags.length() > 0))
  8924. {
  8925. String errorString = "Invalid expression";
  8926. if (!ParseFormatInfo(dbgModule, formatFlags, &formatInfo, &bfPassInstance, &assignExprOffset, &assignExpr, &errorString))
  8927. {
  8928. if (formatInfo.mRawString)
  8929. return "";
  8930. bfPassInstance.FailAt(errorString, parser->mSourceData, exprNode->GetSrcEnd(), (int) expr.length() - exprNode->GetSrcEnd());
  8931. formatFlags = "";
  8932. }
  8933. if (assignExprOffset != -1)
  8934. assignExprOffset += formatOffset;
  8935. }
  8936. }
  8937. if (assignExpr.length() > 0)
  8938. {
  8939. String newEvalStr = exprNode->ToString() + " = ";
  8940. int errorOffset = (int)newEvalStr.length();
  8941. newEvalStr += assignExpr;
  8942. String result = Evaluate(newEvalStr, formatInfo, callStackIdx, cursorPos, language, expressionFlags);
  8943. if (result[0] == '!')
  8944. {
  8945. int tabPos = (int)result.IndexOf('\t');
  8946. if (tabPos > 0)
  8947. {
  8948. int errorStart = atoi(result.Substring(1, tabPos - 1).c_str());
  8949. if (errorStart >= errorOffset)
  8950. {
  8951. result = StrFormat("!%d", errorStart - errorOffset + assignExprOffset) + result.Substring(tabPos);
  8952. }
  8953. }
  8954. }
  8955. return result;
  8956. }
  8957. pendingExpr->mUsedSpecifiedLock = usedSpecifiedLock;
  8958. pendingExpr->mStackIdxOverride = stackIdxOverride;
  8959. pendingExpr->mExplitType = explicitType;
  8960. pendingExpr->mFormatInfo = formatInfo;
  8961. String result = EvaluateContinue(pendingExpr, bfPassInstance);
  8962. if (result == "!pending")
  8963. {
  8964. BF_ASSERT(mDebugPendingExpr == NULL);
  8965. if (mDebugPendingExpr != NULL)
  8966. {
  8967. return "!retry"; // We already have a pending
  8968. }
  8969. mDebugPendingExpr = pendingExpr;
  8970. mDebugEvalThreadInfo = *mActiveThread;
  8971. mActiveThread->mIsAtBreakpointAddress = 0;
  8972. mActiveThread->mStoppedAtAddress = 0;
  8973. mActiveThread->mBreakpointAddressContinuing = 0;
  8974. }
  8975. else
  8976. delete pendingExpr;
  8977. return result;
  8978. }
  8979. String WinDebugger::Evaluate(const StringImpl& expr, int callStackIdx, int cursorPos, int language, DwEvalExpressionFlags expressionFlags)
  8980. {
  8981. DwFormatInfo formatInfo;
  8982. return Evaluate(expr, formatInfo, callStackIdx, cursorPos, language, expressionFlags);
  8983. }
  8984. static void ConvertDoubleToFloat80(double d, byte fp80[10])
  8985. {
  8986. uint64 di = *reinterpret_cast<uint64*>(&d);
  8987. uint64 m = di & (((uint64)1 << 52) - 1);
  8988. uint64 e = (di >> 52) & 0x7ff;
  8989. memset(fp80, 0, 10);
  8990. // sign bit is directly transferred
  8991. if (di & ((uint64)1 << 63))
  8992. fp80[9] |= 0x80;
  8993. if (!e && !m)
  8994. return; // zero
  8995. fp80[7] |= 0x80; // leading integer bit in mantissa (always 1 in normalized numbers)
  8996. if (e == 0x7ff)
  8997. {
  8998. fp80[9] |= 0x7f;
  8999. fp80[8] = 0xff;
  9000. if (m == 0)
  9001. return; // inf
  9002. fp80[7] |= 0x3f; // any nonzero value will be a NaN (SNaN or QNaN)
  9003. if (m & ((uint64)1 << 51))
  9004. fp80[7] |= 0x40; // QNaN
  9005. return;
  9006. }
  9007. int useExponent = (int)e - 1023;
  9008. if (!e)
  9009. {
  9010. // denormal; can renormalize though since fp80 supports lower exponents
  9011. BF_ASSERT(m != 0); // we should have trapped zero above
  9012. while (!(m & ((uint64)1 << 51)))
  9013. {
  9014. m <<= 1;
  9015. --useExponent;
  9016. }
  9017. // finally we have our leading 1 bit; strip that off and we have a normalized number again
  9018. m <<= 1;
  9019. --useExponent;
  9020. m &= (((uint64)1 << 52) - 1);
  9021. }
  9022. useExponent += 16383;
  9023. BF_ASSERT((useExponent > 0) && (useExponent < 0x7fff));
  9024. *reinterpret_cast<uint16*>(&fp80[8]) |= (uint16)useExponent;
  9025. *reinterpret_cast<uint64*>(&fp80[0]) |= (m << 11);
  9026. }
  9027. bool WinDebugger::AssignToReg(int callStackIdx, DbgTypedValue regVal, DbgTypedValue value, String& outError)
  9028. {
  9029. BF_ASSERT(regVal.mRegNum >= 0);
  9030. if (mCallStack.size() == 0)
  9031. {
  9032. outError = "No call stack";
  9033. return false;
  9034. }
  9035. if (callStackIdx >= (int)mCallStack.size())
  9036. {
  9037. outError = "Invalid call stack index";
  9038. return false;
  9039. }
  9040. auto registers = &mCallStack[callStackIdx]->mRegisters;
  9041. void* regPtr = NULL;
  9042. #ifdef BF_DBG_32
  9043. if ((regVal.mRegNum >= X86Reg_INTREG_FIRST) && (regVal.mRegNum <= X86Reg_INTREG_LAST))
  9044. {
  9045. BF_ASSERT(regVal.mType->mSize == sizeof(int32));
  9046. registers->mIntRegsArray[regVal.mRegNum - X86Reg_INTREG_FIRST] = (uint64)value.mUInt32; // don't sign-extend
  9047. }
  9048. else if ((regVal.mRegNum >= X86Reg_FPSTREG_FIRST) && (regVal.mRegNum <= X86Reg_FPSTREG_LAST))
  9049. {
  9050. BF_ASSERT(regVal.mType->mSize == sizeof(float) || regVal.mType->mSize == sizeof(double));
  9051. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X86Reg_FPSTREG_FIRST];
  9052. double d;
  9053. if (regVal.mType->mSize == sizeof(float))
  9054. d = (double)value.mSingle;
  9055. else
  9056. d = value.mDouble;
  9057. ConvertDoubleToFloat80(d, reg->fp.fp80);
  9058. }
  9059. else if ((regVal.mRegNum >= X86Reg_MMREG_FIRST) && (regVal.mRegNum <= X86Reg_MMREG_LAST))
  9060. {
  9061. BF_ASSERT(regVal.mType->mSize == sizeof(int32) || regVal.mType->mSize == sizeof(int64));
  9062. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X86Reg_MMREG_FIRST];
  9063. if (regVal.mType->mSize == sizeof(int32))
  9064. reg->mm = (uint64)value.mUInt32; // don't sign-extend
  9065. else if (regVal.mType->mSize == sizeof(int64))
  9066. reg->mm = value.mInt64;
  9067. // 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
  9068. reg->fp.fp80[8] = reg->fp.fp80[9] = 0xFF;
  9069. }
  9070. else if ((regVal.mRegNum >= X86Reg_XMMREG_FIRST) && (regVal.mRegNum <= X86Reg_XMMREG_LAST))
  9071. {
  9072. int xmmMajor = (regVal.mRegNum - X86Reg_XMMREG_FIRST) >> 2;
  9073. int xmmMinor = (regVal.mRegNum - X86Reg_XMMREG_FIRST) & 3;
  9074. registers->mXmmRegsArray[xmmMajor].f[xmmMinor] = value.mSingle;
  9075. }
  9076. else if ((regVal.mRegNum >= X86Reg_M128_XMMREG_FIRST) && (regVal.mRegNum <= X86Reg_M128_XMMREG_LAST))
  9077. {
  9078. outError = "Cannot write directly to 128-bit XMM register, please use inner float components";
  9079. return false;
  9080. }
  9081. else if ((regVal.mRegNum >= X86Reg_FLAG_FIRST) && (regVal.mRegNum <= X86Reg_FLAG_LAST))
  9082. {
  9083. int flagBit = CPURegisters::GetFlagBitForRegister(regVal.mRegNum);
  9084. if (flagBit >= 0)
  9085. {
  9086. if (value.mBool)
  9087. registers->mIntRegs.efl |= ((uint64)1 << flagBit);
  9088. else
  9089. registers->mIntRegs.efl &= ~((uint64)1 << flagBit);
  9090. }
  9091. else
  9092. {
  9093. outError = "Unrecognized flag";
  9094. return false;
  9095. }
  9096. }
  9097. else if ((regVal.mRegNum >= X86Reg_CAT_FIRST) && (regVal.mRegNum <= X86Reg_CAT_LAST))
  9098. {
  9099. outError = "Cannot write directly to register categories, please use inner float components";
  9100. return false;
  9101. }
  9102. #else
  9103. if ((regVal.mRegNum >= X64Reg_INTREG_FIRST) && (regVal.mRegNum <= X64Reg_INTREG_LAST))
  9104. {
  9105. //BF_ASSERT(regVal.mType->mSize == sizeof(addr_target));
  9106. registers->mIntRegsArray[regVal.mRegNum - X64Reg_INTREG_FIRST] = value.GetInt64(); // don't sign-extend
  9107. regPtr = &registers->mIntRegsArray[regVal.mRegNum - X64Reg_INTREG_FIRST];
  9108. }
  9109. else if ((regVal.mRegNum >= X64Reg_FPSTREG_FIRST) && (regVal.mRegNum <= X64Reg_FPSTREG_LAST))
  9110. {
  9111. BF_ASSERT(regVal.mType->mSize == sizeof(float) || regVal.mType->mSize == sizeof(double));
  9112. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X64Reg_FPSTREG_FIRST];
  9113. double d;
  9114. if (regVal.mType->mSize == sizeof(float))
  9115. d = (double)value.mSingle;
  9116. else
  9117. d = value.mDouble;
  9118. ConvertDoubleToFloat80(d, reg->fp.fp80);
  9119. regPtr = reg;
  9120. }
  9121. else if ((regVal.mRegNum >= X64Reg_MMREG_FIRST) && (regVal.mRegNum <= X64Reg_MMREG_LAST))
  9122. {
  9123. BF_ASSERT(regVal.mType->mSize == sizeof(int32) || regVal.mType->mSize == sizeof(int64));
  9124. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X64Reg_MMREG_FIRST];
  9125. if (regVal.mType->mSize == sizeof(int32))
  9126. reg->mm = (uint64)value.mUInt32; // don't sign-extend
  9127. else if (regVal.mType->mSize == sizeof(int64))
  9128. reg->mm = value.mInt64;
  9129. // 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
  9130. reg->fp.fp80[8] = reg->fp.fp80[9] = 0xFF;
  9131. regPtr = reg;
  9132. }
  9133. else if ((regVal.mRegNum >= X64Reg_XMMREG_FIRST) && (regVal.mRegNum <= X64Reg_XMMREG_LAST))
  9134. {
  9135. int xmmMajor = (regVal.mRegNum - X64Reg_XMMREG_FIRST) >> 2;
  9136. int xmmMinor = (regVal.mRegNum - X64Reg_XMMREG_FIRST) & 3;
  9137. if (value.mType->GetByteCount() == 4)
  9138. registers->mXmmRegsArray[xmmMajor].f[xmmMinor] = value.mSingle;
  9139. else if (value.mType->GetByteCount() == 8)
  9140. registers->mXmmDRegsArray[xmmMajor].d[xmmMinor] = value.mDouble;
  9141. else
  9142. BF_FATAL("Invalid XMM set value type");
  9143. regPtr = &registers->mXmmRegsArray[xmmMajor];
  9144. }
  9145. else if ((regVal.mRegNum >= X64Reg_M128_XMMREG_FIRST) && (regVal.mRegNum <= X64Reg_M128_XMMREG_LAST))
  9146. {
  9147. outError = "Cannot write directly to 128-bit XMM register, please use inner float components";
  9148. return false;
  9149. }
  9150. else if ((regVal.mRegNum >= X64Reg_FLAG_FIRST) && (regVal.mRegNum <= X64Reg_FLAG_LAST))
  9151. {
  9152. int flagBit = CPURegisters::GetFlagBitForRegister(regVal.mRegNum);
  9153. if (flagBit >= 0)
  9154. {
  9155. if (value.mBool)
  9156. registers->mIntRegs.efl |= ((uint64)1 << flagBit);
  9157. else
  9158. registers->mIntRegs.efl &= ~((uint64)1 << flagBit);
  9159. regPtr = &registers->mIntRegs.efl;
  9160. }
  9161. else
  9162. {
  9163. outError = "Unrecognized flag";
  9164. return false;
  9165. }
  9166. }
  9167. else if ((regVal.mRegNum >= X64Reg_CAT_FIRST) && (regVal.mRegNum <= X64Reg_CAT_LAST))
  9168. {
  9169. outError = "Cannot write directly to register categories, please use inner float components";
  9170. return false;
  9171. }
  9172. else
  9173. BF_FATAL("Not implemented");
  9174. #endif
  9175. if (callStackIdx == 0)
  9176. {
  9177. SetRegisters(&mCallStack[0]->mRegisters);
  9178. return true;
  9179. }
  9180. else
  9181. {
  9182. bool wasSaved = false;
  9183. for (int calleeStackIdx = callStackIdx - 1; calleeStackIdx >= 0; calleeStackIdx--)
  9184. {
  9185. auto calleeRegisters = &mCallStack[calleeStackIdx]->mRegisters;
  9186. if (!mDebugTarget->PropogateRegisterUpCallStack(registers, calleeRegisters, regPtr, wasSaved))
  9187. {
  9188. outError = "Failed to set register";
  9189. return false;
  9190. }
  9191. if (wasSaved)
  9192. return true;
  9193. }
  9194. // This register wasn't saved, so commit it to the callstack top
  9195. return AssignToReg(0, regVal, value, outError);
  9196. }
  9197. }
  9198. String WinDebugger::GetAutocompleteOutput(DwAutoComplete& autoComplete)
  9199. {
  9200. String val = "\n:autocomplete\n";
  9201. if (autoComplete.mInsertStartIdx != -1)
  9202. {
  9203. val += StrFormat("insertRange\t%d %d\n", autoComplete.mInsertStartIdx, autoComplete.mInsertEndIdx);
  9204. }
  9205. Array<AutoCompleteEntry*> entries;
  9206. for (auto& entry : autoComplete.mEntriesSet)
  9207. {
  9208. entries.Add(&entry);
  9209. }
  9210. std::sort(entries.begin(), entries.end(), [](AutoCompleteEntry* lhs, AutoCompleteEntry* rhs)
  9211. {
  9212. return stricmp(lhs->mDisplay, rhs->mDisplay) < 0;
  9213. });
  9214. for (auto entry : entries)
  9215. {
  9216. val += String(entry->mEntryType);
  9217. val += "\t";
  9218. val += String(entry->mDisplay);
  9219. val += "\n";
  9220. }
  9221. /*if (autoComplete.mEntries.size() != 0)
  9222. {
  9223. for (auto& entry : autoComplete.mEntries)
  9224. {
  9225. val += String(entry.mEntryType) + "\t" + String(entry.mDisplay) + "\n";
  9226. }
  9227. }*/
  9228. return val;
  9229. }
  9230. String WinDebugger::EvaluateToAddress(const StringImpl& expr, int callStackIdx, int cursorPos)
  9231. {
  9232. AutoCrit autoCrit(mDebugManager->mCritSect);
  9233. if (IsInRunState())
  9234. return "!Target not paused";
  9235. auto dbgModule = GetCallStackDbgModule(callStackIdx);
  9236. auto dbgCompileUnit = GetCallStackCompileUnit(callStackIdx);
  9237. BfParser parser(mBfSystem);
  9238. parser.mCompatMode = true;
  9239. BfPassInstance bfPassInstance(mBfSystem);
  9240. auto terminatedExpr = expr + ";";
  9241. parser.SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  9242. parser.Parse(&bfPassInstance);
  9243. BfReducer bfReducer;
  9244. bfReducer.mAlloc = parser.mAlloc;
  9245. bfReducer.mSystem = mBfSystem;
  9246. bfReducer.mPassInstance = &bfPassInstance;
  9247. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser.mRootNode);
  9248. bfReducer.mVisitorPos.MoveNext();
  9249. bfReducer.mSource = &parser;
  9250. auto exprNode = bfReducer.CreateExpression(parser.mRootNode->GetFirst());
  9251. parser.Close();
  9252. DwAutoComplete autoComplete;
  9253. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, callStackIdx, cursorPos);
  9254. if (cursorPos != -1)
  9255. dbgExprEvaluator.mAutoComplete = &autoComplete;
  9256. dbgExprEvaluator.mDbgCompileUnit = dbgCompileUnit;
  9257. DwFormatInfo formatInfo;
  9258. formatInfo.mCallStackIdx = callStackIdx;
  9259. DbgTypedValue exprResult;
  9260. if (exprNode != NULL)
  9261. exprResult = dbgExprEvaluator.Resolve(exprNode);
  9262. DbgType* resultType = exprResult.mType->RemoveModifiers();
  9263. String val;
  9264. if (bfPassInstance.HasFailed())
  9265. {
  9266. val = StrFormat("!%d\t%d\t%s", bfPassInstance.mErrors[0]->mSrcStart, bfPassInstance.mErrors[0]->GetSrcLength(), bfPassInstance.mErrors[0]->mError.c_str());
  9267. }
  9268. else if (exprResult.mType == NULL)
  9269. {
  9270. val = "!Invalid expression";
  9271. }
  9272. else if (!resultType->IsPointerOrRef())
  9273. {
  9274. if (exprResult.mSrcAddress != 0)
  9275. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  9276. else
  9277. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  9278. }
  9279. else
  9280. {
  9281. auto innerType = resultType->mTypeParam;
  9282. int byteCount = innerType->GetByteCount();
  9283. if (byteCount == 0)
  9284. {
  9285. 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());
  9286. }
  9287. #ifdef BF_DBG_32
  9288. else if ((byteCount != 1) && (byteCount != 2) && (byteCount != 4))
  9289. {
  9290. 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);
  9291. }
  9292. #else
  9293. else if ((byteCount != 1) && (byteCount != 2) && (byteCount != 4) && (byteCount != 8))
  9294. {
  9295. 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);
  9296. }
  9297. #endif
  9298. else
  9299. {
  9300. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", byteCount);
  9301. }
  9302. }
  9303. if (cursorPos != -1)
  9304. val += GetAutocompleteOutput(autoComplete);
  9305. return val;
  9306. }
  9307. // This is currently only used for autocomplete during conditional breakpoint expression entry.
  9308. // If we want to use it for more than that then remove DwEvalExpressionFlags_ValidateOnly
  9309. String WinDebugger::EvaluateAtAddress(const StringImpl& expr, intptr atAddr, int cursorPos)
  9310. {
  9311. AutoCrit autoCrit(mDebugManager->mCritSect);
  9312. if (IsInRunState())
  9313. return "!Target not paused";
  9314. if (!IsPaused())
  9315. return "!Target not running";
  9316. WdStackFrame stackFrame;
  9317. memset(&stackFrame.mRegisters, 0, sizeof(stackFrame.mRegisters));
  9318. stackFrame.mHasGottenSubProgram = true;
  9319. *stackFrame.mRegisters.GetPCRegisterRef() = (intptr_target)atAddr;
  9320. stackFrame.mSubProgram = mDebugTarget->FindSubProgram((addr_target)atAddr);
  9321. if (stackFrame.mSubProgram == NULL)
  9322. return "!Invalid address";
  9323. mCallStack.push_back(&stackFrame);
  9324. int callStackIdx = (int)mCallStack.size() - 1;
  9325. String val = Evaluate(expr, callStackIdx, cursorPos, -1, DwEvalExpressionFlag_ValidateOnly);
  9326. mCallStack.pop_back();
  9327. return val;
  9328. }
  9329. String WinDebugger::GetAutoExpressions(int callStackIdx, uint64 memoryRangeStart, uint64 memoryRangeLen)
  9330. {
  9331. BP_ZONE("WinDebugger::GetAutoExpressions");
  9332. AutoCrit autoCrit(mDebugManager->mCritSect);
  9333. if (IsInRunState())
  9334. return "!Not paused";
  9335. if (!IsPaused())
  9336. return "!Not running";
  9337. if (!FixCallStackIdx(callStackIdx))
  9338. return "";
  9339. CPUStackFrame* stackFrame = (callStackIdx >= 0) ? mCallStack[callStackIdx] : mCallStack.front();
  9340. String result;
  9341. DbgAutoValueMapType dwarfAutos;
  9342. mDebugTarget->GetAutoValueNames(dwarfAutos, stackFrame, memoryRangeStart, memoryRangeLen);
  9343. for (auto const &a : dwarfAutos)
  9344. {
  9345. std::pair<uint64, uint64> varRange = a.mValue;
  9346. if (varRange.first != 0)
  9347. result += StrFormat("&%s\t%llu\t%llu\n", a.mKey.c_str(), varRange.second, varRange.first);
  9348. else
  9349. result += StrFormat("?%s\t%llu\n", a.mKey.c_str(), varRange.second);
  9350. }
  9351. #ifdef BF_DBG_64
  9352. // add int regs
  9353. const char* regStrs[] = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "rip", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", 0 };
  9354. #else
  9355. // add int regs
  9356. const char* regStrs[] = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "eip", 0 };
  9357. #endif
  9358. for (const char** p = regStrs; *p; ++p)
  9359. result += StrFormat("$%s\t%d\n", *p, sizeof(addr_target));
  9360. if (callStackIdx < (int)mCallStack.size() - 2)
  9361. {
  9362. WdStackFrame* prevStackFrame = mCallStack[callStackIdx + 1];
  9363. // Inlined methods have no stack frame
  9364. int stackSize = prevStackFrame->mRegisters.GetSP() - stackFrame->mRegisters.GetSP();
  9365. result += StrFormat("&$StackFrame\t%llu\t%llu\n", stackSize, stackFrame->mRegisters.GetSP());
  9366. }
  9367. return result;
  9368. }
  9369. String WinDebugger::GetAutoLocals(int stackFrameIdx, bool showRegs)
  9370. {
  9371. BP_ZONE("WinDebugger::GetAutoExpressions");
  9372. AutoCrit autoCrit(mDebugManager->mCritSect);
  9373. if (IsInRunState())
  9374. return "";
  9375. if (!IsPaused())
  9376. return "";
  9377. if (mCallStack.size() == 0)
  9378. UpdateCallStack();
  9379. String result;
  9380. Array<String> localList;
  9381. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9382. UpdateCallStackMethod(actualStackFrameIdx);
  9383. if (actualStackFrameIdx >= mCallStack.size())
  9384. return "";
  9385. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9386. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  9387. if (dwSubprogram == NULL)
  9388. return "";
  9389. auto langage = dwSubprogram->GetLanguage();
  9390. DbgLineData* dwLineData = FindLineDataInSubprogram(wdStackFrame->GetSourcePC(), dwSubprogram);
  9391. if (dwLineData == NULL)
  9392. return "";
  9393. dwSubprogram->PopulateSubprogram();
  9394. mDebugTarget->GetAutoLocalsInBlock(localList, dwSubprogram, &dwSubprogram->mBlock, wdStackFrame, dwLineData);
  9395. String lastLocal;
  9396. for (auto local : localList)
  9397. {
  9398. if (langage == DbgLanguage_C)
  9399. {
  9400. if ((local == "this") && (strncmp(dwSubprogram->mName, "<lambda_", 8) == 0))
  9401. {
  9402. // Use explicit "$this" so we can see the actual capture
  9403. result += "$this\n";
  9404. continue;
  9405. }
  9406. }
  9407. bool wasAlias = false;
  9408. for (int i = 0; i < (int)local.length() - 1; i++)
  9409. {
  9410. if ((local[i] == '$') && (local[i + 1] == 'a'))
  9411. {
  9412. // Alias
  9413. wasAlias = true;
  9414. String localName = local.Substring(0, i) + "\n";
  9415. if (localName != lastLocal)
  9416. {
  9417. result += localName;
  9418. lastLocal = localName;
  9419. }
  9420. break;
  9421. }
  9422. }
  9423. if (!wasAlias)
  9424. result += local + "\n";
  9425. }
  9426. if (showRegs)
  9427. {
  9428. result += "$FLAGS\n";
  9429. UpdateRegisterUsage(stackFrameIdx);
  9430. for (int regIdx = 0; regIdx < (int)wdStackFrame->mRegForms.size(); regIdx++)
  9431. {
  9432. if (wdStackFrame->mRegForms[regIdx] != RegForm_Invalid)
  9433. result += "$" + String(CPURegisters::GetRegisterName(regIdx)) + "\n";
  9434. }
  9435. }
  9436. return result;
  9437. }
  9438. String WinDebugger::CompactChildExpression(const StringImpl& expr, const StringImpl& parentExpr, int callStackIdx)
  9439. {
  9440. DbgCompileUnit* compileUnit = GetCallStackCompileUnit(callStackIdx);
  9441. DbgModule* dbgModule = GetCallStackDbgModule(callStackIdx);
  9442. if (dbgModule == NULL)
  9443. return "!failed";
  9444. DbgLanguage language = DbgLanguage_Unknown;
  9445. if (compileUnit != NULL)
  9446. language = compileUnit->mLanguage;
  9447. auto terminatedParentExpr = parentExpr + ";";
  9448. String parentPrefix;
  9449. int colonIdx = terminatedParentExpr.IndexOf(':');
  9450. if (colonIdx > 0)
  9451. {
  9452. bool isValid = true;
  9453. String lang = terminatedParentExpr.Substring(1, colonIdx - 1);
  9454. lang = ToUpper(lang);
  9455. if ((lang == "") || (lang == "BEEF"))
  9456. {
  9457. language = DbgLanguage_Beef;
  9458. }
  9459. else if (lang == "C")
  9460. {
  9461. language = DbgLanguage_C;
  9462. }
  9463. if (language != DbgLanguage_Unknown)
  9464. {
  9465. parentPrefix += terminatedParentExpr.Substring(0, colonIdx + 1);
  9466. terminatedParentExpr.Remove(0, colonIdx + 1);
  9467. }
  9468. }
  9469. if (terminatedParentExpr.StartsWith('{'))
  9470. {
  9471. int prefixEnd = terminatedParentExpr.IndexOf('}');
  9472. parentPrefix += terminatedParentExpr.Substring(0, prefixEnd + 1);
  9473. terminatedParentExpr.Remove(0, prefixEnd + 1);
  9474. }
  9475. BfPassInstance bfPassInstance(mBfSystem);
  9476. BfParser parser(mBfSystem);
  9477. parser.mCompatMode = language != DbgLanguage_Beef;
  9478. auto terminatedExpr = expr + ";";
  9479. parser.SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  9480. parser.Parse(&bfPassInstance);
  9481. BfParser parentParser(mBfSystem);
  9482. parentParser.mCompatMode = language != DbgLanguage_Beef;
  9483. parentParser.SetSource(terminatedParentExpr.c_str(), terminatedParentExpr.length());
  9484. parentParser.Parse(&bfPassInstance);
  9485. BfReducer bfReducer;
  9486. bfReducer.mCompatMode = true;
  9487. bfReducer.mAlloc = parser.mAlloc;
  9488. bfReducer.mSystem = mBfSystem;
  9489. bfReducer.mPassInstance = &bfPassInstance;
  9490. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser.mRootNode);
  9491. bfReducer.mVisitorPos.MoveNext();
  9492. bfReducer.mSource = &parser;
  9493. auto exprNode = bfReducer.CreateExpression(parser.mRootNode->GetFirst());
  9494. bfReducer.mAlloc = parentParser.mAlloc;
  9495. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parentParser.mRootNode);
  9496. bfReducer.mVisitorPos.MoveNext();
  9497. auto parentExprNode = bfReducer.CreateExpression(parentParser.mRootNode->GetFirst());
  9498. parser.Close();
  9499. if ((exprNode == NULL) || (parentExprNode == NULL))
  9500. return "!failed";
  9501. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, callStackIdx, -1);
  9502. DwFormatInfo formatInfo;
  9503. formatInfo.mCallStackIdx = callStackIdx;
  9504. formatInfo.mLanguage = language;
  9505. String formatFlags;
  9506. String assignExpr;
  9507. if ((exprNode != NULL) && (exprNode->GetSrcEnd() < (int) expr.length()))
  9508. {
  9509. formatFlags = Trim(expr.Substring(exprNode->GetSrcEnd()));
  9510. if (formatFlags.length() > 0)
  9511. {
  9512. String errorString = "Invalid expression";
  9513. if (!ParseFormatInfo(dbgModule, formatFlags, &formatInfo, &bfPassInstance, NULL, &assignExpr, &errorString))
  9514. {
  9515. bfPassInstance.FailAt(errorString, parser.mSourceData, exprNode->GetSrcEnd(), (int) expr.length() - exprNode->GetSrcEnd());
  9516. formatFlags = "";
  9517. }
  9518. }
  9519. }
  9520. dbgExprEvaluator.mExplicitThis = formatInfo.mExplicitThis;
  9521. dbgExprEvaluator.mExplicitThisExpr = parentExprNode;
  9522. DbgTypedValue exprResult = dbgExprEvaluator.Resolve(exprNode);
  9523. BfAstNode* headNode = dbgExprEvaluator.FinalizeExplicitThisReferences(exprNode);
  9524. BfPrinter printer(parser.mRootNode, NULL, NULL);
  9525. printer.mIgnoreTrivia = true;
  9526. printer.mReformatting = true;
  9527. printer.VisitChild(headNode);
  9528. String result;
  9529. result += parentPrefix;
  9530. result += printer.mOutString;
  9531. if (formatInfo.mNoVisualizers)
  9532. result += ", nv";
  9533. if (formatInfo.mNoMembers)
  9534. result += ", nm";
  9535. if (formatInfo.mNoEdit)
  9536. result += ", ne";
  9537. if (formatInfo.mIgnoreDerivedClassInfo)
  9538. result += ", nd";
  9539. if (formatInfo.mDisplayType == DwDisplayType_Ascii)
  9540. result += ", s";
  9541. if (formatInfo.mDisplayType == DwDisplayType_Utf8)
  9542. result += ", s8";
  9543. if (formatInfo.mDisplayType == DwDisplayType_Utf16)
  9544. result += ", s16";
  9545. if (formatInfo.mDisplayType == DwDisplayType_Utf32)
  9546. result += ", s32";
  9547. return result;
  9548. }
  9549. String WinDebugger::GetProcessInfo()
  9550. {
  9551. AutoCrit autoCrit(mDebugManager->mCritSect);
  9552. if ((mActiveThread == NULL) && (!mIsRunning))
  9553. return "";
  9554. SYSTEM_INFO sysinfo = { 0 };
  9555. GetSystemInfo(&sysinfo);
  9556. FILETIME creationTime = { 0 };
  9557. FILETIME exitTime = { 0 };
  9558. FILETIME kernelTime = { 0 };
  9559. FILETIME userTime = { 0 };
  9560. ::GetProcessTimes(mProcessInfo.hProcess, &creationTime, &exitTime, &kernelTime, &userTime);
  9561. String retStr;
  9562. PROCESS_MEMORY_COUNTERS memInfo = { 0 };
  9563. ::GetProcessMemoryInfo(mProcessInfo.hProcess, &memInfo, sizeof(PROCESS_MEMORY_COUNTERS));
  9564. FILETIME currentTime = { 0 };
  9565. ::GetSystemTimeAsFileTime(&currentTime);
  9566. retStr += StrFormat("VirtualMemory\t%lld\n", memInfo.PagefileUsage);
  9567. retStr += StrFormat("WorkingMemory\t%lld\n", memInfo.WorkingSetSize);
  9568. retStr += StrFormat("RunningTime\t%lld\n", *(int64*)&currentTime - *(int64*)&creationTime);
  9569. retStr += StrFormat("KernelTime\t%lld\n", *(int64*)&kernelTime / sysinfo.dwNumberOfProcessors);
  9570. retStr += StrFormat("UserTime\t%lld\n", *(int64*)&userTime / sysinfo.dwNumberOfProcessors);
  9571. return retStr;
  9572. }
  9573. int WinDebugger::GetProcessId()
  9574. {
  9575. AutoCrit autoCrit(mDebugManager->mCritSect);
  9576. if (!mThreadList.IsEmpty())
  9577. return mThreadList[0]->mProcessId;
  9578. return mDbgProcessId;
  9579. }
  9580. String WinDebugger::GetThreadInfo()
  9581. {
  9582. AutoCrit autoCrit(mDebugManager->mCritSect);
  9583. String retStr;
  9584. if ((mActiveThread == NULL) && (!mIsRunning))
  9585. {
  9586. retStr = "";
  9587. }
  9588. else
  9589. {
  9590. if (mActiveThread != NULL)
  9591. retStr = StrFormat("%d", mActiveThread->mThreadId);
  9592. for (auto threadInfo : mThreadList)
  9593. {
  9594. SetAndRestoreValue<WdThreadInfo*> prevThread(mActiveThread, threadInfo);
  9595. retStr += "\n";
  9596. for (int pass = 0; pass < 2; pass++)
  9597. {
  9598. CPURegisters registers;
  9599. PopulateRegisters(&registers);
  9600. String locString = EncodeDataPtr((addr_target)registers.GetPC(), true);
  9601. TryGetThreadName(threadInfo);
  9602. bool hadThreadName = true;
  9603. String threadName = threadInfo->mName;
  9604. if (threadName.IsEmpty())
  9605. {
  9606. hadThreadName = false;
  9607. if (threadInfo->mThreadId == mProcessInfo.dwThreadId)
  9608. threadName = "Main Thread";
  9609. else
  9610. threadName = "Worker Thread";
  9611. }
  9612. bool isInvalid = false;
  9613. addr_target appendAddr = 0;
  9614. for (int stackIdx = 0; true; stackIdx++)
  9615. {
  9616. auto subProgram = mDebugTarget->FindSubProgram(registers.GetPC(), DbgOnDemandKind_LocalOnly);
  9617. if (subProgram != NULL)
  9618. {
  9619. if (subProgram->mLineInfo != NULL)
  9620. {
  9621. DbgModule* module = subProgram->mCompileUnit->mDbgModule;
  9622. DbgModule* linkedModule = module->GetLinkedModule();
  9623. if (linkedModule->mDisplayName.length() > 0)
  9624. {
  9625. locString = linkedModule->mDisplayName + "!" + subProgram->ToString();
  9626. if (!hadThreadName)
  9627. threadName = module->mDisplayName + " thread";
  9628. }
  9629. else
  9630. {
  9631. locString = subProgram->ToString();
  9632. }
  9633. appendAddr = 0;
  9634. break;
  9635. }
  9636. }
  9637. DbgModule* module = mDebugTarget->FindDbgModuleForAddress(registers.GetPC());
  9638. if (module == NULL)
  9639. {
  9640. isInvalid = true;
  9641. break;
  9642. }
  9643. DbgModule* linkedModule = module->GetLinkedModule();
  9644. appendAddr = (addr_target)registers.GetPC();
  9645. locString = linkedModule->mDisplayName + "!" + EncodeDataPtr((addr_target)registers.GetPC(), true);
  9646. if (!hadThreadName)
  9647. threadName = linkedModule->mDisplayName + " thread";
  9648. if ((mActiveThread == mExplicitStopThread) && (mActiveBreakpoint != NULL))
  9649. {
  9650. if ((subProgram == NULL) ||
  9651. (mActiveBreakpoint->mAddr < subProgram->mBlock.mLowPC) ||
  9652. (mActiveBreakpoint->mAddr >= subProgram->mBlock.mHighPC))
  9653. break;
  9654. }
  9655. if (pass == 1) // Just take the first item
  9656. break;
  9657. if (stackIdx == 128)
  9658. break; // Too many!
  9659. addr_target returnAddr;
  9660. if (!mDebugTarget->RollBackStackFrame(&registers, &returnAddr, true))
  9661. {
  9662. isInvalid = true;
  9663. break;
  9664. }
  9665. }
  9666. if ((isInvalid) && (pass == 0))
  9667. continue;
  9668. if (appendAddr != 0)
  9669. {
  9670. String symbolName;
  9671. addr_target offset;
  9672. DbgModule* dwarf;
  9673. if (mDebugTarget->FindSymbolAt(appendAddr, &symbolName, &offset, &dwarf))
  9674. {
  9675. DbgModule* linkedModule = dwarf->GetLinkedModule();
  9676. String demangledName = BfDemangler::Demangle(symbolName, DbgLanguage_Unknown);
  9677. if (!linkedModule->mDisplayName.empty())
  9678. {
  9679. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  9680. }
  9681. locString = demangledName + StrFormat("+0x%X", offset);
  9682. }
  9683. }
  9684. retStr += StrFormat("%d\t%s\t%s", threadInfo->mThreadId, threadName.c_str(), locString.c_str());
  9685. String attrs;
  9686. if (threadInfo->mFrozen)
  9687. {
  9688. attrs += "Fr";
  9689. }
  9690. if (!attrs.IsEmpty())
  9691. {
  9692. retStr += "\t";
  9693. retStr += attrs;
  9694. }
  9695. break;
  9696. }
  9697. }
  9698. }
  9699. return retStr;
  9700. }
  9701. void WinDebugger::SetActiveThread(int threadId)
  9702. {
  9703. AutoCrit autoCrit(mDebugManager->mCritSect);
  9704. if ((mActiveThread != NULL) && (mActiveThread->mThreadId == threadId))
  9705. return;
  9706. auto prevThread = mActiveThread;
  9707. if (mThreadMap.TryGetValue(threadId, &mActiveThread))
  9708. {
  9709. BfLogDbg("SetActiveThread %d\n", threadId);
  9710. if (prevThread != NULL)
  9711. {
  9712. Array<WdStackFrame*>* prevFrameArray = NULL;
  9713. mSavedCallStacks.TryAdd(prevThread, NULL, &prevFrameArray);
  9714. for (auto frameInfo : *prevFrameArray)
  9715. delete frameInfo;
  9716. *prevFrameArray = mCallStack;
  9717. mCallStack.Clear();
  9718. }
  9719. DoClearCallStack(false);
  9720. Array<WdStackFrame*>* newFrameArray = NULL;
  9721. if (mSavedCallStacks.TryGetValue(mActiveThread, &newFrameArray))
  9722. {
  9723. mCallStack = *newFrameArray;
  9724. newFrameArray->Clear();
  9725. }
  9726. }
  9727. else
  9728. {
  9729. BfLogDbg("SetActiveThread %d FAILED\n", threadId);
  9730. }
  9731. }
  9732. int WinDebugger::GetActiveThread()
  9733. {
  9734. AutoCrit autoCrit(mDebugManager->mCritSect);
  9735. if (mActiveThread == NULL)
  9736. return -1;
  9737. return mActiveThread->mThreadId;
  9738. }
  9739. void WinDebugger::FreezeThread(int threadId)
  9740. {
  9741. AutoCrit autoCrit(mDebugManager->mCritSect);
  9742. BF_ASSERT(!IsInRunState());
  9743. auto thread = mThreadMap[threadId];
  9744. if (!thread->mFrozen)
  9745. {
  9746. thread->mFrozen = true;
  9747. ::SuspendThread(thread->mHThread);
  9748. BfLogDbg("SuspendThread %d from FreezeThread\n", thread->mThreadId);
  9749. }
  9750. }
  9751. void WinDebugger::ThawThread(int threadId)
  9752. {
  9753. AutoCrit autoCrit(mDebugManager->mCritSect);
  9754. BF_ASSERT(!IsInRunState());
  9755. auto thread = mThreadMap[threadId];
  9756. if (thread->mFrozen)
  9757. {
  9758. thread->mFrozen = false;
  9759. ::ResumeThread(thread->mHThread);
  9760. BfLogDbg("ResumeThread %d from ThawThread\n", thread->mThreadId);
  9761. }
  9762. }
  9763. bool WinDebugger::IsActiveThreadWaiting()
  9764. {
  9765. AutoCrit autoCrit(mDebugManager->mCritSect);
  9766. return mActiveThread == mDebuggerWaitingThread;
  9767. }
  9768. void WinDebugger::DoClearCallStack(bool clearSavedStacks)
  9769. {
  9770. AutoCrit autoCrit(mDebugManager->mCritSect);
  9771. BfLogDbg("ClearCallstack\n");
  9772. BF_ASSERT(mRunState != RunState_DebugEval);
  9773. for (auto wdStackFrame : mCallStack)
  9774. delete wdStackFrame;
  9775. if (clearSavedStacks)
  9776. {
  9777. for (auto& kv : mSavedCallStacks)
  9778. {
  9779. for (auto wdStackFrame : kv.mValue)
  9780. delete wdStackFrame;
  9781. }
  9782. mSavedCallStacks.Clear();
  9783. }
  9784. mCallStack.Clear();
  9785. mIsPartialCallStack = true;
  9786. }
  9787. void WinDebugger::ClearCallStack()
  9788. {
  9789. DoClearCallStack(true);
  9790. }
  9791. void WinDebugger::UpdateCallStack(bool slowEarlyOut)
  9792. {
  9793. AutoCrit autoCrit(mDebugManager->mCritSect);
  9794. if (!mIsPartialCallStack)
  9795. return;
  9796. if (mActiveThread == NULL)
  9797. return;
  9798. if (IsInRunState())
  9799. return;
  9800. uint32 tickStart = BFTickCount();
  9801. CPURegisters registers;
  9802. if (mCallStack.size() > 0)
  9803. {
  9804. WdStackFrame* wdStackFrame = mCallStack.back();
  9805. if (wdStackFrame->mIsEnd)
  9806. {
  9807. return;
  9808. }
  9809. memcpy(&registers, &wdStackFrame->mRegisters, sizeof(registers));
  9810. bool regsRolledBack = RollBackStackFrame(&registers, mCallStack.size() == 1);
  9811. // If we can't roll them back then mIsEnd should have been set for the previous frame
  9812. BF_ASSERT(regsRolledBack);
  9813. }
  9814. else
  9815. {
  9816. BF_ASSERT(mIsPartialCallStack);
  9817. mCallStack.Reserve(1024);
  9818. PopulateRegisters(&registers);
  9819. BfLogDbg("UpdateCallStack starting. Thread=%d PC=0x%p\n", mActiveThread->mThreadId, registers.GetPC());
  9820. }
  9821. bool isPartial = false;
  9822. // Incrementally fill callstack structure to avoid stepping slowdown during deep nesting
  9823. for (int fillIdx = 0; fillIdx < (slowEarlyOut ? 10000 : 100000); fillIdx++)
  9824. {
  9825. WdStackFrame* wdStackFrame = new WdStackFrame();
  9826. memcpy(&wdStackFrame->mRegisters, &registers, sizeof(registers));
  9827. wdStackFrame->mIsStart = mCallStack.size() == 0;
  9828. wdStackFrame->mIsEnd = false;
  9829. bool rollbackSuccess = false;
  9830. for (int tryCount = 0; tryCount < 16; tryCount++)
  9831. {
  9832. if (!RollBackStackFrame(&registers, wdStackFrame->mIsStart))
  9833. {
  9834. break;
  9835. }
  9836. if (registers.GetPC() > 0xFFFF)
  9837. {
  9838. rollbackSuccess = true;
  9839. break;
  9840. }
  9841. if (mCallStack.size() > 0)
  9842. break; // Only retry for the first frame
  9843. }
  9844. if (!rollbackSuccess)
  9845. wdStackFrame->mIsEnd = true;
  9846. if (registers.GetSP() <= wdStackFrame->mRegisters.GetSP())
  9847. {
  9848. // SP went the wrong direction, stop rolling back
  9849. wdStackFrame->mIsEnd = true;
  9850. }
  9851. mCallStack.push_back(wdStackFrame);
  9852. if (IsMiniDumpDebugger())
  9853. {
  9854. // Make sure to queue up any debug stuff we need
  9855. UpdateCallStackMethod((int)mCallStack.size() - 1);
  9856. }
  9857. if (wdStackFrame->mIsEnd)
  9858. break;
  9859. // Time-limit callstack generation. Most useful for debug mode.
  9860. if ((slowEarlyOut) && ((fillIdx % 100) == 0))
  9861. {
  9862. uint32 tickEnd = BFTickCount();
  9863. if (tickEnd - tickStart >= 10)
  9864. {
  9865. isPartial = true;
  9866. break;
  9867. }
  9868. }
  9869. }
  9870. if (!isPartial)
  9871. mIsPartialCallStack = false;
  9872. }
  9873. int WinDebugger::GetCallStackCount()
  9874. {
  9875. AutoCrit autoCrit(mDebugManager->mCritSect);
  9876. return (int)mCallStack.size();
  9877. }
  9878. int WinDebugger::GetRequestedStackFrameIdx()
  9879. {
  9880. AutoCrit autoCrit(mDebugManager->mCritSect);
  9881. if ((mActiveThread == mExplicitStopThread) && (mRequestedStackFrameIdx >= -1))
  9882. {
  9883. if (mActiveBreakpoint != NULL)
  9884. mRequestedStackFrameIdx = GetBreakStackFrameIdx();
  9885. if (mRequestedStackFrameIdx == -1)
  9886. mRequestedStackFrameIdx = 0;
  9887. return mRequestedStackFrameIdx;
  9888. }
  9889. int newCallStackIdx = 0;
  9890. while (true)
  9891. {
  9892. if (newCallStackIdx >= (int)mCallStack.size() - 1)
  9893. UpdateCallStack();
  9894. if (newCallStackIdx >= (int)mCallStack.size() - 1)
  9895. break;
  9896. intptr addr;
  9897. String file;
  9898. int hotIdx;
  9899. int defLineStart;
  9900. int defLineEnd;
  9901. int line;
  9902. int column;
  9903. int language;
  9904. int stackSize;
  9905. int8 flags;
  9906. GetStackFrameInfo(newCallStackIdx, &addr, &file, &hotIdx, &defLineStart, &defLineEnd, &line, &column, &language, &stackSize, &flags);
  9907. if (!file.empty())
  9908. return newCallStackIdx;
  9909. newCallStackIdx++;
  9910. }
  9911. return 0;
  9912. }
  9913. int WinDebugger::GetBreakStackFrameIdx()
  9914. {
  9915. AutoCrit autoCrit(mDebugManager->mCritSect);
  9916. if ((mActiveBreakpoint == NULL) || (mRunState != RunState_Breakpoint))
  9917. return -1;
  9918. if ((mBreakStackFrameIdx != -1) || (mActiveThread != mExplicitStopThread))
  9919. return mBreakStackFrameIdx;
  9920. mBreakStackFrameIdx = 0;
  9921. BF_ASSERT(mActiveBreakpoint != NULL);
  9922. if (mCallStack.IsEmpty())
  9923. UpdateCallStack();
  9924. if (!mCallStack.IsEmpty())
  9925. {
  9926. UpdateCallStackMethod(0);
  9927. for (int stackIdx = 0; stackIdx < (int)mCallStack.size(); stackIdx++)
  9928. {
  9929. auto callStackEntry = mCallStack[stackIdx];
  9930. if (callStackEntry->mSubProgram == NULL)
  9931. break;
  9932. if ((mActiveBreakpoint->mAddr < callStackEntry->mSubProgram->mBlock.mLowPC) ||
  9933. (mActiveBreakpoint->mAddr >= callStackEntry->mSubProgram->mBlock.mHighPC))
  9934. break;
  9935. DbgSubprogram* specificSubprogram = callStackEntry->mSubProgram;
  9936. auto dwLineData = callStackEntry->mSubProgram->FindClosestLine(mActiveBreakpoint->mAddr, &specificSubprogram);
  9937. if (dwLineData == NULL)
  9938. break;
  9939. if (mActiveBreakpoint->mLineData == dwLineData)
  9940. {
  9941. mBreakStackFrameIdx = stackIdx;
  9942. break;
  9943. }
  9944. }
  9945. }
  9946. return mBreakStackFrameIdx;
  9947. }
  9948. static const char* SafeString(const char* str)
  9949. {
  9950. if (str == NULL)
  9951. return "???";
  9952. return str;
  9953. }
  9954. void WinDebugger::UpdateRegisterUsage(int stackFrameIdx)
  9955. {
  9956. WdStackFrame* wdStackFrame = mCallStack[stackFrameIdx];
  9957. if (wdStackFrame->mRegForms.size() != 0)
  9958. return;
  9959. auto dwSubprogram = wdStackFrame->mSubProgram;
  9960. if (dwSubprogram == NULL)
  9961. return;
  9962. addr_target addr = dwSubprogram->mBlock.mLowPC;
  9963. const uint8* baseOp = nullptr;
  9964. while (addr < dwSubprogram->mBlock.mHighPC)
  9965. {
  9966. CPUInst inst;
  9967. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  9968. break;
  9969. bool overrideForm = inst.mAddress <= (addr_target)wdStackFrame->mRegisters.GetPC();
  9970. inst.MarkRegsUsed(wdStackFrame->mRegForms, overrideForm);
  9971. addr += inst.GetLength();
  9972. }
  9973. }
  9974. // It's safe to pass an invalid idx in here
  9975. void WinDebugger::UpdateCallStackMethod(int stackFrameIdx)
  9976. {
  9977. if (mCallStack.empty())
  9978. return;
  9979. int startIdx = std::min(stackFrameIdx, (int)mCallStack.size() - 1);
  9980. while (startIdx >= 0)
  9981. {
  9982. WdStackFrame* wdStackFrame = mCallStack[startIdx];
  9983. if (wdStackFrame->mHasGottenSubProgram)
  9984. break;
  9985. startIdx--;
  9986. }
  9987. startIdx++;
  9988. for (int checkFrameIdx = startIdx; checkFrameIdx <= stackFrameIdx; checkFrameIdx++)
  9989. {
  9990. //BF_ASSERT(checkFrameIdx < mCallStack.size());
  9991. if (checkFrameIdx >= mCallStack.size())
  9992. break;
  9993. WdStackFrame* wdStackFrame = mCallStack[checkFrameIdx];
  9994. wdStackFrame->mHasGottenSubProgram = true;
  9995. addr_target pcAddress = (addr_target)wdStackFrame->GetSourcePC();
  9996. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress, DbgOnDemandKind_LocalOnly);
  9997. wdStackFrame->mHasGottenSubProgram = true;
  9998. wdStackFrame->mSubProgram = dwSubprogram;
  9999. if ((dwSubprogram == NULL) && (IsMiniDumpDebugger()))
  10000. {
  10001. // FindSymbolAt will queue up debug info if necessary...
  10002. String symbolName;
  10003. addr_target offset;
  10004. DbgModule* dbgModule;
  10005. mDebugTarget->FindSymbolAt(pcAddress, &symbolName, &offset, &dbgModule);
  10006. }
  10007. auto prevStackFrame = wdStackFrame;
  10008. // Insert inlines
  10009. int insertIdx = checkFrameIdx + 1;
  10010. while ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL))
  10011. {
  10012. WdStackFrame* inlineStackFrame = new WdStackFrame();
  10013. *inlineStackFrame = *wdStackFrame;
  10014. inlineStackFrame->mInInlineMethod = true;
  10015. wdStackFrame->mInInlineCall = true;
  10016. inlineStackFrame->mSubProgram = dwSubprogram->mInlineeInfo->mInlineParent;
  10017. mCallStack.Insert(insertIdx, inlineStackFrame);
  10018. dwSubprogram = dwSubprogram->mInlineeInfo->mInlineParent;
  10019. insertIdx++;
  10020. checkFrameIdx++;
  10021. prevStackFrame = inlineStackFrame;
  10022. }
  10023. }
  10024. }
  10025. void WinDebugger::GetCodeAddrInfo(intptr addr, intptr inlineCallAddr, String* outFile, int* outHotIdx, int* outDefLineStart, int* outDefLineEnd, int* outLine, int* outColumn)
  10026. {
  10027. AutoCrit autoCrit(mDebugManager->mCritSect);
  10028. DbgSubprogram* subProgram = NULL;
  10029. DbgLineData* callingLineData = FindLineDataAtAddress((addr_target)addr, &subProgram);
  10030. if (inlineCallAddr != 0)
  10031. {
  10032. auto inlinedSubProgram = mDebugTarget->FindSubProgram(inlineCallAddr);
  10033. if (inlinedSubProgram != 0)
  10034. {
  10035. FixupLineDataForSubprogram(inlinedSubProgram->mInlineeInfo->mRootInliner);
  10036. DbgSubprogram* parentSubprogram = inlinedSubProgram->mInlineeInfo->mInlineParent; // Require it be in the inline parent
  10037. auto foundLine = parentSubprogram->FindClosestLine(inlinedSubProgram->mBlock.mLowPC, &parentSubprogram);
  10038. if (foundLine != NULL)
  10039. {
  10040. auto srcFile = parentSubprogram->GetLineSrcFile(*foundLine);
  10041. *outFile = srcFile->GetLocalPath();
  10042. *outLine = foundLine->mLine;
  10043. }
  10044. *outHotIdx = inlinedSubProgram->mCompileUnit->mDbgModule->mHotIdx;
  10045. *outColumn = -1;
  10046. DbgSubprogram* callingSubProgram = NULL;
  10047. DbgLineData* callingLineData = FindLineDataAtAddress(inlinedSubProgram->mBlock.mLowPC - 1, &callingSubProgram);
  10048. if ((callingLineData != NULL) && (callingSubProgram == subProgram))
  10049. {
  10050. auto callingSrcFile = callingSubProgram->GetLineSrcFile(*callingLineData);
  10051. auto srcFile = callingSrcFile;
  10052. *outFile = srcFile->GetLocalPath();
  10053. if (*outLine == callingLineData->mLine)
  10054. *outColumn = callingLineData->mColumn;
  10055. }
  10056. return;
  10057. }
  10058. }
  10059. if (subProgram != NULL)
  10060. {
  10061. if ((subProgram->mInlineeInfo != NULL) && ((addr_target)addr >= subProgram->mBlock.mHighPC))
  10062. callingLineData = &subProgram->mInlineeInfo->mLastLineData;
  10063. *outHotIdx = subProgram->mCompileUnit->mDbgModule->mHotIdx;
  10064. *outFile = subProgram->GetLineSrcFile(*callingLineData)->GetLocalPath();
  10065. *outLine = callingLineData->mLine;
  10066. *outColumn = callingLineData->mColumn;
  10067. FixupLineDataForSubprogram(subProgram);
  10068. DbgLineData* dwStartLineData = NULL;
  10069. DbgLineData* dwEndLineData = NULL;
  10070. if (subProgram->mLineInfo != NULL)
  10071. {
  10072. if (subProgram->mLineInfo->mLines.size() > 0)
  10073. {
  10074. dwStartLineData = &subProgram->mLineInfo->mLines[0];
  10075. dwEndLineData = &subProgram->mLineInfo->mLines.back();
  10076. }
  10077. }
  10078. else
  10079. {
  10080. if (subProgram->mInlineeInfo != NULL)
  10081. {
  10082. dwStartLineData = &subProgram->mInlineeInfo->mFirstLineData;
  10083. dwEndLineData = &subProgram->mInlineeInfo->mLastLineData;
  10084. }
  10085. }
  10086. if (dwEndLineData != NULL)
  10087. {
  10088. *outDefLineStart = dwStartLineData->mLine;
  10089. *outDefLineEnd = dwEndLineData->mLine;
  10090. }
  10091. }
  10092. }
  10093. void WinDebugger::GetStackAllocInfo(intptr addr, int* outThreadId, int* outStackIdx)
  10094. {
  10095. AutoCrit autoCrit(mDebugManager->mCritSect);
  10096. *outThreadId = 0;
  10097. if (outStackIdx != NULL)
  10098. *outStackIdx = -1;
  10099. if (!IsPaused())
  10100. return;
  10101. for (auto thread : mThreadList)
  10102. {
  10103. NT_TIB64 tib = { 0 };
  10104. if (!ReadMemory((intptr)thread->mThreadLocalBase, sizeof(tib), &tib))
  10105. continue;
  10106. MEMORY_BASIC_INFORMATION stackInfo = { 0 };
  10107. if (VirtualQueryEx(mProcessInfo.hProcess, (void*)(tib.StackBase - 1), &stackInfo, sizeof(MEMORY_BASIC_INFORMATION)) == 0)
  10108. continue;
  10109. if ((addr >= (intptr)stackInfo.AllocationBase) && (addr < (intptr)tib.StackBase))
  10110. {
  10111. *outThreadId = thread->mThreadId;
  10112. if (outStackIdx == NULL)
  10113. return;
  10114. if (mActiveThread == thread)
  10115. {
  10116. UpdateCallStack(false);
  10117. for (int callStackIdx = 0; callStackIdx < (int)mCallStack.size(); callStackIdx++)
  10118. {
  10119. UpdateCallStackMethod(callStackIdx);
  10120. auto stackFrame = mCallStack[callStackIdx];
  10121. if (addr >= (intptr)stackFrame->mRegisters.GetSP())
  10122. {
  10123. *outStackIdx = callStackIdx;
  10124. }
  10125. }
  10126. }
  10127. return;
  10128. }
  10129. }
  10130. }
  10131. String WinDebugger::GetStackFrameInfo(int stackFrameIdx, intptr* addr, String* outFile, int* outHotIdx, int* outDefLineStart, int* outDefLineEnd,
  10132. int* outLine, int* outColumn, int* outLanguage, int* outStackSize, int8* outFlags)
  10133. {
  10134. enum FrameFlags
  10135. {
  10136. FrameFlags_Optimized = 1,
  10137. FrameFlags_HasPendingDebugInfo = 2,
  10138. FrameFlags_CanGetOldSource = 4,
  10139. FrameFlags_WasHotReplaced = 8,
  10140. FrameFlags_HadError = 0x10
  10141. };
  10142. AutoCrit autoCrit(mDebugManager->mCritSect);
  10143. if (mCallStack.size() == 0)
  10144. UpdateCallStack();
  10145. *addr = 0;
  10146. *outFile = "";
  10147. *outHotIdx = 0;
  10148. *outDefLineStart = -1;
  10149. *outDefLineEnd = -1;
  10150. *outLine = -1;
  10151. *outColumn = 0;
  10152. *outLanguage = 0;
  10153. *outStackSize = 0;
  10154. *outFlags = 0;
  10155. UpdateCallStackMethod(stackFrameIdx);
  10156. if (stackFrameIdx >= mCallStack.size())
  10157. {
  10158. return "";
  10159. }
  10160. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  10161. UpdateCallStackMethod(actualStackFrameIdx);
  10162. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  10163. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  10164. if (stackFrameIdx == -1)
  10165. pcAddress = mShowPCOverride;
  10166. *addr = pcAddress;
  10167. if (actualStackFrameIdx < (int)mCallStack.size() - 2)
  10168. {
  10169. WdStackFrame* prevStackFrame = mCallStack[actualStackFrameIdx + 1];
  10170. // Inlined methods have no stack frame
  10171. *outStackSize = prevStackFrame->mRegisters.GetSP() - wdStackFrame->mRegisters.GetSP();
  10172. }
  10173. const auto& _CheckHashSrcFile = [&](String& outStr, DbgModule* dbgModule, DbgSrcFile* srcFile)
  10174. {
  10175. if (srcFile->mHashKind != DbgHashKind_None)
  10176. {
  10177. outStr += "#";
  10178. srcFile->GetHash(outStr);
  10179. }
  10180. };
  10181. auto _SetFlags = [&](DbgSubprogram* dwSubprogram)
  10182. {
  10183. DbgModule* dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  10184. if (dwSubprogram->mIsOptimized)
  10185. *outFlags |= FrameFlags_Optimized;
  10186. if (dbgModule->HasPendingDebugInfo())
  10187. *outFlags |= FrameFlags_HasPendingDebugInfo;
  10188. if (dbgModule->CanGetOldSource())
  10189. *outFlags |= FrameFlags_CanGetOldSource;
  10190. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) || (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid))
  10191. *outFlags |= FrameFlags_WasHotReplaced;
  10192. };
  10193. auto _FixFilePath = [&](DbgModule* dbgModule)
  10194. {
  10195. if (outFile == NULL)
  10196. return;
  10197. if (outFile->StartsWith("$Emit"))
  10198. {
  10199. int dollarPos = outFile->IndexOf('$', 1);
  10200. if (dollarPos == -1)
  10201. return;
  10202. outFile->Insert(dollarPos, StrFormat("%d", dbgModule->mId));
  10203. }
  10204. };
  10205. if (wdStackFrame->mInInlineMethod)
  10206. {
  10207. WdStackFrame* nextStackFrame = mCallStack[actualStackFrameIdx - 1];
  10208. auto subProgram = nextStackFrame->mSubProgram;
  10209. _SetFlags(subProgram);
  10210. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  10211. DbgSubprogram* parentSubprogram = subProgram->mInlineeInfo->mInlineParent; // Require it be in the inline parent
  10212. auto foundLine = parentSubprogram->FindClosestLine(subProgram->mBlock.mLowPC, &parentSubprogram);
  10213. if (foundLine != NULL)
  10214. {
  10215. auto srcFile = parentSubprogram->GetLineSrcFile(*foundLine);
  10216. *outFile = srcFile->GetLocalPath();
  10217. _CheckHashSrcFile(*outFile, subProgram->mCompileUnit->mDbgModule, srcFile);
  10218. *outLine = foundLine->mLine;
  10219. }
  10220. *outLanguage = subProgram->GetLanguage();
  10221. *outHotIdx = subProgram->mCompileUnit->mDbgModule->mHotIdx;
  10222. *outColumn = -1;
  10223. DbgSubprogram* callingSubProgram = NULL;
  10224. DbgLineData* callingLineData = FindLineDataAtAddress(nextStackFrame->mSubProgram->mBlock.mLowPC - 1, &callingSubProgram);
  10225. if ((callingLineData != NULL) && (callingSubProgram == wdStackFrame->mSubProgram))
  10226. {
  10227. auto callingSrcFile = callingSubProgram->GetLineSrcFile(*callingLineData);
  10228. *outLanguage = callingSubProgram->mCompileUnit->mLanguage;
  10229. auto srcFile = callingSrcFile;
  10230. *outFile = srcFile->GetLocalPath();
  10231. _CheckHashSrcFile(*outFile, subProgram->mCompileUnit->mDbgModule, srcFile);
  10232. if (*outLine == callingLineData->mLine)
  10233. *outColumn = callingLineData->mColumn;
  10234. }
  10235. String name = wdStackFrame->mSubProgram->ToString();
  10236. DbgModule* dbgModule = wdStackFrame->mSubProgram->mCompileUnit->mDbgModule;
  10237. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  10238. if (!linkedModule->mDisplayName.empty())
  10239. name = linkedModule->mDisplayName + "!" + name;
  10240. _FixFilePath(dbgModule);
  10241. return name;
  10242. }
  10243. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  10244. if (dwSubprogram != NULL)
  10245. {
  10246. String demangledName;
  10247. if ((dwSubprogram->mName != NULL) && (strncmp(dwSubprogram->mName, ":Sep@", 5) == 0))
  10248. {
  10249. char* p;
  10250. auto addr = strtoll(dwSubprogram->mName + 5, &p, 16);
  10251. if (addr != 0)
  10252. {
  10253. auto parentSubprogram = mDebugTarget->FindSubProgram(addr);
  10254. if (parentSubprogram != NULL)
  10255. demangledName = parentSubprogram->ToString();
  10256. }
  10257. }
  10258. if (demangledName.IsEmpty())
  10259. {
  10260. dwSubprogram->ToString(demangledName, true);
  10261. }
  10262. DbgSrcFile* dwSrcFile = NULL;
  10263. DbgLineData* dwLineData = NULL;
  10264. FixupLineDataForSubprogram(dwSubprogram);
  10265. addr_target findAddress = wdStackFrame->GetSourcePC();
  10266. DbgSubprogram* specificSubprogram = dwSubprogram;
  10267. dwLineData = dwSubprogram->FindClosestLine(findAddress, &specificSubprogram);
  10268. if ((dwLineData == NULL) && (dwSubprogram->mInlineeInfo != NULL) && (findAddress >= dwSubprogram->mBlock.mHighPC))
  10269. dwLineData = &dwSubprogram->mInlineeInfo->mLastLineData;
  10270. if (dwLineData != NULL)
  10271. dwSrcFile = dwSubprogram->GetLineSrcFile(*dwLineData);
  10272. DbgLineData* dwStartLineData = NULL;
  10273. DbgLineData* dwEndLineData = NULL;
  10274. if (dwSubprogram->mLineInfo != NULL)
  10275. {
  10276. if (dwSubprogram->mLineInfo->mLines.size() > 0)
  10277. {
  10278. dwStartLineData = &dwSubprogram->mLineInfo->mLines[0];
  10279. dwEndLineData = &dwSubprogram->mLineInfo->mLines.back();
  10280. }
  10281. }
  10282. else
  10283. {
  10284. if (dwSubprogram->mInlineeInfo != NULL)
  10285. {
  10286. dwStartLineData = &dwSubprogram->mInlineeInfo->mFirstLineData;
  10287. dwEndLineData = &dwSubprogram->mInlineeInfo->mLastLineData;
  10288. }
  10289. }
  10290. DbgModule* dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  10291. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  10292. if (!linkedModule->mDisplayName.empty())
  10293. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  10294. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) || (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid))
  10295. demangledName = "#" + demangledName;
  10296. _SetFlags(dwSubprogram);
  10297. if ((dwLineData != NULL) && (dwSrcFile != NULL))
  10298. {
  10299. *outFile = dwSrcFile->GetLocalPath();
  10300. _CheckHashSrcFile(*outFile, dbgModule, dwSrcFile);
  10301. *outHotIdx = dbgModule->mHotIdx;
  10302. *outLine = dwLineData->mLine;
  10303. *outColumn = dwLineData->mColumn;
  10304. *outLanguage = (int)dwSubprogram->mCompileUnit->mLanguage;
  10305. if (dwEndLineData != NULL)
  10306. {
  10307. *outDefLineStart = dwStartLineData->mLine;
  10308. *outDefLineEnd = dwEndLineData->mLine;
  10309. }
  10310. _FixFilePath(dbgModule);
  10311. return demangledName;
  10312. }
  10313. else
  10314. {
  10315. _FixFilePath(dbgModule);
  10316. return demangledName + StrFormat("+0x%X", pcAddress - dwSubprogram->mBlock.mLowPC);
  10317. }
  10318. }
  10319. else
  10320. {
  10321. String symbolName;
  10322. addr_target offset;
  10323. DbgModule* dbgModule = NULL;
  10324. if (mDebugTarget->FindSymbolAt(pcAddress, &symbolName, &offset, &dbgModule))
  10325. {
  10326. if (dbgModule->HasPendingDebugInfo())
  10327. {
  10328. *outFlags |= FrameFlags_HasPendingDebugInfo;
  10329. if (mPendingDebugInfoLoad.ContainsKey(dbgModule))
  10330. {
  10331. String outName = EncodeDataPtr(pcAddress, true);
  10332. if ((dbgModule != NULL) && (!dbgModule->mDisplayName.empty()))
  10333. outName = dbgModule->mDisplayName + "!<Loading...>" + outName;
  10334. return outName;
  10335. }
  10336. }
  10337. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  10338. String demangledName = BfDemangler::Demangle(symbolName, DbgLanguage_Unknown);
  10339. if (!linkedModule->mDisplayName.empty())
  10340. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  10341. _FixFilePath(dbgModule);
  10342. return demangledName + StrFormat("+0x%X", offset);
  10343. }
  10344. }
  10345. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress(pcAddress);
  10346. DbgModule* linkedModule = NULL;
  10347. if (dbgModule != NULL)
  10348. {
  10349. linkedModule = dbgModule->GetLinkedModule();
  10350. if (dbgModule->HasPendingDebugInfo())
  10351. *outFlags |= FrameFlags_HasPendingDebugInfo;
  10352. }
  10353. String outName = EncodeDataPtr(pcAddress, true);
  10354. if ((linkedModule != NULL) && (!linkedModule->mDisplayName.empty()))
  10355. outName = linkedModule->mDisplayName + "!" + outName;
  10356. _FixFilePath(dbgModule);
  10357. return outName;
  10358. }
  10359. String WinDebugger::GetStackFrameId(int stackFrameIdx)
  10360. {
  10361. AutoCrit autoCrit(mDebugManager->mCritSect);
  10362. if (!FixCallStackIdx(stackFrameIdx))
  10363. return "";
  10364. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  10365. UpdateCallStackMethod(actualStackFrameIdx);
  10366. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  10367. intptr addr = 0;
  10368. if (wdStackFrame->mSubProgram != NULL)
  10369. addr = wdStackFrame->mSubProgram->mBlock.mLowPC;
  10370. else
  10371. addr = wdStackFrame->mRegisters.GetPC();
  10372. String str = StrFormat("Thread:%d SP:%llX Func:%llX", mActiveThread->mThreadId, wdStackFrame->mRegisters.GetSP(), addr);
  10373. return str;
  10374. }
  10375. String WinDebugger::Callstack_GetStackFrameOldFileInfo(int stackFrameIdx)
  10376. {
  10377. AutoCrit autoCrit(mDebugManager->mCritSect);
  10378. if (!FixCallStackIdx(stackFrameIdx))
  10379. return "";
  10380. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  10381. UpdateCallStackMethod(actualStackFrameIdx);
  10382. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  10383. DbgModule* dbgModule = NULL;
  10384. DbgSrcFile* dbgSrcFile = NULL;
  10385. if (wdStackFrame->mInInlineMethod)
  10386. {
  10387. WdStackFrame* nextStackFrame = mCallStack[actualStackFrameIdx - 1];
  10388. auto subProgram = nextStackFrame->mSubProgram;
  10389. dbgModule = subProgram->mCompileUnit->mDbgModule;
  10390. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  10391. DbgSubprogram* parentSubprogram = subProgram->mInlineeInfo->mInlineParent; // Require it be in the inline parent
  10392. auto foundLine = parentSubprogram->FindClosestLine(subProgram->mBlock.mLowPC, &parentSubprogram);
  10393. if (foundLine != NULL)
  10394. dbgSrcFile = parentSubprogram->GetLineSrcFile(*foundLine);
  10395. DbgSubprogram* callingSubProgram = NULL;
  10396. DbgLineData* callingLineData = FindLineDataAtAddress(nextStackFrame->mSubProgram->mBlock.mLowPC - 1, &callingSubProgram);
  10397. if ((callingLineData != NULL) && (callingSubProgram == wdStackFrame->mSubProgram))
  10398. dbgSrcFile = callingSubProgram->GetLineSrcFile(*callingLineData);
  10399. }
  10400. else
  10401. {
  10402. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  10403. if (dwSubprogram != NULL)
  10404. {
  10405. FixupLineDataForSubprogram(dwSubprogram);
  10406. addr_target findAddress = wdStackFrame->GetSourcePC();
  10407. DbgSubprogram* dbgSubprogram = NULL;
  10408. DbgLineData* dwLineData = dwSubprogram->FindClosestLine(findAddress, &dbgSubprogram, &dbgSrcFile);
  10409. dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  10410. }
  10411. }
  10412. if (dbgSrcFile != NULL)
  10413. {
  10414. // Note: we must use mFilePath here, make sure we don't use GetLocalPath()
  10415. return dbgModule->GetOldSourceCommand(dbgSrcFile->mFilePath);
  10416. }
  10417. return "";
  10418. }
  10419. int WinDebugger::GetJmpState(int stackFrameIdx)
  10420. {
  10421. AutoCrit autoCrit(mDebugManager->mCritSect);
  10422. if (!FixCallStackIdx(stackFrameIdx))
  10423. return -1;
  10424. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  10425. UpdateCallStackMethod(actualStackFrameIdx);
  10426. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  10427. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  10428. CPUInst inst;
  10429. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  10430. return -1;
  10431. return inst.GetJmpState(wdStackFrame->mRegisters.mIntRegs.efl);
  10432. }
  10433. intptr WinDebugger::GetStackFrameCalleeAddr(int stackFrameIdx)
  10434. {
  10435. AutoCrit autoCrit(mDebugManager->mCritSect);
  10436. if (!FixCallStackIdx(stackFrameIdx))
  10437. return -1;
  10438. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  10439. UpdateCallStackMethod(actualStackFrameIdx);
  10440. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  10441. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  10442. if (stackFrameIdx == -1)
  10443. pcAddress = mShowPCOverride;
  10444. if (wdStackFrame->mInInlineMethod)
  10445. {
  10446. WdStackFrame* inlineStackFrame = mCallStack[actualStackFrameIdx - 1];
  10447. return inlineStackFrame->mSubProgram->mBlock.mLowPC - 1;
  10448. }
  10449. return pcAddress - 1;
  10450. }
  10451. String WinDebugger::GetStackMethodOwner(int stackFrameIdx, int& language)
  10452. {
  10453. AutoCrit autoCrit(mDebugManager->mCritSect);
  10454. if (!FixCallStackIdx(stackFrameIdx))
  10455. return "";
  10456. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  10457. if (actualStackFrameIdx >= (int)mCallStack.size())
  10458. actualStackFrameIdx = 0;
  10459. UpdateCallStackMethod(actualStackFrameIdx);
  10460. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  10461. if (wdStackFrame->mSubProgram == NULL)
  10462. return "";
  10463. auto parentType = wdStackFrame->mSubProgram->GetParent();
  10464. if (parentType == NULL)
  10465. return "";
  10466. parentType = parentType->GetPrimaryType();
  10467. language = (int)parentType->GetLanguage();
  10468. return parentType->ToString();
  10469. }
  10470. String WinDebugger::FindCodeAddresses(const StringImpl& fileName, int line, int column, bool allowAutoResolve)
  10471. {
  10472. String result;
  10473. if (mDebugTarget == NULL)
  10474. return "";
  10475. DbgSrcFile* srcFile = mDebugTarget->GetSrcFile(fileName);
  10476. if (srcFile == NULL)
  10477. return result;
  10478. bool foundInSequence = false;
  10479. WdBreakpoint* prevBreakpoint = NULL;
  10480. int bestLineOffset = 0x7FFFFFFF;
  10481. for (auto dbgSubprogram : srcFile->mLineDataRefs)
  10482. {
  10483. for (auto& lineData : dbgSubprogram->mLineInfo->mLines)
  10484. {
  10485. auto lineSrcFile = dbgSubprogram->GetLineSrcFile(lineData);
  10486. if (lineSrcFile != srcFile)
  10487. continue;
  10488. int lineOffset = lineData.mLine - line;
  10489. if ((lineOffset >= 0) && (lineOffset <= 12) && (lineOffset <= bestLineOffset))
  10490. {
  10491. if (lineOffset < bestLineOffset)
  10492. {
  10493. bestLineOffset = lineOffset;
  10494. result = "";
  10495. }
  10496. if (!foundInSequence)
  10497. {
  10498. auto addr = dbgSubprogram->GetLineAddr(lineData);
  10499. result += EncodeDataPtr(addr, false) + "\t" + dbgSubprogram->ToString() + "\n";
  10500. }
  10501. }
  10502. // New sequence?
  10503. if (!lineData.IsStackFrameSetup())
  10504. foundInSequence = false;
  10505. }
  10506. }
  10507. return result;
  10508. }
  10509. String WinDebugger::GetAddressSourceLocation(intptr address)
  10510. {
  10511. DbgSubprogram* subProgram = NULL;
  10512. DbgLineData* lineData = FindLineDataAtAddress(address, &subProgram);
  10513. if (lineData != NULL)
  10514. return StrFormat("%s:%d:%d", subProgram->GetLineSrcFile(*lineData)->GetLocalPath().c_str(), lineData->mLine + 1, lineData->mColumn + 1);
  10515. String outSymbol;
  10516. addr_target offset = 0;
  10517. DbgModule* dbgModule;
  10518. if (mDebugTarget->FindSymbolAt(address, &outSymbol, &offset, &dbgModule))
  10519. {
  10520. if (offset < 0x10000)
  10521. {
  10522. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  10523. if (offset > 0)
  10524. outSymbol += StrFormat("+%x", offset);
  10525. return outSymbol;
  10526. }
  10527. }
  10528. return StrFormat("0x%@", address);
  10529. }
  10530. String WinDebugger::GetAddressSymbolName(intptr address, bool demangle)
  10531. {
  10532. auto subProgram = mDebugTarget->FindSubProgram(address);
  10533. if (subProgram != NULL)
  10534. return subProgram->ToString();
  10535. String outSymbol;
  10536. addr_target offset = 0;
  10537. DbgModule* dbgModule;
  10538. if (mDebugTarget->FindSymbolAt(address, &outSymbol, &offset, &dbgModule))
  10539. {
  10540. if (offset < 0x10000)
  10541. {
  10542. if (demangle)
  10543. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  10544. if (offset > 0)
  10545. outSymbol += StrFormat("+%x", offset);
  10546. return outSymbol;
  10547. }
  10548. }
  10549. return StrFormat("0x%@", address);
  10550. }
  10551. String WinDebugger::DisassembleAtRaw(intptr inAddress)
  10552. {
  10553. addr_target address = (addr_target)inAddress;
  10554. const int addrBorder = 1024;
  10555. for (int offset = 0; offset < 8; offset++)
  10556. {
  10557. String result;
  10558. bool addOffset = true;
  10559. bool hadAddr = false;
  10560. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress(address);
  10561. DbgModuleMemoryCache* memCache = NULL;
  10562. defer
  10563. (
  10564. if (dbgModule == NULL)
  10565. delete memCache;
  10566. );
  10567. if ((dbgModule != NULL) && (dbgModule->mOrigImageData == NULL))
  10568. dbgModule = NULL;
  10569. result += "R\n"; // Raw
  10570. addr_target addrStart = address;
  10571. if (dbgModule != NULL)
  10572. {
  10573. dbgModule->ParseSymbolData();
  10574. memCache = dbgModule->mOrigImageData;
  10575. addrStart = BF_MAX((addr_target)dbgModule->mImageBase, address - addrBorder - offset);
  10576. }
  10577. else
  10578. {
  10579. memCache = new DbgModuleMemoryCache(addrStart & (4096 - 1), 4096 * 2);
  10580. }
  10581. if (memCache->mAddr == 0)
  10582. return "";
  10583. //addr_target imageBase = dbgModule->mImageBase;
  10584. //int imageSize = dbgModule->mImageSize;
  10585. addr_target dataAddr = addrStart;
  10586. addr_target addrEnd = addrStart + addrBorder * 2 + 16;
  10587. while (dataAddr < addrEnd)
  10588. {
  10589. if (dataAddr == address)
  10590. hadAddr = true;
  10591. if (dataAddr > address)
  10592. {
  10593. if (!hadAddr)
  10594. {
  10595. if (offset == 7)
  10596. {
  10597. dataAddr = address;
  10598. }
  10599. break;
  10600. }
  10601. }
  10602. String outSymbol;
  10603. addr_target symOffset = 0;
  10604. DbgModule* symDWARF;
  10605. if (mDebugTarget->FindSymbolAt(dataAddr, &outSymbol, &symOffset, &symDWARF))
  10606. {
  10607. if (symOffset == 0)
  10608. {
  10609. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  10610. if ((symDWARF != NULL) && (!symDWARF->mDisplayName.empty()))
  10611. outSymbol = symDWARF->GetLinkedModule()->mDisplayName + "!" + outSymbol;
  10612. result += "T " + outSymbol + ":\n";
  10613. }
  10614. }
  10615. CPUInst inst;
  10616. if (!mCPU->Decode(dataAddr, memCache, &inst))
  10617. {
  10618. if ((offset == 7) && (!hadAddr))
  10619. {
  10620. uint8 instData[1];
  10621. memCache->Read(dataAddr, instData, 1);
  10622. int instLen = 1;
  10623. #ifdef BF_DBG_32
  10624. result += StrFormat("D %08X: ", dataAddr);
  10625. #else
  10626. result += StrFormat("D %@: ", dataAddr);
  10627. #endif
  10628. for (int i = 0; i < instLen; i++)
  10629. result += StrFormat("%02X ", instData[i]);
  10630. for (int i = instLen; i < 8; i++)
  10631. result += " ";
  10632. result += "\n";
  10633. dataAddr++;
  10634. continue;
  10635. }
  10636. break;
  10637. }
  10638. int instLen = inst.GetLength();
  10639. #ifdef BF_DBG_32
  10640. result += StrFormat("D %08X: ", dataAddr);
  10641. #else
  10642. result += StrFormat("D %@: ", dataAddr);
  10643. #endif
  10644. uint8 instData[32];
  10645. int showInstLen = BF_MIN(32, instLen);
  10646. memCache->Read(dataAddr, instData, showInstLen);
  10647. for (int i = 0; i < showInstLen; i++)
  10648. result += StrFormat("%02X ", instData[i]);
  10649. for (int i = instLen; i < 8; i++)
  10650. result += " ";
  10651. result += mCPU->InstructionToString(&inst, dataAddr);
  10652. if ((inst.IsCall()) || (inst.IsBranch()))
  10653. {
  10654. addr_target targetAddr = inst.GetTarget();
  10655. if (targetAddr != 0)
  10656. {
  10657. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &symOffset))
  10658. {
  10659. if (symOffset < 0x10000)
  10660. {
  10661. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  10662. result += " ; " + outSymbol;
  10663. if (symOffset > 0)
  10664. result += StrFormat("+%x", symOffset);
  10665. //result += ">";
  10666. }
  10667. }
  10668. }
  10669. }
  10670. result += "\n";
  10671. dataAddr += instLen;
  10672. }
  10673. if (!hadAddr)
  10674. continue;
  10675. return result;
  10676. }
  10677. return "";
  10678. }
  10679. String WinDebugger::DisassembleAt(intptr inAddress)
  10680. {
  10681. BP_ZONE("WinDebugger::DisassembleAt");
  10682. AutoCrit autoCrit(mDebugManager->mCritSect);
  10683. addr_target address = (addr_target)inAddress;
  10684. if (mDebugTarget == NULL)
  10685. return "";
  10686. String result;
  10687. auto dwSubProgram = mDebugTarget->FindSubProgram(address);
  10688. if (dwSubProgram == NULL)
  10689. return DisassembleAtRaw(address);
  10690. dwSubProgram = dwSubProgram->GetRootInlineParent();
  10691. DbgModule* dwarf = dwSubProgram->mCompileUnit->mDbgModule;
  10692. int frameBaseRegister = mDebugTarget->GetFrameBaseRegister(dwSubProgram);
  10693. addr_target addrStart = dwSubProgram->mBlock.mLowPC;
  10694. addr_target addrEnd = dwSubProgram->mBlock.mHighPC;
  10695. auto dwCompileUnit = dwSubProgram->mCompileUnit;
  10696. {
  10697. FixupLineData(dwCompileUnit);
  10698. }
  10699. DbgSrcFile* dwSrcFile = NULL;
  10700. FixupLineDataForSubprogram(dwSubProgram);
  10701. DbgLineData* dwLineData = NULL;
  10702. if (dwSubProgram->mLineInfo != NULL)
  10703. dwLineData = &dwSubProgram->mLineInfo->mLines[0];
  10704. int nextLineDataIdx = 1;
  10705. if (dwSubProgram->mIsOptimized)
  10706. result += "O\n";
  10707. DbgSrcFile* srcFile = NULL;
  10708. int firstLine = 0;
  10709. int curLine = 0;
  10710. if (dwLineData != NULL)
  10711. {
  10712. srcFile = dwSubProgram->GetLineSrcFile(*dwLineData);
  10713. result += "S " + srcFile->GetLocalPath() + "\n";
  10714. if (srcFile->mHashKind != DbgHashKind_None)
  10715. {
  10716. result += "H ";
  10717. srcFile->GetHash(result);
  10718. result += "\n";
  10719. }
  10720. curLine = BF_MAX(0, dwLineData->mLine - 5);
  10721. //for (; curLine <= dwLineData->mLine; curLine++)
  10722. result += StrFormat("L %d %d\n", curLine, dwLineData->mLine - curLine + 1);
  10723. curLine = dwLineData->mLine + 1;
  10724. firstLine = dwLineData->mLine;
  10725. }
  10726. Array<DbgSubprogram*> inlineStack;
  10727. Array<DbgBlock*> blockList;
  10728. blockList.push_back(&dwSubProgram->mBlock);
  10729. addr_target dataAddr = addrStart;
  10730. int decodeFailureCount = 0;
  10731. auto& _PopInlineStack = [&]()
  10732. {
  10733. int depth = inlineStack.size();
  10734. auto curStackEntry = inlineStack.back();
  10735. if (depth > 1)
  10736. result += StrFormat("T <<<%d Inline End ", depth);
  10737. else
  10738. result += "T <<< Inline End ";
  10739. result += curStackEntry->ToString();
  10740. result += "\n";
  10741. inlineStack.pop_back();
  10742. };
  10743. std::function<void(DbgSubprogram* subprogram, int depth)> _UpdateInlineStackHelper = [&](DbgSubprogram* subprogram, int depth)
  10744. {
  10745. int stackIdx = depth - 1;
  10746. if (stackIdx < inlineStack.size())
  10747. {
  10748. auto curStackEntry = inlineStack[stackIdx];
  10749. if (curStackEntry != subprogram)
  10750. _PopInlineStack();
  10751. }
  10752. if (depth > 1)
  10753. {
  10754. _UpdateInlineStackHelper(subprogram->mInlineeInfo->mInlineParent, depth - 1);
  10755. }
  10756. if (stackIdx >= inlineStack.size())
  10757. {
  10758. if (depth > 1)
  10759. result += StrFormat("T >>>%d Inline ", depth);
  10760. else
  10761. result += "T >>> Inline ";
  10762. result += subprogram->ToString();
  10763. result += "\n";
  10764. inlineStack.push_back(subprogram);
  10765. }
  10766. };
  10767. auto _UpdateInlineStack = [&](DbgSubprogram* subprogram)
  10768. {
  10769. if (subprogram == NULL)
  10770. {
  10771. while (!inlineStack.IsEmpty())
  10772. _PopInlineStack();
  10773. return;
  10774. }
  10775. int inlineDepth = subprogram->GetInlineDepth();
  10776. while (inlineDepth < inlineStack.size())
  10777. _PopInlineStack();
  10778. if (inlineDepth > 0)
  10779. _UpdateInlineStackHelper(subprogram, inlineDepth);
  10780. };
  10781. while (dataAddr < addrEnd)
  10782. {
  10783. // Pop off old scopes
  10784. while (blockList.size() > 0)
  10785. {
  10786. auto lastBlock = blockList.back();
  10787. if (dataAddr < lastBlock->mHighPC)
  10788. break;
  10789. blockList.pop_back();
  10790. }
  10791. // Check entry into new child scopes
  10792. auto lastBlock = blockList.back();
  10793. for (auto checkBlock : lastBlock->mSubBlocks)
  10794. {
  10795. if ((dataAddr >= checkBlock->mLowPC) && (dataAddr < checkBlock->mHighPC))
  10796. {
  10797. blockList.push_back(checkBlock);
  10798. break;
  10799. }
  10800. }
  10801. bool allowSourceJump = false;
  10802. if ((dwLineData != NULL) && (dwLineData->mContribSize != 0) && (dataAddr >= dwSubProgram->GetLineAddr(*dwLineData) + dwLineData->mContribSize))
  10803. {
  10804. DbgSubprogram* inlinedSubprogram = NULL;
  10805. auto inlinedLine = dwSubProgram->FindClosestLine(dataAddr, &inlinedSubprogram);
  10806. _UpdateInlineStack(dwSubProgram);
  10807. }
  10808. // Update line data
  10809. while ((dwLineData != NULL) && (dwSubProgram->GetLineAddr(*dwLineData) <= dataAddr))
  10810. {
  10811. _UpdateInlineStack(dwSubProgram->GetLineInlinee(*dwLineData));
  10812. const int lineLimit = 5; // 15
  10813. if (allowSourceJump)
  10814. curLine = dwLineData->mLine;
  10815. auto lineSrcFile = dwSubProgram->GetLineSrcFile(*dwLineData);
  10816. if (lineSrcFile != srcFile)
  10817. {
  10818. srcFile = lineSrcFile;
  10819. result += "S ";
  10820. result += srcFile->GetLocalPath();
  10821. result += "\n";
  10822. // Just show the one line from the new file
  10823. curLine = dwLineData->mLine;
  10824. }
  10825. if (dwLineData->mLine < curLine - 1)
  10826. {
  10827. // Jumping backwards - possibly into inlined method, or possibly in current method.
  10828. // Show previous 6 lines, for context
  10829. curLine = BF_MAX(0, dwLineData->mLine - lineLimit);
  10830. }
  10831. if ((curLine <= firstLine) && (dwLineData->mLine >= firstLine))
  10832. {
  10833. // Jumping from inlined method (declared above) back into main method
  10834. curLine = dwLineData->mLine;
  10835. }
  10836. if (curLine < dwLineData->mLine - lineLimit)
  10837. {
  10838. // Don't show huge span of source - only show the last 6 lines at maximum
  10839. curLine = dwLineData->mLine - lineLimit;
  10840. }
  10841. //for ( ; curLine <= dwLineData->mLine; curLine++)
  10842. result += StrFormat("L %d %d\n", curLine, dwLineData->mLine - curLine + 1);
  10843. curLine = dwLineData->mLine + 1;
  10844. DbgLineData* nextLineData = NULL;
  10845. while (nextLineDataIdx < dwSubProgram->mLineInfo->mLines.mSize)
  10846. {
  10847. nextLineData = &dwSubProgram->mLineInfo->mLines[nextLineDataIdx];
  10848. //TODO:
  10849. /*{
  10850. result += StrFormat("T LineIdx: %d (%@ to %@)", nextLineDataIdx, dwSubProgram->GetLineAddr(*nextLineData), dwSubProgram->GetLineAddr(*nextLineData) + nextLineData->mContribSize);
  10851. auto inlinee = dwSubProgram->GetLineInlinee(*nextLineData);
  10852. if (inlinee != NULL)
  10853. {
  10854. result += StrFormat(" Inlinee: %s Depth: %d", inlinee->mName, inlinee->GetInlineDepth());
  10855. }
  10856. result += "\n";
  10857. }*/
  10858. auto nextLineAddr = dwSubProgram->GetLineAddr(*nextLineData);
  10859. if (nextLineAddr > dataAddr)
  10860. {
  10861. if (nextLineDataIdx + 1 < dwSubProgram->mLineInfo->mLines.mSize)
  10862. {
  10863. auto peekLineData = &dwSubProgram->mLineInfo->mLines[nextLineDataIdx + 1];
  10864. if (peekLineData->mRelAddress == nextLineData->mRelAddress)
  10865. {
  10866. // Use the later entry
  10867. ++nextLineDataIdx;
  10868. continue;
  10869. }
  10870. }
  10871. break;
  10872. }
  10873. // If we go back to an older entry beacuse of a gap then we need to catch back up...
  10874. ++nextLineDataIdx;
  10875. nextLineData = NULL; // Keep searching...
  10876. }
  10877. dwLineData = nextLineData;
  10878. nextLineDataIdx++;
  10879. }
  10880. // Have we gone off the end of the inline function?
  10881. // We may not have an explicit non-inlined line data at the transition point...
  10882. while (!inlineStack.IsEmpty())
  10883. {
  10884. auto subProgram = inlineStack.back();
  10885. if (dataAddr < subProgram->mBlock.mHighPC)
  10886. break;
  10887. _PopInlineStack();
  10888. }
  10889. bool hadDecodeFailure = false;
  10890. CPUInst inst;
  10891. if (!mCPU->Decode(dataAddr, dwarf->mOrigImageData, &inst))
  10892. hadDecodeFailure = true;
  10893. if ((decodeFailureCount == 8) || ((decodeFailureCount > 0) && (!hadDecodeFailure)))
  10894. {
  10895. for (int i = decodeFailureCount; i < 4 + sizeof(addr_target); i++)
  10896. result += " ";
  10897. result += " ???\n";
  10898. decodeFailureCount = 0;
  10899. }
  10900. if (decodeFailureCount == 0)
  10901. {
  10902. #ifdef BF_DBG_32
  10903. result += StrFormat("D %08X: ", dataAddr);
  10904. #else
  10905. result += StrFormat("D %@: ", dataAddr);
  10906. #endif
  10907. }
  10908. if (hadDecodeFailure)
  10909. {
  10910. uint8 byte = 0;
  10911. dwarf->mOrigImageData->Read(dataAddr, &byte, 1);
  10912. result += StrFormat("%02X ", byte);
  10913. dataAddr++;
  10914. decodeFailureCount++;
  10915. continue;
  10916. }
  10917. int instLen = inst.GetLength();
  10918. uint8 instData[32];
  10919. int showInstLen = BF_MIN(32, instLen);
  10920. dwarf->mOrigImageData->Read(dataAddr, instData, showInstLen);
  10921. for (int i = 0; i < showInstLen; i++)
  10922. result += StrFormat("%02X ", instData[i]);
  10923. for (int i = instLen; i < 4 + sizeof(addr_target); i++)
  10924. result += " ";
  10925. result += " ";
  10926. result += mCPU->InstructionToString(&inst, dataAddr);
  10927. int reg;
  10928. int offset;
  10929. if (inst.GetIndexRegisterAndOffset(&reg, &offset))
  10930. {
  10931. for (int blockIdx = (int)blockList.size() - 1; blockIdx >= 0; blockIdx--)
  10932. {
  10933. auto dwBlock = blockList[blockIdx];
  10934. for (auto variable : dwBlock->mVariables)
  10935. {
  10936. int varRegister;
  10937. int varOffset;
  10938. if (mDebugTarget->GetVariableIndexRegisterAndOffset(variable, &varRegister, &varOffset))
  10939. {
  10940. if (varRegister == -1)
  10941. varRegister = frameBaseRegister;
  10942. if ((reg == varRegister) && (offset == varOffset))
  10943. {
  10944. result += " ; ";
  10945. result += variable->mName;
  10946. break;
  10947. }
  10948. }
  10949. }
  10950. }
  10951. }
  10952. else if ((inst.IsCall()) || (inst.IsBranch()) || (inst.IsLoadAddress()))
  10953. {
  10954. addr_target targetAddr = inst.GetTarget();
  10955. if (targetAddr != 0)
  10956. {
  10957. if ((targetAddr >= addrStart) && (targetAddr < addrEnd))
  10958. {
  10959. result += StrFormat("\nJ %s", EncodeDataPtr(targetAddr, false).c_str());
  10960. }
  10961. else
  10962. {
  10963. String outSymbol;
  10964. addr_target offset = 0;
  10965. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &offset))
  10966. {
  10967. if (offset < 0x10000)
  10968. {
  10969. outSymbol = BfDemangler::Demangle(outSymbol, dwSubProgram->GetLanguage());
  10970. result += " ; " + outSymbol;
  10971. if (offset > 0)
  10972. result += StrFormat("+%x", offset);
  10973. }
  10974. }
  10975. }
  10976. }
  10977. }
  10978. result += "\n";
  10979. dataAddr += instLen;
  10980. }
  10981. // Why did we want to "show lines at end"??
  10982. // Show lines at end
  10983. /*if (curLine > 0)
  10984. {
  10985. for (int i = 0; i < 6; i++, curLine++)
  10986. result += StrFormat("L %d\n", curLine);
  10987. }*/
  10988. return result;
  10989. }
  10990. String WinDebugger::FindLineCallAddresses(intptr inAddress)
  10991. {
  10992. String callAddresses;
  10993. addr_target address = (addr_target)inAddress;
  10994. DbgSubprogram* dwSubprogram = NULL;
  10995. DbgLineData* startLineData = FindLineDataAtAddress(address, &dwSubprogram, NULL);
  10996. if (dwSubprogram == NULL)
  10997. return "";
  10998. CPURegisters registers;
  10999. PopulateRegisters(&registers);
  11000. auto inlinerSubprogram = dwSubprogram->GetRootInlineParent();
  11001. FixupLineDataForSubprogram(inlinerSubprogram);
  11002. if (inlinerSubprogram->mLineInfo->mLines.mSize == 0)
  11003. return "";
  11004. auto lineData = &inlinerSubprogram->mLineInfo->mLines[0];
  11005. addr_target addr = dwSubprogram->mBlock.mLowPC;
  11006. addr_target endAddr = dwSubprogram->mBlock.mHighPC;
  11007. DbgSubprogram* checkSubprogram = dwSubprogram;
  11008. DbgLineData* checkLineData = lineData;
  11009. addr_target checkLineAddr = 0;
  11010. int lineIdx = 0;
  11011. while (checkLineData != NULL)
  11012. {
  11013. //auto nextLineData = dwSubprogram->mCompileUnit->mLineDataMap.GetNext(checkLineData);
  11014. ++lineIdx;
  11015. DbgLineData* nextLineData = NULL;
  11016. addr_target nextLineAddr;
  11017. if (lineIdx < inlinerSubprogram->mLineInfo->mLines.size())
  11018. {
  11019. nextLineData = &inlinerSubprogram->mLineInfo->mLines[lineIdx];
  11020. nextLineAddr = dwSubprogram->GetLineAddr(*nextLineData);
  11021. }
  11022. else
  11023. nextLineAddr = inlinerSubprogram->mBlock.mHighPC;
  11024. // This stuff doesn't make sense...
  11025. DbgSubprogram* nextSubProgram;
  11026. if (nextLineData != NULL)
  11027. {
  11028. if (nextLineAddr > dwSubprogram->mBlock.mHighPC)
  11029. break;
  11030. endAddr = nextLineAddr;
  11031. nextSubProgram = mDebugTarget->FindSubProgram(endAddr);
  11032. if (nextSubProgram != NULL)
  11033. {
  11034. auto dbgModule = nextSubProgram->mCompileUnit->mDbgModule;
  11035. dbgModule->ParseSymbolData();
  11036. }
  11037. }
  11038. else
  11039. {
  11040. nextSubProgram = dwSubprogram;
  11041. endAddr = dwSubprogram->mBlock.mHighPC;
  11042. }
  11043. auto _HandleSection = [&]()
  11044. {
  11045. while (addr < endAddr)
  11046. {
  11047. CPUInst inst;
  11048. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  11049. break;
  11050. *registers.GetPCRegisterRef() = addr;
  11051. if (inst.IsCall())
  11052. {
  11053. bool addSymbol = true;
  11054. if (addr < (addr_target)inAddress)
  11055. callAddresses += "-";
  11056. callAddresses += EncodeDataPtr(addr, false);
  11057. addr_target targetAddr = inst.GetTarget(this, &registers);
  11058. if (targetAddr != 0)
  11059. {
  11060. String outSymbol;
  11061. auto subprogram = mDebugTarget->FindSubProgram(targetAddr);
  11062. if (subprogram != NULL)
  11063. {
  11064. CreateFilterName(outSymbol, subprogram);
  11065. addSymbol = true;
  11066. }
  11067. else
  11068. {
  11069. addr_target offset = 0;
  11070. String fullSymbolName;
  11071. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &offset))
  11072. {
  11073. if (offset < 0x200)
  11074. {
  11075. //outSymbol = BfDemangler::Demangle(outSymbol, dwSubprogram->GetLanguage());
  11076. if (outSymbol == "___chkstk_ms")
  11077. addSymbol = false;
  11078. else
  11079. {
  11080. String demangledName = BfDemangler::Demangle(outSymbol, DbgLanguage_C);
  11081. outSymbol.clear();
  11082. CreateFilterName(outSymbol, demangledName.c_str(), DbgLanguage_C);
  11083. }
  11084. }
  11085. else
  11086. outSymbol.clear();
  11087. }
  11088. }
  11089. if (addSymbol)
  11090. {
  11091. if (outSymbol.empty())
  11092. callAddresses += "\tFunc@" + EncodeDataPtr(targetAddr, false);
  11093. else
  11094. callAddresses += "\t" + outSymbol;
  11095. String attrs;
  11096. bool isFiltered = false;
  11097. if (subprogram != NULL)
  11098. {
  11099. subprogram->PopulateSubprogram();
  11100. isFiltered = subprogram->mIsStepFilteredDefault;
  11101. if (isFiltered)
  11102. attrs += "d"; // 'd' for default filtered
  11103. }
  11104. StepFilter* stepFilterPtr = NULL;
  11105. if (mDebugManager->mStepFilters.TryGetValue(outSymbol, &stepFilterPtr))
  11106. isFiltered = stepFilterPtr->IsFiltered(isFiltered);
  11107. if (isFiltered)
  11108. attrs += "f"; // 'f' for filter
  11109. if (!attrs.IsEmpty())
  11110. callAddresses += "\t" + attrs;
  11111. }
  11112. }
  11113. if (addSymbol)
  11114. callAddresses += "\n";
  11115. }
  11116. inst.PartialSimulate(this, &registers);
  11117. addr += inst.GetLength();
  11118. }
  11119. };
  11120. // For inlining - only add calls that are found either directly in our main block (not an inlined block)
  11121. // But add inlined methods when their parent is our current block
  11122. if ((checkSubprogram == dwSubprogram) && (checkLineData->mLine == startLineData->mLine))
  11123. {
  11124. _HandleSection();
  11125. }
  11126. else if ((checkSubprogram->mInlineeInfo != NULL) && (checkSubprogram->mInlineeInfo->mInlineParent == dwSubprogram))
  11127. {
  11128. if (checkLineAddr == checkSubprogram->mBlock.mLowPC)
  11129. {
  11130. addr_target inlineStartAddr = checkSubprogram->mBlock.mLowPC;
  11131. // Find the calling line
  11132. DbgSubprogram* callingSubprogram = dwSubprogram;
  11133. auto checkLineData = dwSubprogram->FindClosestLine(inlineStartAddr, &callingSubprogram);
  11134. if ((checkLineData != NULL) && (checkLineData->mCtxIdx == startLineData->mCtxIdx) && (checkLineData->mLine == startLineData->mLine))
  11135. {
  11136. if (inlineStartAddr <= (addr_target)inAddress)
  11137. callAddresses += "-";
  11138. callAddresses += EncodeDataPtr(inlineStartAddr, false);
  11139. String outSymbol;
  11140. CreateFilterName(outSymbol, checkSubprogram);
  11141. callAddresses += "\t" + outSymbol;
  11142. bool isFiltered = dwSubprogram->mIsStepFilteredDefault;
  11143. StepFilter* stepFilterPtr;
  11144. if (mDebugManager->mStepFilters.TryGetValue(outSymbol, &stepFilterPtr))
  11145. isFiltered = stepFilterPtr->IsFiltered(isFiltered);
  11146. if (isFiltered)
  11147. callAddresses += "\tf"; // 'f' for filter
  11148. callAddresses += "\n";
  11149. }
  11150. // if (checkSubprogram->mBlock.mHighPC < endAddr)
  11151. // {
  11152. // addr = checkSubprogram->mBlock.mHighPC;
  11153. // _HandleSection();
  11154. // }
  11155. }
  11156. // If we have unattributed data after the end of an inlined method, add that
  11157. if ((endAddr > checkSubprogram->mBlock.mHighPC) && (nextSubProgram == dwSubprogram))
  11158. {
  11159. addr = checkSubprogram->mBlock.mHighPC;
  11160. _HandleSection();
  11161. }
  11162. }
  11163. checkLineData = nextLineData;
  11164. checkSubprogram = nextSubProgram;
  11165. checkLineAddr = nextLineAddr;
  11166. addr = endAddr;
  11167. }
  11168. return callAddresses;
  11169. }
  11170. String WinDebugger::GetCurrentException()
  11171. {
  11172. AutoCrit autoCrit(mDebugManager->mCritSect);
  11173. String result = StrFormat("%s\n%08X",
  11174. EncodeDataPtr((addr_target)(intptr)mCurException.ExceptionAddress, true).c_str(),
  11175. mCurException.ExceptionCode);
  11176. String exStr;
  11177. switch (mCurException.ExceptionCode)
  11178. {
  11179. case EXCEPTION_ACCESS_VIOLATION:
  11180. {
  11181. String accessType;
  11182. if (mCurException.ExceptionInformation[0] == 0)
  11183. accessType = "reading from";
  11184. else if (mCurException.ExceptionInformation[0] == 8)
  11185. accessType = "executing";
  11186. else
  11187. accessType = "writing to";
  11188. exStr = StrFormat("EXCEPTION_ACCESS_VIOLATION %s %s", accessType.c_str(), EncodeDataPtr((addr_target)mCurException.ExceptionInformation[1], true).c_str());
  11189. }
  11190. break;
  11191. case EXCEPTION_DATATYPE_MISALIGNMENT:
  11192. exStr = "EXCEPTION_DATATYPE_MISALIGNMENT";
  11193. case EXCEPTION_SINGLE_STEP:
  11194. exStr = "EXCEPTION_SINGLE_STEP";
  11195. break;
  11196. case EXCEPTION_BREAKPOINT:
  11197. exStr = "EXCEPTION_BREAKPOINT";
  11198. break;
  11199. case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
  11200. exStr = "EXCEPTION_ARRAY_BOUNDS_EXCEEDED";
  11201. break;
  11202. case EXCEPTION_FLT_DENORMAL_OPERAND:
  11203. exStr = "EXCEPTION_FLT_DENORMAL_OPERAND";
  11204. break;
  11205. case EXCEPTION_FLT_DIVIDE_BY_ZERO:
  11206. exStr = "EXCEPTION_FLT_DIVIDE_BY_ZERO";
  11207. break;
  11208. case EXCEPTION_FLT_INEXACT_RESULT:
  11209. exStr = "EXCEPTION_FLT_INEXACT_RESULT";
  11210. break;
  11211. case EXCEPTION_FLT_INVALID_OPERATION:
  11212. exStr = "EXCEPTION_FLT_INVALID_OPERATIO";
  11213. break;
  11214. case EXCEPTION_FLT_OVERFLOW:
  11215. exStr = "EXCEPTION_FLT_OVERFLOW";
  11216. break;
  11217. case EXCEPTION_FLT_STACK_CHECK:
  11218. exStr = "EXCEPTION_FLT_STACK_CHECK";
  11219. break;
  11220. case EXCEPTION_FLT_UNDERFLOW:
  11221. exStr = "EXCEPTION_FLT_UNDERFLOW";
  11222. break;
  11223. case EXCEPTION_INT_DIVIDE_BY_ZERO:
  11224. exStr = "EXCEPTION_INT_DIVIDE_BY_ZERO";
  11225. break;
  11226. case EXCEPTION_INT_OVERFLOW:
  11227. exStr = "EXCEPTION_INT_OVERFLOW";
  11228. break;
  11229. case EXCEPTION_PRIV_INSTRUCTION:
  11230. exStr = "EXCEPTION_PRIV_INSTRUCTION";
  11231. break;
  11232. case EXCEPTION_IN_PAGE_ERROR:
  11233. exStr = "EXCEPTION_IN_PAGE_ERROR";
  11234. break;
  11235. case EXCEPTION_ILLEGAL_INSTRUCTION:
  11236. exStr = "EXCEPTION_ILLEGAL_INSTRUCTION";
  11237. break;
  11238. case EXCEPTION_NONCONTINUABLE_EXCEPTION:
  11239. exStr = "EXCEPTION_NONCONTINUABLE_EXCEPTION";
  11240. break;
  11241. case EXCEPTION_STACK_OVERFLOW:
  11242. exStr = "EXCEPTION_STACK_OVERFLOW";
  11243. break;
  11244. case EXCEPTION_INVALID_DISPOSITION:
  11245. exStr = "EXCEPTION_INVALID_DISPOSITION";
  11246. break;
  11247. case EXCEPTION_GUARD_PAGE:
  11248. exStr = "EXCEPTION_GUARD_PAGE";
  11249. break;
  11250. case EXCEPTION_INVALID_HANDLE:
  11251. exStr = "EXCEPTION_INVALID_HANDLE";
  11252. break;
  11253. case CONTROL_C_EXIT:
  11254. exStr = "CONTROL_C_EXIT";
  11255. break;
  11256. default:
  11257. exStr += StrFormat("EXCEPTION %08X", mCurException.ExceptionCode);
  11258. }
  11259. if (mActiveThread != NULL)
  11260. exStr += StrFormat(" in thread %d", mActiveThread->mThreadId);
  11261. if (!exStr.empty())
  11262. result += "\n" + exStr;
  11263. // After we retrieve the exception then we can go back to just being normal 'paused'
  11264. // This allows us to evaluate stuff, Set Next Statement, etc.
  11265. mRunState = RunState_Paused;
  11266. return result.c_str();
  11267. }
  11268. void WinDebugger::SetAliasPath(const StringImpl& origPath, const StringImpl& localPath)
  11269. {
  11270. AutoCrit autoCrit(mDebugManager->mCritSect);
  11271. String fixedOrigPath = FixPathAndCase(origPath);
  11272. String fixedLocalPath = FixPathAndCase(localPath);
  11273. auto origFile = mDebugTarget->AddSrcFile(origPath);
  11274. origFile->mLocalPath = FixPath(localPath);
  11275. mDebugTarget->mLocalToOrigSrcMap[fixedLocalPath] = fixedOrigPath;
  11276. // We invalidate the step filters, because previously-failing 'CheckSourceFileExist' checks may now succeed
  11277. mDebugManager->mStepFilterVersion++;
  11278. }
  11279. String WinDebugger::GetModulesInfo()
  11280. {
  11281. AutoCrit autoCrit(mDebugManager->mCritSect);
  11282. String str;
  11283. for (auto module : mDebugTarget->mDbgModules)
  11284. {
  11285. COFF* coff = (COFF*)module;
  11286. if (module->mHotIdx > 0)
  11287. continue;
  11288. str += module->mDisplayName;
  11289. str += "\t";
  11290. if (module->mLoadState == DbgModuleLoadState_Loaded)
  11291. {
  11292. str += module->mFilePath;
  11293. }
  11294. else if (module->mLoadState == DbgModuleLoadState_NotLoaded)
  11295. {
  11296. str += module->mFilePath;
  11297. str += " (Loading...)";
  11298. }
  11299. else if (module->mLoadState == DbgModuleLoadState_Failed)
  11300. {
  11301. str += "!";
  11302. str += module->mFilePath;
  11303. }
  11304. if (module->mMappedImageFile != NULL)
  11305. {
  11306. str += " (";
  11307. str += module->mMappedImageFile->mFileName;
  11308. str += ")";
  11309. }
  11310. str += "\t";
  11311. str += coff->mPDBPath;
  11312. str += "\t";
  11313. str += module->mVersion;
  11314. str += StrFormat("\t%@-%@\t%dk\t", module->mImageBase, module->mImageBase + module->mImageSize, module->mImageSize / 1024);
  11315. time_t timestamp = coff->mTimeStamp;
  11316. if (timestamp == 0)
  11317. timestamp = GetFileTimeWrite(coff->mFilePath);
  11318. if (timestamp != 0)
  11319. {
  11320. char timeString[256];
  11321. auto time_info = localtime(&timestamp);
  11322. strftime(timeString, sizeof(timeString), "%D %T", time_info);
  11323. str += timeString;
  11324. }
  11325. str += "\n";
  11326. }
  11327. return str;
  11328. }
  11329. String WinDebugger::GetModuleInfo(const StringImpl& modulePath)
  11330. {
  11331. AutoCrit autoCrit(mDebugManager->mCritSect);
  11332. String result;
  11333. for (auto dbgModule : mDebugTarget->mDbgModules)
  11334. {
  11335. if (modulePath.Equals(dbgModule->mFilePath, StringImpl::CompareKind_OrdinalIgnoreCase))
  11336. {
  11337. dbgModule->ParseGlobalsData();
  11338. dbgModule->PopulateStaticVariableMap();
  11339. auto coff = (COFF*)dbgModule;
  11340. coff->ParseCompileUnits();
  11341. int fileSize = 0;
  11342. //
  11343. {
  11344. FileStream fs;
  11345. fs.Open(coff->mFilePath, "rb");
  11346. fileSize = fs.GetSize();
  11347. }
  11348. result += StrFormat("Path: %s FileSize:%0.2fk MemoryImage:%0.2fk\n", coff->mFilePath.c_str(), fileSize / 1024.0f, coff->mImageSize / 1024.0f);
  11349. result += "Sections:\n";
  11350. for (auto& section : coff->mSections)
  11351. {
  11352. result += StrFormat("\t%s\t%0.2fk\n", section.mName.c_str(), (section.mAddrLength) / 1024.0f);
  11353. }
  11354. result += "\n";
  11355. result += "Compile Units:\n";
  11356. for (auto compileUnit : dbgModule->mCompileUnits)
  11357. {
  11358. coff->MapCompileUnitMethods(compileUnit);
  11359. result += StrFormat("\t%s PCRange:%0.2fk\n", compileUnit->mName.c_str(), (compileUnit->mHighPC - compileUnit->mLowPC) / 1024.0f);
  11360. }
  11361. result += "\n";
  11362. Array<CvModuleInfo*> moduleInfos;
  11363. for (auto moduleInfo : coff->mCvModuleInfo)
  11364. {
  11365. if (moduleInfo->mSectionContrib.mSize > 0)
  11366. moduleInfos.Add(moduleInfo);
  11367. }
  11368. moduleInfos.Sort([](CvModuleInfo* lhs, CvModuleInfo* rhs)
  11369. {
  11370. return lhs->mSectionContrib.mSize > rhs->mSectionContrib.mSize;
  11371. });
  11372. int totalContrib = 0;
  11373. result += "CV Module Info:\n";
  11374. for (auto moduleInfo : moduleInfos)
  11375. {
  11376. auto section = coff->mSections[moduleInfo->mSectionContrib.mSection - 1];
  11377. result += StrFormat("\t%s\t%s\t%0.2fk\t%@-%@\n", moduleInfo->mModuleName, section.mName.c_str(), (moduleInfo->mSectionContrib.mSize) / 1024.0f,
  11378. coff->GetSectionAddr(moduleInfo->mSectionContrib.mSection, moduleInfo->mSectionContrib.mOffset),
  11379. coff->GetSectionAddr(moduleInfo->mSectionContrib.mSection, moduleInfo->mSectionContrib.mOffset + moduleInfo->mSectionContrib.mSize));
  11380. totalContrib += moduleInfo->mSectionContrib.mSize;
  11381. }
  11382. result += StrFormat("\tTOTAL: %0.2fk\n", (totalContrib) / 1024.0f);
  11383. result += "\n";
  11384. addr_target minAddr = 0;
  11385. Array<DbgCompileUnitContrib*> contribs;
  11386. for (auto itr = mDebugTarget->mContribMap.begin(); itr != mDebugTarget->mContribMap.end(); ++itr)
  11387. {
  11388. auto contrib = *itr;
  11389. if (contrib->mDbgModule != coff)
  11390. continue;
  11391. if (contrib->mAddress < minAddr)
  11392. continue;
  11393. minAddr = contrib->mAddress + contrib->mLength;
  11394. auto section = &coff->mSectionHeaders[contrib->mSection - 1];
  11395. if (section->mSizeOfRawData <= 0)
  11396. continue;
  11397. contribs.Add(contrib);
  11398. }
  11399. contribs.Sort([](DbgCompileUnitContrib* lhs, DbgCompileUnitContrib* rhs)
  11400. {
  11401. return lhs->mLength > rhs->mLength;
  11402. });
  11403. totalContrib = 0;
  11404. result += "Contribs:\n";
  11405. for (auto contrib : contribs)
  11406. {
  11407. auto cvModule = coff->mCvModuleInfo[contrib->mCompileUnitId];
  11408. auto section = &coff->mSectionHeaders[contrib->mSection - 1];
  11409. result += StrFormat("\t%s\t%s\t%0.2fk\t%@\n", cvModule->mModuleName, section->mName, (contrib->mLength)/1024.0f, contrib->mAddress);
  11410. totalContrib += contrib->mLength;
  11411. }
  11412. result += StrFormat("\tTOTAL: %0.2fk\n", (totalContrib) / 1024.0f);
  11413. result += "\n";
  11414. struct SymbolEntry
  11415. {
  11416. const char* mName;
  11417. addr_target mAddress;
  11418. int mSize;
  11419. };
  11420. Array<SymbolEntry> symbolEntries;
  11421. for (auto symbol : mDebugTarget->mSymbolMap)
  11422. {
  11423. if (symbol->mDbgModule != coff)
  11424. continue;
  11425. if (!symbolEntries.IsEmpty())
  11426. {
  11427. auto lastSymbol = &symbolEntries.back();
  11428. if (lastSymbol->mSize == 0)
  11429. lastSymbol->mSize = symbol->mAddress - lastSymbol->mAddress;
  11430. }
  11431. SymbolEntry symbolEntry;
  11432. symbolEntry.mName = symbol->mName;
  11433. symbolEntry.mAddress = symbol->mAddress;
  11434. symbolEntry.mSize = 0;
  11435. symbolEntries.Add(symbolEntry);
  11436. }
  11437. if (!symbolEntries.IsEmpty())
  11438. {
  11439. auto lastSymbol = &symbolEntries.back();
  11440. for (auto contrib : contribs)
  11441. {
  11442. if ((lastSymbol->mAddress >= contrib->mAddress) && (lastSymbol->mAddress < contrib->mAddress + contrib->mLength))
  11443. {
  11444. lastSymbol->mSize = (contrib->mAddress + contrib->mLength) - lastSymbol->mAddress;
  11445. break;
  11446. }
  11447. }
  11448. }
  11449. symbolEntries.Sort([](const SymbolEntry& lhs, const SymbolEntry& rhs)
  11450. {
  11451. return lhs.mSize > rhs.mSize;
  11452. });
  11453. totalContrib = 0;
  11454. result += "Symbols:\n";
  11455. for (auto symbolEntry : symbolEntries)
  11456. {
  11457. result += StrFormat("\t%s\t%0.2fk\t%@\n", symbolEntry.mName, (symbolEntry.mSize) / 1024.0f, symbolEntry.mAddress);
  11458. totalContrib += symbolEntry.mSize;
  11459. }
  11460. result += StrFormat("\tTOTAL: %0.2fk\n", (totalContrib) / 1024.0f);
  11461. result += "\n";
  11462. //////////////////////////////////////////////////////////////////////////
  11463. totalContrib = 0;
  11464. result += "Static Variables:\n";
  11465. for (auto& variable : coff->mStaticVariables)
  11466. {
  11467. result += StrFormat("\t%s\t%0.2fk\n", variable->mName, (variable->mType->GetByteCount()) / 1024.0f);
  11468. totalContrib += variable->mType->GetByteCount();
  11469. }
  11470. result += StrFormat("\tTOTAL: %0.2fk\n", (totalContrib) / 1024.0f);
  11471. result += "\n";
  11472. totalContrib = 0;
  11473. result += "Methods:\n";
  11474. Array<DbgSubprogram*> methods;
  11475. for (int typeIdx = 0; typeIdx < coff->mTypes.mSize; typeIdx++)
  11476. {
  11477. auto type = coff->mTypes[typeIdx];
  11478. type->PopulateType();
  11479. for (auto method : type->mMethodList)
  11480. methods.Add(method);
  11481. }
  11482. for (auto compileUnit : dbgModule->mCompileUnits)
  11483. {
  11484. for (auto method : compileUnit->mOrphanMethods)
  11485. methods.Add(method);
  11486. }
  11487. methods.Sort([](DbgSubprogram* lhs, DbgSubprogram* rhs)
  11488. {
  11489. return lhs->GetByteCount() > rhs->GetByteCount();
  11490. });
  11491. for (auto method : methods)
  11492. {
  11493. int methodSize = method->GetByteCount();
  11494. if (methodSize <= 0)
  11495. continue;
  11496. auto name = method->ToString();
  11497. result += StrFormat("\t%s\t%0.2fk\n", name.c_str(), methodSize / 1024.0f);
  11498. totalContrib += methodSize;
  11499. }
  11500. result += StrFormat("\tTOTAL: %0.2fk\n", (totalContrib) / 1024.0f);
  11501. result += "\n";
  11502. }
  11503. }
  11504. return result;
  11505. }
  11506. void WinDebugger::CancelSymSrv()
  11507. {
  11508. AutoCrit autoCrit(mDebugManager->mCritSect);
  11509. if (mActiveSymSrvRequest != NULL)
  11510. mActiveSymSrvRequest->Cancel();
  11511. }
  11512. bool WinDebugger::HasPendingDebugLoads()
  11513. {
  11514. AutoCrit autoCrit(mDebugManager->mCritSect);
  11515. return (!mPendingImageLoad.IsEmpty()) || (!mPendingDebugInfoLoad.IsEmpty());
  11516. }
  11517. int WinDebugger::LoadImageForModule(const StringImpl &modulePath, const StringImpl& imagePath)
  11518. {
  11519. AutoCrit autoCrit(mDebugManager->mCritSect);
  11520. for (auto dbgModule : mDebugTarget->mDbgModules)
  11521. {
  11522. if (modulePath.Equals(dbgModule->mFilePath, StringImpl::CompareKind_OrdinalIgnoreCase))
  11523. {
  11524. auto coff = (COFF*)dbgModule;
  11525. if (!coff->LoadModuleImage(imagePath))
  11526. {
  11527. mDebugManager->mOutMessages.push_back("error Failed to load image " + imagePath);
  11528. }
  11529. ModuleChanged(dbgModule);
  11530. return 0;
  11531. }
  11532. }
  11533. return 0;
  11534. }
  11535. int WinDebugger::LoadDebugInfoForModule(DbgModule* dbgModule)
  11536. {
  11537. if (!dbgModule->HasPendingDebugInfo())
  11538. return 0;
  11539. if (dbgModule->RequestDebugInfo())
  11540. {
  11541. ClearCallStack(); // Make this re-resolve with debug info
  11542. return 1;
  11543. }
  11544. DbgPendingDebugInfoLoad* dbgPendingDebugInfoLoad = NULL;
  11545. if (mPendingDebugInfoLoad.TryAdd(dbgModule, NULL, &dbgPendingDebugInfoLoad))
  11546. {
  11547. dbgPendingDebugInfoLoad->mModule = dbgModule;
  11548. dbgPendingDebugInfoLoad->mAllowRemote = true;
  11549. return 2;
  11550. }
  11551. dbgPendingDebugInfoLoad->mAllowRemote = true;
  11552. return 0;
  11553. }
  11554. int WinDebugger::LoadDebugInfoForModule(const StringImpl& moduleName)
  11555. {
  11556. AutoCrit autoCrit(mDebugManager->mCritSect);
  11557. for (auto dbgModule : mDebugTarget->mDbgModules)
  11558. {
  11559. String checkModuleName = GetFileName(dbgModule->mFilePath);
  11560. if (moduleName.Equals(checkModuleName, StringImpl::CompareKind_OrdinalIgnoreCase))
  11561. {
  11562. return LoadDebugInfoForModule(dbgModule);
  11563. }
  11564. }
  11565. return 0;
  11566. }
  11567. int WinDebugger::LoadDebugInfoForModule(const StringImpl& modulePath, const StringImpl& debugFileName)
  11568. {
  11569. AutoCrit autoCrit(mDebugManager->mCritSect);
  11570. for (auto dbgModule : mDebugTarget->mDbgModules)
  11571. {
  11572. if (modulePath.Equals(dbgModule->mFilePath, StringImpl::CompareKind_OrdinalIgnoreCase))
  11573. {
  11574. auto coff = (COFF*)dbgModule;
  11575. String err;
  11576. if (!coff->mPDBLoaded)
  11577. {
  11578. dbgModule->mFailMsgPtr = &err;
  11579. if (coff->TryLoadPDB(debugFileName, coff->mWantPDBGuid, coff->mWantAge))
  11580. {
  11581. ModuleChanged(dbgModule);
  11582. }
  11583. dbgModule->mFailMsgPtr = NULL;
  11584. }
  11585. else
  11586. {
  11587. err = StrFormat("Module '%s' already has debug information loaded", GetFileName(modulePath).c_str());
  11588. }
  11589. if (!err.IsEmpty())
  11590. {
  11591. mDebugManager->mOutMessages.push_back("error " + err);
  11592. }
  11593. return 0;
  11594. }
  11595. }
  11596. return 0;
  11597. }
  11598. void WinDebugger::FixupLineData(DbgCompileUnit* compileUnit)
  11599. {
  11600. if (!compileUnit || !compileUnit->mNeedsLineDataFixup)
  11601. return;
  11602. compileUnit->mNeedsLineDataFixup = false;
  11603. }
  11604. static int CompareLineData(const void* lineDataP1, const void* lineDataP2)
  11605. {
  11606. int cmpResult = (int)(((DbgLineData*)lineDataP1)->mRelAddress - ((DbgLineData*)lineDataP2)->mRelAddress);
  11607. if (cmpResult != 0)
  11608. return cmpResult;
  11609. // A larger contrib size means it's the 'outer' inlinee
  11610. cmpResult = -(((DbgLineData*)lineDataP1)->mContribSize - ((DbgLineData*)lineDataP2)->mContribSize);
  11611. if (cmpResult != 0)
  11612. return cmpResult;
  11613. return -(((DbgLineData*)lineDataP1)->mCtxIdx - ((DbgLineData*)lineDataP2)->mCtxIdx);
  11614. }
  11615. void WinDebugger::FixupLineDataForSubprogram(DbgSubprogram* subProgram)
  11616. {
  11617. if ((subProgram == NULL) || (!subProgram->mNeedLineDataFixup))
  11618. return;
  11619. BP_ZONE("FixupLineDataForSubprogram");
  11620. subProgram->mNeedLineDataFixup = false;
  11621. if (subProgram->mInlineeInfo != NULL)
  11622. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  11623. if ((subProgram->mLineInfo == NULL) || (subProgram->mLineInfo->mLines.mSize == 0))
  11624. return;
  11625. //TODO: I think this was covering up a bug in DWARF line encoding? Figure this out
  11626. // if (subProgram->mLineInfo->mLines.mSize >= 2)
  11627. // {
  11628. // DbgLineData* line0 = &subProgram->mLineInfo->mLines[0];
  11629. // DbgLineData* line1 = &subProgram->mLineInfo->mLines[1];
  11630. //
  11631. //
  11632. // if ((line0->mRelAddress == line1->mRelAddress) && (!line0->IsStackFrameSetup()) && (line1->IsStackFrameSetup()))
  11633. // {
  11634. // CPUInst inst;
  11635. // if (mCPU->Decode(line0->mAddress, subProgram->mCompileUnit->mDbgModule->mOrigImageData, &inst))
  11636. // line1->mAddress += inst.GetLength();
  11637. // }
  11638. // }
  11639. qsort(subProgram->mLineInfo->mLines.mVals, subProgram->mLineInfo->mLines.mSize, sizeof(DbgLineData), CompareLineData);
  11640. // If we have multiple lines with the same line/column/context, merge them
  11641. if (!subProgram->mLineInfo->mLines.IsEmpty())
  11642. {
  11643. auto prevLine = &subProgram->mLineInfo->mLines[0];
  11644. for (int i = 1; i < subProgram->mLineInfo->mLines.mSize; i++)
  11645. {
  11646. auto nextLine = &subProgram->mLineInfo->mLines[i];
  11647. if ((nextLine->mLine == prevLine->mLine) && (nextLine->mColumn == prevLine->mColumn) && (nextLine->mCtxIdx == prevLine->mCtxIdx) &&
  11648. (nextLine->mRelAddress == prevLine->mRelAddress + prevLine->mContribSize))
  11649. {
  11650. prevLine->mContribSize += nextLine->mContribSize;
  11651. // This messed up inline cases because mContribSize actually INCLUDES inlined lines so it caused the address to skip too far
  11652. //nextLine->mRelAddress += nextLine->mContribSize;
  11653. //nextLine->mContribSize = 0;
  11654. }
  11655. else
  11656. {
  11657. prevLine = nextLine;
  11658. }
  11659. }
  11660. }
  11661. }
  11662. void WinDebugger::ReserveHotTargetMemory(int size)
  11663. {
  11664. HotTargetMemory hotTargetMemory;
  11665. hotTargetMemory.mOffset = 0;
  11666. hotTargetMemory.mSize = 0;
  11667. hotTargetMemory.mPtr = NULL;
  11668. if (size > 0)
  11669. {
  11670. // In 64-bit mode we have a reserved region on program load that we commit here because the offsets
  11671. // must be within 32-bits of the original EXE image, but in 32-bit mode we don't reserve anything
  11672. // until here
  11673. #ifdef BF_DBG_32
  11674. //hotTargetMemory.mSize = std::max(1024 * 1024, size);
  11675. BF_ASSERT((size & (mPageSize - 1)) == 0);
  11676. hotTargetMemory.mSize = size;
  11677. hotTargetMemory.mPtr = (addr_target)(intptr)VirtualAllocEx(mProcessInfo.hProcess, NULL, hotTargetMemory.mSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
  11678. mDebugTarget->mHotHeap->AddTrackedRegion(hotTargetMemory.mPtr, hotTargetMemory.mSize);
  11679. #else
  11680. hotTargetMemory.mSize = size;
  11681. hotTargetMemory.mPtr = mDebugTarget->mHotHeap->Alloc(size);
  11682. BF_ASSERT(hotTargetMemory.mPtr != 0);
  11683. auto ptr = ::VirtualAllocEx(mProcessInfo.hProcess, (void*)(intptr)hotTargetMemory.mPtr, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  11684. BF_ASSERT(ptr == (void*)(intptr)hotTargetMemory.mPtr);
  11685. #endif
  11686. }
  11687. BfLogDbg("ReserveHotTargetMemory %p %d\n", hotTargetMemory.mPtr, hotTargetMemory.mSize);
  11688. int err = GetLastError();
  11689. mHotTargetMemory.push_back(hotTargetMemory);
  11690. }
  11691. addr_target WinDebugger::AllocHotTargetMemory(int size, bool canExecute, bool canWrite, int* outAllocSize)
  11692. {
  11693. int prot = PAGE_READWRITE;
  11694. if (canExecute && canWrite)
  11695. prot = PAGE_EXECUTE_READWRITE;
  11696. else if (canExecute)
  11697. prot = PAGE_EXECUTE_READ;
  11698. size = (size + (mPageSize - 1)) & ~(mPageSize - 1);
  11699. *outAllocSize = size;
  11700. HotTargetMemory* hotTargetMemory = NULL;
  11701. bool foundHotTargetMemory = false;
  11702. for (int i = mHotTargetMemory.mSize - 1; i >= BF_MAX(mHotTargetMemory.mSize - 32, 0); i--)
  11703. {
  11704. hotTargetMemory = &mHotTargetMemory[i];
  11705. if (hotTargetMemory->mPtr == 0)
  11706. {
  11707. Fail("Failed to allocate memory for hot loading");
  11708. return 0;
  11709. }
  11710. if (hotTargetMemory->GetSizeLeft() >= size)
  11711. {
  11712. foundHotTargetMemory = true;
  11713. break;
  11714. }
  11715. }
  11716. if (!foundHotTargetMemory)
  11717. {
  11718. ReserveHotTargetMemory(size);
  11719. foundHotTargetMemory = true;
  11720. hotTargetMemory = &mHotTargetMemory.back();
  11721. }
  11722. BF_ASSERT(hotTargetMemory->mOffset + size <= hotTargetMemory->mSize);
  11723. addr_target result = hotTargetMemory->mPtr + hotTargetMemory->mOffset;
  11724. ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)result, size, prot, NULL);
  11725. BfLogDbg("AllocHotTargetMemory: %p %d %d %d\n", result, size, canExecute, canWrite);
  11726. hotTargetMemory->mOffset += size;
  11727. return result;
  11728. }
  11729. void WinDebugger::ReleaseHotTargetMemory(addr_target addr, int size)
  11730. {
  11731. #ifdef BF_DBG_32
  11732. ::VirtualFreeEx(mProcessInfo.hProcess, (void*)(intptr)addr, 0, MEM_RELEASE);
  11733. #else
  11734. mDebugTarget->mHotHeap->Release(addr, size);
  11735. ::VirtualFreeEx(mProcessInfo.hProcess, (void*)(intptr)addr, size, MEM_DECOMMIT);
  11736. #endif
  11737. }
  11738. void WinDebugger::CleanupHotHeap()
  11739. {
  11740. mDebugTarget->mLastHotHeapCleanIdx = mDebugTarget->mHotHeap->mBlockAllocIdx;
  11741. // Our criteria for determining whether a hot loaded file is still being used:
  11742. // 1) If we are currently executing a method from that object file.
  11743. // 2) If the symbol map has a symbol with that address.
  11744. // 3) If the static variable map contains a reference - including a conservative scan of the data
  11745. // This handles vdata references
  11746. // This is a conservative check which won't purge hot reloads that contain deleted
  11747. // methods (for example), but it will purge hot reloads where all the changed
  11748. // data has been overwritten.
  11749. // For delegate bindings, the original module declaring the bind creates a "preserve"
  11750. // global such as "bf_hs_preserve@_ZN5TestO4TestEv", whose preserved symbol ensures it
  11751. // doesn't get unloaded. The current version of that method resides in "_ZN5TestO4TestEv",
  11752. // ensuring that the method pointed to by the global variable is valid
  11753. mDebugTarget->mHotHeap->ClearReferencedFlags();
  11754. addr_target lowAddr = mDebugTarget->mHotHeap->mHotAreaStart;
  11755. addr_target highAddr = lowAddr + mDebugTarget->mHotHeap->mHotAreaSize;
  11756. // Do conservative scan through all thread stacks. Stack traces aren't 100% reliable, so we
  11757. // need to do a full conservative scan of any addresses stored in the stack
  11758. // to ensure we don't miss any return addresses
  11759. for (int threadIdx = 0; threadIdx < (int)mThreadList.size(); threadIdx++)
  11760. {
  11761. WdThreadInfo* threadInfo = mThreadList[threadIdx];
  11762. BF_CONTEXT lcContext;
  11763. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  11764. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  11765. addr_target checkStackAddr = BF_CONTEXT_SP(lcContext);
  11766. checkStackAddr &= ~(sizeof(addr_target) - 1);
  11767. // Conservative check on registers
  11768. for (int regNum = 0; regNum < sizeof(BF_CONTEXT)/sizeof(addr_target); regNum++)
  11769. {
  11770. addr_target checkAddr = ((addr_target*)&lcContext)[regNum];
  11771. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  11772. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  11773. }
  11774. // Conservative check on all stack data
  11775. while (checkStackAddr < threadInfo->mStartSP)
  11776. {
  11777. addr_target checkAddrArr[1024];
  11778. int numAddrsChecking = BF_MIN(1024, (int)((threadInfo->mStartSP - checkStackAddr) / sizeof(addr_target)));
  11779. ReadMemory(checkStackAddr, numAddrsChecking * sizeof(addr_target), checkAddrArr);
  11780. checkStackAddr += numAddrsChecking * sizeof(addr_target);
  11781. for (int addrIdx = 0; addrIdx < numAddrsChecking; addrIdx++)
  11782. {
  11783. addr_target checkAddr = checkAddrArr[addrIdx];
  11784. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  11785. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  11786. }
  11787. }
  11788. }
  11789. auto mainModule = mDebugTarget->mTargetBinary;
  11790. for (auto entry : mainModule->mSymbolNameMap)
  11791. {
  11792. auto dwSymbol = entry->mValue;
  11793. addr_target checkAddr = dwSymbol->mAddress;
  11794. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  11795. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  11796. }
  11797. mDebugTarget->CleanupHotHeap();
  11798. BfLogDbg("Hot load memory used: %dk\n", (int)mDebugTarget->mHotHeap->GetUsedSize() / 1024);
  11799. }
  11800. int WinDebugger::EnableWriting(intptr address, int size)
  11801. {
  11802. DWORD oldProt;
  11803. bool success = ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)address, size, PAGE_READWRITE, &oldProt);
  11804. if (!success)
  11805. {
  11806. int err = GetLastError();
  11807. }
  11808. return (int)oldProt;
  11809. }
  11810. int WinDebugger::SetProtection(intptr address, int size, int prot)
  11811. {
  11812. DWORD oldProt;
  11813. ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)address, size, prot, &oldProt);
  11814. return (int)oldProt;
  11815. }
  11816. void WinDebugger::EnableMemCache()
  11817. {
  11818. mMemCacheAddr = 1;
  11819. }
  11820. void WinDebugger::DisableMemCache()
  11821. {
  11822. mMemCacheAddr = 0;
  11823. }
  11824. bool WinDebugger::ReadMemory(intptr address, uint64 length, void* dest, bool local)
  11825. {
  11826. if (local)
  11827. {
  11828. __try
  11829. {
  11830. memcpy(dest, (void*)address, length);
  11831. return true;
  11832. }
  11833. __except(EXCEPTION_EXECUTE_HANDLER)
  11834. {
  11835. return false;
  11836. }
  11837. }
  11838. if (mMemCacheAddr != 0)
  11839. {
  11840. addr_target targetAddr = (addr_target)address;
  11841. if ((targetAddr >= mMemCacheAddr) && (targetAddr + length <= mMemCacheAddr + WD_MEMCACHE_SIZE) && (mMemCacheAddr > 1))
  11842. {
  11843. memcpy(dest, mMemCacheData + (targetAddr - mMemCacheAddr), length);
  11844. return true;
  11845. }
  11846. // We need a new block
  11847. SIZE_T dwReadBytes;
  11848. if (::ReadProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, mMemCacheData, (SIZE_T)WD_MEMCACHE_SIZE, &dwReadBytes) != 0)
  11849. {
  11850. mMemCacheAddr = targetAddr;
  11851. memcpy(dest, mMemCacheData, length);
  11852. return true;
  11853. }
  11854. // Failed, turn off caching
  11855. mMemCacheAddr = 0;
  11856. }
  11857. SIZE_T dwReadBytes;
  11858. if (::ReadProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, dest, (SIZE_T)length, &dwReadBytes) != 0)
  11859. return true;
  11860. int lastErr = ::GetLastError();
  11861. memset(dest, 0, length);
  11862. return false;
  11863. }
  11864. bool WinDebugger::WriteMemory(intptr address, void* src, uint64 length)
  11865. {
  11866. SIZE_T dwBytesWritten = 0;
  11867. int result = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, src, (SIZE_T)length, &dwBytesWritten);
  11868. return result != 0;
  11869. }
  11870. addr_target WinDebugger::GetTLSOffset(int tlsIndex)
  11871. {
  11872. typedef LONG NTSTATUS;
  11873. typedef DWORD KPRIORITY;
  11874. typedef WORD UWORD;
  11875. enum THREADINFOCLASS
  11876. {
  11877. ThreadBasicInformation,
  11878. };
  11879. struct CLIENT_ID
  11880. {
  11881. HANDLE UniqueProcess;
  11882. HANDLE UniqueThread;
  11883. };
  11884. struct
  11885. {
  11886. NTSTATUS mExitStatus;
  11887. void* mTebBaseAddress;
  11888. CLIENT_ID mClientId;
  11889. KAFFINITY mAffinityMask;
  11890. KPRIORITY mPriority;
  11891. KPRIORITY mBasePriority;
  11892. } threadInfo = { 0 };
  11893. ULONG len = 0;
  11894. bool loadedManually = false;
  11895. static HMODULE module = NULL;
  11896. static NTSTATUS(__stdcall *NtQueryInformationThread)(HANDLE ThreadHandle, THREADINFOCLASS ThreadInformationClass, PVOID ThreadInformation, ULONG ThreadInformationLength, PULONG ReturnLength);
  11897. if (module == NULL)
  11898. {
  11899. module = GetModuleHandleA("ntdll.dll");
  11900. NtQueryInformationThread = reinterpret_cast<decltype(NtQueryInformationThread)>(GetProcAddress(module, "NtQueryInformationThread"));
  11901. }
  11902. if (NtQueryInformationThread == NULL)
  11903. return 0;
  11904. NTSTATUS status = NtQueryInformationThread(mActiveThread->mHThread, (THREADINFOCLASS)0, &threadInfo, sizeof(threadInfo), nullptr);
  11905. if (status < 0)
  11906. return 0;
  11907. #ifdef BF_DBG_32
  11908. addr_target tibAddr = ReadMemory<addr_target>((intptr)threadInfo.mTebBaseAddress + 0x0);
  11909. addr_target tlsTable = ReadMemory<addr_target>((intptr)tibAddr + 0x2C);
  11910. #else
  11911. addr_target tlsTable = ReadMemory<addr_target>((intptr)threadInfo.mTebBaseAddress + 0x58);
  11912. #endif
  11913. return ReadMemory<addr_target>(tlsTable + tlsIndex * sizeof(addr_target));
  11914. }
  11915. bool WinDebugger::WriteInstructions(intptr address, void* src, uint64 length)
  11916. {
  11917. SIZE_T dwBytesWritten = 0;
  11918. bool result = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, src, (SIZE_T)length, &dwBytesWritten) != 0;
  11919. result |= ::FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, (SIZE_T)length) != 0;
  11920. BF_ASSERT(result);
  11921. BfLogDbg("WriteInstructions: %p %d\n", address, length);
  11922. return result;
  11923. }
  11924. DbgMemoryFlags WinDebugger::GetMemoryFlags(intptr address)
  11925. {
  11926. MEMORY_BASIC_INFORMATION memBasicInfo;
  11927. if (::VirtualQueryEx(mProcessInfo.hProcess, (void*)address, &memBasicInfo, sizeof(MEMORY_BASIC_INFORMATION)) == 0)
  11928. {
  11929. //BfLogDbg("VirtualQueryEx failed with %d\n", GetLastError());
  11930. return DbgMemoryFlags_None;
  11931. }
  11932. DbgMemoryFlags flags = DbgMemoryFlags_None;
  11933. if (memBasicInfo.AllocationProtect & PAGE_READWRITE)
  11934. {
  11935. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11936. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11937. }
  11938. if (memBasicInfo.AllocationProtect & PAGE_READONLY)
  11939. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11940. if (memBasicInfo.AllocationProtect & PAGE_WRITECOPY)
  11941. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11942. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE)
  11943. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11944. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_READ)
  11945. {
  11946. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11947. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11948. }
  11949. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_READWRITE)
  11950. {
  11951. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11952. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11953. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11954. }
  11955. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_WRITECOPY)
  11956. {
  11957. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11958. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11959. }
  11960. return flags;
  11961. }
  11962. #ifdef BF_DBG_32
  11963. Debugger* Beefy::CreateDebugger32(DebugManager* debugManager, DbgMiniDump* miniDump)
  11964. #else
  11965. Debugger* Beefy::CreateDebugger64(DebugManager* debugManager, DbgMiniDump* miniDump)
  11966. #endif
  11967. {
  11968. if (miniDump != NULL)
  11969. {
  11970. auto debugger = new MiniDumpDebugger(debugManager, miniDump);
  11971. return debugger;
  11972. }
  11973. return new WinDebugger(debugManager);
  11974. }
  11975. #ifdef BF_DBG_32
  11976. void WdAllocTest()
  11977. {
  11978. Array<BeefyDbg32::WdStackFrame*> stackFrameList;
  11979. for (int i = 0; true; i++)
  11980. {
  11981. WdStackFrame* stackFrame = new WdStackFrame();
  11982. stackFrameList.push_back(stackFrame);
  11983. }
  11984. }
  11985. #endif
  11986. #endif //!defined BF32 || !defined BF_DBG_64