WinDebugger.cpp 375 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874
  1. #pragma warning(disable:4996)
  2. // TODO: Remove for 64-bit
  3. #pragma warning(disable:4244)
  4. #pragma warning(disable:4267)
  5. #define NTDDI_VERSION 0x06020000
  6. #include "WinDebugger.h"
  7. #include "CPU.h"
  8. #include "DbgModule.h"
  9. #include "DebugVisualizers.h"
  10. #include "MiniDumpDebugger.h"
  11. #include "X86.h"
  12. #include "BeefySysLib/Common.h"
  13. #include "BeefySysLib/util/PerfTimer.h"
  14. #include "BeefySysLib/util/BeefPerf.h"
  15. #include "BeefySysLib/util/CritSect.h"
  16. #include "BeefySysLib/util/UTF8.h"
  17. #include "BeefySysLib/FileStream.h"
  18. #include "BeefySysLib/FileHandleStream.h"
  19. #include "BeefySysLib/util/FileEnumerator.h"
  20. #include <inttypes.h>
  21. #include <windows.h>
  22. #include "DbgExprEvaluator.h"
  23. #include "Compiler/BfSystem.h"
  24. #include "Compiler/BfParser.h"
  25. #include "Compiler/BfReducer.h"
  26. #include "Compiler/BfDemangler.h"
  27. #include "Compiler/BfPrinter.h"
  28. #include <Shlobj.h>
  29. #include "NetManager.h"
  30. #include "DebugManager.h"
  31. #include "X86Target.h"
  32. #include "HotHeap.h"
  33. #include "HotScanner.h"
  34. #include "Profiler.h"
  35. #include <float.h>
  36. #include <psapi.h>
  37. #if !defined BF32 || !defined BF_DBG_64
  38. #define STATUS_WX86_CONTINUE 0x4000001DL
  39. #define STATUS_WX86_SINGLE_STEP 0x4000001EL
  40. #define STATUS_WX86_BREAKPOINT 0x4000001FL
  41. #define STATUS_WX86_EXCEPTION_CONTINUE 0x40000020L
  42. #pragma pack(push, 1)
  43. struct HotJumpOp
  44. {
  45. uint8 mOpCode;
  46. int32 mRelTarget;
  47. };
  48. #pragma pack(pop)
  49. #include "BeefySysLib/util/AllocDebug.h"
  50. #include <limits>
  51. USING_NS_BF_DBG;
  52. static void FilterThreadName(String& name)
  53. {
  54. for (int i = 0; i < (int)name.length(); i++)
  55. {
  56. uint8 c = name[i];
  57. if (c == 0)
  58. {
  59. name.RemoveToEnd(i);
  60. return;
  61. }
  62. if (c < 32)
  63. {
  64. name.Remove(i);
  65. i--;
  66. continue;
  67. }
  68. }
  69. }
  70. //////////////////////////////////////////////////////////////////////////
  71. WdBreakpointCondition::~WdBreakpointCondition()
  72. {
  73. delete mDbgEvaluationContext;
  74. }
  75. //////////////////////////////////////////////////////////////////////////
  76. DbgEvaluationContext::DbgEvaluationContext(WinDebugger* winDebugger, DbgModule* dbgModule, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  77. {
  78. Init(winDebugger, dbgModule, expr, formatInfo, contextValue);
  79. }
  80. DbgEvaluationContext::DbgEvaluationContext(WinDebugger* winDebugger, DbgCompileUnit* dbgCompileUnit, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  81. {
  82. DbgModule* dbgModule = NULL;
  83. if (dbgCompileUnit != NULL)
  84. dbgModule = dbgCompileUnit->mDbgModule;
  85. Init(winDebugger, dbgModule, expr, formatInfo, contextValue);
  86. }
  87. void DbgEvaluationContext::Init(WinDebugger* winDebugger, DbgModule* dbgModule, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  88. {
  89. if (expr.empty())
  90. {
  91. mParser = NULL;
  92. mReducer = NULL;
  93. mPassInstance = NULL;
  94. mDbgExprEvaluator = NULL;
  95. mExprNode = NULL;
  96. return;
  97. }
  98. mParser = new BfParser(winDebugger->mBfSystem);
  99. mParser->mCompatMode = true;
  100. mPassInstance = new BfPassInstance(winDebugger->mBfSystem);
  101. auto terminatedExpr = expr + ";";
  102. mParser->SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  103. mParser->Parse(mPassInstance);
  104. mReducer = new BfReducer();
  105. mReducer->mAlloc = mParser->mAlloc;
  106. mReducer->mSystem = winDebugger->mBfSystem;
  107. mReducer->mPassInstance = mPassInstance;
  108. mReducer->mVisitorPos = BfReducer::BfVisitorPos(mParser->mRootNode);
  109. mReducer->mVisitorPos.MoveNext();
  110. mReducer->mCompatMode = mParser->mCompatMode;
  111. mReducer->mSource = mParser;
  112. mExprNode = mReducer->CreateExpression(mParser->mRootNode->GetFirst());
  113. mParser->Close();
  114. mDbgExprEvaluator = new DbgExprEvaluator(winDebugger, dbgModule, mPassInstance, -1, -1);
  115. if ((formatInfo != NULL) && (mExprNode != NULL) && (mExprNode->GetSrcEnd() < (int) expr.length()))
  116. {
  117. String formatFlags = expr.Substring(mExprNode->GetSrcEnd());
  118. String errorString = "Invalid expression";
  119. if (!winDebugger->ParseFormatInfo(dbgModule, formatFlags, formatInfo, mPassInstance, NULL, NULL, &errorString, contextValue))
  120. {
  121. mPassInstance->FailAt(errorString, mParser->mSourceData, mExprNode->GetSrcEnd(), (int)expr.length() - mExprNode->GetSrcEnd());
  122. formatFlags = "";
  123. }
  124. }
  125. if (formatInfo != NULL)
  126. {
  127. mDbgExprEvaluator->mExplicitThis = formatInfo->mExplicitThis;
  128. mDbgExprEvaluator->mCallStackIdx = formatInfo->mCallStackIdx;
  129. mDbgExprEvaluator->mLanguage = formatInfo->mLanguage;
  130. }
  131. }
  132. bool DbgEvaluationContext::HasExpression()
  133. {
  134. return mExprNode != NULL;
  135. }
  136. DbgEvaluationContext::~DbgEvaluationContext()
  137. {
  138. delete mParser;
  139. delete mReducer;
  140. delete mDbgExprEvaluator;
  141. delete mPassInstance;
  142. }
  143. DbgTypedValue DbgEvaluationContext::EvaluateInContext(DbgTypedValue contextTypedValue)
  144. {
  145. if (mExprNode == NULL)
  146. return DbgTypedValue();
  147. mPassInstance->ClearErrors();
  148. if (contextTypedValue)
  149. {
  150. mDbgExprEvaluator->mExplicitThis = contextTypedValue;
  151. if ((mDbgExprEvaluator->mExplicitThis.mType->IsPointer()) && (mDbgExprEvaluator->mExplicitThis.mType->mTypeParam->WantsRefThis()))
  152. {
  153. mDbgExprEvaluator->mExplicitThis.mType = mDbgExprEvaluator->mExplicitThis.mType->mTypeParam;
  154. mDbgExprEvaluator->mExplicitThis.mSrcAddress = mDbgExprEvaluator->mExplicitThis.mPtr;
  155. mDbgExprEvaluator->mExplicitThis.mPtr = 0;
  156. }
  157. if ((mDbgExprEvaluator->mExplicitThis.mType->IsCompositeType()) && (!mDbgExprEvaluator->mExplicitThis.mType->WantsRefThis()))
  158. {
  159. if (mDbgExprEvaluator->mExplicitThis.mSrcAddress != 0)
  160. {
  161. mDbgExprEvaluator->mExplicitThis.mType = mDbgExprEvaluator->mDbgModule->GetPointerType(mDbgExprEvaluator->mExplicitThis.mType);
  162. mDbgExprEvaluator->mExplicitThis.mPtr = mDbgExprEvaluator->mExplicitThis.mSrcAddress;
  163. mDbgExprEvaluator->mExplicitThis.mSrcAddress = 0;
  164. }
  165. }
  166. }
  167. if (contextTypedValue.mType != NULL)
  168. mDbgExprEvaluator->mDbgCompileUnit = contextTypedValue.mType->mCompileUnit;
  169. DbgTypedValue exprResult;
  170. auto result = mDbgExprEvaluator->Resolve(mExprNode);
  171. return result;
  172. }
  173. bool DbgEvaluationContext::HadError()
  174. {
  175. return mPassInstance->mFailedIdx != 0;
  176. }
  177. String DbgEvaluationContext::GetErrorStr()
  178. {
  179. String errorStr = mPassInstance->mErrors[0]->mError;
  180. if (mExprNode != NULL)
  181. {
  182. errorStr += ": ";
  183. errorStr += mExprNode->ToString();
  184. }
  185. return errorStr;
  186. }
  187. //////////////////////////////////////////////////////////////////////////
  188. typedef HRESULT(WINAPI* SetThreadDescription_t)(HANDLE hThread, PCWSTR lpThreadDescription);
  189. typedef HRESULT(WINAPI* GetThreadDescription_t)(HANDLE hThread, PWSTR* lpThreadDescription);
  190. static SetThreadDescription_t gSetThreadDescription = NULL;
  191. static GetThreadDescription_t gGetThreadDescription = NULL;
  192. static HMODULE gKernelDll = NULL;
  193. static void ImportKernel()
  194. {
  195. if (gKernelDll != NULL)
  196. return;
  197. WCHAR path[MAX_PATH];
  198. GetSystemDirectory(path, MAX_PATH);
  199. wcscat(path, L"\\kernel32.dll");
  200. gKernelDll = GetModuleHandle(path);
  201. if (gKernelDll == NULL)
  202. {
  203. return;
  204. }
  205. gSetThreadDescription = (SetThreadDescription_t)GetProcAddress(gKernelDll, "SetThreadDescription");
  206. gGetThreadDescription = (GetThreadDescription_t)GetProcAddress(gKernelDll, "GetThreadDescription");
  207. }
  208. void WinDebugger::TryGetThreadName(WdThreadInfo* threadInfo)
  209. {
  210. if (threadInfo->mHThread == NULL)
  211. return;
  212. ImportKernel();
  213. PWSTR wStr = NULL;
  214. if (gGetThreadDescription != NULL)
  215. {
  216. gGetThreadDescription(threadInfo->mHThread, &wStr);
  217. if (wStr == NULL)
  218. return;
  219. threadInfo->mName = UTF8Encode(wStr);
  220. FilterThreadName(threadInfo->mName);
  221. LocalFree(wStr);
  222. }
  223. }
  224. static void CreateFilterName(String& name, DbgType* type)
  225. {
  226. CreateFilterName(name, type->mParent);
  227. switch (type->mTypeCode)
  228. {
  229. case DbgType_Namespace:
  230. case DbgType_Struct:
  231. case DbgType_Class:
  232. name += type->mName;
  233. break;
  234. }
  235. }
  236. static void CreateFilterName(String& name, const char* srcStr, DbgLanguage language)
  237. {
  238. int chevronDepth = 0;
  239. const char* cPtr = srcStr;
  240. for (; true; cPtr++)
  241. {
  242. char c = *cPtr;
  243. if (c == 0)
  244. break;
  245. if (c == '>')
  246. chevronDepth--;
  247. bool inGeneric = chevronDepth > 0;
  248. if (c == '<')
  249. chevronDepth++;
  250. if (inGeneric) // Bundle all generic instances together
  251. continue;
  252. if (c == '[') // Bundle all arrays together
  253. name.clear();
  254. if (c == '(')
  255. return; // Start of params
  256. if ((c == ':') && (cPtr[1] == ':') && (language == DbgLanguage_Beef))
  257. {
  258. name.Append('.');
  259. cPtr++;
  260. }
  261. else
  262. name.Append(c);
  263. }
  264. }
  265. static void CreateFilterName(String& name, DbgSubprogram* subprogram)
  266. {
  267. auto language = subprogram->GetLanguage();
  268. if (subprogram->mName == NULL)
  269. {
  270. if (subprogram->mLinkName[0] == '<')
  271. {
  272. name += subprogram->mLinkName;
  273. return;
  274. }
  275. name = BfDemangler::Demangle(subprogram->mLinkName, language);
  276. // Strip off the params since we need to generate those ourselves
  277. int parenPos = (int)name.IndexOf('(');
  278. if (parenPos != -1)
  279. name.RemoveToEnd(parenPos);
  280. return;
  281. }
  282. else if (subprogram->mHasQualifiedName)
  283. {
  284. const char* cPtr = subprogram->mName;
  285. if (strncmp(cPtr, "_bf::", 5) == 0)
  286. {
  287. CreateFilterName(name, cPtr + 5, DbgLanguage_Beef);
  288. name.Replace(".__BfStaticCtor", ".this$static");
  289. name.Replace(".__BfCtorClear", ".this$clear");
  290. name.Replace(".__BfCtor", ".this");
  291. }
  292. else
  293. CreateFilterName(name, subprogram->mName, language);
  294. return;
  295. }
  296. else
  297. {
  298. if (subprogram->mParentType != NULL)
  299. {
  300. String parentName = subprogram->mParentType->ToString();
  301. CreateFilterName(name, parentName.c_str(), language);
  302. if (!name.empty())
  303. {
  304. if (language == DbgLanguage_Beef)
  305. name += ".";
  306. else
  307. name += "::";
  308. }
  309. }
  310. if ((language == DbgLanguage_Beef) && (subprogram->mParentType != NULL) && (subprogram->mParentType->mTypeName != NULL) &&
  311. (strcmp(subprogram->mName, subprogram->mParentType->mTypeName) == 0))
  312. name += "this";
  313. else if ((language == DbgLanguage_Beef) && (subprogram->mName[0] == '~'))
  314. name += "~this";
  315. else if (strncmp(subprogram->mName, "_bf::", 5) == 0)
  316. {
  317. CreateFilterName(name, subprogram->mName + 5, DbgLanguage_Beef);
  318. }
  319. else
  320. {
  321. CreateFilterName(name, subprogram->mName, language);
  322. }
  323. }
  324. if (name.empty())
  325. name += "`anon";
  326. if ((name[name.length() - 1] == '!') || (name[0] == '<'))
  327. {
  328. if (language == DbgLanguage_Beef)
  329. {
  330. // It's a mixin - assert that there's no params
  331. //BF_ASSERT(subprogram->mParams.Size() == 0);
  332. }
  333. return;
  334. }
  335. }
  336. //////////////////////////////////////////////////////////////////////////
  337. DbgPendingExpr::DbgPendingExpr()
  338. {
  339. mThreadId = -1;
  340. mCallStackIdx = -1;
  341. mParser = NULL;
  342. mCursorPos = -1;
  343. mExprNode = NULL;
  344. mIdleTicks = 0;
  345. mExplitType = NULL;
  346. mExpressionFlags = DwEvalExpressionFlag_None;
  347. }
  348. DbgPendingExpr::~DbgPendingExpr()
  349. {
  350. delete mParser;
  351. }
  352. // conversion logic based on table at http://en.wikipedia.org/wiki/Extended_precision
  353. //CDH TODO put this somewhere more general
  354. static double ConvertFloat80ToDouble(const byte fp80[10])
  355. {
  356. uint16 e = *((uint16*)&fp80[8]);
  357. uint64 m = *((uint64*)&fp80[0]);
  358. uint64 bit63 = (uint64)1 << 63;
  359. uint64 bit62 = (uint64)1 << 62;
  360. bool isNegative = (e & 0x8000) != 0;
  361. double s = isNegative ? -1.0 : 1.0;
  362. e &= 0x7fff;
  363. if (!e)
  364. {
  365. // the high bit and mantissa content will determine whether it's an actual zero, or a denormal or
  366. // pseudo-denormal number with an effective exponent of -16382. But since that exponent is so far
  367. // below anything we can handle in double-precision (even accounting for denormal bit shifts), we're
  368. // effectively still dealing with zero.
  369. return s * 0.0;
  370. }
  371. else if (e == 0x7fff)
  372. {
  373. if (m & bit63)
  374. {
  375. if (m & bit62)
  376. {
  377. return std::numeric_limits<double>::quiet_NaN();
  378. }
  379. else
  380. {
  381. if (m == bit63)
  382. return s * std::numeric_limits<double>::infinity();
  383. else
  384. return std::numeric_limits<double>::signaling_NaN();
  385. }
  386. }
  387. else
  388. {
  389. return std::numeric_limits<double>::quiet_NaN();
  390. }
  391. }
  392. else
  393. {
  394. if (!(m & bit63))
  395. return std::numeric_limits<double>::quiet_NaN(); // unnormal (we don't handle these since 80387 and later treat them as invalid operands anyway)
  396. // else is a normalized value
  397. }
  398. int useExponent = (int)e - 16383;
  399. if (useExponent < -1022)
  400. return s * 0.0; // we could technically support e from -1023 to -1074 as denormals, but don't bother with that for now.
  401. else if (useExponent > 1023)
  402. return s * HUGE_VAL;
  403. useExponent += 1023;
  404. BF_ASSERT((useExponent > 0) && (useExponent < 0x7ff)); // assume we've filtered for valid exponent range
  405. BF_ASSERT(m & bit63); // assume we've filtered out values that aren't normalized by now
  406. uint64 result = 0;
  407. if (isNegative)
  408. result |= bit63;
  409. result |= (uint64)useExponent << 52;
  410. result |= (m & ~bit63) >> 11;
  411. return *reinterpret_cast<double*>(&result);
  412. }
  413. addr_target NS_BF_DBG::DecodeTargetDataPtr(const char*& strRef)
  414. {
  415. addr_target val = (addr_target)stouln(strRef, sizeof(intptr_target) * 2);
  416. strRef += sizeof(intptr_target) * 2;
  417. return val;
  418. }
  419. WinDebugger::WinDebugger(DebugManager* debugManager) : mDbgSymSrv(this)
  420. {
  421. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  422. mActiveHotIdx = -1;
  423. mGotStartupEvent = false;
  424. mIsContinuingFromException = false;
  425. mDestroying = false;
  426. mDebugManager = debugManager;
  427. mNeedsRehupBreakpoints = false;
  428. mStepInAssembly = false;
  429. mStepSP = 0;
  430. mStepIsRecursing = false;
  431. mStepStopOnNextInstruction = false;
  432. mDebugTarget = NULL;
  433. mShuttingDown = false;
  434. mBfSystem = new BfSystem();
  435. mAtBreakThread = NULL;
  436. mActiveThread = NULL;
  437. mActiveBreakpoint = NULL;
  438. mSteppingThread = NULL;
  439. mExplicitStopThread = NULL;
  440. mStepSwitchedThreads = false;
  441. mIsDebuggerWaiting = false;
  442. mWantsDebugContinue = false;
  443. mContinueFromBreakpointFailed = false;
  444. mIsStepIntoSpecific = false;
  445. mDbgBreak = false;
  446. mDebuggerWaitingThread = NULL;
  447. mStepType = StepType_None;
  448. mOrigStepType = StepType_None;
  449. mLastValidStepIntoPC = 0;
  450. mActiveSymSrvRequest = NULL;
  451. mStoredReturnValueAddr = 0;
  452. #ifdef BF_DBG_32
  453. mCPU = gX86Target->mX86CPU;
  454. #else
  455. mCPU = gX86Target->mX64CPU;
  456. #endif
  457. mRunState = RunState_NotStarted;
  458. mIsRunning = false;
  459. mSavedAtBreakpointAddress = 0;
  460. mSavedBreakpointAddressContinuing = 0;
  461. mRequestedStackFrameIdx = 0;
  462. mShowPCOverride = 0;
  463. mCurNoInfoStepTries = 0;
  464. mDbgAttachFlags = BfDbgAttachFlag_None;
  465. mDbgProcessHandle = 0;
  466. mDbgThreadHandle = 0;
  467. mDbgProcessId = 0;
  468. mDbgHeapData = NULL;
  469. mIsPartialCallStack = true;
  470. for (int i = 0; i < 4; i++)
  471. {
  472. mFreeMemoryBreakIndices.push_back(i);
  473. }
  474. SYSTEM_INFO systemInfo;
  475. GetSystemInfo(&systemInfo);
  476. mPageSize = systemInfo.dwPageSize;
  477. mEmptyDebugTarget = new DebugTarget(this);
  478. mEmptyDebugTarget->CreateEmptyTarget();
  479. mEmptyDebugTarget->mIsEmpty = true;
  480. mDebugTarget = mEmptyDebugTarget;
  481. mDebugPendingExpr = NULL;
  482. mDebugEvalThreadInfo = WdThreadInfo();
  483. mMemCacheAddr = 0;
  484. mDebuggerThreadId = 0;
  485. }
  486. WinDebugger::~WinDebugger()
  487. {
  488. mDestroying = true;
  489. delete gDbgPerfManager;
  490. gDbgPerfManager = NULL;
  491. if ((mDebugTarget != NULL) && (mDebugTarget != mEmptyDebugTarget))
  492. Detach();
  493. for (auto breakpoint : mBreakpoints)
  494. {
  495. auto checkBreakpoint = breakpoint->mLinkedSibling;
  496. while (checkBreakpoint != NULL)
  497. {
  498. auto nextBreakpoint = checkBreakpoint->mLinkedSibling;
  499. delete checkBreakpoint;
  500. checkBreakpoint = nextBreakpoint;
  501. }
  502. delete breakpoint;
  503. }
  504. delete mEmptyDebugTarget;
  505. delete mBfSystem;
  506. for (auto kv : mPendingProfilerMap)
  507. delete kv.mValue;
  508. for (auto profiler : mNewProfilerList)
  509. delete profiler;
  510. delete mDebugPendingExpr;
  511. }
  512. void WinDebugger::Fail(const StringImpl& error)
  513. {
  514. if (mIsRunning)
  515. mDebugManager->mOutMessages.push_back(StrFormat("error %s", error.c_str()));
  516. }
  517. // Leave active thread unpaused
  518. void WinDebugger::ThreadRestorePause(WdThreadInfo* onlyPauseThread, WdThreadInfo* dontPauseThread)
  519. {
  520. BfLogDbg("ThreadRestorePause %d %d\n", (onlyPauseThread != NULL) ? onlyPauseThread->mThreadId : 0, (dontPauseThread != NULL) ? dontPauseThread->mThreadId : 0);
  521. for (auto threadInfo : mThreadList)
  522. {
  523. if (((threadInfo != dontPauseThread) && (!threadInfo->mIsBreakRestorePaused)) &&
  524. ((onlyPauseThread == NULL) || (threadInfo == onlyPauseThread)))
  525. {
  526. BF_ASSERT(!threadInfo->mIsBreakRestorePaused);
  527. BfLogDbg("SuspendThread %d\n", threadInfo->mThreadId);
  528. ::SuspendThread(threadInfo->mHThread);
  529. threadInfo->mIsBreakRestorePaused = true;
  530. }
  531. }
  532. }
  533. void WinDebugger::ThreadRestoreUnpause()
  534. {
  535. BfLogDbg("ThreadRestoreUnpause\n");
  536. for (auto threadInfo : mThreadList)
  537. {
  538. if (threadInfo->mIsBreakRestorePaused)
  539. {
  540. BfLogDbg("ResumeThread %d\n", threadInfo->mThreadId);
  541. ::ResumeThread(threadInfo->mHThread);
  542. threadInfo->mIsBreakRestorePaused = false;
  543. }
  544. }
  545. }
  546. void WinDebugger::UpdateThreadDebugRegisters(WdThreadInfo* threadInfo)
  547. {
  548. auto threadId = threadInfo->mHThread;
  549. BF_CONTEXT lcContext;
  550. lcContext.ContextFlags = BF_CONTEXT_DEBUG_REGISTERS;
  551. BF_GetThreadContext(threadId, &lcContext);
  552. for (int memoryBreakIdx = 0; memoryBreakIdx < 4; memoryBreakIdx++)
  553. {
  554. WdMemoryBreakpointBind memoryBreakpointBind = mMemoryBreakpoints[memoryBreakIdx];
  555. WdBreakpoint* wdBreakpoint = memoryBreakpointBind.mBreakpoint;
  556. if (wdBreakpoint == NULL)
  557. {
  558. *(&lcContext.Dr0 + memoryBreakIdx) = 0;
  559. lcContext.Dr7 &= ~((1 << (memoryBreakIdx * 2)) | (1 << (16 + memoryBreakIdx * 4)) | (3 << (18 + memoryBreakIdx * 4)));
  560. }
  561. else
  562. {
  563. int sizeCode = 0;
  564. if (memoryBreakpointBind.mByteCount == 2)
  565. sizeCode = 1;
  566. else if (memoryBreakpointBind.mByteCount == 4)
  567. sizeCode = 3;
  568. else if (memoryBreakpointBind.mByteCount == 8)
  569. sizeCode = 2;
  570. addr_target calcAddr = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress + memoryBreakpointBind.mOfs;
  571. BF_ASSERT(calcAddr == memoryBreakpointBind.mAddress);
  572. *(&lcContext.Dr0 + memoryBreakIdx) = calcAddr;
  573. lcContext.Dr7 |= (1 << (memoryBreakIdx * 2)) | (1 << (16 + memoryBreakIdx * 4)) | (sizeCode << (18 + memoryBreakIdx * 4));
  574. }
  575. }
  576. bool worked = BF_SetThreadContext(threadId, &lcContext) != 0;
  577. BF_ASSERT(worked || (mRunState == RunState_Terminating) || (mRunState == RunState_Terminated));
  578. }
  579. void WinDebugger::UpdateThreadDebugRegisters()
  580. {
  581. for (auto threadInfo : mThreadList)
  582. {
  583. ::SuspendThread(threadInfo->mHThread);
  584. UpdateThreadDebugRegisters(threadInfo);
  585. ::ResumeThread(threadInfo->mHThread);
  586. }
  587. }
  588. void WinDebugger::PhysSetBreakpoint(addr_target address)
  589. {
  590. BfLogDbg("PhysSetBreakpoint %p\n", address);
  591. uint8 newData = 0xCC;
  592. // This ensure that we have the orig image data cached
  593. DbgMemoryFlags flags = mDebugTarget->ReadOrigImageData(address, NULL, 1);
  594. if ((flags & DbgMemoryFlags_Execute) == 0)
  595. {
  596. BfLogDbg("Breakpoint ignored - execute flag NOT set in breakpoint address\n", address);
  597. BfLogDbg("Memory Flags = %d\n", gDebugger->GetMemoryFlags(address));
  598. return;
  599. }
  600. // Replace it with Breakpoint
  601. SIZE_T dwReadBytes;
  602. BOOL worked = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, &newData, 1, &dwReadBytes);
  603. if (!worked)
  604. {
  605. int err = GetLastError();
  606. BfLogDbg("SetBreakpoint FAILED %p\n", address);
  607. }
  608. FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, 1);
  609. {
  610. uint8 mem = ReadMemory<uint8>(address);
  611. BfLogDbg("Breakpoint byte %X\n", mem);
  612. }
  613. }
  614. void WinDebugger::SetBreakpoint(addr_target address, bool fromRehup)
  615. {
  616. int* countPtr = NULL;
  617. if (mPhysBreakpointAddrMap.TryAdd(address, NULL, &countPtr))
  618. {
  619. BfLogDbg("SetBreakpoint %p\n", address);
  620. *countPtr = 1;
  621. }
  622. else
  623. {
  624. if (fromRehup)
  625. {
  626. BfLogDbg("SetBreakpoint %p Count: %d. Rehup (ignored).\n", address, *countPtr);
  627. return;
  628. }
  629. (*countPtr)++;
  630. BfLogDbg("SetBreakpoint %p Count: %d\n", address, *countPtr);
  631. return;
  632. }
  633. PhysSetBreakpoint(address);
  634. }
  635. void WinDebugger::SetTempBreakpoint(addr_target address)
  636. {
  637. BfLogDbg("SetTempBreakpoint %p\n", address);
  638. mTempBreakpoint.push_back(address);
  639. SetBreakpoint(address);
  640. }
  641. void WinDebugger::PhysRemoveBreakpoint(addr_target address)
  642. {
  643. BfLogDbg("PhysRemoveBreakpoint %p\n", address);
  644. uint8 origData;
  645. DbgMemoryFlags flags = mDebugTarget->ReadOrigImageData(address, &origData, 1);
  646. if ((flags & DbgMemoryFlags_Execute) == 0)
  647. {
  648. //BF_ASSERT("Failed" == 0);
  649. return;
  650. }
  651. SIZE_T dwReadBytes;
  652. if (!WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, &origData, 1, &dwReadBytes))
  653. {
  654. int err = GetLastError();
  655. BfLogDbg("RemoveBreakpoint FAILED %p\n", address);
  656. }
  657. FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, 1);
  658. }
  659. void WinDebugger::RemoveBreakpoint(addr_target address)
  660. {
  661. int* countPtr = NULL;
  662. mPhysBreakpointAddrMap.TryGetValue(address, &countPtr);
  663. // This can happen when we shutdown and we're continuing from a breakpoint
  664. //BF_ASSERT(*countPtr != NULL);
  665. if (countPtr == NULL)
  666. {
  667. BfLogDbg("RemoveBreakpoint %p FAILED\n", address);
  668. return;
  669. }
  670. BfLogDbg("RemoveBreakpoint %p count: %d\n", address, *countPtr);
  671. if (*countPtr > 1)
  672. {
  673. (*countPtr)--;
  674. return;
  675. }
  676. mPhysBreakpointAddrMap.Remove(address);
  677. PhysRemoveBreakpoint(address);
  678. }
  679. void WinDebugger::SingleStepX86()
  680. {
  681. // In what cases did this catch bugs?
  682. // This caused other failures (caught in tests)
  683. // if (mActiveThread->mIsAtBreakpointAddress != 0)
  684. // {
  685. // ContinueFromBreakpoint();
  686. // return;
  687. // }
  688. BfLogDbg("Setup SingleStepX86 ActiveThread: %d\n", (mActiveThread != NULL) ? mActiveThread->mThreadId : -1);
  689. BF_CONTEXT lcContext;
  690. lcContext.ContextFlags = BF_CONTEXT_ALL;
  691. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  692. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  693. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  694. }
  695. bool WinDebugger::IsInRunState()
  696. {
  697. return (mRunState == RunState_Running) || (mRunState == RunState_Running_ToTempBreakpoint);
  698. }
  699. bool WinDebugger::ContinueFromBreakpoint()
  700. {
  701. if (mDebuggerWaitingThread->mFrozen)
  702. {
  703. BfLogDbg("ContinueFromBreakpoint bailout on frozen thread\n");
  704. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  705. mDebuggerWaitingThread->mIsAtBreakpointAddress = 0;
  706. return true;
  707. }
  708. mActiveThread = mDebuggerWaitingThread;
  709. mActiveBreakpoint = NULL;
  710. BfLogDbg("ContinueFromBreakpoint. ActiveThread: %d\n", (mActiveThread != NULL) ? mActiveThread->mThreadId : -1);
  711. BfLogDbg("ResumeThread %d\n", mActiveThread->mThreadId);
  712. BOOL success = ::ResumeThread(mActiveThread->mHThread);
  713. if (success)
  714. {
  715. // It's possible the active thread is suspended - possibly by the GC, so we would deadlock if we
  716. // attempted to pause the other threads
  717. BfLogDbg("SuspendThread %d\n", mActiveThread->mThreadId);
  718. BfLogDbg("Thread already paused!\n");
  719. ::SuspendThread(mActiveThread->mHThread);
  720. return false;
  721. }
  722. ThreadRestorePause(NULL, mActiveThread);
  723. PhysRemoveBreakpoint(mActiveThread->mIsAtBreakpointAddress);
  724. BF_CONTEXT lcContext;
  725. lcContext.ContextFlags = BF_CONTEXT_ALL;
  726. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  727. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  728. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  729. mActiveThread->mStoppedAtAddress = 0;
  730. mActiveThread->mBreakpointAddressContinuing = mActiveThread->mIsAtBreakpointAddress;
  731. mActiveThread->mIsAtBreakpointAddress = 0;
  732. BfLogDbg("ContinueFromBreakpoint set mIsAtBreakpointAddress = 0\n");
  733. return true;
  734. }
  735. void WinDebugger::ValidateBreakpoints()
  736. {
  737. HashSet<addr_target> usedBreakpoints;
  738. std::function<void(WdBreakpoint*)> _AddBreakpoint = [&](WdBreakpoint* breakpoint)
  739. {
  740. if (breakpoint->mAddr != 0)
  741. {
  742. usedBreakpoints.Add(breakpoint->mAddr);
  743. WdBreakpoint* foundBreakpoint = NULL;
  744. auto itr = mBreakpointAddrMap.Find(breakpoint->mAddr);
  745. bool found = false;
  746. while (itr != mBreakpointAddrMap.end())
  747. {
  748. WdBreakpoint* foundBreakpoint = itr->mValue;
  749. found |= foundBreakpoint == breakpoint;
  750. itr.NextWithSameKey(breakpoint->mAddr);
  751. }
  752. BF_ASSERT(found);
  753. }
  754. auto checkSibling = (WdBreakpoint*)breakpoint->mLinkedSibling;
  755. while (checkSibling != NULL)
  756. {
  757. _AddBreakpoint(checkSibling);
  758. checkSibling = (WdBreakpoint*)checkSibling->mLinkedSibling;
  759. }
  760. };
  761. for (auto breakpoint : mBreakpoints)
  762. _AddBreakpoint(breakpoint);
  763. for (auto& entry : mBreakpointAddrMap)
  764. {
  765. BF_ASSERT(usedBreakpoints.Contains(entry.mKey));
  766. }
  767. }
  768. Breakpoint* WinDebugger::FindBreakpointAt(intptr address)
  769. {
  770. #ifdef _DEBUG
  771. //ValidateBreakpoints();
  772. #endif
  773. WdBreakpoint* breakpoint = NULL;
  774. mBreakpointAddrMap.TryGetValue(address, &breakpoint);
  775. return breakpoint;
  776. }
  777. Breakpoint* WinDebugger::GetActiveBreakpoint()
  778. {
  779. if ((mActiveBreakpoint != NULL) && (mActiveBreakpoint->mHead != NULL))
  780. return mActiveBreakpoint->mHead;
  781. return mActiveBreakpoint;
  782. }
  783. void WinDebugger::DebugThreadProc()
  784. {
  785. BpSetThreadName("DebugThread");
  786. BfpThread_SetName(NULL, "DebugThread", NULL);
  787. mDebuggerThreadId = GetCurrentThreadId();
  788. if (!IsMiniDumpDebugger())
  789. {
  790. if (!DoOpenFile(mLaunchPath, mArgs, mWorkingDir, mEnvBlock))
  791. {
  792. if (mDbgProcessId != 0)
  793. OutputRawMessage("error Unable to attach to process");
  794. else
  795. OutputRawMessage(StrFormat("error Failed to launch: %s", mLaunchPath.c_str()));
  796. mShuttingDown = true;
  797. mRunState = RunState_Terminated;
  798. }
  799. }
  800. while (!mShuttingDown)
  801. {
  802. DoUpdate();
  803. }
  804. mIsRunning = false;
  805. for (int i = 0; i < (int) mBreakpoints.size(); i++)
  806. {
  807. WdBreakpoint* wdBreakpoint = mBreakpoints[i];
  808. if (wdBreakpoint->mAddr != 0)
  809. mBreakpointAddrMap.Remove(wdBreakpoint->mAddr, wdBreakpoint);
  810. wdBreakpoint->mAddr = 0;
  811. wdBreakpoint->mLineData = DbgLineDataEx();
  812. wdBreakpoint->mSrcFile = NULL;
  813. if (wdBreakpoint->mLinkedSibling != NULL)
  814. {
  815. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  816. wdBreakpoint->mLinkedSibling = NULL;
  817. }
  818. }
  819. if (!IsMiniDumpDebugger())
  820. {
  821. while (true)
  822. {
  823. if (!mIsDebuggerWaiting)
  824. {
  825. if (!WaitForDebugEvent(&mDebugEvent, 0))
  826. break;
  827. }
  828. if (mDebuggerWaitingThread != NULL)
  829. {
  830. BF_ASSERT_REL((mDebuggerWaitingThread->mIsAtBreakpointAddress == 0) || (mShuttingDown));
  831. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_CONTINUE);
  832. BfLogDbg("::ContinueDebugEvent startup ThreadId:%d\n", mDebuggerWaitingThread->mThreadId);
  833. }
  834. mIsDebuggerWaiting = false;
  835. mDebuggerWaitingThread = NULL;
  836. }
  837. }
  838. mDebuggerThreadId = 0;
  839. }
  840. static void DebugThreadProcThunk(void* winDebugger)
  841. {
  842. ((WinDebugger*) winDebugger)->DebugThreadProc();
  843. }
  844. int WinDebugger::GetAddrSize()
  845. {
  846. return sizeof(addr_target);
  847. }
  848. bool WinDebugger::CanOpen(const StringImpl& fileName, DebuggerResult* outResult)
  849. {
  850. FILE* fp = fopen(fileName.c_str(), "rb");
  851. if (fp == NULL)
  852. {
  853. *outResult = DebuggerResult_CannotOpen;
  854. return false;
  855. }
  856. FileStream fs;
  857. fs.mFP = fp;
  858. *outResult = DebuggerResult_Ok;
  859. bool canRead = DbgModule::CanRead(&fs, outResult);
  860. fclose(fp);
  861. return canRead;
  862. }
  863. void WinDebugger::OpenFile(const StringImpl& launchPath, const StringImpl& targetPath, const StringImpl& args, const StringImpl& workingDir, const Array<uint8>& envBlock)
  864. {
  865. BF_ASSERT(!mIsRunning);
  866. mLaunchPath = launchPath;
  867. mTargetPath = targetPath;
  868. mArgs = args;
  869. mWorkingDir = workingDir;
  870. mEnvBlock = envBlock;
  871. mDebugTarget = new DebugTarget(this);
  872. }
  873. bool WinDebugger::Attach(int processId, BfDbgAttachFlags attachFlags)
  874. {
  875. BF_ASSERT(!mIsRunning);
  876. mDbgAttachFlags = attachFlags;
  877. mDbgProcessHandle = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)processId);
  878. if (mDbgProcessHandle == 0)
  879. return false;
  880. BOOL is32Bit = false;
  881. if (!IsWow64Process(mDbgProcessHandle, &is32Bit))
  882. {
  883. mDbgProcessHandle = 0;
  884. ::CloseHandle(mDbgProcessHandle);
  885. return false;
  886. }
  887. bool want32Bit = sizeof(intptr_target) == 4;
  888. if (want32Bit != (is32Bit != 0))
  889. {
  890. mDbgProcessHandle = 0;
  891. ::CloseHandle(mDbgProcessHandle);
  892. return false;
  893. }
  894. HMODULE mainModule = 0;
  895. DWORD memNeeded = 0;
  896. ::EnumProcessModules(mDbgProcessHandle, &mainModule, sizeof(HMODULE), &memNeeded);
  897. WCHAR fileName[MAX_PATH] = {0};
  898. GetModuleFileNameExW(mDbgProcessHandle, mainModule, fileName, MAX_PATH);
  899. mLaunchPath = UTF8Encode(fileName);
  900. mTargetPath = mLaunchPath;
  901. mDbgProcessId = processId;
  902. mDbgProcessHandle = 0;
  903. ::CloseHandle(mDbgProcessHandle);
  904. mDebugTarget = new DebugTarget(this);
  905. return true;
  906. }
  907. void WinDebugger::Run()
  908. {
  909. mIsRunning = true;
  910. DWORD localThreadId;
  911. HANDLE hThread = ::CreateThread(NULL, 64 * 1024, (LPTHREAD_START_ROUTINE) &DebugThreadProcThunk, (void*)this, 0, &localThreadId);
  912. CloseHandle(hThread);
  913. }
  914. void WinDebugger::HotLoad(const Array<String>& objectFiles, int hotIdx)
  915. {
  916. AutoCrit autoCrit(mDebugManager->mCritSect);
  917. if (mDebugTarget->mTargetBinary == NULL)
  918. {
  919. Fail("Hot swapping failed because the hot target binary has not yet been loaded.");
  920. return;
  921. }
  922. if (mDebugTarget->mHotHeap == NULL)
  923. {
  924. Fail("There is no hot heap space available for hot swapping.");
  925. return;
  926. }
  927. BfLogDbg("WinDebugger::HotLoad Start %d\n", hotIdx);
  928. SetAndRestoreValue<int> prevHotIdx(mActiveHotIdx, hotIdx);
  929. BF_ASSERT(mHotThreadStates.empty());
  930. mHotThreadStates.Resize(mThreadList.size());
  931. for (int threadIdx = 0; threadIdx < (int)mThreadList.size(); threadIdx++)
  932. {
  933. WdThreadInfo* threadInfo = mThreadList[threadIdx];
  934. SetAndRestoreValue<WdThreadInfo*> prevActiveThread(mActiveThread, threadInfo);
  935. BfLogDbg("SuspendThread %d\n", threadInfo->mThreadId);
  936. ::SuspendThread(threadInfo->mHThread);
  937. mHotThreadStates[threadIdx].mThreadId = threadInfo->mThreadId;
  938. PopulateRegisters(&mHotThreadStates[threadIdx].mRegisters);
  939. }
  940. for (auto address : mTempBreakpoint)
  941. RemoveBreakpoint(address);
  942. mTempBreakpoint.Clear();
  943. mStepBreakpointAddrs.Clear();
  944. for (auto breakpoint : mBreakpoints)
  945. {
  946. DetachBreakpoint(breakpoint);
  947. }
  948. int startingModuleIdx = (int)mDebugTarget->mDbgModules.size();
  949. bool failed = false;
  950. for (auto fileName : objectFiles)
  951. {
  952. BfLogDbg("WinDebugger::HotLoad: %s\n", fileName.c_str());
  953. DbgModule* newBinary = mDebugTarget->HotLoad(fileName, hotIdx);
  954. if ((newBinary != NULL) && (newBinary->mFailed))
  955. failed = true;
  956. }
  957. for (int moduleIdx = startingModuleIdx; moduleIdx < (int)mDebugTarget->mDbgModules.size(); moduleIdx++)
  958. {
  959. auto dbgModule = mDebugTarget->mDbgModules[moduleIdx];
  960. BF_ASSERT(dbgModule->IsObjectFile());
  961. BF_ASSERT(dbgModule->mHotIdx == hotIdx);
  962. dbgModule->FinishHotSwap();
  963. }
  964. for (auto dwarf : mDebugTarget->mDbgModules)
  965. dwarf->RevertWritingEnable();
  966. int blockAllocSinceClean = mDebugTarget->mHotHeap->mBlockAllocIdx - mDebugTarget->mLastHotHeapCleanIdx;
  967. // Clean up the hot heap every 64MB
  968. int blocksBetweenCleans = (64 * 1024 * 1024) / HotHeap::BLOCK_SIZE;
  969. #ifdef _DEBUG
  970. //TODO: This is just for testing
  971. blocksBetweenCleans = 1;
  972. #endif
  973. //TODO: Put this back after we fix the cleanup
  974. if (blockAllocSinceClean >= blocksBetweenCleans)
  975. CleanupHotHeap();
  976. mDebugTarget->RehupSrcFiles();
  977. for (int breakIdx = 0; breakIdx < (int)mBreakpoints.size(); breakIdx++)
  978. {
  979. auto breakpoint = mBreakpoints[breakIdx];
  980. CheckBreakpoint(breakpoint);
  981. }
  982. for (int hotThreadIdx = 0; hotThreadIdx < (int)mHotThreadStates.size(); hotThreadIdx++)
  983. {
  984. auto& hotThreadState = mHotThreadStates[hotThreadIdx];
  985. WdThreadInfo* threadInfo = NULL;
  986. if (!mThreadMap.TryGetValue((uint32)hotThreadState.mThreadId, &threadInfo))
  987. continue;
  988. BfLogDbg("ResumeThread %d\n", threadInfo->mThreadId);
  989. ::ResumeThread(threadInfo->mHThread);
  990. }
  991. mHotThreadStates.Clear();
  992. if (IsPaused())
  993. {
  994. ClearCallStack();
  995. UpdateCallStack();
  996. }
  997. }
  998. void WinDebugger::InitiateHotResolve(DbgHotResolveFlags flags)
  999. {
  1000. AutoCrit autoCrit(mDebugManager->mCritSect);
  1001. delete mHotResolveData;
  1002. mHotResolveData = NULL;
  1003. mHotResolveData = new DbgHotResolveData();
  1004. DbgHotScanner* hotScanner = new DbgHotScanner(this);
  1005. hotScanner->Scan(flags);
  1006. delete hotScanner;
  1007. }
  1008. intptr WinDebugger::GetDbgAllocHeapSize()
  1009. {
  1010. if (mDbgHeapData == NULL)
  1011. {
  1012. Beefy::String memName = StrFormat("BFGC_stats_%d", mProcessInfo.dwProcessId);
  1013. mDbgHeapData = new WinDbgHeapData();
  1014. mDbgHeapData->mFileMapping = ::OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, memName.c_str());
  1015. if (mDbgHeapData->mFileMapping == 0)
  1016. {
  1017. delete mDbgHeapData;
  1018. mDbgHeapData = NULL;
  1019. return 0;
  1020. }
  1021. mDbgHeapData->mStats = (WinDbgHeapData::Stats*)MapViewOfFile(mDbgHeapData->mFileMapping, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(WinDbgHeapData::Stats));
  1022. }
  1023. if (mDbgHeapData->mStats == NULL)
  1024. return 0;
  1025. return mDbgHeapData->mStats->mHeapSize;
  1026. }
  1027. String WinDebugger::GetDbgAllocInfo()
  1028. {
  1029. AutoCrit autoCrit(mDebugManager->mCritSect);
  1030. for (auto threadInfo : mThreadList)
  1031. ::SuspendThread(threadInfo->mHThread);
  1032. delete mHotResolveData;
  1033. mHotResolveData = NULL;
  1034. mHotResolveData = new DbgHotResolveData();
  1035. DbgHotScanner* hotScanner = new DbgHotScanner(this);
  1036. hotScanner->Scan(DbgHotResolveFlag_Allocations);
  1037. delete hotScanner;
  1038. String result;
  1039. if (mHotResolveData != NULL)
  1040. {
  1041. DbgExprEvaluator exprEvaluator(this, NULL, NULL, -1, -1);
  1042. exprEvaluator.mDebugTarget = mDebugTarget;
  1043. String typeName;
  1044. result += ":types\n";
  1045. for (int typeId = 0; typeId < mHotResolveData->mTypeData.size(); typeId++)
  1046. {
  1047. auto& typeData = mHotResolveData->mTypeData[typeId];
  1048. if (typeData.mCount > 0)
  1049. {
  1050. auto type = exprEvaluator.GetBeefTypeById(typeId);
  1051. typeName.Clear();
  1052. exprEvaluator.BeefTypeToString(type, typeName);
  1053. if (typeName.IsEmpty())
  1054. typeName = StrFormat("Type #%d", typeId);
  1055. result += StrFormat("type\t%d\t%s\t%lld\t%lld\n", typeId, typeName.c_str(), typeData.mCount, typeData.mSize);
  1056. }
  1057. }
  1058. }
  1059. for (auto threadInfo : mThreadList)
  1060. ::ResumeThread(threadInfo->mHThread);
  1061. return result;
  1062. }
  1063. bool WinDebugger::DoOpenFile(const StringImpl& fileName, const StringImpl& args, const StringImpl& workingDir, const Array<uint8>& envBlock)
  1064. {
  1065. BP_ZONE("WinDebugger::DoOpenFile");
  1066. AutoCrit autoCrit(mDebugManager->mCritSect);
  1067. //gDbgPerfManager->StartRecording();
  1068. STARTUPINFOW si;
  1069. ZeroMemory(&si, sizeof(si));
  1070. si.cb = sizeof(si);
  1071. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  1072. if (mDbgProcessId != 0)
  1073. {
  1074. BOOL success = ::DebugActiveProcess(mDbgProcessId);
  1075. if (!success)
  1076. return false;
  1077. mProcessInfo.dwProcessId = mDbgProcessId;
  1078. }
  1079. else
  1080. {
  1081. BP_ZONE("DoOpenFile_CreateProcessW");
  1082. UTF16String envW;
  1083. DWORD flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS | CREATE_DEFAULT_ERROR_MODE;
  1084. void* envPtr = NULL;
  1085. if (!envBlock.IsEmpty())
  1086. {
  1087. //UTF16?
  1088. if (envBlock[1] == 0)
  1089. {
  1090. envPtr = (void*)&envBlock[0];
  1091. flags |= CREATE_UNICODE_ENVIRONMENT;
  1092. }
  1093. else
  1094. {
  1095. String str8((char*)&envBlock[0], (int)envBlock.size());
  1096. envW = UTF8Decode(str8);
  1097. envPtr = (void*)envW.c_str();
  1098. flags |= CREATE_UNICODE_ENVIRONMENT;
  1099. }
  1100. }
  1101. String cmdLine = "\"";
  1102. cmdLine += fileName;
  1103. cmdLine += "\"";
  1104. if (!args.IsEmpty())
  1105. {
  1106. cmdLine += " ";
  1107. cmdLine += args;
  1108. }
  1109. BOOL worked = CreateProcessW(NULL, (WCHAR*)UTF8Decode(cmdLine).c_str(), NULL, NULL, FALSE,
  1110. flags, envPtr, (WCHAR*)UTF8Decode(workingDir).c_str(), &si, &mProcessInfo);
  1111. if (!worked)
  1112. {
  1113. auto lastError = ::GetLastError();
  1114. if (lastError == ERROR_DIRECTORY)
  1115. {
  1116. mDebugManager->mOutMessages.push_back(StrFormat("error Unable to locate specified working directory '%s'", SlashString(workingDir, false, false).c_str()));
  1117. }
  1118. return false;
  1119. }
  1120. WdThreadInfo* threadInfo = new WdThreadInfo();
  1121. threadInfo->mProcessId = mProcessInfo.dwProcessId;
  1122. threadInfo->mThreadId = mProcessInfo.dwThreadId;
  1123. threadInfo->mHThread = mProcessInfo.hThread;
  1124. threadInfo->mThreadLocalBase = NULL;
  1125. threadInfo->mStartAddress = NULL;
  1126. mThreadMap[mProcessInfo.dwThreadId] = threadInfo;
  1127. mThreadList.push_back(threadInfo);
  1128. }
  1129. mRunState = RunState_Running;
  1130. while (true)
  1131. {
  1132. BP_ZONE("DoOpenFile_WaitForImageBase");
  1133. autoCrit.mCritSect->Unlock();
  1134. DoUpdate();
  1135. autoCrit.mCritSect->Lock();
  1136. ContinueDebugEvent();
  1137. if ((mDebugTarget->mLaunchBinary != NULL) && (mDebugTarget->mLaunchBinary->mOrigImageData != NULL))
  1138. break;
  1139. }
  1140. RehupBreakpoints(true);
  1141. //gDbgPerfManager->StopRecording();
  1142. //gDbgPerfManager->DbgPrint();
  1143. return true;
  1144. }
  1145. void WinDebugger::StopDebugging()
  1146. {
  1147. AutoCrit autoCrit(mDebugManager->mCritSect);
  1148. BfLogDbg("WinDebugger::Terminate\n");
  1149. if (mActiveSymSrvRequest != NULL)
  1150. mActiveSymSrvRequest->Cancel();
  1151. if ((mRunState == RunState_NotStarted) || (mRunState == RunState_Terminated) || (mRunState == RunState_Terminating))
  1152. return;
  1153. if ((mDbgProcessId != 0) && ((mDbgAttachFlags & BfDbgAttachFlag_ShutdownOnExit) == 0))
  1154. {
  1155. for (auto address : mTempBreakpoint)
  1156. RemoveBreakpoint(address);
  1157. for (auto breakpoint : mBreakpoints)
  1158. DetachBreakpoint(breakpoint);
  1159. BfLogDbg("StopDebugging\n");
  1160. ::DebugActiveProcessStop(mDbgProcessId);
  1161. mRunState = RunState_Terminated;
  1162. BfLogDbg("mRunState = RunState_Terminated\n");
  1163. }
  1164. else
  1165. {
  1166. TerminateProcess(mProcessInfo.hProcess, 0);
  1167. mRunState = RunState_Terminating;
  1168. BfLogDbg("mRunState = RunState_Terminating\n");
  1169. }
  1170. }
  1171. void WinDebugger::Terminate()
  1172. {
  1173. AutoCrit autoCrit(mDebugManager->mCritSect);
  1174. BfLogDbg("WinDebugger::Terminate\n");
  1175. if (mActiveSymSrvRequest != NULL)
  1176. mActiveSymSrvRequest->Cancel();
  1177. if ((mRunState == RunState_NotStarted) || (mRunState == RunState_Terminated) || (mRunState == RunState_Terminating))
  1178. return;
  1179. TerminateProcess(mProcessInfo.hProcess, 0);
  1180. mRunState = RunState_Terminating;
  1181. BfLogDbg("mRunState = RunState_Terminating\n");
  1182. }
  1183. static int gDebugUpdateCnt = 0;
  1184. void WinDebugger::Detach()
  1185. {
  1186. BfLogDbg("Debugger Detach\n");
  1187. mDebugManager->mNetManager->CancelAll();
  1188. while ((mIsRunning) || (mDebuggerThreadId != 0))
  1189. {
  1190. mShuttingDown = true;
  1191. Sleep(1);
  1192. }
  1193. for (auto profiler : mProfilerSet)
  1194. profiler->Stop();
  1195. BfLogDbg("Debugger Detach - thread finished\n");
  1196. mPendingProfilerMap.Clear();
  1197. for (auto profiler : mNewProfilerList)
  1198. delete profiler;
  1199. mNewProfilerList.Clear();
  1200. mPendingImageLoad.Clear();
  1201. mPendingDebugInfoLoad.Clear();
  1202. RemoveTempBreakpoints();
  1203. mContinueEvent.Reset();
  1204. if (mDebugTarget != mEmptyDebugTarget)
  1205. delete mDebugTarget;
  1206. mDebugTarget = mEmptyDebugTarget;
  1207. mShuttingDown = false;
  1208. mStepSP = 0;
  1209. ClearCallStack();
  1210. mRunState = RunState_NotStarted;
  1211. mStepType = StepType_None;
  1212. mHadImageFindError = false;
  1213. mIsPartialCallStack = true;
  1214. delete mDebugPendingExpr;
  1215. mDebugPendingExpr = NULL;
  1216. for (auto threadPair : mThreadMap)
  1217. {
  1218. auto threadInfo = threadPair.mValue;
  1219. delete threadInfo;
  1220. }
  1221. mThreadMap.Clear();
  1222. mThreadList.Clear();
  1223. mHotTargetMemory.Clear();
  1224. // We don't need to close the hThread when we have attached to a process
  1225. if (mDbgProcessId == 0)
  1226. {
  1227. CloseHandle(mProcessInfo.hThread);
  1228. CloseHandle(mProcessInfo.hProcess);
  1229. }
  1230. for (auto breakpoint : mBreakpoints)
  1231. {
  1232. if (!mDestroying)
  1233. {
  1234. BF_FATAL("Breakpoints should be deleted already");
  1235. }
  1236. if (breakpoint->mMemoryBreakpointInfo != NULL)
  1237. {
  1238. DetachBreakpoint(breakpoint);
  1239. }
  1240. }
  1241. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  1242. mStepBreakpointAddrs.Clear();
  1243. mIsRunning = false;
  1244. mDbgAttachFlags = BfDbgAttachFlag_None;
  1245. mDbgProcessId = 0;
  1246. delete mDbgHeapData;
  1247. mDbgHeapData = NULL;
  1248. mDbgProcessHandle = 0;
  1249. ClearCallStack();
  1250. mWantsDebugContinue = false;
  1251. mAtBreakThread = NULL;
  1252. mActiveThread = NULL;
  1253. mActiveBreakpoint = NULL;
  1254. mSteppingThread = NULL;
  1255. mExplicitStopThread = NULL;
  1256. mIsContinuingFromException = false;
  1257. mGotStartupEvent = false;
  1258. mIsDebuggerWaiting = false;
  1259. mPhysBreakpointAddrMap.Clear();
  1260. mBreakpointAddrMap.Clear();
  1261. gDebugUpdateCnt = 0;
  1262. }
  1263. Profiler* WinDebugger::StartProfiling()
  1264. {
  1265. return new DbgProfiler(this);
  1266. }
  1267. Profiler* WinDebugger::PopProfiler()
  1268. {
  1269. AutoCrit autoCrit(mDebugManager->mCritSect);
  1270. if (mNewProfilerList.IsEmpty())
  1271. return NULL;
  1272. auto profiler = (DbgProfiler*)mNewProfilerList[0];
  1273. mNewProfilerList.erase(mNewProfilerList.begin());
  1274. return profiler;
  1275. }
  1276. void WinDebugger::AddProfiler(DbgProfiler * profiler)
  1277. {
  1278. AutoCrit autoCrit(mDebugManager->mCritSect);
  1279. mProfilerSet.Add(profiler);
  1280. }
  1281. void WinDebugger::RemoveProfiler(DbgProfiler * profiler)
  1282. {
  1283. AutoCrit autoCrit(mDebugManager->mCritSect);
  1284. mProfilerSet.Remove(profiler);
  1285. }
  1286. void WinDebugger::ReportMemory(MemReporter* memReporter)
  1287. {
  1288. mEmptyDebugTarget->ReportMemory(memReporter);
  1289. if (mDebugTarget != mEmptyDebugTarget)
  1290. mDebugTarget->ReportMemory(memReporter);
  1291. }
  1292. void WinDebugger::ModuleChanged(DbgModule* dbgModule)
  1293. {
  1294. mDebugManager->mOutMessages.push_back(String("dbgInfoLoaded ") + dbgModule->mFilePath);
  1295. }
  1296. bool WinDebugger::DoUpdate()
  1297. {
  1298. if ((mDbgProcessId != 0) && ((mDbgAttachFlags & BfDbgAttachFlag_ShutdownOnExit) == 0))
  1299. ::DebugSetProcessKillOnExit(FALSE);
  1300. else
  1301. ::DebugSetProcessKillOnExit(TRUE);
  1302. //
  1303. {
  1304. AutoCrit autoCrit(mDebugManager->mCritSect);
  1305. auto _ModuleChanged = [&](DbgModule* dbgModule)
  1306. {
  1307. ModuleChanged(dbgModule);
  1308. ClearCallStack(); // We may have actual dbgSubprograms and stuff now...
  1309. };
  1310. for (auto dbgModule : mPendingImageLoad)
  1311. {
  1312. dbgModule->PreCacheImage();
  1313. }
  1314. for (auto kv : mPendingDebugInfoLoad)
  1315. {
  1316. kv.mKey->PreCacheDebugInfo();
  1317. }
  1318. while (!mPendingImageLoad.IsEmpty())
  1319. {
  1320. auto dbgModule = mPendingImageLoad.back();
  1321. mPendingImageLoad.pop_back();
  1322. dbgModule->RequestImage();
  1323. _ModuleChanged(dbgModule);
  1324. }
  1325. if (!mPendingDebugInfoLoad.IsEmpty())
  1326. {
  1327. Array<DbgPendingDebugInfoLoad> pendingList;
  1328. for (auto kv : mPendingDebugInfoLoad)
  1329. pendingList.Add(kv.mValue);
  1330. mPendingDebugInfoLoad.Clear();
  1331. for (auto& entry : pendingList)
  1332. {
  1333. auto dbgModule = entry.mModule;
  1334. entry.mModule->RequestDebugInfo(entry.mAllowRemote);
  1335. // We do a "_ModuleChanged" even if the load failed, so we rehup the callstack and stop
  1336. // saying "<Loading...>"
  1337. _ModuleChanged(entry.mModule);
  1338. }
  1339. }
  1340. }
  1341. if (IsMiniDumpDebugger())
  1342. {
  1343. //
  1344. {
  1345. AutoCrit autoCrit(mDebugManager->mCritSect);
  1346. if (mRunState == RunState_Terminating)
  1347. {
  1348. mRunState = RunState_Terminated;
  1349. return false;
  1350. }
  1351. }
  1352. Sleep(20);
  1353. return false;
  1354. }
  1355. if (mIsDebuggerWaiting)
  1356. {
  1357. if ((IsInRunState()) || (mRunState == RunState_Terminating) || (mRunState == RunState_DebugEval))
  1358. ContinueDebugEvent();
  1359. if (mContinueEvent.WaitFor(8))
  1360. {
  1361. BF_ASSERT(!mWantsDebugContinue); // mWantsDebugContinue should already been reset
  1362. BfLogDbg("::ContinueDebugEvent 1 ThreadId:%d\n", mDebuggerWaitingThread->mThreadId);
  1363. BF_ASSERT_REL(mDebuggerWaitingThread->mIsAtBreakpointAddress == 0);
  1364. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, mIsContinuingFromException ? DBG_EXCEPTION_NOT_HANDLED : DBG_CONTINUE);
  1365. mIsContinuingFromException = false;
  1366. mIsDebuggerWaiting = false;
  1367. mDebuggerWaitingThread = NULL;
  1368. }
  1369. else
  1370. return false;
  1371. }
  1372. if (!WaitForDebugEvent(&mDebugEvent, 8))
  1373. return false;
  1374. gDebugUpdateCnt++;
  1375. static const char* eventNames[] = { "DBG_EVENT ?",
  1376. "EXCEPTION_DEBUG_EVENT",
  1377. "CREATE_THREAD_DEBUG_EVENT",
  1378. "CREATE_PROCESS_DEBUG_EVENT",
  1379. "EXIT_THREAD_DEBUG_EVENT",
  1380. "EXIT_PROCESS_DEBUG_EVENT",
  1381. "LOAD_DLL_DEBUG_EVENT",
  1382. "UNLOAD_DLL_DEBUG_EVENT",
  1383. "OUTPUT_DEBUG_STRING_EVENT",
  1384. "RIP_EVENT"};
  1385. BfLogDbg("WaitForDebugEvent %s ThreadId:%d\n", eventNames[mDebugEvent.dwDebugEventCode], mDebugEvent.dwThreadId);
  1386. BP_ZONE(eventNames[mDebugEvent.dwDebugEventCode]);
  1387. AutoCrit autoCrit(mDebugManager->mCritSect);
  1388. mActiveBreakpoint = NULL;
  1389. mIsDebuggerWaiting = true;
  1390. mWantsDebugContinue = true;
  1391. mRequestedStackFrameIdx = 0;
  1392. mBreakStackFrameIdx = 0;
  1393. mShowPCOverride = 0;
  1394. WdThreadInfo* threadInfo = NULL;
  1395. mThreadMap.TryGetValue(mDebugEvent.dwThreadId, &threadInfo);
  1396. mDebuggerWaitingThread = threadInfo;
  1397. mExplicitStopThread = mDebuggerWaitingThread;
  1398. switch (mDebugEvent.dwDebugEventCode)
  1399. {
  1400. case CREATE_PROCESS_DEBUG_EVENT:
  1401. {
  1402. if (threadInfo == NULL)
  1403. {
  1404. BF_ASSERT(mThreadMap.size() == 0);
  1405. WdThreadInfo* newThreadInfo = new WdThreadInfo();
  1406. newThreadInfo->mProcessId = mDebugEvent.dwProcessId;
  1407. newThreadInfo->mThreadId = mDebugEvent.dwThreadId;
  1408. newThreadInfo->mHThread = mDebugEvent.u.CreateProcessInfo.hThread;
  1409. newThreadInfo->mThreadLocalBase = mDebugEvent.u.CreateProcessInfo.lpThreadLocalBase;
  1410. newThreadInfo->mStartAddress = (void*)mDebugEvent.u.CreateProcessInfo.lpStartAddress;
  1411. BF_CONTEXT lcContext;
  1412. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1413. BF_GetThreadContext(newThreadInfo->mHThread, &lcContext);
  1414. newThreadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1415. mThreadMap[mDebugEvent.dwThreadId] = newThreadInfo;
  1416. mDebuggerWaitingThread = newThreadInfo;
  1417. mThreadList.push_back(mDebuggerWaitingThread);
  1418. UpdateThreadDebugRegisters();
  1419. OutputMessage(StrFormat("Creating thread from CREATE_PROCESS_DEBUG_EVENT %d\n", mDebugEvent.dwThreadId));
  1420. threadInfo = mDebuggerWaitingThread;
  1421. mProcessInfo.dwThreadId = threadInfo->mThreadId;
  1422. mProcessInfo.hThread = threadInfo->mHThread;
  1423. mProcessInfo.hProcess = mDebugEvent.u.CreateProcessInfo.hProcess;
  1424. }
  1425. else
  1426. {
  1427. threadInfo->mThreadLocalBase = mDebugEvent.u.CreateProcessInfo.lpThreadLocalBase;
  1428. threadInfo->mStartAddress = (void*)mDebugEvent.u.CreateProcessInfo.lpStartAddress;
  1429. }
  1430. BF_CONTEXT lcContext;
  1431. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1432. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1433. threadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1434. DbgModule* launchBinary = mDebugTarget->Init(mLaunchPath, mTargetPath, (addr_target)(intptr)mDebugEvent.u.CreateProcessInfo.lpBaseOfImage);
  1435. addr_target gotImageBase = (addr_target)(intptr)mDebugEvent.u.CreateProcessInfo.lpBaseOfImage;
  1436. if (launchBinary->mImageBase != gotImageBase)
  1437. {
  1438. BF_FATAL("Image base didn't match");
  1439. }
  1440. launchBinary->mImageBase = gotImageBase;
  1441. launchBinary->mImageSize = (int)launchBinary->GetImageSize();
  1442. launchBinary->mOrigImageData = new DbgModuleMemoryCache(launchBinary->mImageBase, launchBinary->mImageSize);
  1443. if (launchBinary == mDebugTarget->mTargetBinary)
  1444. mDebugTarget->SetupTargetBinary();
  1445. if (mDebugEvent.u.CreateProcessInfo.hFile != NULL)
  1446. CloseHandle(mDebugEvent.u.CreateProcessInfo.hFile);
  1447. mDbgProcessHandle = mDebugEvent.u.CreateProcessInfo.hProcess;
  1448. mDbgThreadHandle = mDebugEvent.u.CreateProcessInfo.hThread;
  1449. mGotStartupEvent = true;
  1450. mDebugManager->mOutMessages.push_back("modulesChanged");
  1451. }
  1452. break;
  1453. case EXIT_PROCESS_DEBUG_EVENT:
  1454. {
  1455. BfLogDbg("EXIT_PROCESS_DEBUG_EVENT\n");
  1456. DWORD exitCode = mDebugEvent.u.ExitProcess.dwExitCode;
  1457. String exitMessage;
  1458. switch (exitCode)
  1459. {
  1460. case STATUS_DLL_NOT_FOUND:
  1461. exitMessage = "STATUS_DLL_NOT_FOUND";
  1462. break;
  1463. case STATUS_DLL_INIT_FAILED:
  1464. exitMessage = "STATUS_DLL_INIT_FAILED";
  1465. break;
  1466. case STATUS_ENTRYPOINT_NOT_FOUND:
  1467. exitMessage = "STATUS_ENTRYPOINT_NOT_FOUND";
  1468. break;
  1469. }
  1470. String exitCodeStr;
  1471. if ((exitCode >= 0x10000000) && (exitCode <= 0xF7000000))
  1472. exitCodeStr = StrFormat("0x%X", exitCode);
  1473. else
  1474. exitCodeStr = StrFormat("%d", exitCode);
  1475. if (!exitMessage.IsEmpty())
  1476. OutputMessage(StrFormat("Process terminated. ExitCode: %s (%s).\n", exitCodeStr.c_str(), exitMessage.c_str()));
  1477. else
  1478. OutputMessage(StrFormat("Process terminated. ExitCode: %s.\n", exitCodeStr.c_str()));
  1479. mRunState = RunState_Terminated;
  1480. mDebugManager->mOutMessages.push_back("modulesChanged");
  1481. }
  1482. break;
  1483. case LOAD_DLL_DEBUG_EVENT:
  1484. {
  1485. WCHAR moduleNameStr[MAX_PATH] = { 0 };
  1486. GetFinalPathNameByHandleW(mDebugEvent.u.LoadDll.hFile, moduleNameStr, MAX_PATH, FILE_NAME_NORMALIZED);
  1487. std::wstring wow64Dir;
  1488. std::wstring systemDir;
  1489. PWSTR wow64DirPtr = NULL;
  1490. SHGetKnownFolderPath(FOLDERID_SystemX86, KF_FLAG_NO_ALIAS, NULL, &wow64DirPtr);
  1491. if (wow64DirPtr != NULL)
  1492. {
  1493. wow64Dir = wow64DirPtr;
  1494. CoTaskMemFree(wow64DirPtr);
  1495. }
  1496. PWSTR systemDirPtr = NULL;
  1497. SHGetKnownFolderPath(FOLDERID_System, KF_FLAG_NO_ALIAS, NULL, &systemDirPtr);
  1498. if (systemDirPtr != NULL)
  1499. {
  1500. systemDir = systemDirPtr;
  1501. CoTaskMemFree(systemDirPtr);
  1502. }
  1503. if ((mDebugEvent.u.LoadDll.lpImageName != 0) && (mDebugEvent.u.LoadDll.fUnicode))
  1504. {
  1505. addr_target strAddr = ReadMemory<addr_target>((addr_target)(intptr)mDebugEvent.u.LoadDll.lpImageName);
  1506. for (int i = 0; i < MAX_PATH - 1; i++)
  1507. {
  1508. WCHAR c = ReadMemory<WCHAR>(strAddr + i*2);
  1509. moduleNameStr[i] = (WCHAR)c;
  1510. if (c == 0)
  1511. break;
  1512. }
  1513. }
  1514. String origModuleName = UTF8Encode(moduleNameStr);
  1515. String moduleName = origModuleName;
  1516. String loadMsg;
  1517. HANDLE altFileHandle = INVALID_HANDLE_VALUE;
  1518. if (moduleName != origModuleName)
  1519. {
  1520. loadMsg = StrFormat("Loading DLL: %s(%s) @ %s", origModuleName.c_str(), moduleName.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.LoadDll.lpBaseOfDll, true).c_str());
  1521. altFileHandle = ::CreateFileW(UTF8Decode(moduleName).c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  1522. }
  1523. else
  1524. {
  1525. loadMsg = StrFormat("Loading DLL: %s @ %s", moduleName.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.LoadDll.lpBaseOfDll, true).c_str());
  1526. }
  1527. BfLogDbg("LOAD_DLL_DEBUG_EVENT %s\n", moduleName.c_str());
  1528. bool skipLoad = false;
  1529. #ifdef BF_DBG_32
  1530. if (((uintptr)mDebugEvent.u.LoadDll.lpBaseOfDll & 0xFFFFFFFF00000000LL) != 0)
  1531. {
  1532. skipLoad = true;
  1533. loadMsg += " - Skipped";
  1534. }
  1535. #endif
  1536. if (!skipLoad)
  1537. {
  1538. FileHandleStream stream;
  1539. stream.mFileHandle = mDebugEvent.u.LoadDll.hFile;
  1540. if (altFileHandle != INVALID_HANDLE_VALUE)
  1541. stream.mFileHandle = altFileHandle;
  1542. if (mDebugTarget->SetupDyn(moduleName, &stream, (intptr)mDebugEvent.u.LoadDll.lpBaseOfDll) == NULL)
  1543. loadMsg += " - Failed to load";
  1544. stream.mFileHandle = 0;
  1545. }
  1546. OutputMessage(loadMsg + "\n");
  1547. if (altFileHandle != INVALID_HANDLE_VALUE)
  1548. ::CloseHandle(altFileHandle);
  1549. ::CloseHandle(mDebugEvent.u.LoadDll.hFile);
  1550. // Try to bind any breakpoints tied to this DLL
  1551. RehupBreakpoints(true);
  1552. mDebugManager->mOutMessages.push_back("modulesChanged");
  1553. }
  1554. break;
  1555. case UNLOAD_DLL_DEBUG_EVENT:
  1556. {
  1557. bool needsBreakpointRehup = false;
  1558. String name = "???";
  1559. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress((addr_target)(intptr)mDebugEvent.u.UnloadDll.lpBaseOfDll);
  1560. if (dbgModule != NULL)
  1561. {
  1562. name = dbgModule->mFilePath;
  1563. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  1564. {
  1565. auto breakpoint = mBreakpoints[i];
  1566. auto checkBreakpoint = breakpoint;
  1567. bool hasAddr = false;
  1568. while (checkBreakpoint != NULL)
  1569. {
  1570. if ((checkBreakpoint->mAddr >= dbgModule->mImageBase) && (checkBreakpoint->mAddr < dbgModule->mImageBase + dbgModule->mImageSize))
  1571. hasAddr = true;
  1572. checkBreakpoint = (WdBreakpoint*)checkBreakpoint->mLinkedSibling;
  1573. }
  1574. if (hasAddr)
  1575. {
  1576. DetachBreakpoint(breakpoint);
  1577. needsBreakpointRehup = true;
  1578. }
  1579. }
  1580. mDebugTarget->UnloadDyn(dbgModule->mImageBase);
  1581. if (needsBreakpointRehup)
  1582. RehupBreakpoints(true);
  1583. mPendingDebugInfoLoad.Remove(dbgModule);
  1584. mPendingDebugInfoRequests.Remove(dbgModule);
  1585. mDebugManager->mOutMessages.push_back("modulesChanged");
  1586. }
  1587. if (!name.empty())
  1588. OutputMessage(StrFormat("Unloading DLL: %s @ %0s\n", name.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.UnloadDll.lpBaseOfDll, true).c_str()));
  1589. BfLogDbg("UNLOAD_DLL_DEBUG_EVENT %s\n", name.c_str());
  1590. }
  1591. break;
  1592. case OUTPUT_DEBUG_STRING_EVENT:
  1593. {
  1594. const int maxChars = 1024 * 1024;
  1595. int len = BF_MIN(maxChars, (int)mDebugEvent.u.DebugString.nDebugStringLength); // 1MB max
  1596. char* message = new char[len + 1];
  1597. message[0] = 0;
  1598. message[len] = 0;
  1599. ReadMemory((addr_target)(intptr)mDebugEvent.u.DebugString.lpDebugStringData, len, message);
  1600. if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId == mDebugEvalThreadInfo.mThreadId))
  1601. mDebugManager->mOutMessages.push_back(String("dbgEvalMsg ") + message);
  1602. else
  1603. mDebugManager->mOutMessages.push_back(String("msg ") + message);
  1604. BfLogDbg("OUTPUT_DEBUG_STRING_EVENT (BreakAddr:%@): %s\n", threadInfo->mIsAtBreakpointAddress, message);
  1605. BF_ASSERT_REL(threadInfo->mIsAtBreakpointAddress == 0);
  1606. delete [] message;
  1607. }
  1608. break;
  1609. case CREATE_THREAD_DEBUG_EVENT:
  1610. {
  1611. WdThreadInfo* threadInfo = new WdThreadInfo();
  1612. threadInfo->mProcessId = mDebugEvent.dwProcessId;
  1613. threadInfo->mThreadId = mDebugEvent.dwThreadId;
  1614. threadInfo->mHThread = mDebugEvent.u.CreateThread.hThread;
  1615. threadInfo->mThreadLocalBase = mDebugEvent.u.CreateThread.lpThreadLocalBase;
  1616. threadInfo->mStartAddress = (void*)mDebugEvent.u.CreateThread.lpStartAddress;
  1617. BF_CONTEXT lcContext;
  1618. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1619. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1620. threadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1621. mThreadMap[mDebugEvent.dwThreadId] = threadInfo;
  1622. mDebuggerWaitingThread = threadInfo;
  1623. mThreadList.push_back(mDebuggerWaitingThread);
  1624. UpdateThreadDebugRegisters();
  1625. OutputMessage(StrFormat("Creating thread %d\n", mDebugEvent.dwThreadId));
  1626. }
  1627. break;
  1628. case EXIT_THREAD_DEBUG_EVENT:
  1629. {
  1630. OutputMessage(StrFormat("Exiting thread %d\n", mDebugEvent.dwThreadId));
  1631. if (mSteppingThread == threadInfo)
  1632. {
  1633. // We were attempting stepping on this thread, but not anymore!
  1634. ClearStep();
  1635. }
  1636. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_CONTINUE);
  1637. mIsDebuggerWaiting = false;
  1638. mWantsDebugContinue = false;
  1639. if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId == mDebugEvalThreadInfo.mThreadId))
  1640. {
  1641. // Thread terminated while evaluating! Is there a more graceful way of handling this?
  1642. CleanupDebugEval(false);
  1643. mRunState = RunState_Running;
  1644. }
  1645. mThreadList.Remove(mDebuggerWaitingThread);
  1646. delete mDebuggerWaitingThread;
  1647. mDebuggerWaitingThread = NULL;
  1648. mThreadMap.Remove(mDebugEvent.dwThreadId);
  1649. return true;
  1650. }
  1651. break;
  1652. case RIP_EVENT:
  1653. OutputMessage("RIP Event\n");
  1654. break;
  1655. case EXCEPTION_DEBUG_EVENT:
  1656. {
  1657. auto exceptionRecord = &mDebugEvent.u.Exception.ExceptionRecord;
  1658. switch (exceptionRecord->ExceptionCode)
  1659. {
  1660. case STATUS_WX86_BREAKPOINT:
  1661. case EXCEPTION_BREAKPOINT:
  1662. {
  1663. if (mRunState == RunState_Terminating)
  1664. {
  1665. BfLogDbg("Ignoring event because of RunState_Terminating\n");
  1666. break;
  1667. }
  1668. mAtBreakThread = threadInfo;
  1669. mActiveThread = mAtBreakThread;
  1670. bool isHighAddr = false;
  1671. #ifdef BF_DBG_32
  1672. if (((uintptr)exceptionRecord->ExceptionAddress & 0xFFFFFFFF00000000) != 0)
  1673. {
  1674. if (mActiveThread == mThreadList.front())
  1675. {
  1676. // Skip the initial Wow64 ntdll.dll!LdrpDoDebuggerBreak
  1677. mRunState = RunState_Running;
  1678. break;
  1679. }
  1680. isHighAddr = true;
  1681. }
  1682. #endif
  1683. addr_target pcAddress = (addr_target)(intptr)exceptionRecord->ExceptionAddress;
  1684. if (isHighAddr)
  1685. pcAddress = (addr_target)-1;
  1686. //mStoppedAtAddress = pcAddress;
  1687. bool isStepOut = false;
  1688. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto))
  1689. {
  1690. isStepOut = mStepBreakpointAddrs.Contains(pcAddress);
  1691. }
  1692. BF_CONTEXT lcContext;
  1693. lcContext.ContextFlags = BF_CONTEXT_ALL;
  1694. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1695. BfLogDbg("EXCEPTION_BREAKPOINT Thread:%d %p SP:%p\n", mActiveThread->mThreadId, pcAddress, BF_CONTEXT_SP(lcContext));
  1696. uint8 origImageData = 0xCC;
  1697. mDebugTarget->ReadOrigImageData(pcAddress, &origImageData, 1);
  1698. bool wasDebugBreakpoint = origImageData != 0xCC;
  1699. DbgSubprogram* dwSubprogram = NULL;
  1700. DbgLineData* dwLineData = NULL;
  1701. if (!isStepOut)
  1702. {
  1703. dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  1704. if (dwSubprogram == NULL)
  1705. dwSubprogram = mDebugTarget->FindSubProgram(pcAddress, DbgOnDemandKind_LocalOnly);
  1706. }
  1707. bool isLineStart = (dwLineData != NULL) && (dwSubprogram->GetLineAddr(*dwLineData) == pcAddress);
  1708. bool isNonDebuggerBreak = false;
  1709. if (wasDebugBreakpoint)
  1710. {
  1711. // Go ahead and set EIP back one instruction
  1712. BF_CONTEXT_IP(lcContext)--;
  1713. BF_SetThreadContext(threadInfo->mHThread, &lcContext);
  1714. if ((dwSubprogram != NULL) && (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid) &&
  1715. (pcAddress == dwSubprogram->mBlock.mLowPC))
  1716. {
  1717. BfLogDbg("Hit HotReplaceKind_Invalid breakpoint\n");
  1718. mRunState = RunState_Paused;
  1719. mDebugManager->mOutMessages.push_back("error This lambda was replaced by a new version that has incompatible captures. A program restart is required.");
  1720. PhysRemoveBreakpoint(pcAddress);
  1721. break;
  1722. }
  1723. }
  1724. else
  1725. {
  1726. // This was an actual "break" instruction
  1727. BfLogDbg("Non-debugger break\n");
  1728. isNonDebuggerBreak = true;
  1729. auto prevState = mRunState;
  1730. // Make it an "auto" stop, so for example when we have an assert/retry we won't stop inside assembly
  1731. mRequestedStackFrameIdx = -2;
  1732. mRunState = RunState_Paused;
  1733. CheckNonDebuggerBreak();
  1734. if (IsInRunState())
  1735. {
  1736. BF_ASSERT((prevState == RunState_Running) || (prevState == RunState_DebugEval));
  1737. mRunState = prevState;
  1738. break; // Continue as if nothing happened
  1739. }
  1740. if (prevState == RunState_DebugEval)
  1741. mRequestedStackFrameIdx = -1; // Don't show a rolled back stack idx if a debug eval fails
  1742. ClearStep();
  1743. }
  1744. if (threadInfo->mIsBreakRestorePaused)
  1745. {
  1746. // The thread is supposed to be paused, but the IP has been reset
  1747. // so just break here so we'll hit that breakpoint again once we're
  1748. // actually unpaused properly
  1749. BfLogDbg("Ignoring EXCEPTION_BREAKPOINT\n", threadInfo->mThreadId);
  1750. break;
  1751. }
  1752. if ((mRunState == RunState_DebugEval) || (mRunState == RunState_HotStep))
  1753. {
  1754. // If we hit a breakpoint while doing a debug eval, we just remove the breakpoint
  1755. // and expect to reinstate it during a rehup after the evaluation has completed
  1756. WdBreakpoint* breakpoint = (WdBreakpoint*)FindBreakpointAt((uintptr_t) exceptionRecord->ExceptionAddress);
  1757. if (breakpoint != NULL)
  1758. {
  1759. mNeedsRehupBreakpoints = true;
  1760. RemoveBreakpoint(breakpoint->mLineData.GetAddress());
  1761. }
  1762. break;
  1763. }
  1764. bool isDeeper = false;
  1765. int stepBreakAddrIdx = (int)mStepBreakpointAddrs.IndexOf(pcAddress);
  1766. WdBreakpoint* breakpoint = NULL;
  1767. bool ignoreBreakpoint = false;
  1768. if ((mStepType != StepType_None) && (mSteppingThread == mAtBreakThread))
  1769. {
  1770. if (mStepType == StepType_ToTempBreakpoint)
  1771. {
  1772. RemoveTempBreakpoints();
  1773. mRunState = RunState_Paused;
  1774. break;
  1775. }
  1776. if (mContinueFromBreakpointFailed)
  1777. {
  1778. BfLogDbg("Continuing from ContinueFromBreakpointFailed\n");
  1779. SetupStep(mStepType);
  1780. mRunState = RunState_Running;
  1781. break;
  1782. }
  1783. if (!isStepOut)
  1784. breakpoint = (WdBreakpoint*)FindBreakpointAt(pcAddress);
  1785. // Ignore breakpoint if it's on the line we're stepping off of
  1786. if ((breakpoint != NULL) && (breakpoint->mAddr == mStepPC) &&
  1787. (mStepSP == BF_CONTEXT_SP(lcContext)))
  1788. {
  1789. ignoreBreakpoint = true;
  1790. }
  1791. else if ((breakpoint != NULL) && (stepBreakAddrIdx == -1) && (!CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress)))
  1792. {
  1793. ignoreBreakpoint = true;
  1794. }
  1795. if ((stepBreakAddrIdx == -1) && (breakpoint == NULL) && (!isNonDebuggerBreak))
  1796. {
  1797. // If a breakpoint is removed in a prior thread
  1798. BfLogDbg("Ignoring step break (old breakpoint)\n");
  1799. if ((mSteppingThread == mAtBreakThread) && (mStepSwitchedThreads))
  1800. {
  1801. SetupStep(mStepType);
  1802. }
  1803. break;
  1804. }
  1805. if ((stepBreakAddrIdx != -1) && (breakpoint == NULL) && (mSteppingThread != mActiveThread))
  1806. {
  1807. BfLogDbg("Ignoring break (wrong thread)\n");
  1808. ThreadRestorePause(mSteppingThread, mActiveThread);
  1809. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1810. break;
  1811. }
  1812. isDeeper = mStepSP > BF_CONTEXT_SP(lcContext);
  1813. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto))
  1814. {
  1815. isDeeper = mStepSP >= BF_CONTEXT_SP(lcContext);
  1816. BfLogDbg("StepOut Iteration SP:%p StartSP:%p IsDeeper:%d\n", BF_CONTEXT_SP(lcContext), mStepSP, isDeeper);
  1817. }
  1818. if (((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto)) && (breakpoint == NULL) && (isDeeper))
  1819. {
  1820. // We're encountered recursion
  1821. // Make sure we don't already have one of these stored
  1822. BF_ASSERT(mStoredReturnValueAddr == 0);
  1823. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1824. break; // Don't fall through, we don't want to set mIsAtBreakpointAddress
  1825. }
  1826. if (isStepOut)
  1827. {
  1828. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1829. if (mStepType == StepType_StepOut_ThenInto)
  1830. {
  1831. dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  1832. if ((dwLineData != NULL) && (pcAddress == dwSubprogram->GetLineAddr(*dwLineData)))
  1833. {
  1834. // Our step out from a filtered function put us at the start of a new line. Stop here
  1835. // <do nothing>
  1836. }
  1837. else
  1838. {
  1839. // .. otherwise keep going until we get to the start of a new line
  1840. SetupStep(StepType_StepInto);
  1841. mRunState = RunState_Running;
  1842. break;
  1843. }
  1844. }
  1845. if (!mStepInAssembly)
  1846. {
  1847. // Keep stepping out until we find a frame that we have source for
  1848. DbgSubprogram* dwSubprogram = NULL;
  1849. DbgLineData* dwLineData = FindLineDataAtAddress(BF_CONTEXT_IP(lcContext), &dwSubprogram);
  1850. if (dwLineData == NULL)
  1851. {
  1852. SetupStep(StepType_StepOut);
  1853. break;
  1854. }
  1855. if ((dwLineData->mColumn == -1) && (!dwSubprogram->HasValidLines()))
  1856. {
  1857. // This is a method we don't actually want to be in, it has no valid lines!
  1858. SetupStep(StepType_StepOut);
  1859. break;
  1860. }
  1861. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  1862. {
  1863. // We've stepped out, but right into the start of an inlined method, so step out of this inlined method now...
  1864. SetupStep(StepType_StepOut);
  1865. break;
  1866. }
  1867. }
  1868. ClearStep();
  1869. mRunState = RunState_Paused;
  1870. threadInfo->mStoppedAtAddress = pcAddress;
  1871. break;
  1872. }
  1873. mRunState = RunState_Paused;
  1874. if (breakpoint != NULL)
  1875. {
  1876. // While stepping we hit a legit breakpoint
  1877. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  1878. // Ignore breakpoint on return statement if we're return-stepping
  1879. mRunState = RunState_Breakpoint;
  1880. }
  1881. if ((mStepType == StepType_StepInto) && (dwSubprogram != NULL))
  1882. {
  1883. // Don't filter out the current subprogram (would break cases where we explicitly stepped into or hit breakpoint in a filtered subprogram)
  1884. bool isInStartSubprogram = (mStepStartPC >= dwSubprogram->mBlock.mLowPC) && (mStepStartPC < dwSubprogram->mBlock.mHighPC);
  1885. if ((!isInStartSubprogram) && (IsStepFiltered(dwSubprogram, dwLineData)))
  1886. {
  1887. BfLogDbg("Hit step filter\n");
  1888. mRunState = RunState_Running;
  1889. SetupStep(StepType_StepOut_ThenInto);
  1890. break;
  1891. }
  1892. }
  1893. if ((mStepType == StepType_StepOver) && (stepBreakAddrIdx == 0) && (mStepBreakpointAddrs[0] != 0) && (mStepBreakpointAddrs.size() > 1))
  1894. {
  1895. // Break was on the 'call' instruction, not the instruction after it -- means recursion
  1896. BfLogDbg("StepOver detected recursing\n");
  1897. mStepIsRecursing = true;
  1898. if (mTempBreakpoint.Remove(mStepBreakpointAddrs[0]))
  1899. {
  1900. RemoveBreakpoint(mStepBreakpointAddrs[0]);
  1901. }
  1902. mStepBreakpointAddrs[0] = 0;
  1903. mRunState = RunState_Running;
  1904. break;
  1905. }
  1906. if ((mStepType == StepType_StepOver) && (stepBreakAddrIdx > 0) && (mStepBreakpointAddrs[0] != 0) && (isDeeper))
  1907. {
  1908. // This is the first time we've hit the target breakpoint.
  1909. if (HasSteppedIntoCall())
  1910. {
  1911. mStepIsRecursing = true;
  1912. RemoveBreakpoint(mStepBreakpointAddrs[0]);
  1913. mStepBreakpointAddrs[0] = 0;
  1914. //mStepBreakpointAddrs.erase(mStepBreakpointAddrs.begin());
  1915. }
  1916. }
  1917. if ((mStepType == StepType_StepOver) && (mStepIsRecursing) && (stepBreakAddrIdx != -1) && (isDeeper))
  1918. {
  1919. // Decrement so the equality test on "step out" marks us as not being deeper when we
  1920. // hit the expected SP
  1921. BfLogDbg("Converting StepOver to StepOut\n");
  1922. mStepSP--;
  1923. mStepType = StepType_StepOut_ThenInto;
  1924. //SetupStep(StepType_StepOut);
  1925. mRunState = RunState_Running;
  1926. break;
  1927. }
  1928. if ((mStepType == StepType_StepOver) && (!ignoreBreakpoint) && (breakpoint == NULL) && (!mStepInAssembly))
  1929. {
  1930. // Test for stepping over inline method
  1931. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  1932. // mTempBreakpoints will have 2 entries if we are on a 'call' line. If we have an inlined call immediately following a call, then we
  1933. // assume we're hitting a return break
  1934. /*if ((dwSubprogram != NULL) && (dwSubprogram->mInlineParent != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC) && (mTempBreakpoint.size() < 2))
  1935. {
  1936. BfLogDbg("Attempting StepOver of inlined method\n");
  1937. SetupStep(StepType_StepOut);
  1938. mRunState = RunState_Running;
  1939. break;
  1940. } */
  1941. //TODO: The previous logic with the "(mTempBreakpoint.size() < 2)" was causing Try!(Method()); stepovers to enter into Try!. What did we mean by
  1942. // "assume we're hitting a return break"?
  1943. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  1944. {
  1945. RemoveTempBreakpoints();
  1946. BfLogDbg("Attempting StepOver of inlined method\n");
  1947. SetupStep(StepType_StepOut);
  1948. mRunState = RunState_Running;
  1949. break;
  1950. }
  1951. }
  1952. if (mStepType == StepType_StepOut_Inline)
  1953. {
  1954. if (mOrigStepType == StepType_StepOver)
  1955. {
  1956. // For the step over, if we are still inside the source line after an inline then step over again...
  1957. DbgSubprogram* origSubprogram = NULL;
  1958. auto origLineData = FindLineDataAtAddress(mStepStartPC, &origSubprogram);
  1959. DbgSubprogram* curSubprogram = NULL;
  1960. auto curLineData = FindLineDataAtAddress(pcAddress, &curSubprogram);
  1961. if ((origLineData != NULL) &&
  1962. ((origLineData == curLineData) ||
  1963. ((origSubprogram == curSubprogram) && (origLineData->mLine == curLineData->mLine))))
  1964. {
  1965. mRunState = RunState_Running;
  1966. SetupStep(StepType_StepOver);
  1967. break;
  1968. }
  1969. }
  1970. ClearStep();
  1971. break;
  1972. }
  1973. if ((mStepType != StepType_None) && (ignoreBreakpoint) && (!mStepInAssembly) && (stepBreakAddrIdx == -1))
  1974. {
  1975. // Ignore breakpoint by just continuing...
  1976. mRunState = RunState_Running;
  1977. break;
  1978. }
  1979. RemoveTempBreakpoints();
  1980. if ((mStepType != StepType_None) && (!mStepInAssembly) && (!isLineStart) && (stepBreakAddrIdx != -1))
  1981. {
  1982. SetupStep(mStepType);
  1983. mRunState = RunState_Running;
  1984. }
  1985. else
  1986. {
  1987. //if (mStepType != StepType_Return)
  1988. if (stepBreakAddrIdx != -1)
  1989. {
  1990. // Even if we've detected we're at a breakpoint, we mark ourselves as just stepping if we also
  1991. // have a step breakpoint here
  1992. StepLineTryPause(pcAddress, true);
  1993. }
  1994. if (mRunState == RunState_Paused)
  1995. ClearStep();
  1996. }
  1997. if (ignoreBreakpoint)
  1998. {
  1999. SetupStep(mStepType);
  2000. mRunState = RunState_Running;
  2001. }
  2002. if ((mRunState == RunState_Paused) && (breakpoint != NULL))
  2003. {
  2004. // Just do the 'check' here so we can do the logging/condition stuff
  2005. CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress);
  2006. }
  2007. }
  2008. else
  2009. {
  2010. breakpoint = (WdBreakpoint*)FindBreakpointAt((uintptr_t)exceptionRecord->ExceptionAddress);
  2011. if ((breakpoint != NULL) && (!CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress)))
  2012. {
  2013. ClearCallStack();
  2014. BfLogDbg("Skipping conditional breakpoint. Setting mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  2015. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  2016. mRunState = RunState_Running;
  2017. break;
  2018. }
  2019. if (breakpoint != NULL)
  2020. {
  2021. BfLogDbg("Breakpoint hit. mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  2022. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  2023. mRunState = RunState_Breakpoint;
  2024. }
  2025. else if ((stepBreakAddrIdx != -1) || (isNonDebuggerBreak))
  2026. {
  2027. if (mRunState != RunState_DebugEval)
  2028. {
  2029. // Was in mStepBreakpointAddrs list
  2030. if ((isNonDebuggerBreak) || (mStepType == StepType_None) || (mSteppingThread == mAtBreakThread))
  2031. {
  2032. BfLogDbg("Hit mStepBreakpointAddrs breakpoint\n");
  2033. mRunState = RunState_Paused;
  2034. }
  2035. else
  2036. {
  2037. BfLogDbg("Ignored mStepBreakpointAddrs breakpoint (wrong thread)\n");
  2038. mRunState = RunState_Running;
  2039. }
  2040. }
  2041. }
  2042. else
  2043. {
  2044. BfLogDbg("Ignoring break (old or ignored breakpoint)\n");
  2045. mRunState = RunState_Running;
  2046. }
  2047. }
  2048. if ((breakpoint != NULL) && (!ignoreBreakpoint))
  2049. {
  2050. mActiveBreakpoint = breakpoint;
  2051. mBreakStackFrameIdx = -1;
  2052. }
  2053. if ((mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint))
  2054. threadInfo->mStoppedAtAddress = pcAddress;
  2055. }
  2056. break;
  2057. case STATUS_WX86_SINGLE_STEP:
  2058. case EXCEPTION_SINGLE_STEP:
  2059. {
  2060. if (mRunState == RunState_Terminating)
  2061. {
  2062. BfLogDbg("Ignoring event because of RunState_Terminating\n");
  2063. break;
  2064. }
  2065. if ((mStepSwitchedThreads) && (mActiveThread == mSteppingThread) && (mActiveThread->mIsAtBreakpointAddress != NULL))
  2066. {
  2067. ContinueFromBreakpoint();
  2068. break;
  2069. }
  2070. if (mRunState == RunState_HotStep)
  2071. {
  2072. BF_ASSERT(mActiveThread == mDebuggerWaitingThread);
  2073. mRunState = RunState_Paused;
  2074. break;
  2075. }
  2076. mActiveThread = mDebuggerWaitingThread;
  2077. BF_CONTEXT lcContext;
  2078. lcContext.ContextFlags = BF_CONTEXT_ALL;
  2079. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  2080. addr_target pcAddress = BF_CONTEXT_IP(lcContext);
  2081. bool wasUnfilteredStep = mStepType == StepType_StepInto_Unfiltered;
  2082. if (mStepType == StepType_StepInto_UnfilteredSingle)
  2083. {
  2084. wasUnfilteredStep = true;
  2085. mStepType = StepType_StepInto;
  2086. mStepStartPC = pcAddress;
  2087. }
  2088. BfLogDbg("EXCEPTION_SINGLE_STEP Thread:%d PC:%p\n", mActiveThread->mThreadId, exceptionRecord->ExceptionAddress);
  2089. if (lcContext.Dr6 & 0x0F) // Memory breakpoint hit
  2090. {
  2091. WdBreakpoint* foundBreakpoint = NULL;
  2092. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  2093. {
  2094. if ((lcContext.Dr6 & ((intptr_target)1 << memoryWatchSlot)) != 0)
  2095. {
  2096. foundBreakpoint = mMemoryBreakpoints[memoryWatchSlot].mBreakpoint;
  2097. break;
  2098. }
  2099. }
  2100. BF_ASSERT(foundBreakpoint != NULL);
  2101. DbgSubprogram* subprogram = mDebugTarget->FindSubProgram(pcAddress);
  2102. if (CheckConditionalBreakpoint(foundBreakpoint, subprogram, pcAddress))
  2103. {
  2104. if (foundBreakpoint != NULL)
  2105. {
  2106. mDebugManager->mOutMessages.push_back(StrFormat("memoryBreak %s", EncodeDataPtr(foundBreakpoint->mMemoryBreakpointInfo->mMemoryAddress, false).c_str()));
  2107. mRunState = RunState_Paused;
  2108. }
  2109. mActiveBreakpoint = foundBreakpoint;
  2110. mBreakStackFrameIdx = -1;
  2111. RemoveTempBreakpoints();
  2112. BfLogDbg("Memory breakpoint hit: %p\n", foundBreakpoint);
  2113. }
  2114. else
  2115. ClearCallStack();
  2116. break;
  2117. }
  2118. if ((mRunState == RunState_DebugEval) && (mDebugEvalThreadInfo.mThreadId == mDebuggerWaitingThread->mThreadId))
  2119. {
  2120. if ((addr_target)(intptr)exceptionRecord->ExceptionAddress == mDebugEvalSetRegisters.GetPC())
  2121. {
  2122. // This indicates we are returning from kernel mode and our registers are clobbered
  2123. SetRegisters(&mDebugEvalSetRegisters);
  2124. }
  2125. break;
  2126. }
  2127. bool hadBreakpointContinue = true;
  2128. if (threadInfo->mBreakpointAddressContinuing != 0)
  2129. {
  2130. bool wantsBreakpoint = WantsBreakpointAt(threadInfo->mBreakpointAddressContinuing);
  2131. BfLogDbg("Continuing breakpoint at %p WantsReset:%d\n", threadInfo->mBreakpointAddressContinuing, wantsBreakpoint);
  2132. if (wantsBreakpoint)
  2133. {
  2134. PhysSetBreakpoint(threadInfo->mBreakpointAddressContinuing);
  2135. }
  2136. threadInfo->mBreakpointAddressContinuing = NULL;
  2137. hadBreakpointContinue = true;
  2138. ThreadRestoreUnpause();
  2139. }
  2140. if ((mSteppingThread != NULL) && (mSteppingThread != mActiveThread))
  2141. {
  2142. // This SINGLE_STEP happened in the wrong thread - we need the stepping thread to do the stepping!
  2143. // Try again.
  2144. mActiveThread = mSteppingThread;
  2145. SingleStepX86();
  2146. break;
  2147. }
  2148. bool isDeeper = mStepSP > BF_CONTEXT_SP(lcContext);
  2149. if ((mStepSwitchedThreads) && (mStepType == StepType_StepOver) && (isDeeper))
  2150. {
  2151. if (HasSteppedIntoCall())
  2152. {
  2153. // Since we switched threads, we needed to do a hardware step which has placed us inside a
  2154. // call, so we need to step out of that now...
  2155. SetupStep(StepType_StepOut_NoFrame);
  2156. break;
  2157. }
  2158. }
  2159. // If we don't have a mStepBreakpointAddrs set, that means we're stepping through individual instructions --
  2160. // so process the new location here
  2161. if (((mStepType == StepType_StepInto) || (mStepType == StepType_StepInto_Unfiltered) || (mStepType == StepType_StepOver)) && (mStepBreakpointAddrs.size() == 0))
  2162. {
  2163. DbgSubprogram* dwSubprogram = NULL;
  2164. DbgLineData* dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  2165. if ((dwSubprogram != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC) && (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced))
  2166. {
  2167. BfLogDbg("Stepping through hot thunk\n");
  2168. mRunState = RunState_Running;
  2169. SingleStepX86();
  2170. break;
  2171. }
  2172. if ((mStepType == StepType_StepOver) && (!mStepInAssembly))
  2173. {
  2174. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  2175. {
  2176. BfLogDbg("Attempting StepOver of inlined method - SingleStep\n");
  2177. SetupStep(StepType_StepOut);
  2178. mRunState = RunState_Running;
  2179. break;
  2180. }
  2181. }
  2182. // Column of -1 means "Illegal", keep stepping!
  2183. if ((mStepInAssembly) ||
  2184. ((dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dwLineData->mColumn >= 0) &&
  2185. ((dwSubprogram->GetLineAddr(*dwLineData) == pcAddress) || (mStepStopOnNextInstruction))))
  2186. {
  2187. // Hit a line while stepping, we're done!
  2188. mRunState = RunState_Paused;
  2189. StepLineTryPause(pcAddress, false);
  2190. if (mRunState == RunState_Paused)
  2191. {
  2192. if ((mStepType == StepType_StepInto) && (!wasUnfilteredStep) && (!mStepInAssembly) && (dwSubprogram != NULL))
  2193. {
  2194. // Don't filter out the current subprogram (would break cases where we explicitly stepped into or hit breakpoint in a filtered subprogram)
  2195. bool isInStartSubprogram = (mStepStartPC >= dwSubprogram->mBlock.mLowPC) && (mStepStartPC < dwSubprogram->mBlock.mHighPC);
  2196. if ((!isInStartSubprogram) && (IsStepFiltered(dwSubprogram, dwLineData)))
  2197. {
  2198. BfLogDbg("Hit step filter (2)\n");
  2199. mRunState = RunState_Running;
  2200. SetupStep(StepType_StepOut_ThenInto);
  2201. break;
  2202. }
  2203. }
  2204. ClearStep();
  2205. mCurNoInfoStepTries = 0; // Reset
  2206. }
  2207. else
  2208. SetupStep(mStepType);
  2209. }
  2210. else if (dwSubprogram != NULL)
  2211. {
  2212. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && ((mStepType == StepType_StepInto) || (mStepType == StepType_StepInto_Unfiltered)))
  2213. {
  2214. SingleStepX86();
  2215. }
  2216. else
  2217. {
  2218. // Inside a line's instruction, keep going
  2219. SetupStep(mStepType);
  2220. mCurNoInfoStepTries = 0; // Reset
  2221. }
  2222. }
  2223. else if (mStepType == StepType_StepInto_Unfiltered)
  2224. {
  2225. CPUInst inst;
  2226. if (mDebugTarget->DecodeInstruction(pcAddress, &inst))
  2227. {
  2228. if (inst.IsBranch())
  2229. {
  2230. auto target = inst.GetTarget();
  2231. if (target != 0)
  2232. {
  2233. DbgSubprogram* destSubprogram = mDebugTarget->FindSubProgram(target);
  2234. if ((destSubprogram != NULL) && (target == destSubprogram->mBlock.mLowPC))
  2235. {
  2236. // We're jumping to an actual subprogram, so continue stepping here
  2237. mStepType = StepType_StepInto_UnfilteredSingle;
  2238. SingleStepX86();
  2239. break;
  2240. }
  2241. }
  2242. }
  2243. }
  2244. // We requested to step into this method so stop here even if we don't have source
  2245. mRunState = RunState_Paused;
  2246. }
  2247. else
  2248. {
  2249. // No debug info!
  2250. bool doStepOut = false;
  2251. if (mCurNoInfoStepTries < 16)
  2252. {
  2253. mCurNoInfoStepTries++;
  2254. BfLogDbg("NoInfoStepTries: %d\n", mCurNoInfoStepTries);
  2255. if (!SetupStep(mStepType))
  2256. doStepOut = true;
  2257. }
  2258. else
  2259. doStepOut = true;
  2260. if (doStepOut)
  2261. {
  2262. // Step out of current call.
  2263. mStepSP = 0;
  2264. SetupStep(StepType_StepOut_NoFrame);
  2265. // Aggressive stepout - don't monitor BP
  2266. mStepSP = 0;
  2267. }
  2268. }
  2269. }
  2270. else if (!hadBreakpointContinue)
  2271. {
  2272. BF_DBG_FATAL("EXCEPTION_SINGLE_STEP bad debugger state");
  2273. }
  2274. if (mRunState == RunState_Paused)
  2275. threadInfo->mStoppedAtAddress = pcAddress;
  2276. }
  2277. break;
  2278. default:
  2279. {
  2280. bool isSystemException =
  2281. (exceptionRecord->ExceptionCode >= STATUS_ACCESS_VIOLATION) &&
  2282. (exceptionRecord->ExceptionCode <= STATUS_ASSERTION_FAILURE);
  2283. bool isFirstChance = mDebugEvent.u.Exception.dwFirstChance != 0;
  2284. bool handled = false;
  2285. //TODO: Use a user-defined filter here to determine whether to stop or continue
  2286. if ((!isSystemException) && (isFirstChance))
  2287. {
  2288. if (exceptionRecord->ExceptionCode == 0x406D1388) // Visual C
  2289. {
  2290. if ((int32)exceptionRecord->ExceptionInformation[0] == 0x1000)
  2291. {
  2292. struct THREADNAME_INFO
  2293. {
  2294. DWORD dwType; // Must be 0x1000.
  2295. LPCSTR szName; // Pointer to name (in user addr space).
  2296. DWORD dwThreadID; // Thread ID (-1=caller thread).
  2297. DWORD dwFlags; // Reserved for future use, must be zero.
  2298. };
  2299. THREADNAME_INFO* threadNameInfo = (THREADNAME_INFO*)exceptionRecord->ExceptionInformation;
  2300. DwFormatInfo formatInfo;
  2301. formatInfo.mRawString = true;
  2302. String nameStr = ReadString(DbgType_SChar, (intptr)threadNameInfo->szName, false, 1024, formatInfo);
  2303. WdThreadInfo* namingThreadInfo = threadInfo;
  2304. if (threadNameInfo->dwThreadID != (DWORD)-1)
  2305. {
  2306. namingThreadInfo = NULL;
  2307. mThreadMap.TryGetValue(threadNameInfo->dwThreadID, &namingThreadInfo);
  2308. }
  2309. if (namingThreadInfo != NULL)
  2310. {
  2311. namingThreadInfo->mName = nameStr;
  2312. FilterThreadName(namingThreadInfo->mName);
  2313. }
  2314. }
  2315. else if (((int32)exceptionRecord->ExceptionInformation[0] == 0x1001) && ((int32)exceptionRecord->ExceptionInformation[1] == 0x1002))
  2316. {
  2317. struct FailMessage
  2318. {
  2319. addr_target mPtr0; // Unknown
  2320. addr_target mPtr1; // 0
  2321. addr_target mPtr2; // 0
  2322. addr_target mPtr3; // Unknown
  2323. addr_target mErrorStr;
  2324. };
  2325. FailMessage failMessage = ReadMemory<FailMessage>(exceptionRecord->ExceptionInformation[2]);
  2326. DwFormatInfo formatInfo;
  2327. String failStr = ReadString(DbgType_SChar16, failMessage.mErrorStr, false, 8192, formatInfo);
  2328. mDebugManager->mOutMessages.push_back(StrFormat("error Run-Time Check Failure %d - %s", exceptionRecord->ExceptionInformation[6], failStr.c_str()));
  2329. mRunState = RunState_Paused;
  2330. mRequestedStackFrameIdx = -2; // -2 = "auto"
  2331. handled = true;
  2332. }
  2333. }
  2334. if (!handled)
  2335. {
  2336. OutputMessage(StrFormat("Skipping first chance exception %08Xd at address %@ in thread %d\n", exceptionRecord->ExceptionCode, exceptionRecord->ExceptionAddress, threadInfo->mThreadId));
  2337. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_EXCEPTION_NOT_HANDLED);
  2338. mIsDebuggerWaiting = false;
  2339. }
  2340. }
  2341. else
  2342. {
  2343. BfLogDbg("EXCEPTION in thread %d at %p\n", threadInfo->mThreadId, exceptionRecord->ExceptionAddress);
  2344. OutputDebugStrF("EXCEPTION\n");
  2345. mActiveThread = threadInfo;
  2346. memcpy(&mCurException, exceptionRecord, sizeof(EXCEPTION_RECORD));
  2347. if (mRunState == RunState_DebugEval)
  2348. {
  2349. if ((intptr)mCurException.ExceptionAddress == 42)
  2350. {
  2351. BfLogDbg("RunState_DebugEval_Done\n");
  2352. OutputDebugStrF(" RunState_DebugEval_Done\n");
  2353. }
  2354. else
  2355. {
  2356. BfLogDbg("Exception at 0x%@ in thread %d, exception code 0x%08X",
  2357. mCurException.ExceptionAddress, mActiveThread->mThreadId, mCurException.ExceptionCode);
  2358. mDebugPendingExpr->mException = StrFormat("Exception at 0x%@ in thread %d, exception code 0x%08X",
  2359. mCurException.ExceptionAddress, mActiveThread->mThreadId, mCurException.ExceptionCode);
  2360. }
  2361. mRunState = RunState_DebugEval_Done;
  2362. mExplicitStopThread = mActiveThread;
  2363. mRequestedStackFrameIdx = mDebugPendingExpr->mCallStackIdx;
  2364. }
  2365. else
  2366. {
  2367. mRunState = RunState_Exception;
  2368. }
  2369. }
  2370. }
  2371. break;
  2372. }
  2373. }
  2374. break;
  2375. }
  2376. if ((mDebugEvalThreadInfo.mThreadId != 0) && (mRunState != RunState_DebugEval) && (mRunState != RunState_DebugEval_Done))
  2377. {
  2378. CleanupDebugEval();
  2379. }
  2380. // Stepping done?
  2381. if (mStepType == StepType_None)
  2382. {
  2383. mLastValidStepIntoPC = 0;
  2384. }
  2385. BF_ASSERT(mDebuggerWaitingThread != NULL);
  2386. return true;
  2387. }
  2388. void WinDebugger::Update()
  2389. {
  2390. AutoCrit autoCrit(mDebugManager->mCritSect);
  2391. // if (mRunState == RunState_DebugEval)
  2392. // ContinueDebugEvent();
  2393. if (mRunState == RunState_DebugEval_Done)
  2394. {
  2395. if (mDebugPendingExpr != NULL)
  2396. {
  2397. mDebugPendingExpr->mIdleTicks++;
  2398. if (mDebugPendingExpr->mIdleTicks >= 2)
  2399. {
  2400. BfLogDbg("Finishing pending expr in thread %d\n", mDebugEvalThreadInfo.mThreadId);
  2401. mRunState = RunState_Paused;
  2402. CleanupDebugEval();
  2403. }
  2404. }
  2405. }
  2406. else if (mDebugPendingExpr != NULL)
  2407. {
  2408. mDebugPendingExpr->mIdleTicks = 0;
  2409. }
  2410. }
  2411. void WinDebugger::ContinueDebugEvent()
  2412. {
  2413. AutoCrit autoCrit(mDebugManager->mCritSect);
  2414. BF_ASSERT(mRunState != RunState_DebugEval_Done);
  2415. if (!mWantsDebugContinue)
  2416. return;
  2417. if (!TryRunContinue())
  2418. return;
  2419. // if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId != mDebugEvalThreadInfo.mThreadId))
  2420. // {
  2421. // // Don't process the 'mIsAtBreakpointAddress' stuff
  2422. // mWantsDebugContinue = false;
  2423. // mContinueEvent.Set();
  2424. // return;
  2425. // }
  2426. if ((mDebuggerWaitingThread->mIsAtBreakpointAddress == 0) && (mDebuggerWaitingThread->mStoppedAtAddress != 0))
  2427. {
  2428. auto breakpoint = FindBreakpointAt(mDebuggerWaitingThread->mStoppedAtAddress);
  2429. if (breakpoint != NULL)
  2430. {
  2431. mDebuggerWaitingThread->mIsAtBreakpointAddress = mDebuggerWaitingThread->mStoppedAtAddress;
  2432. }
  2433. }
  2434. if (mDebuggerWaitingThread->mIsAtBreakpointAddress != 0)
  2435. {
  2436. if (!ContinueFromBreakpoint())
  2437. {
  2438. BfLogDbg("ContinueFromBreakpoint failed\n");
  2439. ClearCallStack();
  2440. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  2441. mDebuggerWaitingThread->mIsAtBreakpointAddress = 0;
  2442. mWantsDebugContinue = false;
  2443. mContinueFromBreakpointFailed = true;
  2444. mContinueEvent.Set();
  2445. return;
  2446. }
  2447. }
  2448. if ((mRunState == RunState_Breakpoint) || (mRunState == RunState_Paused))
  2449. {
  2450. ClearCallStack();
  2451. mRunState = RunState_Running;
  2452. }
  2453. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  2454. mWantsDebugContinue = false;
  2455. BF_ASSERT_REL(mDebuggerWaitingThread->mIsAtBreakpointAddress == 0);
  2456. mContinueEvent.Set();
  2457. }
  2458. static BOOL CALLBACK WdEnumWindowsProc(HWND hwnd, LPARAM lParam)
  2459. {
  2460. HWND owner = GetWindow(hwnd, GW_OWNER);
  2461. if (!IsWindowVisible(hwnd))
  2462. return TRUE;
  2463. DWORD processId = 0;
  2464. DWORD threadId = GetWindowThreadProcessId(hwnd, &processId);
  2465. if (processId != ((WinDebugger*)gDebugger)->mProcessInfo.dwProcessId)
  2466. return TRUE;
  2467. SetForegroundWindow(hwnd);
  2468. return TRUE;
  2469. }
  2470. void WinDebugger::ForegroundTarget()
  2471. {
  2472. EnumWindows(WdEnumWindowsProc, 0);
  2473. }
  2474. static int gFindLineDataAt = 0;
  2475. DbgLineData* WinDebugger::FindLineDataAtAddress(addr_target address, DbgSubprogram** outSubProgram, DbgSrcFile** outSrcFile, int* outLineIdx, DbgOnDemandKind onDemandKind)
  2476. {
  2477. gFindLineDataAt++;
  2478. BP_ZONE("WinDebugger::FindLineDataAtAddress");
  2479. auto dwSubprogram = mDebugTarget->FindSubProgram((addr_target)address, onDemandKind);
  2480. if (dwSubprogram == NULL)
  2481. return NULL;
  2482. FixupLineDataForSubprogram(dwSubprogram);
  2483. auto lineData = dwSubprogram->FindClosestLine(address, outSubProgram, outSrcFile, outLineIdx);
  2484. return lineData;
  2485. }
  2486. DbgLineData* WinDebugger::FindLineDataInSubprogram(addr_target address, DbgSubprogram* dwSubprogram)
  2487. {
  2488. auto dwCompileUnit = dwSubprogram->mCompileUnit;
  2489. FixupLineDataForSubprogram(dwSubprogram);
  2490. auto lineData = dwSubprogram->FindClosestLine(address);
  2491. return lineData;
  2492. }
  2493. bool WinDebugger::IsStepFiltered(DbgSubprogram* dbgSubprogram, DbgLineData* dbgLineData)
  2494. {
  2495. if (mIsStepIntoSpecific)
  2496. return false;
  2497. if (dbgSubprogram->mStepFilterVersion != mDebugManager->mStepFilterVersion)
  2498. {
  2499. String filterName;
  2500. CreateFilterName(filterName, dbgSubprogram);
  2501. dbgSubprogram->PopulateSubprogram();
  2502. bool doDefault = false;
  2503. StepFilter* stepFilterPtr;
  2504. if (mDebugManager->mStepFilters.TryGetValue(filterName, &stepFilterPtr))
  2505. {
  2506. switch (stepFilterPtr->mFilterKind)
  2507. {
  2508. case BfStepFilterKind_Default:
  2509. doDefault = true;
  2510. break;
  2511. case BfStepFilterKind_Filtered:
  2512. dbgSubprogram->mIsStepFiltered = true;
  2513. break;
  2514. case BfStepFilterKind_NotFiltered:
  2515. dbgSubprogram->mIsStepFiltered = false;
  2516. break;
  2517. }
  2518. }
  2519. else
  2520. {
  2521. doDefault = true;
  2522. }
  2523. if (doDefault)
  2524. {
  2525. dbgSubprogram->mIsStepFiltered = dbgSubprogram->mIsStepFilteredDefault;
  2526. }
  2527. dbgSubprogram->mStepFilterVersion = mDebugManager->mStepFilterVersion;
  2528. }
  2529. if (!dbgSubprogram->mIsStepFiltered)
  2530. {
  2531. if (dbgLineData != NULL)
  2532. {
  2533. auto dbgSrcFile = dbgSubprogram->GetLineSrcFile(*dbgLineData);
  2534. if (dbgSrcFile->mStepFilterVersion != mDebugManager->mStepFilterVersion)
  2535. {
  2536. dbgSrcFile->mFileExistKind = dbgSubprogram->mCompileUnit->mDbgModule->CheckSourceFileExist(dbgSrcFile->GetLocalPath());
  2537. dbgSrcFile->mStepFilterVersion = mDebugManager->mStepFilterVersion;
  2538. }
  2539. switch (dbgSrcFile->mFileExistKind)
  2540. {
  2541. case DbgFileExistKind_NotFound:
  2542. return true;
  2543. case DbgFileExistKind_HasOldSourceCommand:
  2544. if (mDebugManager->mStepOverExternalFiles)
  2545. return true;
  2546. }
  2547. }
  2548. }
  2549. return dbgSubprogram->mIsStepFiltered;
  2550. }
  2551. void WinDebugger::RemoveTempBreakpoints()
  2552. {
  2553. BfLogDbg("RemoveTempBreakpoints\n");
  2554. for (auto address : mTempBreakpoint)
  2555. {
  2556. RemoveBreakpoint(address);
  2557. // if (FindBreakpointAt(address) == NULL)
  2558. // {
  2559. // RemoveBreakpoint(address);
  2560. // }
  2561. // else
  2562. // {
  2563. // BfLogDbg("Ignoring remove on temp breakpoint %p\n", address);
  2564. // }
  2565. }
  2566. mTempBreakpoint.Clear();
  2567. mStepBreakpointAddrs.Clear();
  2568. }
  2569. void WinDebugger::RehupBreakpoints(bool doFlush)
  2570. {
  2571. BfLogDbg("RehupBreakpoints\n");
  2572. // First pass- detach breakpoints that need to be rebound
  2573. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  2574. {
  2575. auto breakpoint = mBreakpoints[i];
  2576. while (breakpoint != NULL)
  2577. {
  2578. if (((breakpoint->mSrcFile != NULL) && (breakpoint->mSrcFile->mDeferredRefs.size() > 0)) ||
  2579. (!breakpoint->mSymbolName.IsEmpty()))
  2580. {
  2581. // This breakpoint was already bound, but we loaded a debug module that also had this file so rebind it
  2582. DetachBreakpoint(breakpoint);
  2583. }
  2584. breakpoint = (WdBreakpoint*)breakpoint->mLinkedSibling;
  2585. }
  2586. }
  2587. // Second pass- actually set breakpoints
  2588. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  2589. {
  2590. auto breakpoint = mBreakpoints[i];
  2591. while (breakpoint != NULL)
  2592. {
  2593. CheckBreakpoint(breakpoint);
  2594. if (breakpoint->mAddr != 0)
  2595. SetBreakpoint(breakpoint->mAddr, true);
  2596. breakpoint = (WdBreakpoint*)breakpoint->mLinkedSibling;
  2597. }
  2598. }
  2599. mNeedsRehupBreakpoints = false;
  2600. }
  2601. bool WinDebugger::WantsBreakpointAt(addr_target address)
  2602. {
  2603. if (mTempBreakpoint.Contains(address))
  2604. return true;
  2605. for (auto breakpoint : mBreakpoints)
  2606. {
  2607. WdBreakpoint* checkBreakpoint = breakpoint;
  2608. while (checkBreakpoint != NULL)
  2609. {
  2610. if (address == checkBreakpoint->mAddr)
  2611. return true;
  2612. checkBreakpoint = (WdBreakpoint*)checkBreakpoint->mLinkedSibling;
  2613. }
  2614. }
  2615. return false;
  2616. }
  2617. void WinDebugger::CheckBreakpoint(WdBreakpoint* wdBreakpoint, DbgSrcFile* srcFile, int lineNum, int hotIdx)
  2618. {
  2619. BP_ZONE("WinDebugger::CheckBreakpoint:atLoc");
  2620. if (hotIdx == -1)
  2621. {
  2622. BF_ASSERT(wdBreakpoint->mPendingHotBindIdx == -1);
  2623. }
  2624. WdBreakpoint* headBreakpoint = wdBreakpoint;
  2625. headBreakpoint->mPendingHotBindIdx = -1;
  2626. bool foundInSequence = false;
  2627. DbgSubprogram* lastFoundSubprogram = NULL;
  2628. int highestHotIdx = -1;
  2629. bool foundLine = false;
  2630. int bestLineNum = -1;
  2631. int bestLineOffset = 0x7FFFFFFF;
  2632. auto _CheckLineInfo = [&](DbgSubprogram* dbgSubprogram, DbgLineInfo* dbgLineInfo)
  2633. {
  2634. // Scan first so we can determine if we want to do fix up line data or not.
  2635. bool hasNear = false;
  2636. int maxLineDist = 6;
  2637. for (int lineIdx = 0; lineIdx < dbgLineInfo->mLines.mSize; lineIdx++)
  2638. {
  2639. auto lineData = &dbgLineInfo->mLines[lineIdx];
  2640. auto& ctx = dbgLineInfo->mContexts[lineData->mCtxIdx];
  2641. if (ctx.mSrcFile != srcFile)
  2642. continue;
  2643. int lineOffset = lineData->mLine - lineNum;
  2644. if ((lineOffset >= 0) && (lineOffset <= maxLineDist))
  2645. hasNear = true;
  2646. }
  2647. if (!hasNear)
  2648. return;
  2649. FixupLineDataForSubprogram(dbgSubprogram);
  2650. for (int lineIdx = 0; lineIdx < dbgLineInfo->mLines.mSize; lineIdx++)
  2651. {
  2652. //TODO: Do fixup lineData... ?
  2653. auto lineData = &dbgLineInfo->mLines[lineIdx];
  2654. auto& ctx = dbgLineInfo->mContexts[lineData->mCtxIdx];
  2655. if (ctx.mSrcFile != srcFile)
  2656. continue;
  2657. // if (ctx.mInlinee != NULL)
  2658. // {
  2659. // if (lineIdx + 1 < dbgLineInfo->mLines.mSize)
  2660. // {
  2661. // auto nextLineData = &dbgLineInfo->mLines[lineIdx + 1];
  2662. // if (nextLineData->mRelAddress == lineData->mRelAddress)
  2663. // {
  2664. // // Use the later entry (same logic from DisassembleAt)
  2665. // continue;
  2666. // }
  2667. // }
  2668. // }
  2669. if ((lineData->mColumn == -1) && (wdBreakpoint->mInstrOffset == -1))
  2670. continue;
  2671. int lineOffset = lineData->mLine - lineNum;
  2672. if (lineOffset == 0)
  2673. {
  2674. foundLine = true;
  2675. auto address = dbgSubprogram->GetLineAddr(*lineData);
  2676. auto subProgram = mDebugTarget->FindSubProgram(address);
  2677. if (subProgram->mNeedLineDataFixup)
  2678. FixupLineDataForSubprogram(subProgram);
  2679. if (subProgram != NULL)
  2680. highestHotIdx = BF_MAX(highestHotIdx, subProgram->mCompileUnit->mDbgModule->mHotIdx);
  2681. if ((foundInSequence) && (subProgram != lastFoundSubprogram))
  2682. foundInSequence = false;
  2683. if ((subProgram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && (address < subProgram->mBlock.mLowPC + sizeof(HotJumpOp)))
  2684. {
  2685. // If this breakpoint ends up on the hot jmp instruction
  2686. continue;
  2687. }
  2688. if (!foundInSequence)
  2689. {
  2690. lastFoundSubprogram = subProgram;
  2691. if ((subProgram != NULL) && (subProgram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && (address == subProgram->mBlock.mLowPC))
  2692. {
  2693. // This instruction is actually the hot jump, we don't need a breakpoint here
  2694. foundInSequence = true;
  2695. continue;
  2696. }
  2697. if (wdBreakpoint->mSrcFile != NULL)
  2698. {
  2699. wdBreakpoint = new WdBreakpoint();
  2700. // Insert at head
  2701. wdBreakpoint->mLinkedSibling = headBreakpoint->mLinkedSibling;
  2702. headBreakpoint->mLinkedSibling = wdBreakpoint;
  2703. wdBreakpoint->mRequestedLineNum = headBreakpoint->mRequestedLineNum;
  2704. wdBreakpoint->mLineNum = headBreakpoint->mLineNum;
  2705. wdBreakpoint->mColumn = headBreakpoint->mColumn;
  2706. wdBreakpoint->mInstrOffset = headBreakpoint->mInstrOffset;
  2707. wdBreakpoint->mIsLinkedSibling = true;
  2708. wdBreakpoint->mHead = headBreakpoint;
  2709. }
  2710. if (wdBreakpoint->mInstrOffset > 0)
  2711. {
  2712. for (int instIdx = 0; instIdx < wdBreakpoint->mInstrOffset; instIdx++)
  2713. {
  2714. CPUInst inst;
  2715. if (!mDebugTarget->DecodeInstruction(address, &inst))
  2716. break;
  2717. address += inst.mSize;
  2718. }
  2719. }
  2720. wdBreakpoint->mSrcFile = ctx.mSrcFile;
  2721. wdBreakpoint->mLineData = DbgLineDataEx(lineData, subProgram);
  2722. wdBreakpoint->mBreakpointType = BreakpointType_User;
  2723. wdBreakpoint->mAddr = address;
  2724. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mStoppedAtAddress == address))
  2725. {
  2726. BfLogDbg("CheckBreakpoint setting mIsAtBreakpointAddress = %p\n", address);
  2727. mDebuggerWaitingThread->mIsAtBreakpointAddress = address;
  2728. }
  2729. BfLogDbg("Breakpoint %p found at %s in %s\n", wdBreakpoint, subProgram->mName, GetFileName(subProgram->mCompileUnit->mDbgModule->mFilePath).c_str());
  2730. mBreakpointAddrMap.ForceAdd(address, wdBreakpoint);
  2731. SetBreakpoint(address);
  2732. foundInSequence = true;
  2733. }
  2734. }
  2735. else
  2736. {
  2737. //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
  2738. // multiple places so we need to ensure this will break on them all
  2739. foundInSequence = false;
  2740. }
  2741. if ((lineOffset >= 0) && (lineOffset <= maxLineDist) && (lineOffset <= bestLineOffset))
  2742. {
  2743. if (lineOffset < bestLineOffset)
  2744. {
  2745. bestLineNum = lineData->mLine;
  2746. bestLineOffset = lineOffset;
  2747. }
  2748. }
  2749. }
  2750. };
  2751. for (int pass = 0; pass < 2; pass++)
  2752. {
  2753. if (lineNum == -1)
  2754. break;
  2755. bestLineNum = -1;
  2756. bestLineOffset = 0x7FFFFFFF;
  2757. if (hotIdx >= 0)
  2758. {
  2759. if (hotIdx >= srcFile->mHotReplacedDbgLineInfo.size())
  2760. return;
  2761. auto hotReplacedLineInfo = srcFile->mHotReplacedDbgLineInfo[hotIdx];
  2762. for (auto& hotReplacedEntry : hotReplacedLineInfo->mEntries)
  2763. {
  2764. _CheckLineInfo(hotReplacedEntry.mSubprogram, hotReplacedEntry.mLineInfo);
  2765. }
  2766. }
  2767. else
  2768. {
  2769. for (auto subprogram : srcFile->mLineDataRefs)
  2770. _CheckLineInfo(subprogram, subprogram->mLineInfo);
  2771. }
  2772. if (foundLine)
  2773. break;
  2774. // Don't allow the breakpoint to be inexactly bound -- only match on pass 0
  2775. if (hotIdx != -1)
  2776. break;
  2777. if (bestLineNum == -1)
  2778. break;
  2779. lineNum = bestLineNum;
  2780. wdBreakpoint->mLineNum = bestLineNum;
  2781. }
  2782. int highestCheckHotIdx = highestHotIdx - 1;
  2783. if (hotIdx != -1)
  2784. highestCheckHotIdx = hotIdx - 1;
  2785. for (int hotFileIdx = highestCheckHotIdx; hotFileIdx >= 0; hotFileIdx--)
  2786. {
  2787. auto& hotReplacedDbgLineData = wdBreakpoint->mSrcFile->mHotReplacedDbgLineInfo;
  2788. // Only try to bind to an old hot version if we haven't unloaded the hot module
  2789. if ((hotFileIdx < (int)hotReplacedDbgLineData.size()) && (hotReplacedDbgLineData[hotFileIdx]->mEntries.size() > 0))
  2790. {
  2791. headBreakpoint->mPendingHotBindIdx = hotFileIdx;
  2792. break;
  2793. }
  2794. }
  2795. }
  2796. void WinDebugger::HotBindBreakpoint(Breakpoint* breakpoint, int lineNum, int hotIdx)
  2797. {
  2798. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  2799. CheckBreakpoint(wdBreakpoint, wdBreakpoint->mSrcFile, lineNum, hotIdx);
  2800. }
  2801. void WinDebugger::CheckBreakpoint(WdBreakpoint* wdBreakpoint)
  2802. {
  2803. if (!mGotStartupEvent)
  2804. return;
  2805. if (wdBreakpoint->mThreadId == 0) // Not bound to threadId yet...
  2806. {
  2807. return;
  2808. }
  2809. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  2810. {
  2811. if (wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap != 0)
  2812. return;
  2813. if (mFreeMemoryBreakIndices.size() == 0)
  2814. return;
  2815. if ((IsInRunState()) || (mActiveThread == NULL))
  2816. return;
  2817. int wantBytes[4];
  2818. int wantBindCount = 0;
  2819. int bytesLeft = wdBreakpoint->mMemoryBreakpointInfo->mByteCount;
  2820. addr_target curAddr = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress;
  2821. while (bytesLeft > 0)
  2822. {
  2823. if (wantBindCount >= mFreeMemoryBreakIndices.size())
  2824. return;
  2825. int curByteCount = 1;
  2826. #ifdef BF_DBG_64
  2827. if ((bytesLeft >= 8) && ((curAddr & 7) == 0))
  2828. curByteCount = 8;
  2829. else
  2830. #endif
  2831. if ((bytesLeft >= 4) && ((curAddr & 3) == 0))
  2832. curByteCount = 4;
  2833. else if ((bytesLeft >= 2) && ((curAddr & 1) == 0))
  2834. curByteCount = 2;
  2835. wantBytes[wantBindCount++] = curByteCount;
  2836. bytesLeft -= curByteCount;
  2837. curAddr += curByteCount;
  2838. }
  2839. addr_target curOfs = 0;
  2840. for (int i = 0; i < wantBindCount; i++)
  2841. {
  2842. int memoryBreakIdx = mFreeMemoryBreakIndices.back();
  2843. mFreeMemoryBreakIndices.pop_back();
  2844. mMemoryBreakpoints[memoryBreakIdx].mBreakpoint = wdBreakpoint;
  2845. mMemoryBreakpoints[memoryBreakIdx].mAddress = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress + curOfs;
  2846. mMemoryBreakpoints[memoryBreakIdx].mByteCount = wantBytes[i];
  2847. mMemoryBreakpoints[memoryBreakIdx].mOfs = curOfs;
  2848. curOfs += wantBytes[i];
  2849. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap |= 1<<memoryBreakIdx;
  2850. }
  2851. UpdateThreadDebugRegisters();
  2852. }
  2853. if (wdBreakpoint->mAddr != 0)
  2854. return;
  2855. if (!wdBreakpoint->mSymbolName.IsEmpty())
  2856. {
  2857. auto headBreakpoint = wdBreakpoint->GetHeadBreakpoint();
  2858. String symbolName = wdBreakpoint->mSymbolName;
  2859. bool onlyBindFirst = false;
  2860. if (symbolName.StartsWith("-"))
  2861. {
  2862. symbolName.Remove(0);
  2863. onlyBindFirst = true;
  2864. }
  2865. for (auto dbgModule : mDebugTarget->mDbgModules)
  2866. {
  2867. dbgModule->ParseSymbolData();
  2868. addr_target targetAddr = -1;
  2869. auto entry = dbgModule->mSymbolNameMap.Find(symbolName.c_str());
  2870. if (entry != NULL)
  2871. {
  2872. DbgSymbol* dwSymbol = entry->mValue;
  2873. targetAddr = dwSymbol->mAddress;
  2874. }
  2875. if (targetAddr == -1)
  2876. {
  2877. if (symbolName == ".")
  2878. {
  2879. targetAddr = mDebugTarget->mLaunchBinary->mImageBase + mDebugTarget->mLaunchBinary->mEntryPoint;
  2880. onlyBindFirst = true;
  2881. }
  2882. }
  2883. if (targetAddr != -1)
  2884. {
  2885. if (wdBreakpoint->mAddr == 0)
  2886. {
  2887. wdBreakpoint->mAddr = targetAddr;
  2888. wdBreakpoint->mBreakpointType = BreakpointType_User;
  2889. mBreakpointAddrMap.ForceAdd(wdBreakpoint->mAddr, wdBreakpoint);
  2890. SetBreakpoint(wdBreakpoint->mAddr);
  2891. }
  2892. else
  2893. {
  2894. wdBreakpoint = new WdBreakpoint();
  2895. // Insert at head
  2896. wdBreakpoint->mLinkedSibling = headBreakpoint->mLinkedSibling;
  2897. headBreakpoint->mLinkedSibling = wdBreakpoint;
  2898. wdBreakpoint->mSymbolName = headBreakpoint->mSymbolName;
  2899. wdBreakpoint->mIsLinkedSibling = true;
  2900. wdBreakpoint->mHead = headBreakpoint;
  2901. }
  2902. if (onlyBindFirst)
  2903. break;
  2904. }
  2905. }
  2906. return;
  2907. }
  2908. BP_ZONE("WinDebugger::CheckBreakpoint");
  2909. // Rehup if we load a DLL that also uses this file we bound to (thus the mDeferredRefs check)
  2910. if (wdBreakpoint->mSrcFile == NULL)
  2911. {
  2912. DbgSrcFile* srcFile = mDebugTarget->GetSrcFile(wdBreakpoint->mFilePath);
  2913. if (srcFile == NULL)
  2914. return;
  2915. for (auto& deferredSrcFileRef : srcFile->mDeferredRefs)
  2916. {
  2917. deferredSrcFileRef.mDbgModule->ParseCompileUnit(deferredSrcFileRef.mCompileUnitId);
  2918. }
  2919. srcFile->mDeferredRefs.Clear();
  2920. CheckBreakpoint(wdBreakpoint, srcFile, wdBreakpoint->mRequestedLineNum, -1);
  2921. }
  2922. }
  2923. bool WinDebugger::IsMemoryBreakpointSizeValid(addr_target addr, int size)
  2924. {
  2925. int wantBindCount = 0;
  2926. int bytesLeft = size;
  2927. addr_target curAddr = addr;
  2928. for (int i = 0; i < 4; i++)
  2929. {
  2930. int curByteCount = 1;
  2931. #ifdef BF_DBG_64
  2932. if ((bytesLeft >= 8) && ((curAddr & 7) == 0))
  2933. curByteCount = 8;
  2934. else
  2935. #endif
  2936. if ((bytesLeft >= 4) && ((curAddr & 3) == 0))
  2937. curByteCount = 4;
  2938. else if ((bytesLeft >= 2) && ((curAddr & 1) == 0))
  2939. curByteCount = 2;
  2940. bytesLeft -= curByteCount;
  2941. curAddr += curByteCount;
  2942. if (bytesLeft == 0)
  2943. return true;
  2944. }
  2945. return false;
  2946. }
  2947. bool WinDebugger::HasMemoryBreakpoint(addr_target addr, int size)
  2948. {
  2949. for (int i = 0; i < 4; i++)
  2950. {
  2951. if ((mMemoryBreakpoints[i].mAddress == addr) &&
  2952. (mMemoryBreakpoints[i].mOfs == 0) &&
  2953. (mMemoryBreakpoints[i].mBreakpoint->mMemoryBreakpointInfo->mByteCount == size))
  2954. return true;
  2955. }
  2956. return false;
  2957. }
  2958. Breakpoint* WinDebugger::CreateBreakpoint(const StringImpl& fileName, int lineNum, int wantColumn, int instrOffset)
  2959. {
  2960. AutoCrit autoCrit(mDebugManager->mCritSect);
  2961. BfLogDbg("CreateBreakpoint %s %d %d\n", fileName.c_str(), lineNum, wantColumn);
  2962. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  2963. wdBreakpoint->mFilePath = FixPathAndCase(fileName);
  2964. wdBreakpoint->mRequestedLineNum = lineNum;
  2965. wdBreakpoint->mLineNum = lineNum;
  2966. wdBreakpoint->mColumn = wantColumn;
  2967. wdBreakpoint->mInstrOffset = instrOffset;
  2968. mBreakpoints.push_back(wdBreakpoint);
  2969. BfLogDbg("CreateBreakpoint Created %p\n", wdBreakpoint);
  2970. return wdBreakpoint;
  2971. }
  2972. void WinDebugger::CheckBreakpoint(Breakpoint* checkBreakpoint)
  2973. {
  2974. AutoCrit autoCrit(mDebugManager->mCritSect);
  2975. CheckBreakpoint((WdBreakpoint*)checkBreakpoint);
  2976. }
  2977. Breakpoint* WinDebugger::CreateMemoryBreakpoint(intptr addr, int byteCount)
  2978. {
  2979. AutoCrit autoCrit(mDebugManager->mCritSect);
  2980. BfLogDbg("CreateMemoryBreakpoint %p %d\n", addr, byteCount);
  2981. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  2982. WdMemoryBreakpointInfo* memoryBreakInfo = new WdMemoryBreakpointInfo();
  2983. memoryBreakInfo->mMemoryAddress = addr;
  2984. memoryBreakInfo->mByteCount = byteCount;
  2985. wdBreakpoint->mMemoryBreakpointInfo = memoryBreakInfo;
  2986. mBreakpoints.push_back(wdBreakpoint);
  2987. CheckBreakpoint(wdBreakpoint);
  2988. return wdBreakpoint;
  2989. }
  2990. Breakpoint* WinDebugger::CreateSymbolBreakpoint(const StringImpl& symbolName)
  2991. {
  2992. AutoCrit autoCrit(mDebugManager->mCritSect);
  2993. BfLogDbg("CreateSymbolBreakpoint %s\n", symbolName.c_str());
  2994. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  2995. wdBreakpoint->mSymbolName = symbolName;
  2996. mBreakpoints.push_back(wdBreakpoint);
  2997. CheckBreakpoint(wdBreakpoint);
  2998. return wdBreakpoint;
  2999. }
  3000. Breakpoint* WinDebugger::CreateAddressBreakpoint(intptr inAddress)
  3001. {
  3002. AutoCrit autoCrit(mDebugManager->mCritSect);
  3003. BfLogDbg("CreateAddressBreakpoint %p\n", inAddress);
  3004. addr_target address = (addr_target)inAddress;
  3005. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  3006. wdBreakpoint->mAddr = address;
  3007. mBreakpointAddrMap.ForceAdd(wdBreakpoint->mAddr, wdBreakpoint);
  3008. SetBreakpoint(address);
  3009. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mStoppedAtAddress == address))
  3010. {
  3011. BfLogDbg("CreateAddressBreakpoint setting mIsAtBreakpointAddress = %p\n", address);
  3012. mDebuggerWaitingThread->mIsAtBreakpointAddress = address;
  3013. }
  3014. mBreakpoints.push_back(wdBreakpoint);
  3015. return wdBreakpoint;
  3016. }
  3017. void WinDebugger::DeleteBreakpoint(Breakpoint* breakpoint)
  3018. {
  3019. AutoCrit autoCrit(mDebugManager->mCritSect);
  3020. if (breakpoint == mActiveBreakpoint)
  3021. mActiveBreakpoint = NULL;
  3022. BfLogDbg("WinDebugger::DeleteBreakpoint %p Count:%d\n", breakpoint, mBreakpoints.size());
  3023. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3024. if (wdBreakpoint->mCondition != NULL)
  3025. {
  3026. if (!wdBreakpoint->mIsLinkedSibling)
  3027. delete wdBreakpoint->mCondition;
  3028. }
  3029. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  3030. {
  3031. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  3032. {
  3033. if (mMemoryBreakpoints[memoryWatchSlot].mBreakpoint == wdBreakpoint)
  3034. {
  3035. mFreeMemoryBreakIndices.push_back(memoryWatchSlot);
  3036. mMemoryBreakpoints[memoryWatchSlot] = WdMemoryBreakpointBind();
  3037. UpdateThreadDebugRegisters();
  3038. }
  3039. }
  3040. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap = 0;
  3041. }
  3042. if (wdBreakpoint->mAddr != 0)
  3043. {
  3044. mBreakpointAddrMap.Remove(wdBreakpoint->mAddr, wdBreakpoint);
  3045. RemoveBreakpoint(wdBreakpoint->mAddr);
  3046. for (auto thread : mThreadList)
  3047. {
  3048. if (thread->mIsAtBreakpointAddress == wdBreakpoint->mAddr)
  3049. thread->mIsAtBreakpointAddress = NULL;
  3050. if (thread->mBreakpointAddressContinuing == wdBreakpoint->mAddr)
  3051. thread->mBreakpointAddressContinuing = NULL;
  3052. }
  3053. }
  3054. if (!wdBreakpoint->mIsLinkedSibling)
  3055. {
  3056. mBreakpoints.Remove(wdBreakpoint);
  3057. }
  3058. if (wdBreakpoint->mLinkedSibling != NULL)
  3059. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  3060. delete wdBreakpoint;
  3061. }
  3062. void WinDebugger::DetachBreakpoint(Breakpoint* breakpoint)
  3063. {
  3064. AutoCrit autoCrit(mDebugManager->mCritSect);
  3065. BfLogDbg("WinDebugger::DetachBreakpoint %p\n", breakpoint);
  3066. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3067. if (wdBreakpoint->mAddr != 0)
  3068. {
  3069. mBreakpointAddrMap.Remove(wdBreakpoint->mAddr, wdBreakpoint);
  3070. RemoveBreakpoint(wdBreakpoint->mAddr);
  3071. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mIsAtBreakpointAddress == wdBreakpoint->mAddr))
  3072. mDebuggerWaitingThread->mIsAtBreakpointAddress = NULL;
  3073. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mBreakpointAddressContinuing == wdBreakpoint->mAddr))
  3074. mDebuggerWaitingThread->mBreakpointAddressContinuing = NULL;
  3075. wdBreakpoint->mLineData = DbgLineDataEx();
  3076. wdBreakpoint->mAddr = 0;
  3077. }
  3078. if (wdBreakpoint->mCondition != NULL)
  3079. {
  3080. delete wdBreakpoint->mCondition->mDbgEvaluationContext;
  3081. wdBreakpoint->mCondition->mDbgEvaluationContext = NULL;
  3082. }
  3083. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  3084. {
  3085. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  3086. {
  3087. if (mMemoryBreakpoints[memoryWatchSlot].mBreakpoint == wdBreakpoint)
  3088. {
  3089. mFreeMemoryBreakIndices.push_back(memoryWatchSlot);
  3090. mMemoryBreakpoints[memoryWatchSlot] = WdMemoryBreakpointBind();
  3091. UpdateThreadDebugRegisters();
  3092. }
  3093. }
  3094. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap = 0;
  3095. }
  3096. if (wdBreakpoint->mLinkedSibling != NULL)
  3097. {
  3098. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  3099. wdBreakpoint->mLinkedSibling = NULL;
  3100. }
  3101. wdBreakpoint->mSrcFile = NULL;
  3102. wdBreakpoint->mPendingHotBindIdx = -1;
  3103. }
  3104. void WinDebugger::MoveBreakpoint(Breakpoint* breakpoint, int lineNum, int wantColumn, bool rebindNow)
  3105. {
  3106. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3107. AutoCrit autoCrit(mDebugManager->mCritSect);
  3108. DetachBreakpoint(wdBreakpoint);
  3109. //TODO: This doesn't actually rebind correctly while the app is running
  3110. if ((lineNum != -1) && (wantColumn != -1))
  3111. {
  3112. wdBreakpoint->mRequestedLineNum = lineNum;
  3113. wdBreakpoint->mLineNum = lineNum;
  3114. wdBreakpoint->mColumn = wantColumn;
  3115. }
  3116. if (rebindNow)
  3117. CheckBreakpoint(wdBreakpoint);
  3118. }
  3119. void WinDebugger::MoveMemoryBreakpoint(Breakpoint* breakpoint, intptr addr, int byteCount)
  3120. {
  3121. AutoCrit autoCrit(mDebugManager->mCritSect);
  3122. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3123. DetachBreakpoint(wdBreakpoint);
  3124. wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress = addr;
  3125. wdBreakpoint->mMemoryBreakpointInfo->mByteCount = byteCount;
  3126. CheckBreakpoint(wdBreakpoint);
  3127. }
  3128. void WinDebugger::DisableBreakpoint(Breakpoint* breakpoint)
  3129. {
  3130. AutoCrit autoCrit(mDebugManager->mCritSect);
  3131. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3132. DetachBreakpoint(wdBreakpoint);
  3133. delete wdBreakpoint->mMemoryBreakpointInfo;
  3134. wdBreakpoint->mMemoryBreakpointInfo = NULL;
  3135. }
  3136. void WinDebugger::SetBreakpointCondition(Breakpoint* breakpoint, const StringImpl& conditionExpr)
  3137. {
  3138. AutoCrit autoCrit(mDebugManager->mCritSect);
  3139. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3140. BF_ASSERT(!wdBreakpoint->mIsLinkedSibling);
  3141. if (conditionExpr.empty())
  3142. {
  3143. delete wdBreakpoint->mCondition;
  3144. WdBreakpoint* curBreakpoint = wdBreakpoint;
  3145. wdBreakpoint->mCondition = NULL;
  3146. }
  3147. else
  3148. {
  3149. delete wdBreakpoint->mCondition;
  3150. auto condition = new WdBreakpointCondition();
  3151. condition->mExpr = conditionExpr;
  3152. wdBreakpoint->mCondition = condition;
  3153. }
  3154. }
  3155. void WinDebugger::SetBreakpointLogging(Breakpoint* breakpoint, const StringImpl& logging, bool breakAfterLogging)
  3156. {
  3157. AutoCrit autoCrit(mDebugManager->mCritSect);
  3158. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3159. BF_ASSERT(!wdBreakpoint->mIsLinkedSibling);
  3160. wdBreakpoint->mLogging = logging;
  3161. wdBreakpoint->mBreakAfterLogging = breakAfterLogging;
  3162. }
  3163. bool WinDebugger::CheckConditionalBreakpoint(WdBreakpoint* breakpoint, DbgSubprogram* dbgSubprogram, addr_target pcAddress)
  3164. {
  3165. // What was this assertion for?
  3166. //BF_ASSERT(mCallStack.size() == 0);
  3167. auto headBreakpoint = breakpoint->GetHeadBreakpoint();
  3168. if (headBreakpoint->mThreadId != -1)
  3169. {
  3170. if ((mActiveThread != NULL) && (mActiveThread->mThreadId != headBreakpoint->mThreadId))
  3171. return false;
  3172. }
  3173. auto _SplitExpr = [&](const StringImpl& expr, StringImpl& outExpr, StringImpl& outSubject)
  3174. {
  3175. int crPos = expr.IndexOf('\n');
  3176. if (crPos != -1)
  3177. {
  3178. outExpr += expr.Substring(0, crPos);
  3179. outSubject += expr.Substring(crPos + 1);
  3180. }
  3181. else
  3182. {
  3183. outExpr += expr;
  3184. }
  3185. };
  3186. if (headBreakpoint->mCondition != NULL)
  3187. {
  3188. ClearCallStack();
  3189. auto conditional = headBreakpoint->mCondition;
  3190. if (conditional->mDbgEvaluationContext == NULL)
  3191. {
  3192. CPURegisters registers;
  3193. PopulateRegisters(&registers);
  3194. auto pcAddress = registers.GetPC();
  3195. DbgSubprogram* subprogram = mDebugTarget->FindSubProgram(pcAddress);
  3196. if (subprogram == NULL)
  3197. {
  3198. return false;
  3199. }
  3200. StringT<256> expr;
  3201. StringT<256> subjectExpr;
  3202. if (breakpoint->mMemoryBreakpointInfo != NULL)
  3203. {
  3204. subjectExpr += "*";
  3205. }
  3206. _SplitExpr(conditional->mExpr, expr, subjectExpr);
  3207. DbgLanguage language = DbgLanguage_Unknown;
  3208. if (expr.StartsWith("@Beef:"))
  3209. {
  3210. expr.Remove(0, 6);
  3211. language = DbgLanguage_Beef;
  3212. }
  3213. else if (expr.StartsWith("@C:"))
  3214. {
  3215. expr.Remove(0, 3);
  3216. language = DbgLanguage_C;
  3217. }
  3218. conditional->mDbgEvaluationContext = new DbgEvaluationContext(this, subprogram->mCompileUnit->mDbgModule, expr);
  3219. if (language != DbgLanguage_Unknown)
  3220. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mLanguage = language;
  3221. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mSubjectExpr = subjectExpr;
  3222. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mDbgCompileUnit = subprogram->mCompileUnit;
  3223. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mCallStackIdx = 0;
  3224. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mExpressionFlags = (DwEvalExpressionFlags)(DwEvalExpressionFlag_AllowSideEffects);
  3225. }
  3226. WdStackFrame* wdStackFrame = new WdStackFrame();
  3227. PopulateRegisters(&wdStackFrame->mRegisters);
  3228. mCallStack.Add(wdStackFrame);
  3229. DbgTypedValue result = conditional->mDbgEvaluationContext->EvaluateInContext(DbgTypedValue());
  3230. ClearCallStack();
  3231. if ((result.mType != NULL) && (result.mType->mTypeCode == DbgType_Bitfield))
  3232. result.mType = result.mType->mTypeParam;
  3233. if (conditional->mDbgEvaluationContext->mPassInstance->HasFailed())
  3234. {
  3235. String errorStr = "FAILED";
  3236. for (auto error : conditional->mDbgEvaluationContext->mPassInstance->mErrors)
  3237. {
  3238. if (!error->mIsWarning)
  3239. errorStr = error->mError;
  3240. }
  3241. String condError = StrFormat("error Conditional breakpoint expression '%s' failed: %s", conditional->mExpr.c_str(), errorStr.c_str());
  3242. mDebugManager->mOutMessages.push_back(condError);
  3243. return true;
  3244. }
  3245. else if (conditional->mDbgEvaluationContext->mDbgExprEvaluator->mBlockedSideEffects)
  3246. {
  3247. mDebugManager->mOutMessages.push_back(StrFormat("error Conditional breakpoint expression '%s' contained function calls, which is not allowed", conditional->mExpr.c_str()));
  3248. return true;
  3249. }
  3250. else if ((!result) || (!result.mType->IsBoolean()))
  3251. {
  3252. mDebugManager->mOutMessages.push_back(StrFormat("error Conditional breakpoint expression '%s' must result in a boolean value", conditional->mExpr.c_str()));
  3253. return true;
  3254. }
  3255. else if (!result.mBool)
  3256. return false;
  3257. }
  3258. headBreakpoint->mHitCount++;
  3259. switch (headBreakpoint->mHitCountBreakKind)
  3260. {
  3261. case DbgHitCountBreakKind_Equals:
  3262. if (headBreakpoint->mHitCount != headBreakpoint->mTargetHitCount)
  3263. return false;
  3264. break;
  3265. case DbgHitCountBreakKind_GreaterEquals:
  3266. if (headBreakpoint->mHitCount < headBreakpoint->mTargetHitCount)
  3267. return false;
  3268. break;
  3269. case DbgHitCountBreakKind_Multiple:
  3270. if ((headBreakpoint->mHitCount % headBreakpoint->mTargetHitCount) != 0)
  3271. return false;
  3272. break;
  3273. }
  3274. mActiveBreakpoint = breakpoint;
  3275. mBreakStackFrameIdx = -1;
  3276. if (!headBreakpoint->mLogging.IsEmpty())
  3277. {
  3278. ClearCallStack();
  3279. DwFormatInfo formatInfo;
  3280. formatInfo.mCallStackIdx = 0;
  3281. DbgCompileUnit* dbgCompileUnit = NULL;
  3282. if (dbgSubprogram == NULL)
  3283. dbgSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3284. if (dbgSubprogram != NULL)
  3285. {
  3286. dbgCompileUnit = dbgSubprogram->mCompileUnit;
  3287. formatInfo.mLanguage = dbgSubprogram->GetLanguage();
  3288. }
  3289. auto prevRunState = mRunState;
  3290. mRunState = RunState_Paused; // We need to be paused to avoid certain errors in the eval
  3291. String displayString;
  3292. String expr;
  3293. _SplitExpr(headBreakpoint->mLogging, expr, formatInfo.mSubjectExpr);
  3294. if (expr.StartsWith("@Beef:"))
  3295. {
  3296. expr.Remove(0, 6);
  3297. formatInfo.mLanguage = DbgLanguage_Beef;
  3298. }
  3299. else if (expr.StartsWith("@C:"))
  3300. {
  3301. expr.Remove(0, 3);
  3302. formatInfo.mLanguage = DbgLanguage_C;
  3303. }
  3304. ProcessEvalString(dbgCompileUnit, DbgTypedValue(), expr, displayString, formatInfo, NULL, false);
  3305. mRunState = prevRunState;
  3306. displayString.Insert(0, "log ");
  3307. displayString.Append("\n");
  3308. mDebugManager->mOutMessages.push_back(displayString);
  3309. if (!headBreakpoint->mBreakAfterLogging)
  3310. return false;
  3311. }
  3312. return true;
  3313. }
  3314. void WinDebugger::CleanupDebugEval(bool restoreRegisters)
  3315. {
  3316. BfLogDbg("CleanupDebugEval ThreadId=%d\n", mDebugEvalThreadInfo.mThreadId);
  3317. WdThreadInfo* evalThreadInfo = NULL;
  3318. if (mThreadMap.TryGetValue(mDebugEvalThreadInfo.mThreadId, &evalThreadInfo))
  3319. {
  3320. if ((restoreRegisters) && (!mDbgBreak))
  3321. {
  3322. SetAndRestoreValue<WdThreadInfo*> activeThread(mActiveThread, evalThreadInfo);
  3323. RestoreAllRegisters();
  3324. // if (mRunState == RunState_Running_ToTempBreakpoint)
  3325. // mRunState = RunState_Paused;
  3326. }
  3327. evalThreadInfo->mStartSP = mDebugEvalThreadInfo.mStartSP;
  3328. evalThreadInfo->mStoppedAtAddress = mDebugEvalThreadInfo.mStoppedAtAddress;
  3329. evalThreadInfo->mIsAtBreakpointAddress = mDebugEvalThreadInfo.mIsAtBreakpointAddress;
  3330. evalThreadInfo->mBreakpointAddressContinuing = mDebugEvalThreadInfo.mBreakpointAddressContinuing;
  3331. }
  3332. delete mDebugPendingExpr;
  3333. mDebugPendingExpr = NULL;
  3334. mDebugEvalThreadInfo = WdThreadInfo();
  3335. OutputRawMessage("rehupLoc");
  3336. }
  3337. bool WinDebugger::FixCallStackIdx(int& callStackIdx)
  3338. {
  3339. callStackIdx = BF_MAX(callStackIdx, 0);
  3340. if (mCallStack.IsEmpty())
  3341. UpdateCallStack();
  3342. int stackSize = (int)mCallStack.size();
  3343. while (callStackIdx >= mCallStack.size())
  3344. {
  3345. UpdateCallStack();
  3346. if (stackSize == (int)mCallStack.size())
  3347. break; // Didn't change
  3348. stackSize = (int)mCallStack.size();
  3349. }
  3350. if (callStackIdx >= stackSize)
  3351. {
  3352. callStackIdx = 0;
  3353. return false;
  3354. }
  3355. return true;
  3356. }
  3357. bool WinDebugger::HasLineInfoAt(addr_target address)
  3358. {
  3359. BP_ZONE("WinDebugger::HasLineInfoAt");
  3360. DbgSubprogram* dbgSubprogram = NULL;
  3361. auto dwLineData = FindLineDataAtAddress(address, &dbgSubprogram);
  3362. return (dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dbgSubprogram->GetLineAddr(*dwLineData) == address);
  3363. }
  3364. void WinDebugger::StepLineTryPause(addr_target address, bool requireExactMatch)
  3365. {
  3366. if (mStepInAssembly)
  3367. return;
  3368. if (mStepLineData.mLineData != NULL)
  3369. {
  3370. DbgSubprogram* dbgSubprogram = NULL;
  3371. DbgSrcFile* dbgSrcFile = NULL;
  3372. auto dwLineData = FindLineDataAtAddress(address, &dbgSubprogram, &dbgSrcFile);
  3373. if ((dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && ((!requireExactMatch) || (dbgSubprogram->GetLineAddr(*dwLineData) == address)))
  3374. {
  3375. // "Invalid" line
  3376. if (dwLineData->mColumn == -1)
  3377. {
  3378. SetupStep(mStepType);
  3379. mRunState = RunState_Running;
  3380. return;
  3381. }
  3382. // If we're on the same line but a different column or a <= address then keep it keep looking
  3383. if ((dbgSrcFile == mStepLineData.GetSrcFile()) &&
  3384. ((!requireExactMatch) || (dwLineData != mStepLineData.mLineData) || (address <= mStepStartPC)) &&
  3385. (dwLineData->mLine == mStepLineData.mLineData->mLine))
  3386. {
  3387. SetupStep(mStepType);
  3388. mRunState = RunState_Running;
  3389. return;
  3390. }
  3391. }
  3392. }
  3393. mRunState = RunState_Paused;
  3394. }
  3395. void WinDebugger::BreakAll()
  3396. {
  3397. AutoCrit autoCrit(mDebugManager->mCritSect);
  3398. ::DebugBreakProcess(mProcessInfo.hProcess);
  3399. }
  3400. void WinDebugger::StepInto(bool inAssembly)
  3401. {
  3402. AutoCrit autoCrit(mDebugManager->mCritSect);
  3403. if (!TryRunContinue())
  3404. return;
  3405. BfLogDbg("StepInto\n");
  3406. mCurNoInfoStepTries = 0; // Reset
  3407. mStepInAssembly = inAssembly;
  3408. SetupStep(StepType_StepInto);
  3409. ContinueDebugEvent();
  3410. }
  3411. void WinDebugger::StepIntoSpecific(intptr inAddr)
  3412. {
  3413. addr_target addr = (addr_target)inAddr;
  3414. AutoCrit autoCrit(mDebugManager->mCritSect);
  3415. if (!TryRunContinue())
  3416. return;
  3417. BfLogDbg("StepIntoSpecific %p\n", addr);
  3418. mCurNoInfoStepTries = 0; // Reset
  3419. mStepInAssembly = false;
  3420. SetupStep(StepType_StepInto);
  3421. mIsStepIntoSpecific = true;
  3422. mStepType = StepType_StepInto_Unfiltered;
  3423. if (mStepStartPC != addr)
  3424. {
  3425. RemoveTempBreakpoints();
  3426. SetTempBreakpoint(addr);
  3427. mStepBreakpointAddrs.push_back(addr);
  3428. }
  3429. ContinueDebugEvent();
  3430. }
  3431. void WinDebugger::PushValue(CPURegisters* registers, int64 val)
  3432. {
  3433. addr_target* regSP = registers->GetSPRegisterRef();
  3434. *regSP -= sizeof(addr_target);
  3435. WriteMemory<addr_target>(*regSP, (addr_target)val);
  3436. }
  3437. void WinDebugger::PushValue(CPURegisters* registers, const DbgTypedValue& typedValue)
  3438. {
  3439. addr_target* regSP = registers->GetSPRegisterRef();
  3440. int byteCount = typedValue.mType->GetByteCount();
  3441. if ((byteCount == 8) || (sizeof(addr_target) == 8))
  3442. {
  3443. *regSP -= sizeof(int64);
  3444. addr_target val = typedValue.mInt64;
  3445. if (typedValue.mType->IsCompositeType())
  3446. val = typedValue.mSrcAddress;
  3447. WriteMemory<int64>(*regSP, val);
  3448. }
  3449. else
  3450. {
  3451. *regSP -= sizeof(int32);
  3452. addr_target val = typedValue.mInt32;
  3453. if (typedValue.mType->IsCompositeType())
  3454. val = typedValue.mSrcAddress;
  3455. WriteMemory<int32>(*regSP, val);
  3456. }
  3457. }
  3458. void WinDebugger::SetThisRegister(CPURegisters* registers, addr_target val)
  3459. {
  3460. #if BF_DBG_32
  3461. registers->mIntRegs.ecx = val;
  3462. #else
  3463. registers->mIntRegs.rcx = val;
  3464. #endif
  3465. }
  3466. void WinDebugger::AddParamValue(int paramIdx, bool hadThis, CPURegisters* registers, const DbgTypedValue& typedValue)
  3467. {
  3468. #if BF_DBG_32
  3469. PushValue(registers, typedValue);
  3470. #else
  3471. int regIdx = paramIdx + (hadThis ? 1 : 0);
  3472. if (typedValue.mType->IsFloat())
  3473. {
  3474. PushValue(registers, typedValue);
  3475. if (regIdx < 4)
  3476. {
  3477. if (typedValue.mType->mTypeCode == DbgType_Single)
  3478. {
  3479. registers->mXmmRegsArray[regIdx].f[0] = typedValue.mSingle;
  3480. }
  3481. else
  3482. {
  3483. registers->mXmmDRegsArray[regIdx].d[0] = typedValue.mDouble;
  3484. }
  3485. }
  3486. }
  3487. else
  3488. {
  3489. PushValue(registers, typedValue);
  3490. if (regIdx < 4)
  3491. {
  3492. int64 val;
  3493. if (typedValue.mType->IsCompositeType())
  3494. val = typedValue.mSrcAddress;
  3495. else
  3496. val = typedValue.mPtr;
  3497. if (regIdx == 0)
  3498. registers->mIntRegs.rcx = val;
  3499. else if (regIdx == 1)
  3500. registers->mIntRegs.rdx = val;
  3501. else if (regIdx == 2)
  3502. registers->mIntRegs.r8 = val;
  3503. else if (regIdx == 3)
  3504. registers->mIntRegs.r9 = val;
  3505. }
  3506. }
  3507. #endif
  3508. }
  3509. bool WinDebugger::CheckNeedsSRetArgument(DbgType* retType)
  3510. {
  3511. if (!retType->IsCompositeType())
  3512. return false;
  3513. //TODO: Change when we change the calling convention
  3514. if (retType->GetLanguage() == DbgLanguage_Beef)
  3515. return true;
  3516. int retSize = retType->GetByteCount();
  3517. //TODO: Check for 'POD' type?
  3518. if ((retSize == 1) || (retSize == 2) || (retSize == 4) || (retSize == sizeof(addr_target)))
  3519. return false;
  3520. return true;
  3521. }
  3522. DbgTypedValue WinDebugger::ReadReturnValue(CPURegisters* registers, DbgType* type)
  3523. {
  3524. DbgTypedValue retValue;
  3525. if (type->IsFloat())
  3526. {
  3527. retValue.mType = type;
  3528. #if BF_DBG_32
  3529. retValue.mDouble = ConvertFloat80ToDouble(registers->mFpMmRegsArray[0].fp.fp80);
  3530. if (type->mSize == 4)
  3531. retValue.mSingle = (float)retValue.mDouble;
  3532. #else
  3533. if (retValue.mType->mTypeCode == DbgType_Single)
  3534. retValue.mSingle = registers->mXmmRegsArray[0].f[0];
  3535. else
  3536. retValue.mDouble = registers->mXmmDRegsArray[0].d[0];
  3537. #endif
  3538. }
  3539. else if (type->IsCompositeType())
  3540. {
  3541. retValue.mType = type;
  3542. if (CheckNeedsSRetArgument(type))
  3543. {
  3544. #ifdef BF_DBG_32
  3545. retValue.mSrcAddress = mSavedContext.Esp - BF_ALIGN(type->GetByteCount(), 16);
  3546. #else
  3547. retValue.mSrcAddress = mSavedContext.Rsp - BF_ALIGN(type->GetByteCount(), 16);
  3548. #endif
  3549. }
  3550. else
  3551. {
  3552. #ifdef BF_DBG_32
  3553. retValue.mInt32 = mSavedContext.Eax;
  3554. #else
  3555. retValue.mInt64 = mSavedContext.Rax;
  3556. #endif
  3557. }
  3558. }
  3559. else
  3560. {
  3561. #ifdef BF_DBG_32
  3562. retValue.mType = type;
  3563. retValue.mInt32 = registers->mIntRegs.eax;
  3564. if (type->mSize == 8)
  3565. (&retValue.mInt32)[1] = registers->mIntRegs.edx;
  3566. #else
  3567. retValue.mType = type;
  3568. retValue.mInt64 = registers->mIntRegs.rax;
  3569. #endif
  3570. return retValue;
  3571. }
  3572. return retValue;
  3573. }
  3574. bool WinDebugger::SetRegisters(CPURegisters* registers)
  3575. {
  3576. BF_CONTEXT lcContext;
  3577. lcContext.ContextFlags = BF_CONTEXT_CONTROL | BF_CONTEXT_INTEGER | BF_CONTEXT_FLOATING_POINT | BF_CONTEXT_EXTENDED_REGISTERS | BF_CONTEXT_SEGMENTS;
  3578. lcContext.ContextFlags |= BF_CONTEXT_EXCEPTION_REQUEST;
  3579. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  3580. #ifdef BF_DBG_32
  3581. lcContext.Eax = registers->mIntRegs.eax;
  3582. lcContext.Ecx = registers->mIntRegs.ecx;
  3583. lcContext.Edx = registers->mIntRegs.edx;
  3584. lcContext.Ebx = registers->mIntRegs.ebx;
  3585. lcContext.Esp = registers->mIntRegs.esp;
  3586. lcContext.Ebp = registers->mIntRegs.ebp;
  3587. lcContext.Esi = registers->mIntRegs.esi;
  3588. lcContext.Edi = registers->mIntRegs.edi;
  3589. lcContext.Eip = registers->mIntRegs.eip;
  3590. lcContext.EFlags = registers->mIntRegs.efl;
  3591. BF_ASSERT(sizeof(lcContext.FloatSave.RegisterArea) == sizeof(registers->mFpMmRegsArray));
  3592. memcpy(lcContext.FloatSave.RegisterArea, registers->mFpMmRegsArray, sizeof(lcContext.FloatSave.RegisterArea));
  3593. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 32*sizeof(float));
  3594. memcpy(&lcContext.ExtendedRegisters[160], registers->mXmmRegsArray, sizeof(registers->mXmmRegsArray));
  3595. #else
  3596. lcContext.Rax = registers->mIntRegs.rax;
  3597. lcContext.Rcx = registers->mIntRegs.rcx;
  3598. lcContext.Rdx = registers->mIntRegs.rdx;
  3599. lcContext.Rbx = registers->mIntRegs.rbx;
  3600. lcContext.Rsp = registers->mIntRegs.rsp;
  3601. lcContext.Rbp = registers->mIntRegs.rbp;
  3602. lcContext.Rsi = registers->mIntRegs.rsi;
  3603. lcContext.Rdi = registers->mIntRegs.rdi;
  3604. lcContext.Rip = registers->mIntRegs.rip;
  3605. lcContext.EFlags = (DWORD)registers->mIntRegs.efl;
  3606. lcContext.R8 = registers->mIntRegs.r8;
  3607. lcContext.R9 = registers->mIntRegs.r9;
  3608. lcContext.R10 = registers->mIntRegs.r10;
  3609. lcContext.R11 = registers->mIntRegs.r11;
  3610. lcContext.R12 = registers->mIntRegs.r12;
  3611. lcContext.R13 = registers->mIntRegs.r13;
  3612. lcContext.R14 = registers->mIntRegs.r14;
  3613. lcContext.R15 = registers->mIntRegs.r15;
  3614. for (int i = 0; i < 8; i++)
  3615. {
  3616. memcpy(&lcContext.FltSave.FloatRegisters[i], &registers->mFpMmRegsArray[i], 10);
  3617. }
  3618. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 64 * sizeof(float));
  3619. memcpy(BF_CONTEXT_XMMDATA(lcContext), registers->mXmmRegsArray, sizeof(registers->mXmmRegsArray));
  3620. #endif
  3621. //lcContext.ContextFlags |= BF_CONTEXT_EXCEPTION_REQUEST;
  3622. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  3623. return (lcContext.ContextFlags & (BF_CONTEXT_EXCEPTION_ACTIVE | BF_CONTEXT_SERVICE_ACTIVE)) == 0;
  3624. }
  3625. void WinDebugger::SaveAllRegisters()
  3626. {
  3627. BfLogDbg("SaveAllRegisters setting mSavedAtBreakpointAddress = %p\n", mActiveThread->mIsAtBreakpointAddress);
  3628. mSavedAtBreakpointAddress = mActiveThread->mIsAtBreakpointAddress;
  3629. mSavedBreakpointAddressContinuing = mActiveThread->mBreakpointAddressContinuing;
  3630. mSavedContext.ContextFlags = BF_CONTEXT_ALL;
  3631. BF_GetThreadContext(mActiveThread->mHThread, &mSavedContext);
  3632. }
  3633. void WinDebugger::RestoreAllRegisters()
  3634. {
  3635. BfLogDbg("RestoreAllRegisters setting mIsAtBreakpointAddress = %p\n", mSavedAtBreakpointAddress);
  3636. mActiveThread->mIsAtBreakpointAddress = mSavedAtBreakpointAddress;
  3637. mActiveThread->mBreakpointAddressContinuing = mSavedBreakpointAddressContinuing;
  3638. BF_SetThreadContext(mActiveThread->mHThread, &mSavedContext);
  3639. #ifdef BF_DBG_32
  3640. //TODO: Find the test that this was required for...
  3641. // if (mActiveThread->mIsAtBreakpointAddress == mSavedContext.Eip)
  3642. // {
  3643. // if (mRunState == RunState_Running_ToTempBreakpoint)
  3644. // mRunState = RunState_Paused;
  3645. // }
  3646. // else
  3647. // {
  3648. // SetTempBreakpoint(mSavedContext.Eip);
  3649. // mRunState = RunState_Running_ToTempBreakpoint;
  3650. // mStepType = StepType_ToTempBreakpoint;
  3651. // mSteppingThread = mActiveThread;
  3652. // }
  3653. #endif
  3654. }
  3655. void WinDebugger::OutputMessage(const StringImpl& msg)
  3656. {
  3657. if (this == NULL)
  3658. return;
  3659. AutoCrit autoCrit(mDebugManager->mCritSect);
  3660. mDebugManager->mOutMessages.push_back("msg " + msg);
  3661. }
  3662. void WinDebugger::OutputRawMessage(const StringImpl& msg)
  3663. {
  3664. if (this == NULL)
  3665. return;
  3666. AutoCrit autoCrit(mDebugManager->mCritSect);
  3667. mDebugManager->mOutMessages.push_back(msg);
  3668. }
  3669. void WinDebugger::SetRunState(RunState runState)
  3670. {
  3671. mRunState = runState;
  3672. }
  3673. bool WinDebugger::TryRunContinue()
  3674. {
  3675. if (mRunState == RunState_Exception)
  3676. {
  3677. mIsContinuingFromException = true;
  3678. mRunState = RunState_Paused;
  3679. }
  3680. if (((mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint)) && (mNeedsRehupBreakpoints))
  3681. RehupBreakpoints(true);
  3682. return true;
  3683. }
  3684. void WinDebugger::ClearStep()
  3685. {
  3686. BfLogDbg("ClearStep\n");
  3687. RemoveTempBreakpoints();
  3688. mOrigStepType = StepType_None;
  3689. mStepType = StepType_None;
  3690. mStepStartPC = 0;
  3691. mStepSP = 0;
  3692. mStepPC = 0;
  3693. mIsStepIntoSpecific = false;
  3694. mStepIsRecursing = false;
  3695. mStepStopOnNextInstruction = false;
  3696. mStepLineData = DbgLineDataEx();
  3697. }
  3698. bool WinDebugger::SetupStep(StepType stepType)
  3699. {
  3700. BP_ZONE("SetupStep");
  3701. RemoveTempBreakpoints();
  3702. if (mNeedsRehupBreakpoints)
  3703. RehupBreakpoints(true);
  3704. if (mOrigStepType == StepType_None)
  3705. mOrigStepType = stepType;
  3706. mStepType = stepType;
  3707. mSteppingThread = mActiveThread;
  3708. mStepSwitchedThreads = false;
  3709. mContinueFromBreakpointFailed = false;
  3710. CPURegisters registers;
  3711. PopulateRegisters(&registers);
  3712. addr_target pcAddress = registers.GetPC();
  3713. if (mStepLineData.IsNull())
  3714. {
  3715. DbgSubprogram* dbgSubprogram = NULL;
  3716. auto dbgLineData = FindLineDataAtAddress(pcAddress, &dbgSubprogram);
  3717. mStepLineData = DbgLineDataEx(dbgLineData, dbgSubprogram);
  3718. mStepStartPC = registers.GetPC();
  3719. }
  3720. bool isDeeper = mStepSP > registers.GetSP();
  3721. 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);
  3722. mStepSP = registers.GetSP();
  3723. mStepPC = registers.GetPC();
  3724. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_NoFrame) || (mStepType == StepType_StepOut_ThenInto))
  3725. {
  3726. if (mStepType != StepType_StepOut_NoFrame)
  3727. {
  3728. // Test for stepping out of an inline method
  3729. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3730. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL))
  3731. {
  3732. DbgSubprogram* topSubprogram = dwSubprogram->GetRootInlineParent();
  3733. if ((mOrigStepType == StepType_StepInto) || (mOrigStepType == StepType_StepInto_Unfiltered))
  3734. {
  3735. mStepType = mOrigStepType;
  3736. }
  3737. else
  3738. {
  3739. mStepType = StepType_StepOut_Inline;
  3740. // Set up pcAddress to detect recursion
  3741. //TODO: We can't set a physical breakpoint here because we will immediately hit it when attempting to step over an inlined method.
  3742. // An inlined method can't recurse anyway, but store the pcAddress in mTempBreakpoints because we still check that for recursion
  3743. // SetTempBreakpoint(pcAddress);
  3744. //mTempBreakpoint.push_back(pcAddress);
  3745. mStepBreakpointAddrs.push_back(pcAddress);
  3746. }
  3747. addr_target endAddress = dwSubprogram->mBlock.mHighPC;
  3748. if (dwSubprogram->mHasLineAddrGaps)
  3749. {
  3750. // Keep bumping out the address as long as we can find lines that contain the nextPC
  3751. addr_target nextAddr = pcAddress;
  3752. for (auto& lineInfo : topSubprogram->mLineInfo->mLines)
  3753. {
  3754. auto lineAddr = topSubprogram->GetLineAddr(lineInfo);
  3755. if ((nextAddr >= lineAddr) && (nextAddr < lineAddr + lineInfo.mContribSize))
  3756. {
  3757. auto ctx = topSubprogram->mLineInfo->mContexts[lineInfo.mCtxIdx];
  3758. if (ctx.mInlinee == dwSubprogram)
  3759. {
  3760. nextAddr = lineAddr + lineInfo.mContribSize;
  3761. }
  3762. }
  3763. }
  3764. if (nextAddr != pcAddress)
  3765. endAddress = nextAddr;
  3766. }
  3767. BfLogDbg("Stepping out of inlined method, end address: %p\n", endAddress);
  3768. SetTempBreakpoint(endAddress);
  3769. mStepBreakpointAddrs.push_back(endAddress);
  3770. addr_target decodeAddress = dwSubprogram->mBlock.mLowPC;
  3771. while (decodeAddress < endAddress)
  3772. {
  3773. CPUInst inst;
  3774. if (!mDebugTarget->DecodeInstruction(decodeAddress, &inst))
  3775. break;
  3776. addr_target targetAddress = inst.GetTarget();
  3777. // We need to find a targetAddress
  3778. if ((targetAddress != 0) &&
  3779. !((targetAddress >= dwSubprogram->mBlock.mLowPC) && (targetAddress < dwSubprogram->mBlock.mHighPC)) &&
  3780. ((targetAddress >= topSubprogram->mBlock.mLowPC) && (targetAddress < topSubprogram->mBlock.mHighPC)))
  3781. {
  3782. BfLogDbg("Stepping out of inlined method, branch address: %p\n", targetAddress);
  3783. SetTempBreakpoint(targetAddress);
  3784. mStepBreakpointAddrs.push_back(targetAddress);
  3785. }
  3786. decodeAddress += inst.GetLength();
  3787. }
  3788. return true;
  3789. }
  3790. }
  3791. if ((mStepType != StepType_StepOut_NoFrame) && (RollBackStackFrame(&registers, true)))
  3792. {
  3793. bool isStackAdjust = false;
  3794. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3795. if (dwSubprogram != NULL)
  3796. {
  3797. if ((strcmp(dwSubprogram->mName, "_chkstk") == 0) ||
  3798. (strcmp(dwSubprogram->mName, "__chkstk") == 0) ||
  3799. (strcmp(dwSubprogram->mName, "_alloca_probe") == 0))
  3800. isStackAdjust = true;
  3801. }
  3802. pcAddress = registers.GetPC();
  3803. if (isStackAdjust)
  3804. {
  3805. // We set it to zero so we never detect an "isDeeper" condition which would skip over the return-location breakpoint
  3806. mStepSP = 0;
  3807. }
  3808. else
  3809. {
  3810. addr_target oldAddress = pcAddress;
  3811. CPUInst inst;
  3812. while (true)
  3813. {
  3814. if (mStepInAssembly)
  3815. break;
  3816. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  3817. break;
  3818. if ((inst.IsBranch()) || (inst.IsCall()) || (inst.IsReturn()))
  3819. break;
  3820. #ifdef BF_DBG_32
  3821. if (!inst.StackAdjust(mStepSP))
  3822. break;
  3823. #endif
  3824. DbgSubprogram* checkSubprogram = NULL;
  3825. auto checkLineData = FindLineDataAtAddress(pcAddress, &checkSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  3826. if (checkLineData == NULL)
  3827. break;
  3828. if (checkSubprogram->GetLineAddr(*checkLineData) == pcAddress)
  3829. break;
  3830. pcAddress += inst.GetLength();
  3831. }
  3832. if (pcAddress != oldAddress)
  3833. {
  3834. BfLogDbg("Adjusting stepout address from %p to %p\n", oldAddress, pcAddress);
  3835. }
  3836. }
  3837. BfLogDbg("SetupStep Stepout SetTempBreakpoint %p\n", pcAddress);
  3838. SetTempBreakpoint(pcAddress);
  3839. mStepBreakpointAddrs.push_back(pcAddress);
  3840. if (mStepType != StepType_StepOut_ThenInto)
  3841. mStepType = StepType_StepOut;
  3842. }
  3843. else
  3844. {
  3845. // Try to handle the case where we just entered this call so the return address is the first entry on the stack
  3846. addr_target* regSP = registers.GetSPRegisterRef();
  3847. pcAddress = ReadMemory<addr_target>(*regSP);
  3848. *regSP += sizeof(addr_target);
  3849. if (mDebugTarget->FindSubProgram(pcAddress) != NULL)
  3850. {
  3851. BfLogDbg("SetupStep Stepout SetTempBreakpoint (2) %p\n", pcAddress);
  3852. SetTempBreakpoint(pcAddress);
  3853. mStepBreakpointAddrs.push_back(pcAddress);
  3854. if (mOrigStepType == StepType_StepInto)
  3855. mStepType = StepType_StepInto;
  3856. else
  3857. mStepType = StepType_StepOver;
  3858. return true;
  3859. }
  3860. else
  3861. {
  3862. // Just do stepovers until we eventually step out
  3863. //BF_DBG_FATAL("StepOut Failed");
  3864. BfLogDbg("StepOut Failed\n");
  3865. if (mLastValidStepIntoPC != 0)
  3866. {
  3867. BfLogDbg("Using mLastValidStepIntoPC: %p\n", mLastValidStepIntoPC);
  3868. if (mOrigStepType == StepType_StepInto)
  3869. mStepType = StepType_StepInto;
  3870. else
  3871. mStepType = StepType_StepOver;
  3872. SetTempBreakpoint(mLastValidStepIntoPC);
  3873. mStepBreakpointAddrs.push_back(0);
  3874. mStepBreakpointAddrs.push_back(mLastValidStepIntoPC);
  3875. mLastValidStepIntoPC = 0;
  3876. return true;
  3877. }
  3878. else
  3879. {
  3880. BfLogDbg("Stopping");
  3881. mStepType = StepType_None;
  3882. mRunState = RunState_Paused;
  3883. return true;
  3884. }
  3885. }
  3886. }
  3887. }
  3888. if ((mStepType != StepType_StepOut) && (mStepType != StepType_StepOut_ThenInto))
  3889. {
  3890. if (mDebuggerWaitingThread != mSteppingThread)
  3891. {
  3892. // We've switched threads, so there's a possible race condition:
  3893. // This new thread may already have an EXCEPTION_BREAKPOINT queued up so the PC is actually
  3894. // located one byte past the BREAK instruction, which is one byte into whatever instruction
  3895. // was previously there. We can't insert normal BREAK instructions because we don't know
  3896. // if the current PC is actually at an instruction start, so we do a single step with a
  3897. // slower stack call check to see if we need to step out after a "step over"
  3898. BfLogDbg("Step - switched threads mIsAtBreakpointAddress:%p\n", mSteppingThread->mIsAtBreakpointAddress);
  3899. mStepSwitchedThreads = true;
  3900. SingleStepX86();
  3901. return true;
  3902. }
  3903. bool breakOnNext = false;
  3904. int instIdx = 0;
  3905. for (instIdx = 0; true; instIdx++)
  3906. {
  3907. bool isAtLine = false;
  3908. DbgSubprogram* dwSubprogram = NULL;
  3909. auto dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  3910. isAtLine = (instIdx > 0) && (dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dwSubprogram->GetLineAddr(*dwLineData) == pcAddress);
  3911. // "Never step into" line
  3912. if ((dwLineData != NULL) && (dwLineData->mColumn == -2) && (stepType == StepType_StepInto))
  3913. stepType = StepType_StepOver;
  3914. CPUInst inst;
  3915. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  3916. {
  3917. BfLogDbg("Decode failed, set up SingleStepX86 %p\n", pcAddress);
  3918. SingleStepX86();
  3919. mStepStopOnNextInstruction = true;
  3920. return true;
  3921. }
  3922. if (instIdx > 256)
  3923. {
  3924. BfLogDbg("Too many SetupStep iterations");
  3925. breakOnNext = true;
  3926. }
  3927. if ((inst.IsReturn()) && (instIdx == 0) && (!mStepInAssembly))
  3928. {
  3929. // Do actual STEP OUT so we set up proper "stepping over unimportant post-return instructions"
  3930. if (stepType == StepType_StepInto)
  3931. return SetupStep(StepType_StepOut_ThenInto);
  3932. else
  3933. return SetupStep(StepType_StepOut);
  3934. }
  3935. if ((breakOnNext) || (mStepInAssembly) || (isAtLine) || (inst.IsBranch()) || (inst.IsCall()) || (inst.IsReturn()))
  3936. {
  3937. if (((instIdx == 0) || (mStepInAssembly)) && (!breakOnNext))
  3938. {
  3939. if ((stepType == StepType_StepOver) && (inst.IsCall()))
  3940. {
  3941. // Continue - sets a breakpoint on the call line to detect recursion.
  3942. // The next loop through will set a breakpoint on the line after the return
  3943. BfLogDbg("StepHadCall\n");
  3944. breakOnNext = true;
  3945. BfLogDbg("StepHadCall setting mIsAtBreakpointAddress = %p\n", pcAddress);
  3946. mSteppingThread->mIsAtBreakpointAddress = pcAddress;
  3947. SetTempBreakpoint(pcAddress);
  3948. mStepBreakpointAddrs.push_back(pcAddress);
  3949. }
  3950. else
  3951. {
  3952. if (inst.IsCall())
  3953. {
  3954. if ((mLastValidStepIntoPC == 0) || (dwSubprogram != NULL))
  3955. mLastValidStepIntoPC = pcAddress + inst.mSize;
  3956. }
  3957. if ((dwLineData != NULL) && (inst.IsBranch()))
  3958. {
  3959. addr_target targetAddr = inst.GetTarget();
  3960. if (targetAddr < dwSubprogram->GetLineAddr(*dwLineData))
  3961. {
  3962. // Jumping backwards, stop at next instruction
  3963. mStepStopOnNextInstruction = true;
  3964. }
  3965. }
  3966. bool isPrefixOnly = false;
  3967. if ((mStepInAssembly) && (stepType == StepType_StepOver) && (inst.IsRep(isPrefixOnly)))
  3968. {
  3969. if (isPrefixOnly)
  3970. {
  3971. CPUInst nextInst;
  3972. if (mDebugTarget->DecodeInstruction(pcAddress + inst.GetLength(), &nextInst))
  3973. {
  3974. if (nextInst.IsBranch())
  3975. {
  3976. // repne jmp - this appears in __chkstk (for example)
  3977. // We don't have a good way to "step over" this one, so just do a single step
  3978. }
  3979. else
  3980. {
  3981. // Step over the rep + target instruction
  3982. auto doneAddr = pcAddress + inst.GetLength() + nextInst.GetLength();
  3983. BfLogDbg("SetupStep SetTempBreakpoint %p\n", doneAddr);
  3984. SetTempBreakpoint(doneAddr);
  3985. mStepBreakpointAddrs.push_back(doneAddr);
  3986. break;
  3987. }
  3988. }
  3989. }
  3990. else
  3991. {
  3992. // Step over the instruction
  3993. auto doneAddr = pcAddress + inst.GetLength();
  3994. BfLogDbg("SetupStep SetTempBreakpoint %p\n", doneAddr);
  3995. SetTempBreakpoint(doneAddr);
  3996. mStepBreakpointAddrs.push_back(doneAddr);
  3997. break;
  3998. }
  3999. }
  4000. // Just step a single instruction
  4001. BfLogDbg("SetupStep SingleStepX86 %p\n", pcAddress);
  4002. SingleStepX86();
  4003. if (inst.IsReturn())
  4004. mStepStopOnNextInstruction = true;
  4005. break;
  4006. }
  4007. }
  4008. else
  4009. {
  4010. // Move us to this instruction so we can hardware single-step into it
  4011. BfLogDbg("SetupStep SetTempBreakpoint %p\n", pcAddress);
  4012. SetTempBreakpoint(pcAddress);
  4013. mStepBreakpointAddrs.push_back(pcAddress);
  4014. break;
  4015. }
  4016. }
  4017. // Not an interesting instruction - move to next
  4018. pcAddress += inst.mSize;
  4019. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress >= dwSubprogram->mBlock.mHighPC))
  4020. {
  4021. auto endAddress = dwSubprogram->mBlock.mHighPC;
  4022. BfLogDbg("Stepping past end of inlined method, end address: %p\n", endAddress);
  4023. mStepType = StepType_StepOut_Inline;
  4024. SetTempBreakpoint(endAddress);
  4025. mStepBreakpointAddrs.push_back(endAddress);
  4026. return true;
  4027. }
  4028. }
  4029. if (instIdx > 1)
  4030. BfLogDbg("SetupStep instIdx: %d\n", instIdx);
  4031. }
  4032. return true;
  4033. }
  4034. void WinDebugger::CheckNonDebuggerBreak()
  4035. {
  4036. enum MessageType
  4037. {
  4038. MessageType_None = 0,
  4039. MessageType_Error = 1,
  4040. MessageType_ProfilerCmd = 2
  4041. };
  4042. CPURegisters registers;
  4043. PopulateRegisters(&registers);
  4044. addr_target pcAddress = registers.GetPC();
  4045. addr_target debugMessageDataAddr = (addr_target)-1;
  4046. if (mDebugTarget->mTargetBinary != NULL)
  4047. {
  4048. mDebugTarget->mTargetBinary->ParseSymbolData();
  4049. debugMessageDataAddr = mDebugTarget->FindSymbolAddr("gBfDebugMessageData");
  4050. }
  4051. if (debugMessageDataAddr != (addr_target)-1)
  4052. {
  4053. struct BfDebugMessageData
  4054. {
  4055. int mMessageType; // 0 = none, 1 = error
  4056. int mStackWindbackCount;
  4057. int mBufParamLen;
  4058. addr_target mBufParam;
  4059. addr_target mPCOverride;
  4060. };
  4061. BfDebugMessageData messageData = ReadMemory<BfDebugMessageData>(debugMessageDataAddr);
  4062. WriteMemory<int>(debugMessageDataAddr, 0); // Zero out type so we won't trigger again
  4063. if (messageData.mMessageType != 0)
  4064. {
  4065. llvm::SmallVector<char, 4096> strBuf;
  4066. int strLen = messageData.mBufParamLen;
  4067. strBuf.resize(strLen + 1);
  4068. char* str = &strBuf[0];
  4069. str[strLen] = 0;
  4070. if (ReadMemory(messageData.mBufParam, strLen, str))
  4071. {
  4072. if (messageData.mMessageType == MessageType_Error)
  4073. {
  4074. mRequestedStackFrameIdx = messageData.mStackWindbackCount;
  4075. if (messageData.mPCOverride != 0)
  4076. {
  4077. mShowPCOverride = messageData.mPCOverride;
  4078. mRequestedStackFrameIdx = -2;
  4079. }
  4080. mDebugManager->mOutMessages.push_back(StrFormat("error %s", str));
  4081. }
  4082. else if (messageData.mMessageType == MessageType_ProfilerCmd)
  4083. {
  4084. // It's important to set this here, because we unlock the critSect during StopSampling and we can't have the
  4085. // IDE thinking that we're actually paused when it checks the mRunState
  4086. mRunState = RunState_Running;
  4087. char* cmd = strtok(str, "\t");
  4088. if (strcmp(cmd, "StartSampling") == 0)
  4089. {
  4090. char* sessionIdStr = strtok(NULL, "\t");
  4091. char* threadIdStr = strtok(NULL, "\t");
  4092. char* sampleRateStr = strtok(NULL, "\t");
  4093. char* descStr = strtok(NULL, "\t");
  4094. if (threadIdStr != NULL)
  4095. {
  4096. int threadId = atoi(threadIdStr);
  4097. int sampleRate = atoi(sampleRateStr);
  4098. int sessionId = atoi(sessionIdStr);
  4099. Profiler** profilerPtr;
  4100. if (mPendingProfilerMap.TryAdd(sessionId, NULL, &profilerPtr))
  4101. {
  4102. DbgProfiler* profiler = new DbgProfiler(this);
  4103. if (descStr != NULL)
  4104. profiler->mDescription = descStr;
  4105. if (sampleRate > 0)
  4106. profiler->mSamplesPerSecond = sampleRate;
  4107. profiler->Start();
  4108. *profilerPtr = profiler;
  4109. mDebugManager->mOutMessages.push_back("newProfiler");
  4110. mNewProfilerList.push_back(profiler);
  4111. }
  4112. }
  4113. }
  4114. else if (strcmp(cmd, "StopSampling") == 0)
  4115. {
  4116. char* sessionIdStr = strtok(NULL, "\t");
  4117. if (sessionIdStr != NULL)
  4118. {
  4119. int sessionId = atoi(sessionIdStr);
  4120. Profiler* profiler;
  4121. if (mPendingProfilerMap.Remove(sessionId, &profiler))
  4122. {
  4123. if (profiler->IsSampling())
  4124. {
  4125. // Need to unlock so we don't deadlock
  4126. mDebugManager->mCritSect.Unlock();
  4127. profiler->Stop();
  4128. mDebugManager->mCritSect.Lock();
  4129. }
  4130. }
  4131. }
  4132. }
  4133. else if (strcmp(cmd, "ClearSampling") == 0)
  4134. {
  4135. for (auto& kv : mPendingProfilerMap)
  4136. {
  4137. auto profiler = kv.mValue;
  4138. profiler->Clear();
  4139. }
  4140. }
  4141. else if (strcmp(cmd, "ClearOutput") == 0)
  4142. {
  4143. mDebugManager->mOutMessages.push_back("clearOutput");
  4144. }
  4145. }
  4146. return;
  4147. }
  4148. }
  4149. }
  4150. intptr_target objAddr;
  4151. if (mDebugTarget->IsObjectAccessBreak(pcAddress, &registers, &objAddr))
  4152. {
  4153. String errorStr = "error Attempted to access deleted object";
  4154. String objectAddr = EncodeDataPtr((addr_target)objAddr, true);
  4155. errorStr += StrFormat("\x1LEAK\t(System.Object)%s\n (%s)%s\n", objectAddr.c_str(), "System.Object", objectAddr.c_str());
  4156. mDebugManager->mOutMessages.push_back(errorStr);
  4157. return;
  4158. }
  4159. bool showMainThread = false;
  4160. String symbol;
  4161. addr_target offset;
  4162. DbgModule* dbgModule;
  4163. if (mDebugTarget->FindSymbolAt(pcAddress, &symbol, &offset, &dbgModule))
  4164. {
  4165. if ((symbol == "DbgBreakPoint") || (symbol == "RtlUserThreadStart") || (symbol == "RtlUserThreadStart@8"))
  4166. {
  4167. showMainThread = true;
  4168. }
  4169. }
  4170. #ifdef BF_DBG_32
  4171. else if ((dbgModule != NULL) && (dbgModule->mDisplayName.Equals("kernel32.dll", StringImpl::CompareKind_OrdinalIgnoreCase)))
  4172. {
  4173. showMainThread = true;
  4174. }
  4175. #endif
  4176. if (showMainThread)
  4177. {
  4178. // This is a manual break, show the main thread
  4179. mActiveThread = mThreadList.front();
  4180. if (mDebugPendingExpr != NULL)
  4181. {
  4182. for (auto thread : mThreadList)
  4183. {
  4184. if (thread->mThreadId == mDebugEvalThreadInfo.mThreadId)
  4185. {
  4186. mActiveThread = thread;
  4187. break;
  4188. }
  4189. }
  4190. }
  4191. }
  4192. }
  4193. bool WinDebugger::HasSteppedIntoCall()
  4194. {
  4195. // Some calls (like __chkstk) actually push results to the stack, so we need to check
  4196. // if we're REALLY deeper or not, by rolling back the callstack once
  4197. CPURegisters registers;
  4198. PopulateRegisters(&registers);
  4199. if (RollBackStackFrame(&registers, true))
  4200. {
  4201. // If the previous frames SP is equal or deeper than our step start then we are indeed inside a call!
  4202. if (mStepSP >= registers.GetSP())
  4203. return true;
  4204. }
  4205. return false;
  4206. }
  4207. void WinDebugger::StepOver(bool inAssembly)
  4208. {
  4209. AutoCrit autoCrit(mDebugManager->mCritSect);
  4210. BfLogDbg("StepOver\n");
  4211. if (!TryRunContinue())
  4212. return;
  4213. mCurNoInfoStepTries = 0; // Reset
  4214. mStepInAssembly = inAssembly;
  4215. SetupStep(StepType_StepOver);
  4216. ContinueDebugEvent();
  4217. }
  4218. void WinDebugger::StepOut(bool inAssembly)
  4219. {
  4220. AutoCrit autoCrit(mDebugManager->mCritSect);
  4221. BfLogDbg("StepOut\n");
  4222. if (!TryRunContinue())
  4223. return;
  4224. mCurNoInfoStepTries = 0; // Reset
  4225. mStepInAssembly = inAssembly;
  4226. SetupStep(StepType_StepOut);
  4227. ContinueDebugEvent();
  4228. }
  4229. void WinDebugger::SetNextStatement(bool inAssembly, const StringImpl& fileName, int64 lineNumOrAsmAddr, int wantColumn)
  4230. {
  4231. AutoCrit autoCrit(mDebugManager->mCritSect);
  4232. DbgSubprogram* subProgram = NULL;
  4233. if (!inAssembly)
  4234. {
  4235. if (mCallStack.size() == 0)
  4236. UpdateCallStack();
  4237. if (mCallStack.size() > 0)
  4238. {
  4239. UpdateCallStackMethod(0);
  4240. subProgram = mCallStack[0]->mSubProgram;
  4241. }
  4242. if (subProgram == NULL)
  4243. return;
  4244. }
  4245. DbgSubprogram* rootInlineParent = NULL;
  4246. if (subProgram != NULL)
  4247. rootInlineParent = subProgram->GetRootInlineParent();
  4248. String result;
  4249. if (mDebugTarget == NULL)
  4250. return;
  4251. DbgSrcFile* srcFile = NULL;
  4252. if (!fileName.IsEmpty())
  4253. {
  4254. srcFile = mDebugTarget->GetSrcFile(fileName);
  4255. if (srcFile == NULL)
  4256. return;
  4257. }
  4258. addr_target pcAddress = 0;
  4259. if (inAssembly)
  4260. {
  4261. pcAddress = lineNumOrAsmAddr;
  4262. }
  4263. else
  4264. {
  4265. int lineNum = (int)lineNumOrAsmAddr;
  4266. addr_target bestAddr[2] = { 0, 0 };
  4267. int checkLineNum[2] = { lineNum - 1, lineNum };
  4268. auto _CheckLineInfo = [&](DbgSubprogram* dbgSubprogram, DbgLineInfo* dbgLineInfo)
  4269. {
  4270. for (int iPass = 0; iPass < 2; ++iPass)
  4271. {
  4272. int bestLineOffset = 0x7FFFFFFF;
  4273. for (auto& lineData : dbgLineInfo->mLines)
  4274. {
  4275. auto addr = dbgSubprogram->GetLineAddr(lineData);
  4276. if ((addr < subProgram->mBlock.mLowPC) || (addr >= subProgram->mBlock.mHighPC))
  4277. continue;
  4278. int lineOffset = lineData.mLine - checkLineNum[iPass];
  4279. if ((lineOffset >= 0) && (lineOffset <= 6) && (lineOffset <= bestLineOffset))
  4280. {
  4281. if (lineOffset < bestLineOffset)
  4282. {
  4283. bestLineOffset = lineOffset;
  4284. bestAddr[iPass] = addr;
  4285. }
  4286. }
  4287. }
  4288. }
  4289. };
  4290. for (int checkHotIdx = -1; checkHotIdx < (int)srcFile->mHotReplacedDbgLineInfo.size(); checkHotIdx++)
  4291. {
  4292. if (checkHotIdx >= 0)
  4293. {
  4294. auto hotReplacedLineInfo = srcFile->mHotReplacedDbgLineInfo[checkHotIdx];
  4295. for (auto& hotReplacedEntry : hotReplacedLineInfo->mEntries)
  4296. {
  4297. _CheckLineInfo(hotReplacedEntry.mSubprogram, hotReplacedEntry.mLineInfo);
  4298. }
  4299. }
  4300. else
  4301. {
  4302. for (auto subprogram : srcFile->mLineDataRefs)
  4303. _CheckLineInfo(subprogram, subprogram->mLineInfo);
  4304. }
  4305. if (bestAddr[1] != 0)
  4306. break;
  4307. }
  4308. if (bestAddr[1] != 0)
  4309. {
  4310. const int kMaxAddrDist = 64; // within reasonable range
  4311. if ((bestAddr[0] != 0) && (bestAddr[1] - bestAddr[0] <= kMaxAddrDist))
  4312. {
  4313. addr_target addrStart = bestAddr[0];
  4314. addr_target addrEnd = bestAddr[1];
  4315. addr_target addr = addrStart;
  4316. BF_ASSERT(addrEnd - addr <= kMaxAddrDist);
  4317. addr_target lastOp = 0;
  4318. while (addr < addrEnd)
  4319. {
  4320. CPUInst inst;
  4321. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  4322. break;
  4323. lastOp = addr;
  4324. addr += inst.GetLength();
  4325. }
  4326. }
  4327. pcAddress = (uint64)bestAddr[1];
  4328. }
  4329. }
  4330. if (pcAddress)
  4331. {
  4332. BF_ASSERT(mActiveThread->mBreakpointAddressContinuing == 0);
  4333. mActiveThread->mIsAtBreakpointAddress = 0;
  4334. mActiveThread->mStoppedAtAddress = pcAddress;
  4335. if (mCallStack.size() == 0)
  4336. UpdateCallStack();
  4337. CPURegisters* regs = &mCallStack.front()->mRegisters;
  4338. *regs->GetPCRegisterRef() = pcAddress;
  4339. SetRegisters(regs);
  4340. WdBreakpoint* breakpoint = (WdBreakpoint*)FindBreakpointAt(pcAddress);
  4341. if (breakpoint != NULL)
  4342. {
  4343. BfLogDbg("SetNextStatement setting mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  4344. mActiveThread->mIsAtBreakpointAddress = breakpoint->mAddr;
  4345. }
  4346. }
  4347. }
  4348. bool WinDebugger::PopulateRegisters(CPURegisters* registers, BF_CONTEXT& lcContext)
  4349. {
  4350. #ifdef BF_DBG_32
  4351. registers->mIntRegs.eax = lcContext.Eax;
  4352. registers->mIntRegs.ecx = lcContext.Ecx;
  4353. registers->mIntRegs.edx = lcContext.Edx;
  4354. registers->mIntRegs.ebx = lcContext.Ebx;
  4355. registers->mIntRegs.esp = lcContext.Esp;
  4356. registers->mIntRegs.ebp = lcContext.Ebp;
  4357. registers->mIntRegs.esi = lcContext.Esi;
  4358. registers->mIntRegs.edi = lcContext.Edi;
  4359. registers->mIntRegs.eip = lcContext.Eip;
  4360. registers->mIntRegs.efl = lcContext.EFlags;
  4361. BF_ASSERT(sizeof(lcContext.FloatSave.RegisterArea) == sizeof(registers->mFpMmRegsArray));
  4362. memcpy(registers->mFpMmRegsArray, lcContext.FloatSave.RegisterArea, sizeof(lcContext.FloatSave.RegisterArea));
  4363. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 32 * sizeof(float));
  4364. memcpy(registers->mXmmRegsArray, &lcContext.ExtendedRegisters[160], sizeof(registers->mXmmRegsArray));
  4365. #else
  4366. registers->mIntRegs.rax = lcContext.Rax;
  4367. registers->mIntRegs.rcx = lcContext.Rcx;
  4368. registers->mIntRegs.rdx = lcContext.Rdx;
  4369. registers->mIntRegs.rbx = lcContext.Rbx;
  4370. registers->mIntRegs.rsp = lcContext.Rsp;
  4371. registers->mIntRegs.rbp = lcContext.Rbp;
  4372. registers->mIntRegs.rsi = lcContext.Rsi;
  4373. registers->mIntRegs.rdi = lcContext.Rdi;
  4374. registers->mIntRegs.rip = lcContext.Rip;
  4375. registers->mIntRegs.efl = lcContext.EFlags;
  4376. registers->mIntRegs.r8 = lcContext.R8;
  4377. registers->mIntRegs.r9 = lcContext.R9;
  4378. registers->mIntRegs.r10 = lcContext.R10;
  4379. registers->mIntRegs.r11 = lcContext.R11;
  4380. registers->mIntRegs.r12 = lcContext.R12;
  4381. registers->mIntRegs.r13 = lcContext.R13;
  4382. registers->mIntRegs.r14 = lcContext.R14;
  4383. registers->mIntRegs.r15 = lcContext.R15;
  4384. registers->mIntRegs.gs = lcContext.SegGs;
  4385. for (int i = 0; i < 8; i++)
  4386. {
  4387. memcpy(&registers->mFpMmRegsArray[i], &lcContext.FltSave.FloatRegisters[i], 10);
  4388. }
  4389. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 64 * sizeof(float));
  4390. memcpy(registers->mXmmRegsArray, BF_CONTEXT_XMMDATA(lcContext), sizeof(registers->mXmmRegsArray));
  4391. #endif
  4392. return (lcContext.ContextFlags & (BF_CONTEXT_EXCEPTION_ACTIVE | BF_CONTEXT_SERVICE_ACTIVE)) == 0;
  4393. }
  4394. bool WinDebugger::PopulateRegisters(CPURegisters* registers)
  4395. {
  4396. /*static bool sCheckedProcessorFeatures = false;
  4397. static bool sMmxAvailable = false;
  4398. static bool sXmmAvailable = false;
  4399. if (!sCheckedProcessorFeatures)
  4400. {
  4401. //CDH we don't do anything with these yet since we grab BF_CONTEXT_ALL anyway, but could be useful
  4402. sMmxAvailable = ::IsProcessorFeaturePresent(PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  4403. sXmmAvailable = ::IsProcessorFeaturePresent(PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  4404. sCheckedProcessorFeatures = true;
  4405. }*/
  4406. BF_ASSERT(registers != nullptr);
  4407. BF_CONTEXT lcContext;
  4408. lcContext.ContextFlags = BF_CONTEXT_ALL | BF_CONTEXT_EXCEPTION_REQUEST;
  4409. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4410. return PopulateRegisters(registers, lcContext);
  4411. }
  4412. bool WinDebugger::RollBackStackFrame(CPURegisters* registers, bool isStackStart)
  4413. {
  4414. BF_ASSERT(registers != nullptr);
  4415. return mDebugTarget->RollBackStackFrame(registers, NULL, isStackStart);
  4416. }
  4417. bool WinDebugger::SetHotJump(DbgSubprogram* oldSubprogram, addr_target newTarget, int newTargetSize)
  4418. {
  4419. BfLogDbg("SetHotJump %s %p->%p\n", oldSubprogram->mName, oldSubprogram->mBlock.mLowPC, newTarget);
  4420. //AutoCrit autoCrit(mDebugManager->mCritSect);
  4421. BF_ASSERT(mDebugManager->mCritSect.mLockCount == 1);
  4422. addr_target jmpInstStart = oldSubprogram->mBlock.mLowPC;
  4423. addr_target jmpInstEnd = jmpInstStart + sizeof(HotJumpOp);
  4424. if (jmpInstEnd > oldSubprogram->mBlock.mHighPC)
  4425. {
  4426. if ((oldSubprogram->mBlock.mHighPC - oldSubprogram->mBlock.mLowPC == 1) &&
  4427. (newTargetSize == 1))
  4428. return true; // Special case for just stub 'ret' methods
  4429. String err = StrFormat("Failed to hot replace method, method '%s' too small to insert hot thunk", oldSubprogram->ToString().c_str());
  4430. Fail(err);
  4431. return false;
  4432. }
  4433. if (oldSubprogram->mHotReplaceKind != DbgSubprogram::HotReplaceKind_Replaced)
  4434. {
  4435. for (int hotThreadIdx = 0; hotThreadIdx < (int)mHotThreadStates.size(); hotThreadIdx++)
  4436. {
  4437. auto& hotThreadState = mHotThreadStates[hotThreadIdx];
  4438. WdThreadInfo* threadInfo = NULL;
  4439. if (!mThreadMap.TryGetValue((uint32)hotThreadState.mThreadId, &threadInfo))
  4440. continue;
  4441. int tryStart = GetTickCount();
  4442. while ((hotThreadState.mRegisters.GetPC() >= jmpInstStart) && (hotThreadState.mRegisters.GetPC() < jmpInstEnd))
  4443. {
  4444. if (GetTickCount() - tryStart >= 8000)
  4445. {
  4446. Fail("Failed to hot replace method, can't move past prelude");
  4447. return false;
  4448. }
  4449. BfLogDbg("SetHotJump skipping through %p\n", hotThreadState.mRegisters.GetPC());
  4450. bool removedBreakpoint = false;
  4451. mActiveThread = threadInfo;
  4452. if ((mActiveThread->mStoppedAtAddress >= jmpInstStart) && (mActiveThread->mStoppedAtAddress < jmpInstEnd))
  4453. {
  4454. for (addr_target addr = jmpInstStart; addr < jmpInstEnd; addr++)
  4455. {
  4456. if (mPhysBreakpointAddrMap.ContainsKey(addr))
  4457. {
  4458. removedBreakpoint = true;
  4459. RemoveBreakpoint(addr);
  4460. }
  4461. }
  4462. }
  4463. RunState oldRunState = mRunState;
  4464. mRunState = RunState_HotStep;
  4465. if (mWantsDebugContinue)
  4466. {
  4467. mWantsDebugContinue = false;
  4468. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4469. mContinueEvent.Set();
  4470. }
  4471. BF_CONTEXT lcContext;
  4472. lcContext.ContextFlags = BF_CONTEXT_ALL;
  4473. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4474. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  4475. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  4476. ::ResumeThread(mActiveThread->mHThread);
  4477. BfLogDbg("ResumeThread %d\n", mActiveThread->mThreadId);
  4478. while (mRunState != RunState_Terminated)
  4479. {
  4480. mDebugManager->mCritSect.Unlock();
  4481. Sleep(0);
  4482. mDebugManager->mCritSect.Lock();
  4483. if (IsPaused())
  4484. break;
  4485. if (mWantsDebugContinue)
  4486. {
  4487. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4488. mWantsDebugContinue = false;
  4489. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4490. mContinueEvent.Set();
  4491. }
  4492. }
  4493. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4494. ::SuspendThread(mActiveThread->mHThread);
  4495. BfLogDbg("SuspendThread %d\n", mActiveThread->mThreadId);
  4496. mRunState = oldRunState;
  4497. if ((mRunState != RunState_Terminated) && (mRunState != RunState_Terminating))
  4498. {
  4499. if (!IsPaused())
  4500. {
  4501. BF_ASSERT(mWantsDebugContinue);
  4502. mWantsDebugContinue = false;
  4503. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4504. mContinueEvent.Set();
  4505. }
  4506. }
  4507. PopulateRegisters(&hotThreadState.mRegisters);
  4508. }
  4509. }
  4510. }
  4511. HotJumpOp jumpOp;
  4512. jumpOp.mOpCode = 0xE9;
  4513. jumpOp.mRelTarget = newTarget - oldSubprogram->mBlock.mLowPC - sizeof(HotJumpOp);
  4514. WriteMemory(oldSubprogram->mBlock.mLowPC, jumpOp);
  4515. ::FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)oldSubprogram->mBlock.mLowPC, sizeof(HotJumpOp));
  4516. return true;
  4517. }
  4518. DbgSubprogram* WinDebugger::TryFollowHotJump(DbgSubprogram* subprogram, addr_target addr)
  4519. {
  4520. if (subprogram->mHotReplaceKind != DbgSubprogram::HotReplaceKind_Replaced)
  4521. return subprogram;
  4522. if (addr != subprogram->mBlock.mLowPC)
  4523. return subprogram;
  4524. auto dbgModule = subprogram->mCompileUnit->mDbgModule;
  4525. HotJumpOp jumpOp = ReadMemory<HotJumpOp>(addr);
  4526. if (jumpOp.mOpCode != 0xE9)
  4527. return subprogram;
  4528. addr_target jumpAddr = addr + jumpOp.mRelTarget + sizeof(HotJumpOp);
  4529. auto jumpSubprogram = mDebugTarget->FindSubProgram(jumpAddr);
  4530. if (jumpSubprogram == NULL)
  4531. return subprogram;
  4532. return jumpSubprogram;
  4533. }
  4534. bool WinDebugger::ShouldShowStaticMember(DbgType* dbgType, DbgVariable* member)
  4535. {
  4536. // If locationData is non-null, that means it was added in addition to the static declaration in the CV type info,
  4537. // so only add the names from the type definition
  4538. auto flavor = dbgType->mCompileUnit->mDbgModule->mDbgFlavor;
  4539. return ((((dbgType->IsNamespace()) || (flavor != DbgFlavor_MS)) && ((member->mLocationData != NULL) || member->mIsConst)) ||
  4540. ((flavor == DbgFlavor_MS) && (member->mLocationData == NULL)));
  4541. }
  4542. String WinDebugger::GetMemberList(DbgType* dbgType, const StringImpl& expr, bool isPtr, bool isStatic, bool forceCast, bool isSplat, bool isReadOnly)
  4543. {
  4544. auto dbgModule = dbgType->GetDbgModule();
  4545. dbgType->PopulateType();
  4546. auto language = dbgType->GetLanguage();
  4547. if (!isStatic)
  4548. {
  4549. String retVal;
  4550. bool needsNewline = false;
  4551. bool isBfObject = false;
  4552. if (dbgType->IsBfObjectPtr())
  4553. {
  4554. isBfObject = true;
  4555. dbgType = dbgType->mTypeParam;
  4556. }
  4557. int baseIdx = 0;
  4558. for (auto baseTypeEntry : dbgType->mBaseTypes)
  4559. {
  4560. auto baseType = baseTypeEntry->mBaseType;
  4561. if ((baseType->mSize > 0) || (baseType->mTypeCode != DbgType_Struct) || (strcmp(baseType->mTypeName, "ValueType") != 0))
  4562. {
  4563. String baseTypeStr = baseType->ToStringRaw(language);
  4564. if (baseIdx > 0)
  4565. retVal += "\n";
  4566. if (isSplat)
  4567. retVal += "[base]\t((" + baseTypeStr + ")" + expr + "), nv";
  4568. else if (dbgType->WantsRefThis())
  4569. retVal += "[base]\t((" + baseTypeStr + ")this), nd, na, nv, this=" + expr;
  4570. else
  4571. retVal += "[base]\t((" + baseTypeStr + "*)this), nd, na, nv, this=" + expr;
  4572. if (isReadOnly)
  4573. retVal += ", ne";
  4574. }
  4575. needsNewline = true;
  4576. baseIdx++;
  4577. }
  4578. String thisExpr = expr;
  4579. String castString;
  4580. if (dbgType->IsBfObject())
  4581. {
  4582. auto ptrType = dbgType->GetDbgModule()->GetPointerType(dbgType);
  4583. castString = ptrType->ToStringRaw(language);
  4584. }
  4585. else
  4586. castString = dbgType->ToStringRaw(language);
  4587. bool hadStatics = false;
  4588. for (auto member : dbgType->mMemberList)
  4589. {
  4590. if (member->mMemberOffset < 0)
  4591. continue;
  4592. if (member->mIsStatic)
  4593. {
  4594. if (ShouldShowStaticMember(dbgType, member))
  4595. hadStatics = true;
  4596. }
  4597. else
  4598. {
  4599. bool ignoreMember = false;
  4600. if (member->mName != NULL)
  4601. {
  4602. if ((member->mName[0] == '?') ||
  4603. (member->mName[0] == '$') ||
  4604. (strncmp(member->mName, "_vptr$", 6) == 0))
  4605. ignoreMember = true;
  4606. }
  4607. if (!ignoreMember)
  4608. {
  4609. if (needsNewline)
  4610. retVal += "\n";
  4611. if (member->mName == NULL)
  4612. {
  4613. retVal += GetMemberList(member->mType, expr, isPtr, isStatic, forceCast, isSplat, isReadOnly);
  4614. }
  4615. else
  4616. {
  4617. retVal += String(member->mName);
  4618. if (isSplat)
  4619. {
  4620. retVal += "\t(" + thisExpr + ")." + String(member->mName);
  4621. // We don't want to rely on this being enforced here. For one, ref types shouldn't get ", ne" added,
  4622. // and this doesn't solve the issue of attempting to assign via the Immediate window
  4623. /*if (isReadOnly)
  4624. retVal += ", ne";*/
  4625. }
  4626. else
  4627. {
  4628. if (forceCast)
  4629. retVal += "\t((" + castString + ")this)." + String(member->mName);
  4630. else if ((member->mName[0] >= '0') && (member->mName[0] <= '9')) // Numbered tuple member?
  4631. retVal += "\tthis." + String(member->mName);
  4632. else
  4633. retVal += "\t" + String(member->mName);
  4634. retVal += ", this=" + thisExpr;
  4635. // if (isReadOnly)
  4636. // retVal += ", ne";
  4637. }
  4638. }
  4639. needsNewline = true;
  4640. }
  4641. }
  4642. }
  4643. if (hadStatics)
  4644. {
  4645. if (needsNewline)
  4646. retVal += "\n";
  4647. retVal += "Static values\t" + castString;
  4648. }
  4649. return retVal;
  4650. }
  4651. else
  4652. {
  4653. if (dbgType->IsBfObjectPtr())
  4654. dbgType = dbgType->mTypeParam;
  4655. String retVal;
  4656. String memberPrefix = expr;
  4657. bool needsNewline = false;
  4658. bool hadStatics = false;
  4659. for (auto member : dbgType->mMemberList)
  4660. {
  4661. if (member->mIsStatic)
  4662. {
  4663. if (ShouldShowStaticMember(dbgType, member))
  4664. {
  4665. if (needsNewline)
  4666. retVal += "\n";
  4667. retVal += String(member->mName) + "\t" + memberPrefix + "." + String(member->mName);
  4668. needsNewline = true;
  4669. }
  4670. }
  4671. }
  4672. return retVal;
  4673. }
  4674. return "";
  4675. }
  4676. bool WinDebugger::ParseFormatInfo(DbgModule* dbgModule, const StringImpl& formatInfoStr, DwFormatInfo* formatInfo, BfPassInstance* bfPassInstance, int* assignExprOffset, String* assignExprString, String* errorString, DbgTypedValue contextTypedValue)
  4677. {
  4678. String formatFlags = formatInfoStr;
  4679. if (assignExprOffset != NULL)
  4680. *assignExprOffset = -1;
  4681. while (formatFlags.length() > 0)
  4682. {
  4683. formatFlags = Trim(formatFlags);
  4684. if (formatFlags.IsEmpty())
  4685. break;
  4686. if (formatFlags[0] != ',')
  4687. {
  4688. return false;
  4689. }
  4690. else
  4691. {
  4692. int nextComma = formatFlags.IndexOf(',', 1);
  4693. int quotePos = formatFlags.IndexOf('"', 1);
  4694. if ((quotePos != -1) && (quotePos < nextComma))
  4695. {
  4696. int nextQuotePos = formatFlags.IndexOf('"', quotePos + 1);
  4697. if (nextQuotePos != -1)
  4698. nextComma = formatFlags.IndexOf(',', nextQuotePos + 1);
  4699. }
  4700. if (nextComma == -1)
  4701. nextComma = formatFlags.length();
  4702. String formatCmd = formatFlags.Substring(1, nextComma - 1);
  4703. formatCmd = Trim(formatCmd);
  4704. bool hadError = false;
  4705. if (strncmp(formatCmd.c_str(), "this=", 5) == 0)
  4706. {
  4707. formatCmd = formatFlags.Substring(1);
  4708. formatCmd = Trim(formatCmd);
  4709. String thisExpr = formatCmd.Substring(5);
  4710. if (thisExpr.empty())
  4711. break;
  4712. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, thisExpr, formatInfo);
  4713. formatInfo->mExplicitThis = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4714. if (dbgEvaluationContext.HadError())
  4715. {
  4716. if (errorString != NULL)
  4717. *errorString = dbgEvaluationContext.GetErrorStr();
  4718. return false;
  4719. }
  4720. formatFlags = thisExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4721. continue;
  4722. }
  4723. else if (strncmp(formatCmd.c_str(), "count=", 6) == 0)
  4724. {
  4725. formatCmd = formatFlags.Substring(1);
  4726. formatCmd = Trim(formatCmd);
  4727. String countExpr = formatCmd.Substring(6);
  4728. if (countExpr.empty())
  4729. break;
  4730. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4731. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4732. if ((countValue) && (countValue.mType->IsInteger()))
  4733. formatInfo->mOverrideCount = (intptr)countValue.GetInt64();
  4734. if (dbgEvaluationContext.HadError())
  4735. {
  4736. if (errorString != NULL)
  4737. *errorString = dbgEvaluationContext.GetErrorStr();
  4738. return false;
  4739. }
  4740. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4741. continue;
  4742. }
  4743. else if (strncmp(formatCmd.c_str(), "maxcount=", 9) == 0)
  4744. {
  4745. formatCmd = formatFlags.Substring(1);
  4746. formatCmd = Trim(formatCmd);
  4747. String countExpr = formatCmd.Substring(9);
  4748. if (countExpr.empty())
  4749. break;
  4750. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4751. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4752. if ((countValue) && (countValue.mType->IsInteger()))
  4753. formatInfo->mMaxCount = (intptr)countValue.GetInt64();
  4754. if (dbgEvaluationContext.HadError())
  4755. {
  4756. if (errorString != NULL)
  4757. *errorString = dbgEvaluationContext.GetErrorStr();
  4758. return false;
  4759. }
  4760. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4761. continue;
  4762. }
  4763. else if (strncmp(formatCmd.c_str(), "arraysize=", 10) == 0)
  4764. {
  4765. formatCmd = formatFlags.Substring(1);
  4766. formatCmd = Trim(formatCmd);
  4767. String countExpr = formatCmd.Substring(10);
  4768. if (countExpr.empty())
  4769. break;
  4770. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4771. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4772. if ((countValue) && (countValue.mType->IsInteger()))
  4773. formatInfo->mArrayLength = (intptr)countValue.GetInt64();
  4774. if (dbgEvaluationContext.HadError())
  4775. {
  4776. if (errorString != NULL)
  4777. *errorString = dbgEvaluationContext.GetErrorStr();
  4778. return false;
  4779. }
  4780. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4781. continue;
  4782. }
  4783. else if (strncmp(formatCmd.c_str(), "assign=", 7) == 0)
  4784. {
  4785. formatCmd = formatFlags.Substring(1);
  4786. formatCmd = Trim(formatCmd);
  4787. String assignExpr = formatCmd.Substring(7);
  4788. if (assignExpr.empty())
  4789. break;
  4790. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, assignExpr, formatInfo);
  4791. if (dbgEvaluationContext.HadError())
  4792. {
  4793. if (errorString != NULL)
  4794. *errorString = dbgEvaluationContext.GetErrorStr();
  4795. return false;
  4796. }
  4797. if (assignExprOffset != NULL)
  4798. {
  4799. //TODO: Keep track of the offset directly, this is a hack
  4800. *assignExprOffset = (int)formatInfoStr.IndexOf("assign=") + 7;
  4801. }
  4802. if (assignExprString != NULL)
  4803. *assignExprString = dbgEvaluationContext.mExprNode->ToString();
  4804. formatFlags = assignExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4805. continue;
  4806. }
  4807. else if (strncmp(formatCmd.c_str(), "refid=", 6) == 0)
  4808. {
  4809. formatInfo->mReferenceId = formatCmd.Substring(6);
  4810. if (formatInfo->mReferenceId[0] == '\"')
  4811. formatInfo->mReferenceId = formatInfo->mReferenceId.Substring(1, formatInfo->mReferenceId.length() - 2);
  4812. }
  4813. else if (strncmp(formatCmd.c_str(), "_=", 2) == 0)
  4814. {
  4815. formatInfo->mSubjectExpr = formatCmd.Substring(2);
  4816. if (formatInfo->mSubjectExpr[0] == '\"')
  4817. formatInfo->mSubjectExpr = formatInfo->mSubjectExpr.Substring(1, formatInfo->mSubjectExpr.length() - 2);
  4818. }
  4819. else if (strncmp(formatCmd.c_str(), "expectedType=", 13) == 0)
  4820. {
  4821. formatInfo->mExpectedType = formatCmd.Substring(13);
  4822. if (formatInfo->mExpectedType[0] == '\"')
  4823. formatInfo->mExpectedType = formatInfo->mExpectedType.Substring(1, formatInfo->mExpectedType.length() - 2);
  4824. }
  4825. else if (strncmp(formatCmd.c_str(), "namespaceSearch=", 16) == 0)
  4826. {
  4827. formatInfo->mNamespaceSearch = formatCmd.Substring(16);
  4828. if (formatInfo->mNamespaceSearch[0] == '\"')
  4829. formatInfo->mNamespaceSearch = formatInfo->mNamespaceSearch.Substring(1, formatInfo->mNamespaceSearch.length() - 2);
  4830. }
  4831. else if (formatCmd == "d")
  4832. {
  4833. formatInfo->mDisplayType = DwDisplayType_Decimal;
  4834. }
  4835. else if (formatCmd == "x")
  4836. {
  4837. formatInfo->mDisplayType = DwDisplayType_HexLower;
  4838. }
  4839. else if (formatCmd == "X")
  4840. {
  4841. formatInfo->mDisplayType = DwDisplayType_HexUpper;
  4842. }
  4843. else if (formatCmd == "s")
  4844. {
  4845. formatInfo->mHidePointers = true;
  4846. formatInfo->mDisplayType = DwDisplayType_Ascii;
  4847. }
  4848. else if (formatCmd == "s8")
  4849. {
  4850. formatInfo->mHidePointers = true;
  4851. formatInfo->mDisplayType = DwDisplayType_Utf8;
  4852. }
  4853. else if (formatCmd == "s16")
  4854. {
  4855. formatInfo->mHidePointers = true;
  4856. formatInfo->mDisplayType = DwDisplayType_Utf16;
  4857. }
  4858. else if (formatCmd == "s32")
  4859. {
  4860. formatInfo->mHidePointers = true;
  4861. formatInfo->mDisplayType = DwDisplayType_Utf32;
  4862. }
  4863. else if (formatCmd == "nd")
  4864. {
  4865. formatInfo->mIgnoreDerivedClassInfo = true;
  4866. }
  4867. else if (formatCmd == "na")
  4868. {
  4869. formatInfo->mHidePointers = true;
  4870. }
  4871. else if (formatCmd == "nm")
  4872. {
  4873. formatInfo->mNoMembers = true;
  4874. }
  4875. else if (formatCmd == "ne")
  4876. {
  4877. formatInfo->mNoEdit = true;
  4878. }
  4879. else if (formatCmd == "nv")
  4880. {
  4881. formatInfo->mNoVisualizers = true;
  4882. }
  4883. else if (formatCmd == "rawStr")
  4884. {
  4885. formatInfo->mRawString = true;
  4886. }
  4887. else if (((!formatCmd.IsEmpty()) && ((formatCmd[0] >= '0') && (formatCmd[0] <= '9'))) ||
  4888. (formatCmd.StartsWith("(")))
  4889. {
  4890. String countExpr = formatCmd;
  4891. if (countExpr.empty())
  4892. break;
  4893. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4894. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4895. if ((countValue) && (countValue.mType->IsInteger()))
  4896. formatInfo->mArrayLength = (intptr)countValue.GetInt64();
  4897. if (dbgEvaluationContext.HadError())
  4898. {
  4899. if (errorString != NULL)
  4900. *errorString = dbgEvaluationContext.GetErrorStr();
  4901. return false;
  4902. }
  4903. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4904. continue;
  4905. }
  4906. else
  4907. hadError = true;
  4908. if (hadError)
  4909. {
  4910. if (errorString != NULL)
  4911. *errorString = "Invalid format flags";
  4912. return false;
  4913. }
  4914. formatFlags = formatFlags.Substring(nextComma);
  4915. }
  4916. }
  4917. return true;
  4918. }
  4919. String WinDebugger::MaybeQuoteFormatInfoParam(const StringImpl& str)
  4920. {
  4921. bool needsQuote = false;
  4922. for (int i = 0; i < (int)str.length(); i++)
  4923. {
  4924. char c = str[i];
  4925. if (c == ',')
  4926. needsQuote = true;
  4927. }
  4928. if (!needsQuote)
  4929. return str;
  4930. String qStr = "\"";
  4931. qStr += str;
  4932. qStr += "\"";
  4933. return qStr;
  4934. }
  4935. DbgTypedValue WinDebugger::EvaluateInContext(DbgCompileUnit* dbgCompileUnit, const DbgTypedValue& contextTypedValue, const StringImpl& subExpr, DwFormatInfo* formatInfo, String* outReferenceId, String* outErrors)
  4936. {
  4937. DbgEvaluationContext dbgEvaluationContext(this, dbgCompileUnit->mDbgModule, subExpr, formatInfo, contextTypedValue);
  4938. dbgEvaluationContext.mDbgExprEvaluator->mDbgCompileUnit = dbgCompileUnit;
  4939. if (formatInfo != NULL)
  4940. {
  4941. dbgEvaluationContext.mDbgExprEvaluator->mLanguage = formatInfo->mLanguage;
  4942. dbgEvaluationContext.mDbgExprEvaluator->mSubjectExpr = formatInfo->mSubjectExpr;
  4943. }
  4944. dbgEvaluationContext.mDbgExprEvaluator->mReferenceId = outReferenceId;
  4945. auto result = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4946. if ((formatInfo != NULL) && (dbgEvaluationContext.mDbgExprEvaluator->mCountResultOverride != -1))
  4947. formatInfo->mOverrideCount = dbgEvaluationContext.mDbgExprEvaluator->mCountResultOverride;
  4948. if (dbgEvaluationContext.mPassInstance->HasFailed())
  4949. {
  4950. if (outErrors != NULL)
  4951. {
  4952. int errIdx = 0;
  4953. for (auto err : dbgEvaluationContext.mPassInstance->mErrors)
  4954. {
  4955. if (errIdx > 0)
  4956. (*outErrors) += "\n";
  4957. (*outErrors) += err->mError;
  4958. errIdx++;
  4959. }
  4960. }
  4961. return DbgTypedValue();
  4962. }
  4963. return result;
  4964. }
  4965. void WinDebugger::DbgVisFailed(DebugVisualizerEntry* debugVis, const StringImpl& evalString, const StringImpl& errors)
  4966. {
  4967. bool onlyMemError = errors.StartsWith("Failed to read") && !errors.Contains('\n');
  4968. if ((!debugVis->mShowedError) && (!onlyMemError))
  4969. {
  4970. debugVis->mShowedError = true;
  4971. String errStr = StrFormat("DbgVis '%s' failed while evaluating condition '%s'\n", debugVis->mName.c_str(), evalString.c_str());
  4972. String spacedErrors = errors;
  4973. spacedErrors.Insert(0, " ");
  4974. spacedErrors.Replace("\n", "\n ");
  4975. errStr += spacedErrors;
  4976. OutputMessage(errStr);
  4977. }
  4978. }
  4979. bool WinDebugger::EvalCondition(DebugVisualizerEntry* debugVis, DbgCompileUnit* dbgCompileUnit, DbgTypedValue typedVal, DwFormatInfo& formatInfo, const StringImpl& condition, const Array<String>& dbgVisWildcardCaptures, String& errorStr)
  4980. {
  4981. DwFormatInfo displayStrFormatInfo = formatInfo;
  4982. displayStrFormatInfo.mHidePointers = false;
  4983. displayStrFormatInfo.mRawString = false;
  4984. String errors;
  4985. const String conditionStr = mDebugManager->mDebugVisualizers->DoStringReplace(condition, dbgVisWildcardCaptures);
  4986. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, typedVal, conditionStr, &displayStrFormatInfo, NULL, &errors);
  4987. if ((!evalResult) || (!evalResult.mType->IsBoolean()))
  4988. {
  4989. if (formatInfo.mRawString)
  4990. return false;
  4991. errorStr += "<DbgVis Failed>";
  4992. DbgVisFailed(debugVis, conditionStr, errors);
  4993. return false;
  4994. }
  4995. return evalResult.mBool;
  4996. }
  4997. String WinDebugger::GetArrayItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgType* valueType, DbgTypedValue& curNode, int& count, String* outContinuationData)
  4998. {
  4999. DbgEvaluationContext conditionEvaluationContext(this, dbgCompileUnit, debugVis->mCondition);
  5000. String addrs;
  5001. bool checkLeft = true;
  5002. int usedCount = 0;
  5003. while (usedCount < count)
  5004. {
  5005. DbgTypedValue condVal = conditionEvaluationContext.EvaluateInContext(curNode);
  5006. if (!condVal)
  5007. break;
  5008. if (condVal.mBool)
  5009. {
  5010. auto val = curNode;
  5011. if (valueType == NULL)
  5012. {
  5013. String typeAddr = val.mType->ToStringRaw();
  5014. // RPad
  5015. typeAddr.Append(' ', sizeof(addr_target) * 2 - typeAddr.length());
  5016. addrs += typeAddr;
  5017. }
  5018. String addr = EncodeDataPtr(val.mPtr, false);
  5019. addrs += addr;
  5020. usedCount++;
  5021. }
  5022. curNode.mPtr += curNode.mType->mTypeParam->GetStride();
  5023. }
  5024. count = usedCount;
  5025. if (outContinuationData != NULL)
  5026. {
  5027. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(valueType, false) +
  5028. EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  5029. }
  5030. return addrs;
  5031. }
  5032. String WinDebugger::GetLinkedListItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, addr_target endNodePtr, DbgType* valueType, DbgTypedValue& curNode, int& count, String* outContinuationData)
  5033. {
  5034. DbgEvaluationContext nextEvaluationContext(this, dbgCompileUnit, debugVis->mNextPointer);
  5035. DbgEvaluationContext valueEvaluationContext(this, dbgCompileUnit, debugVis->mValuePointer);
  5036. String addrs;
  5037. bool checkLeft = true;
  5038. int mapIdx;
  5039. for (mapIdx = 0; mapIdx < count; mapIdx++)
  5040. {
  5041. if (curNode.mPtr == endNodePtr)
  5042. break;
  5043. DbgTypedValue val = valueEvaluationContext.EvaluateInContext(curNode);
  5044. if (!val)
  5045. break;
  5046. if (val.mPtr == 0)
  5047. break;
  5048. if (valueType == NULL)
  5049. {
  5050. String typeAddr = val.mType->ToStringRaw();
  5051. // RPad
  5052. typeAddr.Append(' ', sizeof(addr_target)*2 - typeAddr.length());
  5053. addrs += typeAddr;
  5054. }
  5055. String addr = EncodeDataPtr(val.mPtr, false);
  5056. addrs += addr;
  5057. curNode = nextEvaluationContext.EvaluateInContext(curNode);
  5058. }
  5059. count = mapIdx;
  5060. if (outContinuationData != NULL)
  5061. {
  5062. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(endNodePtr, false) + EncodeDataPtr(valueType, false) +
  5063. EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  5064. }
  5065. return addrs;
  5066. }
  5067. String WinDebugger::GetDictionaryItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgTypedValue dictValue, int bucketIdx, int nodeIdx, int& count, String* outContinuationData)
  5068. {
  5069. //DbgEvaluationContext bucketsEvaluationContext(this, dbgModule, debugVis->mBuckets);
  5070. DbgEvaluationContext nextEvaluationContext(this, dbgCompileUnit->mDbgModule, debugVis->mNextPointer);
  5071. DbgTypedValue bucketsPtr = EvaluateInContext(dbgCompileUnit, dictValue, debugVis->mBuckets);
  5072. DbgTypedValue entriesPtr = EvaluateInContext(dbgCompileUnit, dictValue, debugVis->mEntries);
  5073. if ((!bucketsPtr) || (!entriesPtr))
  5074. {
  5075. count = -1;
  5076. return "";
  5077. }
  5078. int entrySize = entriesPtr.mType->mTypeParam->GetStride();
  5079. int bucketIdxSize = bucketsPtr.mType->mTypeParam->GetStride();
  5080. String addrs;
  5081. bool checkLeft = true;
  5082. int encodeCount = 0;
  5083. while (encodeCount < count)
  5084. {
  5085. if (nodeIdx != -1)
  5086. {
  5087. DbgTypedValue entryValue;
  5088. entryValue.mSrcAddress = entriesPtr.mPtr + (nodeIdx * entrySize);
  5089. entryValue.mType = entriesPtr.mType->mTypeParam;
  5090. addrs += EncodeDataPtr(entryValue.mSrcAddress, false);
  5091. DbgTypedValue nextValue = nextEvaluationContext.EvaluateInContext(entryValue);
  5092. if ((!nextValue) || (!nextValue.mType->IsInteger()))
  5093. {
  5094. break;
  5095. }
  5096. nodeIdx = (int)nextValue.GetInt64();
  5097. encodeCount++;
  5098. }
  5099. else
  5100. {
  5101. if (bucketIdxSize == 4)
  5102. nodeIdx = ReadMemory<int>(bucketsPtr.mPtr + bucketIdx * sizeof(int32));
  5103. else
  5104. nodeIdx = (int)ReadMemory<int64>(bucketsPtr.mPtr + bucketIdx * sizeof(int64));
  5105. bucketIdx++;
  5106. }
  5107. }
  5108. count = encodeCount;
  5109. //count = mapIdx;
  5110. if (outContinuationData != NULL)
  5111. {
  5112. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(dictValue.mType, false) + EncodeDataPtr(dictValue.mSrcAddress, false) +
  5113. EncodeDataPtr((addr_target)bucketIdx, false) + EncodeDataPtr((addr_target)nodeIdx, false);
  5114. }
  5115. return addrs;
  5116. }
  5117. String WinDebugger::GetTreeItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, Array<addr_target>& parentList, DbgType*& valueType, DbgTypedValue& curNode, int count, String* outContinuationData)
  5118. {
  5119. DbgEvaluationContext leftEvaluationContext(this, dbgCompileUnit, debugVis->mLeftPointer);
  5120. DbgEvaluationContext rightEvaluationContext(this, dbgCompileUnit, debugVis->mRightPointer);
  5121. DbgEvaluationContext valueEvaluationContext(this, dbgCompileUnit, debugVis->mValuePointer);
  5122. DbgEvaluationContext conditionEvaluationContext(this, dbgCompileUnit, debugVis->mCondition);
  5123. String addrs;
  5124. bool checkLeft = true;
  5125. if ((curNode.mPtr & 2) != 0) // Flag from continuation
  5126. {
  5127. checkLeft = false;
  5128. curNode.mPtr &= (addr_target)~2;
  5129. }
  5130. HashSet<intptr> seenAddrs;
  5131. for (int mapIdx = 0; mapIdx < count; mapIdx++)
  5132. {
  5133. DbgTypedValue readNode;
  5134. while (true)
  5135. {
  5136. bool checkNode = (curNode.mPtr & 1) == 0;
  5137. readNode = curNode;
  5138. readNode.mPtr &= (addr_target)~1;
  5139. if (checkLeft)
  5140. {
  5141. DbgTypedValue leftValue = leftEvaluationContext.EvaluateInContext(readNode);
  5142. bool isEmpty = leftValue.mPtr == NULL;
  5143. if ((leftValue) && (conditionEvaluationContext.HasExpression()))
  5144. {
  5145. auto condValue = conditionEvaluationContext.EvaluateInContext(leftValue);
  5146. if (condValue)
  5147. isEmpty = !condValue.mBool;
  5148. }
  5149. if (isEmpty)
  5150. {
  5151. checkLeft = false;
  5152. break; // Handle node
  5153. }
  5154. parentList.push_back(curNode.mPtr);
  5155. curNode = leftValue;
  5156. }
  5157. else if (checkNode)
  5158. {
  5159. break; // Handle node
  5160. }
  5161. else
  5162. {
  5163. DbgTypedValue rightValue = rightEvaluationContext.EvaluateInContext(readNode);
  5164. bool isEmpty = rightValue.mPtr == NULL;
  5165. if ((rightValue) && (conditionEvaluationContext.HasExpression()))
  5166. {
  5167. auto condValue = conditionEvaluationContext.EvaluateInContext(rightValue);
  5168. if (condValue)
  5169. isEmpty = !condValue.mBool;
  5170. }
  5171. if (!isEmpty)
  5172. {
  5173. curNode = rightValue;
  5174. checkLeft = true;
  5175. }
  5176. else
  5177. {
  5178. if (parentList.size() == 0)
  5179. {
  5180. // Failed
  5181. break;
  5182. }
  5183. curNode.mPtr = parentList.back();
  5184. parentList.pop_back();
  5185. continue; // Don't check against seenAddrs
  5186. }
  5187. }
  5188. if (!seenAddrs.Add(curNode.mPtr))
  5189. {
  5190. // Failed!
  5191. return "";
  5192. }
  5193. }
  5194. DbgTypedValue val = valueEvaluationContext.EvaluateInContext(readNode);
  5195. if (valueType == NULL)
  5196. valueType = val.mType;
  5197. String addr = EncodeDataPtr(val.mPtr, false);
  5198. addrs += addr;
  5199. curNode.mPtr |= 1; // Node handled
  5200. }
  5201. if (!checkLeft)
  5202. curNode.mPtr |= 2;
  5203. if (outContinuationData != NULL)
  5204. {
  5205. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(valueType, false) + EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  5206. for (auto parent : parentList)
  5207. *outContinuationData += EncodeDataPtr(parent, false);
  5208. }
  5209. return addrs;
  5210. }
  5211. String WinDebugger::GetCollectionContinuation(const StringImpl& continuationData, int callStackIdx, int count)
  5212. {
  5213. DbgCompileUnit* dbgCompileUnit = GetCallStackCompileUnit(callStackIdx);;
  5214. if (!IsPaused())
  5215. return "";
  5216. const char* dataPtr = continuationData.c_str();
  5217. DebugVisualizerEntry* debugVis = (DebugVisualizerEntry*)DecodeLocalDataPtr(dataPtr);
  5218. if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_TreeItems)
  5219. {
  5220. DbgType* valueType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5221. DbgTypedValue curNode;
  5222. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5223. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5224. Array<addr_target> parentList;
  5225. String newContinuationData;
  5226. while (*dataPtr != 0)
  5227. parentList.push_back(DecodeTargetDataPtr(dataPtr));
  5228. String retVal = GetTreeItems(dbgCompileUnit, debugVis, parentList, valueType, curNode, count, &newContinuationData);
  5229. retVal += "\n" + newContinuationData;
  5230. return retVal;
  5231. }
  5232. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_LinkedList)
  5233. {
  5234. addr_target endNodePtr = DecodeTargetDataPtr(dataPtr);
  5235. DbgType* valueType = (DbgType*) DecodeLocalDataPtr(dataPtr);
  5236. DbgTypedValue curNode;
  5237. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5238. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5239. String newContinuationData;
  5240. if (count < 0)
  5241. count = 3;
  5242. String retVal = GetLinkedListItems(dbgCompileUnit, debugVis, endNodePtr, valueType, curNode, count, &newContinuationData);
  5243. retVal += "\n" + newContinuationData;
  5244. return retVal;
  5245. }
  5246. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Array)
  5247. {
  5248. DbgType* valueType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5249. DbgTypedValue curNode;
  5250. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5251. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5252. String newContinuationData;
  5253. if (count < 0)
  5254. count = 3;
  5255. String retVal = GetArrayItems(dbgCompileUnit, debugVis, valueType, curNode, count, &newContinuationData);
  5256. retVal += "\n" + newContinuationData;
  5257. return retVal;
  5258. }
  5259. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Dictionary)
  5260. {
  5261. DbgTypedValue dictValue;
  5262. dictValue.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5263. dictValue.mSrcAddress = DecodeTargetDataPtr(dataPtr);
  5264. int bucketIdx = (int)DecodeTargetDataPtr(dataPtr);
  5265. int nodeIdx = (int)DecodeTargetDataPtr(dataPtr);
  5266. String newContinuationData;
  5267. String retVal = GetDictionaryItems(dbgCompileUnit, debugVis, dictValue, bucketIdx, nodeIdx, count, &newContinuationData);
  5268. retVal += "\n" + newContinuationData;
  5269. return retVal;
  5270. }
  5271. return "";
  5272. }
  5273. template <typename T>
  5274. static String IntTypeToString(T val, const StringImpl& name, DwDisplayInfo* displayInfo, DwFormatInfo& formatInfo)
  5275. {
  5276. auto intDisplayType = displayInfo->mIntDisplayType;
  5277. if (formatInfo.mDisplayType == DwDisplayType_Decimal)
  5278. intDisplayType = DwIntDisplayType_Decimal;
  5279. else if (formatInfo.mDisplayType == DwDisplayType_HexUpper)
  5280. intDisplayType = DwIntDisplayType_HexadecimalUpper;
  5281. else if (formatInfo.mDisplayType == DwDisplayType_HexLower)
  5282. intDisplayType = DwIntDisplayType_HexadecimalLower;
  5283. if (intDisplayType == DwIntDisplayType_Binary)
  5284. {
  5285. String binary;
  5286. for (int i = 0; i < sizeof(T) * 8; i++)
  5287. {
  5288. if ((i != 0) && (i % 4 == 0))
  5289. binary = "'" + binary;
  5290. if ((i != 0) && (i % 16 == 0))
  5291. binary = "'" + binary;
  5292. binary = ((val & ((T)1 << i)) ? "1" : "0") + binary;
  5293. }
  5294. return StrFormat("0b'%s\n%s", binary.c_str(), name.c_str());
  5295. }
  5296. if (intDisplayType == DwIntDisplayType_Octal)
  5297. {
  5298. String format;
  5299. if (sizeof(T) == 8)
  5300. {
  5301. format = StrFormat("0o%%lo\n%s", name.c_str());
  5302. }
  5303. else
  5304. format = StrFormat("0o%%0%do\n%s", sizeof(val) * 2, name.c_str());
  5305. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5306. }
  5307. if (intDisplayType == DwIntDisplayType_HexadecimalUpper)
  5308. {
  5309. String format;
  5310. if (sizeof(T) == 8)
  5311. {
  5312. format = StrFormat("0x%%l@\n%s", name.c_str());
  5313. }
  5314. else
  5315. format = StrFormat("0x%%0%dX\n%s", sizeof(val) * 2, name.c_str());
  5316. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5317. }
  5318. //TODO: Implement HexadecimalLower
  5319. if (intDisplayType == DwIntDisplayType_HexadecimalLower)
  5320. {
  5321. String format;
  5322. if (sizeof(T) == 8)
  5323. {
  5324. format = StrFormat("0x%%l@\n%s", name.c_str());
  5325. }
  5326. else
  5327. format = StrFormat("0x%%0%dX\n%s", sizeof(val) * 2, name.c_str());
  5328. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5329. }
  5330. if (std::is_unsigned<T>::value)
  5331. {
  5332. if (sizeof(T) == 8)
  5333. {
  5334. if (val > 0x7FFFFFFFF)
  5335. return StrFormat("%llu\n%s\n:editVal\t%lluUL", val, name.c_str(), val);
  5336. else
  5337. return StrFormat("%llu\n%s", val, name.c_str());
  5338. }
  5339. else
  5340. return StrFormat("%u\n%s", val, name.c_str());
  5341. }
  5342. else
  5343. {
  5344. if (sizeof(T) == 8)
  5345. {
  5346. if ((val > 0x7FFFFFFFF) || (val < -0x80000000LL))
  5347. return StrFormat("%lld\n%s\n:editVal\t%lldL", val, name.c_str(), val);
  5348. else
  5349. return StrFormat("%lld\n%s", val, name.c_str(), val);
  5350. }
  5351. else
  5352. return StrFormat("%d\n%s", val, name.c_str());
  5353. }
  5354. }
  5355. DwDisplayInfo* WinDebugger::GetDisplayInfo(const StringImpl& referenceId)
  5356. {
  5357. DwDisplayInfo* displayInfo = &mDebugManager->mDefaultDisplayInfo;
  5358. if (!referenceId.empty())
  5359. {
  5360. mDebugManager->mDisplayInfos.TryGetValue(referenceId, &displayInfo);
  5361. }
  5362. return displayInfo;
  5363. }
  5364. static String WrapWithModifiers(const StringImpl& origName, DbgType* dbgType, DbgLanguage language)
  5365. {
  5366. if (language == DbgLanguage_Unknown)
  5367. language = dbgType->GetLanguage();
  5368. String name = origName;
  5369. while (true)
  5370. {
  5371. if (dbgType->mTypeCode == DbgType_Const)
  5372. {
  5373. if (language == DbgLanguage_Beef)
  5374. name = "readonly " + name;
  5375. else
  5376. name = "const " + name;
  5377. dbgType = dbgType->mTypeParam;
  5378. }
  5379. else if (dbgType->mTypeCode == DbgType_Volatile)
  5380. {
  5381. name = "volatile " + name;
  5382. dbgType = dbgType->mTypeParam;
  5383. }
  5384. else if (dbgType->mTypeCode == DbgType_TypeDef)
  5385. {
  5386. dbgType = dbgType->mTypeParam;
  5387. }
  5388. else if (dbgType->mTypeCode == DbgType_Ref)
  5389. {
  5390. if (language == DbgLanguage_Beef)
  5391. name = "ref " + name;
  5392. else
  5393. name = name + "&";
  5394. dbgType = dbgType->mTypeParam;
  5395. }
  5396. else if (dbgType->mTypeCode == DbgType_Bitfield)
  5397. {
  5398. return dbgType->ToString(language);
  5399. }
  5400. else
  5401. return name;
  5402. }
  5403. }
  5404. DebugVisualizerEntry* WinDebugger::FindVisualizerForType(DbgType* dbgType, Array<String>* wildcardCaptures)
  5405. {
  5406. auto entry = mDebugManager->mDebugVisualizers->FindEntryForType(dbgType->ToString(DbgLanguage_Unknown, true), dbgType->mCompileUnit->mDbgModule->mDbgFlavor, wildcardCaptures);
  5407. if (entry == NULL)
  5408. {
  5409. dbgType = dbgType->GetPrimaryType();
  5410. dbgType->PopulateType();
  5411. for (auto baseTypeEntry : dbgType->mBaseTypes)
  5412. {
  5413. entry = FindVisualizerForType(baseTypeEntry->mBaseType, wildcardCaptures);
  5414. if (entry != NULL)
  5415. break;
  5416. }
  5417. }
  5418. return entry;
  5419. }
  5420. #define GET_FROM(ptr, T) *((T*)(ptr += sizeof(T)) - 1)
  5421. String WinDebugger::ReadString(DbgTypeCode charType, intptr addr, bool isLocalAddr, intptr maxLength, DwFormatInfo& formatInfo)
  5422. {
  5423. int origMaxLength = maxLength;
  5424. if (addr == 0)
  5425. return "";
  5426. BP_ZONE("WinDebugger::ReadString");
  5427. String retVal = "\"";
  5428. bool wasTerminated = false;
  5429. String valString;
  5430. intptr maxShowSize = 255;
  5431. if (maxLength == -1)
  5432. maxLength = formatInfo.mOverrideCount;
  5433. else if (formatInfo.mOverrideCount != -1)
  5434. maxLength = BF_MIN(formatInfo.mOverrideCount, maxLength);
  5435. if (formatInfo.mMaxCount != -1)
  5436. maxLength = BF_MIN(formatInfo.mMaxCount, maxLength);
  5437. if (maxLength == -1)
  5438. maxLength = 8 * 1024 * 1024; // Is 8MB crazy?
  5439. if (!formatInfo.mRawString)
  5440. maxLength = BF_MIN(maxLength, maxShowSize);
  5441. //EnableMemCache();
  5442. bool readFailed = false;
  5443. intptr strPtr = addr;
  5444. int charLen = 1;
  5445. if ((charType == DbgType_SChar16) || (charType == DbgType_UChar16))
  5446. charLen = 2;
  5447. else if ((charType == DbgType_SChar32) || (charType == DbgType_UChar32))
  5448. charLen = 4;
  5449. bool isUTF8 = formatInfo.mDisplayType == DwDisplayType_Utf8;
  5450. int readSize = BF_MIN(1024, maxLength * charLen);
  5451. uint8 buf[1024];
  5452. uint8* bufPtr = NULL;
  5453. uint8* bufEnd = NULL;
  5454. bool hasHighAscii = false;
  5455. int i;
  5456. for (i = 0; i < maxLength; i++)
  5457. {
  5458. if (bufPtr >= bufEnd)
  5459. {
  5460. while (true)
  5461. {
  5462. if (readSize < charLen)
  5463. {
  5464. readFailed = true;
  5465. break;
  5466. }
  5467. if (ReadMemory(strPtr, readSize, buf, isLocalAddr))
  5468. break;
  5469. readSize /= 2;
  5470. }
  5471. if (readFailed)
  5472. break;
  5473. bufPtr = buf;
  5474. bufEnd = buf + readSize;
  5475. }
  5476. switch (charLen)
  5477. {
  5478. case 1:
  5479. {
  5480. char c = GET_FROM(bufPtr, char);
  5481. if ((c != 0) || (formatInfo.mOverrideCount != -1))
  5482. {
  5483. if ((uint8)c >= 0x80)
  5484. hasHighAscii = true;
  5485. valString.Append(c);
  5486. }
  5487. else
  5488. wasTerminated = true;
  5489. }
  5490. break;
  5491. case 2:
  5492. {
  5493. uint16 c16 = GET_FROM(bufPtr, uint16);
  5494. if ((c16 != 0) || (formatInfo.mOverrideCount != -1))
  5495. {
  5496. char str[8];
  5497. u8_toutf8(str, 8, c16);
  5498. valString += str;
  5499. }
  5500. else
  5501. wasTerminated = true;
  5502. }
  5503. break;
  5504. case 4:
  5505. {
  5506. uint32 c32 = GET_FROM(bufPtr, uint32);
  5507. if ((c32 != 0) || (formatInfo.mOverrideCount != -1))
  5508. {
  5509. char str[8];
  5510. u8_toutf8(str, 8, c32);
  5511. valString += str;
  5512. }
  5513. else
  5514. wasTerminated = true;
  5515. }
  5516. break;
  5517. }
  5518. if ((wasTerminated) && (formatInfo.mOverrideCount != -1))
  5519. {
  5520. valString += '\x00';
  5521. wasTerminated = false;
  5522. }
  5523. if ((wasTerminated) || (readFailed))
  5524. {
  5525. break;
  5526. }
  5527. strPtr += charLen;
  5528. }
  5529. //DisableMemCache();
  5530. if (formatInfo.mOverrideCount != -1)
  5531. {
  5532. if (i == formatInfo.mOverrideCount)
  5533. wasTerminated = true;
  5534. }
  5535. if (strPtr == addr + origMaxLength)
  5536. wasTerminated = true;
  5537. if (valString.length() == formatInfo.mOverrideCount)
  5538. wasTerminated = true;
  5539. // if (formatInfo.mDisplayType == DwDisplayType_Ascii)
  5540. // {
  5541. // // Our encoding for retVal is already assumed to be UTF8, so the special case here actually Ascii
  5542. // valString = UTF8Encode(ToWString(valString));
  5543. // }
  5544. if (formatInfo.mRawString)
  5545. {
  5546. if ((formatInfo.mDisplayType == DwDisplayType_Utf8) || (!hasHighAscii))
  5547. return valString;
  5548. String utf8Str;
  5549. for (int i = 0; i < (int)valString.length(); i++)
  5550. {
  5551. char c = valString[i];
  5552. if ((uint8)c >= 0x80)
  5553. {
  5554. utf8Str += (char)(0xC0 | (((uint8)c & 0xFF) >> 6));
  5555. utf8Str += (char)(0x80 | ((uint8)c & 0x3F));
  5556. }
  5557. else
  5558. utf8Str += c;
  5559. }
  5560. return utf8Str;
  5561. }
  5562. if ((readFailed) && (valString.IsEmpty()))
  5563. return "< Failed to read string >";
  5564. retVal += SlashString(valString, true, true, formatInfo.mLanguage == DbgLanguage_Beef);
  5565. // We could go over 'maxShowSize' if we have a lot of slashed chars. An uninitialized string can be filled with '\xcc' chars
  5566. if ((!formatInfo.mRawString) && ((int)retVal.length() > maxShowSize))
  5567. {
  5568. retVal = retVal.Substring(0, maxShowSize);
  5569. wasTerminated = false;
  5570. }
  5571. if (wasTerminated)
  5572. retVal += "\"";
  5573. else
  5574. retVal += "...";
  5575. return retVal;
  5576. }
  5577. void WinDebugger::ProcessEvalString(DbgCompileUnit* dbgCompileUnit, DbgTypedValue useTypedValue, String& evalStr, String& displayString, DwFormatInfo& formatInfo, DebugVisualizerEntry* debugVis, bool limitLength)
  5578. {
  5579. for (int i = 0; i < (int)evalStr.length(); i++)
  5580. {
  5581. char c = evalStr[i];
  5582. char nextC = 0;
  5583. if (i < (int)evalStr.length() - 1)
  5584. nextC = evalStr[i + 1];
  5585. if ((c == '{') && (nextC != '{'))
  5586. {
  5587. // Evaluate
  5588. int endIdx = i;
  5589. for (; endIdx < (int)evalStr.length(); endIdx++)
  5590. {
  5591. //TODO: Do better parsing - this paren could be inside a string, for example
  5592. if (evalStr[endIdx] == '}')
  5593. break;
  5594. }
  5595. DwFormatInfo displayStrFormatInfo = formatInfo;
  5596. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + (int)displayString.length();
  5597. displayStrFormatInfo.mHidePointers = false;
  5598. if ((limitLength) && (displayStrFormatInfo.mTotalSummaryLength > 255))
  5599. {
  5600. displayString += "...";
  5601. }
  5602. else
  5603. {
  5604. String evalString = evalStr.Substring(i + 1, endIdx - i - 1);
  5605. String errors;
  5606. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, useTypedValue, evalString, &displayStrFormatInfo, NULL, &errors);
  5607. if (evalResult)
  5608. {
  5609. if (displayStrFormatInfo.mNoEdit)
  5610. formatInfo.mNoEdit = true;
  5611. String result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  5612. if ((formatInfo.mRawString) && (limitLength))
  5613. {
  5614. displayString = result;
  5615. return;
  5616. }
  5617. int crPos = result.IndexOf('\n');
  5618. if (crPos != -1)
  5619. displayString += result.Substring(0, crPos);
  5620. else
  5621. displayString += result;
  5622. }
  5623. else if (debugVis != NULL)
  5624. {
  5625. displayString += "<DbgVis Failed>";
  5626. DbgVisFailed(debugVis, evalString, errors);
  5627. }
  5628. else
  5629. {
  5630. displayString += "<Eval Failed>";
  5631. }
  5632. }
  5633. i = endIdx;
  5634. continue;
  5635. }
  5636. else if ((c == '{') && (nextC == '{'))
  5637. {
  5638. // Skip next paren
  5639. i++;
  5640. }
  5641. else if ((c == '}') && (nextC == '}'))
  5642. {
  5643. // Skip next paren
  5644. i++;
  5645. }
  5646. displayString += c;
  5647. }
  5648. }
  5649. static bool IsNormalChar(uint32 c)
  5650. {
  5651. return (c < 0x80);
  5652. }
  5653. String WinDebugger::DbgTypedValueToString(const DbgTypedValue& origTypedValue, const StringImpl& expr, DwFormatInfo& formatInfo, DbgExprEvaluator* optEvaluator, bool fullPrecision)
  5654. {
  5655. BP_ZONE("WinDebugger::DbgTypedValueToString");
  5656. DbgTypedValue typedValue = origTypedValue;
  5657. auto dbgCompileUnit = typedValue.mType->mCompileUnit;
  5658. auto dbgModule = typedValue.mType->GetDbgModule();
  5659. auto language = origTypedValue.mType->GetLanguage();
  5660. if (language == DbgLanguage_Unknown)
  5661. language = formatInfo.mLanguage;
  5662. formatInfo.mLanguage = language;
  5663. bool isBeef = language == DbgLanguage_Beef;
  5664. char str[32];
  5665. bool readFailed = false;
  5666. bool isCompositeType = false;
  5667. bool isSizedArray = false;
  5668. bool isEnum = false;
  5669. int64 enumVal = 0;
  5670. String result;
  5671. DwDisplayInfo* displayInfo = GetDisplayInfo(formatInfo.mReferenceId);
  5672. DbgType* origValueType = typedValue.mType;
  5673. bool origHadRef = false;
  5674. DbgType* dwValueType = typedValue.mType->RemoveModifiers(&origHadRef);
  5675. if (dwValueType == NULL)
  5676. dwValueType = dbgModule->GetPrimitiveType(DbgType_Void, language);
  5677. else
  5678. dwValueType = dwValueType->GetPrimaryType();
  5679. if (dwValueType->mTypeCode == DbgType_TypeDef)
  5680. {
  5681. DbgTypedValue realTypedVal = typedValue;
  5682. realTypedVal.mType = dwValueType->mTypeParam;
  5683. return DbgTypedValueToString(realTypedVal, expr, formatInfo, optEvaluator);
  5684. }
  5685. if (formatInfo.mRawString)
  5686. {
  5687. if ((dwValueType->mTypeCode != DbgType_Struct) && (dwValueType->mTypeCode != DbgType_Class) && (dwValueType->mTypeCode != DbgType_Ptr) && (dwValueType->mTypeCode != DbgType_SizedArray))
  5688. return "";
  5689. }
  5690. auto _ShowArraySummary = [&](String& retVal, addr_target ptrVal, int64 arraySize, DbgType* innerType)
  5691. {
  5692. String displayString;
  5693. displayString += "{";
  5694. for (int idx = 0; idx < arraySize; idx++)
  5695. {
  5696. if (formatInfo.mTotalSummaryLength + retVal.length() + displayString.length() > 255)
  5697. {
  5698. displayString += "...";
  5699. break;
  5700. }
  5701. if ((idx != 0) && (!displayString.EndsWith('{')))
  5702. displayString += ", ";
  5703. DwFormatInfo displayStrFormatInfo = formatInfo;
  5704. displayStrFormatInfo.mExpandItemDepth = 1;
  5705. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + retVal.length() + displayString.length();
  5706. displayStrFormatInfo.mHidePointers = false;
  5707. displayStrFormatInfo.mArrayLength = -1;
  5708. // Why did we have this "na" on here? It made "void*[3]" type things show up as "{,,}"
  5709. //String evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + StrFormat(")[%d], na", idx);
  5710. String evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + StrFormat(")[%lld]", idx);
  5711. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, typedValue, evalStr, &displayStrFormatInfo);
  5712. String result;
  5713. if (evalResult)
  5714. {
  5715. result = DbgTypedValueToString(evalResult, evalStr, displayStrFormatInfo, NULL);
  5716. int crPos = result.IndexOf('\n');
  5717. if (crPos != -1)
  5718. result.RemoveToEnd(crPos);
  5719. }
  5720. else
  5721. result = "???";
  5722. displayString += result;
  5723. }
  5724. displayString += "}";
  5725. retVal += displayString;
  5726. };
  5727. if (formatInfo.mArrayLength != -1)
  5728. {
  5729. if (formatInfo.mRawString)
  5730. return "";
  5731. if (dwValueType->IsPointer())
  5732. {
  5733. String retVal;
  5734. addr_target ptrVal = (addr_target)typedValue.mPtr;
  5735. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  5736. {
  5737. retVal = EncodeDataPtr(ptrVal, true) + " ";
  5738. retVal += dwValueType->mTypeParam->ToString(language);
  5739. retVal += StrFormat("[%lld] ", (int64)formatInfo.mArrayLength);
  5740. }
  5741. _ShowArraySummary(retVal, ptrVal, formatInfo.mArrayLength, dwValueType->mTypeParam);
  5742. String idxStr = "[{0}]";
  5743. DbgType* innerType = dwValueType->mTypeParam;
  5744. retVal += "\n" + dwValueType->ToString(language);
  5745. String evalStr = "*((" + typedValue.mType->ToStringRaw(language) + ")" + EncodeDataPtr(ptrVal, true) + " + {0})";
  5746. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, (int)BF_MAX(formatInfo.mArrayLength, 0), 10000) +
  5747. "\t" + idxStr + "\t" + evalStr;
  5748. return retVal;
  5749. }
  5750. else
  5751. {
  5752. DwFormatInfo newFormatInfo = formatInfo;
  5753. newFormatInfo.mArrayLength = -1;
  5754. String retVal = DbgTypedValueToString(typedValue, expr, newFormatInfo, optEvaluator);
  5755. int crPos = (int)retVal.IndexOf('\n');
  5756. if (crPos != -1)
  5757. retVal = "!Array length flag not valid with this type" + retVal.Substring(crPos);
  5758. return retVal;
  5759. }
  5760. }
  5761. switch (dwValueType->mTypeCode)
  5762. {
  5763. case DbgType_Void:
  5764. return "\nvoid";
  5765. case DbgType_Bool:
  5766. {
  5767. if (typedValue.mUInt8 == 0)
  5768. return "false\n" + WrapWithModifiers("bool", origValueType, language);
  5769. else if (typedValue.mUInt8 == 1)
  5770. return "true\n" + WrapWithModifiers("bool", origValueType, language);
  5771. else
  5772. return StrFormat("true (%d)\n", typedValue.mUInt8) + WrapWithModifiers("bool", origValueType, language);
  5773. }
  5774. break;
  5775. case DbgType_UChar:
  5776. if (language != DbgLanguage_Beef)
  5777. return IntTypeToString<uint8>(typedValue.mUInt8, WrapWithModifiers("uint8_t", origValueType, language), displayInfo, formatInfo);
  5778. case DbgType_SChar:
  5779. {
  5780. if (typedValue.mInt8 != 0)
  5781. {
  5782. char str[2] = {(char)typedValue.mInt8};
  5783. result = SlashString(str, formatInfo.mDisplayType == DwDisplayType_Utf8, true);
  5784. if (!IsNormalChar(typedValue.mUInt8))
  5785. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt8);
  5786. else
  5787. result = StrFormat("'%s'\n", result.c_str());
  5788. }
  5789. else
  5790. result = "'\\0'\n";
  5791. return result + WrapWithModifiers("char", origValueType, language);
  5792. }
  5793. break;
  5794. case DbgType_UChar16:
  5795. if (language != DbgLanguage_Beef)
  5796. return IntTypeToString<int16>(typedValue.mUInt8, WrapWithModifiers("uint16_t", origValueType, language), displayInfo, formatInfo);
  5797. case DbgType_SChar16:
  5798. {
  5799. if (typedValue.mInt16 != 0)
  5800. {
  5801. u8_toutf8(str, 8, typedValue.mUInt32);
  5802. result = SlashString(str, true, true);
  5803. if (!IsNormalChar(typedValue.mUInt32))
  5804. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt16);
  5805. else
  5806. result = StrFormat("'%s'\n", result.c_str());
  5807. }
  5808. else
  5809. result = "'\\0'\n";
  5810. return result + WrapWithModifiers(isBeef ? "char16" : "int16_t", origValueType, language);
  5811. }
  5812. break;
  5813. case DbgType_UChar32:
  5814. case DbgType_SChar32:
  5815. {
  5816. if (typedValue.mInt32 != 0)
  5817. {
  5818. u8_toutf8(str, 8, typedValue.mUInt32);
  5819. result = SlashString(str, true, true);
  5820. if (!IsNormalChar(typedValue.mUInt32))
  5821. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt32);
  5822. else
  5823. result = StrFormat("'%s'\n", result.c_str());
  5824. }
  5825. else
  5826. result = "'\\0'\n";
  5827. return result + WrapWithModifiers(isBeef ? "char32" : "int32_t", origValueType, language);
  5828. }
  5829. break;
  5830. case DbgType_i8:
  5831. return IntTypeToString<int8>(typedValue.mInt8, WrapWithModifiers(isBeef ? "int8" : "int8_t", origValueType, language), displayInfo, formatInfo);
  5832. case DbgType_u8:
  5833. return IntTypeToString<uint8>(typedValue.mUInt8, WrapWithModifiers(isBeef ? "uint8" : "uint8_t", origValueType, language), displayInfo, formatInfo);
  5834. case DbgType_i16:
  5835. return IntTypeToString<int16>(typedValue.mInt16, WrapWithModifiers(isBeef ? "int16" : "int16_t", origValueType, language), displayInfo, formatInfo);
  5836. case DbgType_u16:
  5837. return IntTypeToString<uint16>(typedValue.mUInt16, WrapWithModifiers(isBeef ? "uint16" : "uint16_t", origValueType, language), displayInfo, formatInfo);
  5838. case DbgType_i32:
  5839. return IntTypeToString<int32>(typedValue.mInt32, WrapWithModifiers(isBeef ? "int32" : "int32_t", origValueType, language), displayInfo, formatInfo);
  5840. case DbgType_u32:
  5841. return IntTypeToString<uint32>(typedValue.mUInt32, WrapWithModifiers(isBeef ? "uint32" : "uint32_t", origValueType, language), displayInfo, formatInfo);
  5842. case DbgType_i64:
  5843. return IntTypeToString<int64>(typedValue.mInt64, WrapWithModifiers(isBeef ? "int64" : "int64_t", origValueType, language), displayInfo, formatInfo);
  5844. case DbgType_u64:
  5845. return IntTypeToString<uint64>(typedValue.mUInt64, WrapWithModifiers(isBeef ? "uint64" : "uint64_t", origValueType, language), displayInfo, formatInfo);
  5846. case DbgType_RegGroup:
  5847. {
  5848. if ((typedValue.mRegNum >= CPUReg_M128_XMMREG_FIRST) && (typedValue.mRegNum <= CPUReg_M128_XMMREG_LAST))
  5849. {
  5850. int callStackIdx = formatInfo.mCallStackIdx;
  5851. FixCallStackIdx(callStackIdx);
  5852. UpdateRegisterUsage(callStackIdx);
  5853. WdStackFrame* wdStackFrame = mCallStack[callStackIdx];
  5854. RegForm regForm = RegForm_Unknown;
  5855. if (typedValue.mRegNum < (int)wdStackFrame->mRegForms.size())
  5856. regForm = wdStackFrame->mRegForms[typedValue.mRegNum];
  5857. int xmmMajor = typedValue.mRegNum - CPUReg_M128_XMMREG_FIRST;
  5858. String headerStr;
  5859. String xmmType = "__m128";
  5860. int xmmCount = 4;
  5861. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2) ||
  5862. (regForm == RegForm_Long) || (regForm == RegForm_Long2) ||
  5863. (regForm == RegForm_ULong) || (regForm == RegForm_ULong2))
  5864. xmmCount = 2;
  5865. //TODO: add byte, short, int, etc...
  5866. if (optEvaluator)
  5867. {
  5868. DwMmDisplayType mmDwMmDisplayType = displayInfo->mMmDisplayType;
  5869. if (mmDwMmDisplayType == DwMmDisplayType_Default)
  5870. {
  5871. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2))
  5872. mmDwMmDisplayType = DwMmDisplayType_Double;
  5873. else if (regForm == RegForm_Int4)
  5874. mmDwMmDisplayType = DwMmDisplayType_Int;
  5875. }
  5876. //TODO: Add support for int types
  5877. if (mmDwMmDisplayType == DwMmDisplayType_Double)
  5878. {
  5879. xmmType = "__m128d";
  5880. xmmCount = 2;
  5881. double xmmRegVals[2];
  5882. CPURegisters* regs = optEvaluator->GetRegisters();
  5883. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5884. {
  5885. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5886. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_Double);
  5887. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5888. xmmRegVals[xmmMinor] = xmmReg.mDouble;
  5889. }
  5890. headerStr = StrFormat("(%f, %f)", xmmRegVals[0], xmmRegVals[1]);
  5891. }
  5892. else if (mmDwMmDisplayType == DwMmDisplayType_Byte)
  5893. {
  5894. int xmmRegVals[4];
  5895. xmmCount = 4;
  5896. CPURegisters* regs = optEvaluator->GetRegisters();
  5897. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5898. {
  5899. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5900. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i32);
  5901. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5902. xmmRegVals[xmmMinor] = xmmReg.mInt8;
  5903. }
  5904. headerStr = StrFormat("(%d, %d, %d, %d)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  5905. }
  5906. else if (mmDwMmDisplayType == DwMmDisplayType_Short)
  5907. {
  5908. int xmmRegVals[4];
  5909. xmmCount = 4;
  5910. CPURegisters* regs = optEvaluator->GetRegisters();
  5911. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5912. {
  5913. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5914. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i32);
  5915. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5916. xmmRegVals[xmmMinor] = xmmReg.mInt16;
  5917. }
  5918. headerStr = StrFormat("(%d, %d, %d, %d)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  5919. }
  5920. else if (mmDwMmDisplayType == DwMmDisplayType_Int)
  5921. {
  5922. int xmmRegVals[4];
  5923. xmmCount = 4;
  5924. CPURegisters* regs = optEvaluator->GetRegisters();
  5925. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5926. {
  5927. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5928. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i32);
  5929. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5930. xmmRegVals[xmmMinor] = xmmReg.mInt32;
  5931. }
  5932. headerStr = StrFormat("(%d, %d, %d, %d)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  5933. }
  5934. else // Float
  5935. {
  5936. float xmmRegVals[4];
  5937. xmmCount = 4;
  5938. CPURegisters* regs = optEvaluator->GetRegisters();
  5939. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5940. {
  5941. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5942. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_Single);
  5943. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5944. xmmRegVals[xmmMinor] = xmmReg.mSingle;
  5945. }
  5946. headerStr = StrFormat("(%f, %f, %f, %f)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  5947. }
  5948. }
  5949. else
  5950. {
  5951. headerStr = StrFormat("XMM%d", xmmMajor);
  5952. }
  5953. result = headerStr + "\n" + xmmType;
  5954. for (int i = 0; i < xmmCount; i++)
  5955. result += WrapWithModifiers(StrFormat("\n[%d]\t$xmm%d_%d", i, xmmMajor, i, language), origValueType, language);
  5956. return result;
  5957. }
  5958. else
  5959. {
  5960. switch (typedValue.mRegNum)
  5961. {
  5962. case CPUReg_CAT_ALLREGS:
  5963. {
  5964. return "ALLREGS\n__allregs\niregs\t$iregs\nflags\t$flags\nfpregs\t$fpregs\nmmregs\t$mmregs\nxmmregs\t$xmmregs";
  5965. }
  5966. break;
  5967. case CPUReg_CAT_IREGS:
  5968. {
  5969. #ifdef BF_DBG_32
  5970. String headerStr;
  5971. if (optEvaluator)
  5972. {
  5973. CPURegisters* regs = optEvaluator->GetRegisters();
  5974. 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)",
  5975. (uint32)regs->mIntRegs.eax, (uint32)regs->mIntRegs.ebx, (uint32)regs->mIntRegs.ecx, (uint32)regs->mIntRegs.edx,
  5976. (uint32)regs->mIntRegs.esi, (uint32)regs->mIntRegs.edi, (uint32)regs->mIntRegs.esp, (uint32)regs->mIntRegs.ebp,
  5977. (uint32)regs->mIntRegs.eip, (uint32)regs->mIntRegs.efl);
  5978. }
  5979. else
  5980. {
  5981. headerStr = "IREGS";
  5982. }
  5983. 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());
  5984. #else
  5985. String headerStr;
  5986. if (optEvaluator)
  5987. {
  5988. CPURegisters* regs = optEvaluator->GetRegisters();
  5989. 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)",
  5990. (uint64)regs->mIntRegs.rax, (uint64)regs->mIntRegs.rbx, (uint64)regs->mIntRegs.rcx, (uint64)regs->mIntRegs.rdx,
  5991. (uint64)regs->mIntRegs.rsi, (uint64)regs->mIntRegs.rdi, (uint64)regs->mIntRegs.rsp, (uint64)regs->mIntRegs.rbp,
  5992. (uint64)regs->mIntRegs.rip,
  5993. (uint64)regs->mIntRegs.r8, (uint64)regs->mIntRegs.r9, (uint64)regs->mIntRegs.r10, (uint64)regs->mIntRegs.r11,
  5994. (uint64)regs->mIntRegs.r12, (uint64)regs->mIntRegs.r13, (uint64)regs->mIntRegs.r14, (uint64)regs->mIntRegs.r15,
  5995. (uint32)regs->mIntRegs.efl);
  5996. }
  5997. else
  5998. {
  5999. headerStr = "IREGS";
  6000. }
  6001. 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());
  6002. #endif
  6003. }
  6004. break;
  6005. case CPUReg_CAT_FPREGS:
  6006. {
  6007. String headerStr;
  6008. if (optEvaluator)
  6009. {
  6010. CPURegisters* regs = optEvaluator->GetRegisters();
  6011. headerStr = "(";
  6012. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6013. {
  6014. if (i)
  6015. headerStr += ", ";
  6016. double val = ConvertFloat80ToDouble(regs->mFpMmRegsArray[i].fp.fp80);
  6017. headerStr += StrFormat("%f", val);
  6018. }
  6019. headerStr += ")";
  6020. }
  6021. else
  6022. {
  6023. headerStr = "FPREGS";
  6024. }
  6025. result = StrFormat("%s\n__fpregs", headerStr.c_str());
  6026. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6027. result += StrFormat("\n[%d]\t$st%d", i, i);
  6028. return result;
  6029. }
  6030. break;
  6031. case CPUReg_CAT_MMREGS:
  6032. {
  6033. String headerStr;
  6034. if (optEvaluator)
  6035. {
  6036. CPURegisters* regs = optEvaluator->GetRegisters();
  6037. headerStr = "(";
  6038. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6039. {
  6040. if (i)
  6041. headerStr += ", ";
  6042. uint64 val = regs->mFpMmRegsArray[i].mm;
  6043. headerStr += StrFormat("0x%016llx", val);
  6044. }
  6045. headerStr += ")";
  6046. }
  6047. else
  6048. {
  6049. headerStr = "MMREGS";
  6050. }
  6051. result = StrFormat("%s\n__mmregs", headerStr.c_str());
  6052. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6053. result += StrFormat("\n[%d]\t$mm%d", i, i);
  6054. return result;
  6055. }
  6056. break;
  6057. case CPUReg_CAT_XMMREGS:
  6058. {
  6059. String headerStr = StrFormat("XMMREGS[%d]", CPURegisters::kNumXmmRegs); // these are too big to put a useful header for the entire category
  6060. result = StrFormat("%s\n__xmmregs", headerStr.c_str());
  6061. for (int i = 0; i < CPURegisters::kNumXmmRegs; ++i)
  6062. result += StrFormat("\n[%d]\t$xmm%d", i, i);
  6063. return result;
  6064. }
  6065. break;
  6066. case CPUReg_CAT_FLAGS:
  6067. {
  6068. String headerStr;
  6069. if (optEvaluator)
  6070. {
  6071. CPURegisters* regs = optEvaluator->GetRegisters();
  6072. #ifdef BF_DBG_32
  6073. #define FLAGVAR(abbr, name) int flag##abbr = ((regs->mIntRegs.efl & ((uint64)1 << CPURegisters::GetFlagBitForRegister(X86Reg_FLAG_##abbr##_##name))) != 0) ? 1 : 0
  6074. FLAGVAR(CF, CARRY);
  6075. FLAGVAR(PF, PARITY);
  6076. FLAGVAR(AF, ADJUST);
  6077. FLAGVAR(ZF, ZERO);
  6078. FLAGVAR(SF, SIGN);
  6079. FLAGVAR(IF, INTERRUPT);
  6080. FLAGVAR(DF, DIRECTION);
  6081. FLAGVAR(OF, OVERFLOW);
  6082. #undef FLAGVAR
  6083. #else
  6084. #define FLAGVAR(abbr, name) int flag##abbr = ((regs->mIntRegs.efl & ((uint64)1 << CPURegisters::GetFlagBitForRegister(X64Reg_FLAG_##abbr##_##name))) != 0) ? 1 : 0
  6085. FLAGVAR(CF, CARRY);
  6086. FLAGVAR(PF, PARITY);
  6087. FLAGVAR(AF, ADJUST);
  6088. FLAGVAR(ZF, ZERO);
  6089. FLAGVAR(SF, SIGN);
  6090. FLAGVAR(IF, INTERRUPT);
  6091. FLAGVAR(DF, DIRECTION);
  6092. FLAGVAR(OF, OVERFLOW);
  6093. #undef FLAGVAR
  6094. #endif
  6095. headerStr = StrFormat("(CF=%d, PF=%d, AF=%d, ZF=%d, SF=%d, IF=%d, DF=%d, OF=%d)",
  6096. flagCF, flagPF, flagAF, flagZF, flagSF, flagIF, flagDF, flagOF);
  6097. }
  6098. else
  6099. {
  6100. headerStr = "FLAGS";
  6101. }
  6102. 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",
  6103. headerStr.c_str());
  6104. }
  6105. break;
  6106. default:
  6107. BF_ASSERT(false && "unknown category register");
  6108. return "UNKNOWNCATEGORY\n__unknown\n";
  6109. }
  6110. }
  6111. }
  6112. break;
  6113. case DbgType_Single:
  6114. {
  6115. DwFloatDisplayType floatDisplayType = displayInfo->mFloatDisplayType;
  6116. if (floatDisplayType == DwFloatDisplayType_Default)
  6117. floatDisplayType = DwFloatDisplayType_Minimal;
  6118. if (floatDisplayType == DwFloatDisplayType_Minimal)
  6119. ExactMinimalFloatToStr(typedValue.mSingle, str);
  6120. else if (floatDisplayType == DwFloatDisplayType_Full)
  6121. sprintf(str, "%1.9g", typedValue.mSingle);
  6122. else if (floatDisplayType == DwFloatDisplayType_HexUpper)
  6123. sprintf(str, "0x%04X", typedValue.mUInt32);
  6124. else //if (floatDisplayType == DwFloatDisplayType_HexLower)
  6125. sprintf(str, "0x%04x", typedValue.mUInt32);
  6126. return StrFormat("%s\n%s", str, WrapWithModifiers("float", origValueType, language).c_str());
  6127. }
  6128. case DbgType_Double:
  6129. {
  6130. DwFloatDisplayType floatDisplayType = displayInfo->mFloatDisplayType;
  6131. if (floatDisplayType == DwFloatDisplayType_Default)
  6132. floatDisplayType = DwFloatDisplayType_Minimal;
  6133. if (floatDisplayType == DwFloatDisplayType_Minimal)
  6134. ExactMinimalDoubleToStr(typedValue.mDouble, str);
  6135. else if (floatDisplayType == DwFloatDisplayType_Full)
  6136. sprintf(str, "%1.17g", typedValue.mDouble);
  6137. else if (floatDisplayType == DwFloatDisplayType_HexUpper)
  6138. sprintf(str, "0x%08llX", typedValue.mUInt64);
  6139. else //if (floatDisplayType == DwFloatDisplayType_HexLower)
  6140. sprintf(str, "0x%08llx", typedValue.mUInt64);
  6141. return StrFormat("%s\n%s", str, WrapWithModifiers("double", origValueType, language).c_str());
  6142. }
  6143. case DbgType_Subroutine:
  6144. if (typedValue.mCharPtr != NULL)
  6145. return StrFormat("%s\nfunc", typedValue.mCharPtr);
  6146. else
  6147. return "\nfunc";
  6148. case DbgType_RawText:
  6149. return StrFormat("%s\nrawtext", typedValue.mCharPtr);
  6150. case DbgType_Ptr:
  6151. {
  6152. addr_target ptrVal = (addr_target)typedValue.mPtr;
  6153. String retVal;
  6154. DbgType* innerType = dwValueType->mTypeParam;
  6155. if (innerType == NULL)
  6156. return EncodeDataPtr(ptrVal, true) + "\nvoid*";
  6157. bool isChar = false;
  6158. DbgType* unmodInnerType = innerType->RemoveModifiers();
  6159. if (unmodInnerType != NULL)
  6160. {
  6161. if (language == DbgLanguage_Beef)
  6162. {
  6163. if ((unmodInnerType->mTypeCode == DbgType_UChar) ||
  6164. (unmodInnerType->mTypeCode == DbgType_UChar16) ||
  6165. (unmodInnerType->mTypeCode == DbgType_UChar32))
  6166. isChar = true;
  6167. }
  6168. else
  6169. {
  6170. if ((unmodInnerType->mTypeCode == DbgType_SChar) ||
  6171. (unmodInnerType->mTypeCode == DbgType_SChar16) ||
  6172. (unmodInnerType->mTypeCode == DbgType_SChar32))
  6173. isChar = true;
  6174. }
  6175. }
  6176. if ((isChar) && (formatInfo.mArrayLength == -1))
  6177. {
  6178. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6179. retVal = EncodeDataPtr(ptrVal, true);
  6180. int strLen = formatInfo.mOverrideCount;
  6181. if (typedValue.mIsLiteral)
  6182. {
  6183. if (strLen == -1)
  6184. strLen = 0x7FFFFFFF;
  6185. if (typedValue.mDataLen > 0)
  6186. strLen = BF_MIN(strLen, typedValue.mDataLen);
  6187. else
  6188. strLen = BF_MIN(strLen, strlen(typedValue.mCharPtr));
  6189. }
  6190. SetAndRestoreValue<intptr> prevOverrideLen(formatInfo.mOverrideCount, strLen);
  6191. String strResult = ReadString(unmodInnerType->mTypeCode, typedValue.mLocalIntPtr, typedValue.mIsLiteral, strLen, formatInfo);
  6192. if (formatInfo.mRawString)
  6193. return strResult;
  6194. if (!strResult.IsEmpty())
  6195. {
  6196. if (!retVal.IsEmpty())
  6197. retVal += " ";
  6198. retVal += strResult;
  6199. }
  6200. retVal += "\n" + origValueType->ToString(language);
  6201. return retVal;
  6202. }
  6203. else if ((unmodInnerType != NULL) &&
  6204. ((unmodInnerType->mTypeCode == DbgType_Class) || (unmodInnerType->mTypeCode == DbgType_Struct) || (unmodInnerType->mTypeCode == DbgType_Union)))
  6205. {
  6206. isCompositeType = true;
  6207. }
  6208. else if ((unmodInnerType != NULL) && (unmodInnerType->mTypeCode == DbgType_SizedArray))
  6209. {
  6210. isSizedArray = true;
  6211. }
  6212. else if (unmodInnerType->mTypeCode == DbgType_Subroutine)
  6213. {
  6214. if (formatInfo.mRawString)
  6215. return "";
  6216. addr_target funcPtr = (addr_target)typedValue.mPtr;
  6217. String retVal;
  6218. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6219. retVal = EncodeDataPtr(funcPtr, true);
  6220. String symbolName;
  6221. addr_target offset;
  6222. DbgModule* dwarf;
  6223. static String demangledName;
  6224. auto subProgram = mDebugTarget->FindSubProgram(funcPtr);
  6225. if (subProgram != NULL)
  6226. {
  6227. demangledName = subProgram->ToString();
  6228. }
  6229. else if (mDebugTarget->FindSymbolAt(funcPtr, &symbolName, &offset, &dwarf))
  6230. {
  6231. demangledName = BfDemangler::Demangle(symbolName, language);
  6232. if (offset != 0)
  6233. demangledName += StrFormat("+%d", offset);
  6234. }
  6235. else
  6236. {
  6237. auto dbgModule = mDebugTarget->FindDbgModuleForAddress(funcPtr);
  6238. if (dbgModule != NULL)
  6239. demangledName += dbgModule->GetLinkedModule()->mDisplayName + "!";
  6240. demangledName += StrFormat("0x%@", funcPtr);
  6241. }
  6242. retVal += " {";
  6243. retVal += demangledName;
  6244. retVal += "}";
  6245. retVal += "\n" + origValueType->ToString(language);
  6246. return retVal;
  6247. }
  6248. else if (unmodInnerType->mTypeCode == DbgType_Void)
  6249. {
  6250. if (formatInfo.mRawString)
  6251. return "";
  6252. addr_target ptr = (addr_target)typedValue.mPtr;
  6253. String symbolName;
  6254. addr_target offset;
  6255. DbgModule* dwarf;
  6256. String demangledName;
  6257. retVal += demangledName = StrFormat("0x%@", ptr);
  6258. if (mDebugTarget->FindSymbolAt(ptr, &symbolName, &offset, &dwarf))
  6259. {
  6260. if (offset == 0)
  6261. {
  6262. retVal += " {";
  6263. retVal += BfDemangler::Demangle(symbolName, language);
  6264. retVal += "}";
  6265. }
  6266. }
  6267. retVal += "\n" + origValueType->ToString(language);
  6268. return retVal;
  6269. }
  6270. else
  6271. {
  6272. if (formatInfo.mRawString)
  6273. return "";
  6274. addr_target ptrVal = (addr_target)typedValue.mPtr;
  6275. String retVal;
  6276. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6277. retVal = EncodeDataPtr(ptrVal, true);
  6278. if (ptrVal != 0)
  6279. {
  6280. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, NULL, -1, -1);
  6281. DbgTypedValue innerTypedVal = dbgExprEvaluator.ReadTypedValue(NULL, innerType, typedValue.mPtr, DbgAddrType_Target);
  6282. if (innerTypedVal)
  6283. {
  6284. DwFormatInfo defaultFormatInfo;
  6285. defaultFormatInfo.mLanguage = formatInfo.mLanguage;
  6286. defaultFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + 2; // Take into accout the necessary {}'s
  6287. defaultFormatInfo.mExpandItemDepth++;
  6288. String innerStr = DbgTypedValueToString(innerTypedVal, "", defaultFormatInfo, &dbgExprEvaluator);
  6289. int crIdx = innerStr.IndexOf('\n');
  6290. if (crIdx != -1)
  6291. {
  6292. String innerDataStr = innerStr.Substring(0, crIdx);
  6293. if (!innerDataStr.empty())
  6294. {
  6295. if (!retVal.empty())
  6296. retVal += " ";
  6297. retVal += "{" + innerDataStr + "}";
  6298. }
  6299. }
  6300. else
  6301. {
  6302. retVal += "{ ??? }";
  6303. }
  6304. }
  6305. }
  6306. retVal += "\n" + origValueType->ToString(language);
  6307. innerType->PopulateType();
  6308. if ((ptrVal != 0) &&
  6309. ((!innerType->mMemberList.IsEmpty()) || (innerType->mSize > 0) || (innerType->mTypeParam != NULL)))
  6310. {
  6311. String ptrDataStr = StrFormat("(%s)", dwValueType->ToStringRaw(language).c_str()) + EncodeDataPtr(typedValue.mPtr, true);
  6312. retVal += "\n*\t";
  6313. // Why did we have this? It messed up a pointer to sized array
  6314. /*if (language == DbgLanguage_Beef)
  6315. retVal += "this";
  6316. else*/
  6317. retVal += "*this";
  6318. if (!formatInfo.mReferenceId.empty())
  6319. retVal += ", refid=" + MaybeQuoteFormatInfoParam(formatInfo.mReferenceId);
  6320. retVal += ", this=" + ptrDataStr;
  6321. }
  6322. return retVal;
  6323. }
  6324. break;
  6325. }
  6326. case DbgType_Union:
  6327. case DbgType_Class:
  6328. case DbgType_Struct:
  6329. isCompositeType = true;
  6330. break;
  6331. case DbgType_Enum:
  6332. enumVal = typedValue.GetInt64();
  6333. isEnum = true;
  6334. break;
  6335. case DbgType_SizedArray:
  6336. {
  6337. isSizedArray = true;
  6338. }
  6339. break;
  6340. default:
  6341. break;
  6342. }
  6343. if (isSizedArray)
  6344. {
  6345. String retVal;
  6346. addr_target ptrVal = 0;
  6347. DbgType* arrayType = dwValueType;
  6348. DbgType* innerType = dwValueType->mTypeParam;
  6349. if (dwValueType->mTypeCode == DbgType_SizedArray)
  6350. {
  6351. ptrVal = (addr_target)typedValue.mSrcAddress;
  6352. }
  6353. else
  6354. {
  6355. BF_ASSERT(dwValueType->mTypeCode == DbgType_Ptr);
  6356. arrayType = innerType;
  6357. innerType = arrayType->mTypeParam;
  6358. ptrVal = typedValue.mPtr;
  6359. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6360. retVal = EncodeDataPtr(ptrVal, true) + " ";
  6361. }
  6362. if (ptrVal == 0)
  6363. ptrVal = typedValue.mPtr;
  6364. intptr arraySize = 0;
  6365. intptr innerSize = innerType->GetStride();
  6366. if (innerSize > 0)
  6367. arraySize = arrayType->GetStride() / innerSize;
  6368. else
  6369. {
  6370. // Failure!
  6371. }
  6372. String idxStr = "[{0}]";
  6373. if (innerType->IsChar(language))
  6374. {
  6375. String strVal = ReadString(innerType->mTypeCode, typedValue.mSrcAddress, false, arraySize, formatInfo);
  6376. if (formatInfo.mRawString)
  6377. return strVal;
  6378. retVal += strVal;
  6379. }
  6380. else
  6381. {
  6382. if (formatInfo.mRawString)
  6383. return "";
  6384. _ShowArraySummary(retVal, ptrVal, arraySize, innerType);
  6385. }
  6386. retVal += "\n" + origValueType->ToString(language);
  6387. String referenceId = dwValueType->ToString(language);
  6388. String evalStr;
  6389. // Why did we have the "na"? Do we not want to show addresses for all members?
  6390. evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + ")[{0}], refid=" + MaybeQuoteFormatInfoParam(referenceId + ".[]");
  6391. if (typedValue.mIsReadOnly)
  6392. evalStr += ", ne";
  6393. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, (int)BF_MAX(arraySize, 0), 10000) +
  6394. "\t" + idxStr + "\t" + evalStr;
  6395. return retVal;
  6396. }
  6397. dwValueType->PopulateType();
  6398. if (isEnum)
  6399. {
  6400. String retVal;
  6401. int64 bitsLeft = enumVal;
  6402. int valueCount = 0;
  6403. String editVal;
  6404. dwValueType = dwValueType->GetPrimaryType();
  6405. dwValueType->PopulateType();
  6406. while ((bitsLeft != 0) || (valueCount == 0))
  6407. {
  6408. DbgVariable* bestMatch = NULL;
  6409. for (auto member : dwValueType->mMemberList)
  6410. {
  6411. if (member->mConstValue == bitsLeft)
  6412. {
  6413. bestMatch = member;
  6414. break;
  6415. }
  6416. }
  6417. if (bestMatch == NULL)
  6418. {
  6419. for (auto member : dwValueType->mMemberList)
  6420. {
  6421. if ((member->mConstValue != 0) &&
  6422. ((member->mConstValue & bitsLeft) == member->mConstValue))
  6423. {
  6424. bestMatch = member;
  6425. break;
  6426. }
  6427. }
  6428. }
  6429. if (bestMatch == NULL)
  6430. break;
  6431. if (valueCount > 0)
  6432. {
  6433. retVal += " | ";
  6434. if (language == DbgLanguage_C)
  6435. editVal += " | ";
  6436. }
  6437. if (language == DbgLanguage_Beef)
  6438. retVal += ".";
  6439. retVal += bestMatch->mName;
  6440. if (language == DbgLanguage_C)
  6441. {
  6442. if (dwValueType->mParent != NULL)
  6443. {
  6444. editVal += dwValueType->mParent->ToString(language);
  6445. editVal += "::";
  6446. }
  6447. editVal += bestMatch->mName;
  6448. }
  6449. valueCount++;
  6450. bitsLeft &= ~bestMatch->mConstValue;
  6451. }
  6452. if ((valueCount == 0) || (bitsLeft != 0))
  6453. {
  6454. if (valueCount > 0)
  6455. retVal += " | ";
  6456. retVal += StrFormat("%d", bitsLeft);
  6457. if (language == DbgLanguage_C)
  6458. {
  6459. if (valueCount > 0)
  6460. editVal += " | ";
  6461. editVal += StrFormat("%d", bitsLeft);
  6462. }
  6463. }
  6464. retVal += "\n" + origValueType->ToString();
  6465. if (language == DbgLanguage_C)
  6466. {
  6467. retVal += "\n:editVal\t";
  6468. retVal += editVal;
  6469. }
  6470. retVal += "\n:canEdit";
  6471. return retVal;
  6472. }
  6473. else if (isCompositeType)
  6474. {
  6475. addr_target ptrVal;
  6476. if (dwValueType->IsPointer())
  6477. ptrVal = (addr_target)typedValue.mPtr;
  6478. else
  6479. ptrVal = (addr_target)typedValue.mSrcAddress;
  6480. String retVal;
  6481. if ((!typedValue.mIsLiteral) && (dwValueType->IsPointer()) &&
  6482. ((!formatInfo.mHidePointers) || (ptrVal == 0)))
  6483. retVal = EncodeDataPtr(ptrVal, true);
  6484. DbgType* innerType = dwValueType;
  6485. bool wasPtr = false;
  6486. if (innerType->mTypeCode == DbgType_Ptr)
  6487. {
  6488. wasPtr = true;
  6489. innerType = dwValueType->mTypeParam;
  6490. innerType = innerType->RemoveModifiers();
  6491. }
  6492. innerType = innerType->GetPrimaryType();
  6493. addr_target dataPtr = wasPtr ? typedValue.mPtr : typedValue.mSrcAddress;
  6494. DbgType* actualType = NULL;
  6495. bool useActualRawType = false;
  6496. bool isBfObject = innerType->IsBfObject();
  6497. bool hasCPPVTable = false;
  6498. if (!isBfObject)
  6499. hasCPPVTable = innerType->HasCPPVTable();
  6500. int bfObjectFlags = 0;
  6501. addr_target classVDataPtr = 0;
  6502. bool isAppendBfObject = false;
  6503. bool isStackBfObject = false;
  6504. bool isDeletedBfObject = false;
  6505. bool isCompositeWithoutAddress = false;
  6506. if (innerType->IsBfPayloadEnum())
  6507. {
  6508. if (formatInfo.mRawString)
  6509. return "";
  6510. auto tagMember = innerType->mMemberList.mTail;
  6511. int tagIdx = 0;
  6512. if (dataPtr == -1)
  6513. {
  6514. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, "(int)" + expr, &formatInfo);
  6515. auto dscValue = dbgEvaluationContext.EvaluateInContext(DbgTypedValue());
  6516. tagIdx = dscValue.mInt32;
  6517. }
  6518. else if (!ReadMemory((intptr)ptrVal + tagMember->mMemberOffset, tagMember->mType->mSize, (void*)&tagIdx))
  6519. {
  6520. return StrFormat("!Failed to read from 0x%@", ptrVal);
  6521. }
  6522. char findStr[16];
  6523. findStr[0] = '_';
  6524. itoa(tagIdx, findStr + 1, 10);
  6525. int len = strlen(findStr);
  6526. findStr[len] = '_';
  6527. len++;
  6528. if (!retVal.empty())
  6529. retVal += " ";
  6530. int startIdx = 0;
  6531. for (auto member : innerType->mMemberList)
  6532. {
  6533. if (strncmp(member->mName, findStr, len) == 0)
  6534. {
  6535. retVal += ".";
  6536. retVal += member->mName + len;
  6537. String tupleExpr;
  6538. DbgTypedValue tupleVal;
  6539. if (dataPtr == -1)
  6540. {
  6541. tupleVal.mSrcAddress = -1;
  6542. tupleVal.mType = member->mType;
  6543. //tupleExpr = "$" + expr + "$u";
  6544. tupleVal.mVariable = typedValue.mVariable;
  6545. tupleExpr = "(" + member->mType->ToStringRaw() + ")(" + expr + ")";
  6546. }
  6547. else
  6548. {
  6549. tupleVal.mType = member->mType;
  6550. tupleVal.mSrcAddress = ptrVal;
  6551. }
  6552. DwFormatInfo displayStrFormatInfo = formatInfo;
  6553. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + (int)retVal.length();
  6554. displayStrFormatInfo.mExpandItemDepth++;
  6555. displayStrFormatInfo.mHidePointers = false;
  6556. retVal += DbgTypedValueToString(tupleVal, tupleExpr, displayStrFormatInfo, NULL);
  6557. int idx = (int)retVal.IndexOf('\n');
  6558. if (idx != -1)
  6559. {
  6560. if ((idx > 2) && (strncmp(retVal.c_str() + idx - 2, "()", 2) == 0))
  6561. {
  6562. // Take off a terminating "()" on the value, if there is one
  6563. retVal.Remove(idx - 2, 2);
  6564. }
  6565. String typeName = innerType->ToString(DbgLanguage_Unknown, true);
  6566. typeName += " ";
  6567. retVal.Insert(idx + 1, typeName);
  6568. }
  6569. return retVal;
  6570. }
  6571. }
  6572. }
  6573. if (isBfObject)
  6574. {
  6575. classVDataPtr = ReadMemory<addr_target>(ptrVal);
  6576. mDebugTarget->GetCompilerSettings();
  6577. if (mDebugTarget->mBfObjectHasFlags)
  6578. {
  6579. bfObjectFlags = ((int)classVDataPtr) & 0xFF;
  6580. if ((bfObjectFlags & BfObjectFlag_Deleted) != 0)
  6581. isDeletedBfObject = true;
  6582. if ((bfObjectFlags & BfObjectFlag_AppendAlloc) != 0)
  6583. isAppendBfObject = true;
  6584. if ((bfObjectFlags & (BfObjectFlag_StackAlloc | BfObjectFlag_Allocated)) == BfObjectFlag_StackAlloc)
  6585. isStackBfObject = true;
  6586. classVDataPtr &= ~0xFF;
  6587. }
  6588. }
  6589. if (!formatInfo.mIgnoreDerivedClassInfo)
  6590. {
  6591. if (isBfObject)
  6592. {
  6593. dbgModule->ParseSymbolData();
  6594. String symbolName;
  6595. addr_target symOffset;
  6596. if ((mDebugTarget->FindSymbolAt(classVDataPtr, &symbolName, &symOffset)) && (symOffset < 0x100))
  6597. {
  6598. String mangledClassName;
  6599. const char* symEnd = "sBfClassVData";
  6600. int symEndLen = strlen(symEnd);
  6601. if (((int)symbolName.length() > symEndLen) && (strstr(symbolName.c_str(), symEnd) != NULL))
  6602. mangledClassName = symbolName;
  6603. // If we have flags then we may be pointing past the _typeData, actually. We could fix this by masking out
  6604. // the flags area, but we need to be sure we are running a build that supports flags
  6605. symEnd = "sBfTypeData";
  6606. symEndLen = strlen(symEnd);
  6607. if (((int) symbolName.length() > symEndLen) && (strstr(symbolName.c_str(), symEnd) != NULL))
  6608. mangledClassName = symbolName;
  6609. if (mangledClassName.length() > 0)
  6610. {
  6611. String className = BfDemangler::Demangle(mangledClassName, innerType->GetLanguage(), BfDemangler::Flag_RawDemangle);
  6612. for (int i = 0; i < className.length() - 3; i++)
  6613. {
  6614. if ((className[i] == 'b') &&
  6615. (className[i + 1] == 'f') &&
  6616. (className[i + 2] == '.'))
  6617. {
  6618. bool matches;
  6619. if (i == 0)
  6620. matches = true;
  6621. else
  6622. {
  6623. char prevC = className[i - 1];
  6624. if ((prevC == ' ') ||
  6625. (prevC == ',') ||
  6626. (prevC == '<'))
  6627. {
  6628. matches = true;
  6629. }
  6630. }
  6631. if (matches)
  6632. className.Remove(i, 3);
  6633. }
  6634. }
  6635. int lastDot = (int)className.LastIndexOf('.');
  6636. if (lastDot > 0)
  6637. className = className.Substring(0, lastDot);
  6638. const char* arrPrefix = "System.Array1<";
  6639. if (strncmp(className.c_str(), arrPrefix, strlen(arrPrefix)) == 0)
  6640. {
  6641. className = className.Substring(strlen(arrPrefix), className.length() - strlen(arrPrefix) - 1);
  6642. className += "[]";
  6643. }
  6644. auto typeEntry = dbgModule->GetLinkedModule()->mTypeMap.Find(className.c_str(), DbgLanguage_BeefUnfixed);
  6645. if (typeEntry != NULL)
  6646. {
  6647. actualType = typeEntry->mValue;
  6648. if (!actualType->IsBfObject())
  6649. {
  6650. if (actualType->mTypeCode == DbgType_Ptr)
  6651. {
  6652. actualType = actualType->mTypeParam;
  6653. }
  6654. }
  6655. }
  6656. }
  6657. }
  6658. }
  6659. else if (hasCPPVTable)
  6660. {
  6661. dbgModule->ParseSymbolData();
  6662. addr_target classVDataPtr = ReadMemory<addr_target>(ptrVal);
  6663. String symbolName;
  6664. addr_target offset = 0;
  6665. if (mDebugTarget->FindSymbolAt(classVDataPtr, &symbolName, &offset, NULL))
  6666. {
  6667. // On GNU, vtable indices can "go negative" for things like RTTI and virtual inheritance, so
  6668. // we can't rely on an exact vtable address lookup
  6669. if (offset < 0x200)
  6670. {
  6671. DbgLanguage lang = innerType->GetLanguage();
  6672. const char* symStart = (innerType->mCompileUnit->mDbgModule->mDbgFlavor == DbgFlavor_GNU) ? "_ZTV" : "??_7";
  6673. if (strncmp(symbolName.c_str(), symStart, strlen(symStart)) == 0)
  6674. {
  6675. //String mangledClassName = symbolName.Substring(1);
  6676. String className = BfDemangler::Demangle(symbolName, lang);
  6677. int vtableNameIdx = (int)className.IndexOf("::`vftable'");
  6678. if (vtableNameIdx != -1)
  6679. className = className.Substring(0, vtableNameIdx);
  6680. auto typeEntry = dbgModule->mTypeMap.Find(className.c_str(), DbgLanguage_C);
  6681. if (typeEntry != NULL)
  6682. {
  6683. actualType = typeEntry->mValue;
  6684. if ((int)className.IndexOf('<') != -1)
  6685. useActualRawType = true;
  6686. int thisOffset = 0;
  6687. if (!DbgExprEvaluator::TypeIsSubTypeOf(actualType, innerType, &thisOffset))
  6688. {
  6689. // This catches virtual inheritance cases where we can't downcast
  6690. actualType = NULL;
  6691. }
  6692. }
  6693. }
  6694. }
  6695. }
  6696. }
  6697. }
  6698. DbgType* displayType = origValueType;
  6699. String displayString;
  6700. bool wantsCustomExpandedItems = false;
  6701. DebugVisualizerEntry* debugVis = NULL;
  6702. Array<String> dbgVisWildcardCaptures;
  6703. DbgType* dwUseType = (actualType != NULL) ? actualType : innerType;
  6704. //auto ptrDataType = dwValueType;
  6705. //TODO: Changed this from the above to account for COFF types where 'this' is always a fwd reference, does this cause any issues?
  6706. auto ptrDataType = innerType;
  6707. String ptrDataStr;
  6708. if (/*(!innerType->IsBfObject()) &&*/ (!ptrDataType->IsPointer()))
  6709. {
  6710. if ((dataPtr != 0) || (ptrDataType->GetByteCount() > sizeof(addr_target)))
  6711. {
  6712. bool wantsRefThis = ptrDataType->WantsRefThis();
  6713. ptrDataType = ptrDataType->GetDbgModule()->GetPointerType(ptrDataType);
  6714. if (wantsRefThis)
  6715. ptrDataStr += "*";
  6716. }
  6717. else
  6718. {
  6719. // Data is inline - must be int-sized or less
  6720. isCompositeWithoutAddress = true;
  6721. dataPtr = typedValue.mPtr;
  6722. }
  6723. }
  6724. String ptrDataTypeStr = ptrDataType->ToStringRaw();
  6725. ptrDataStr += StrFormat("(%s)", ptrDataTypeStr.c_str()) + EncodeDataPtr(dataPtr, true);
  6726. DbgType* dwUsePtrType = dwUseType;
  6727. String ptrUseDataStr;
  6728. if (!dwUsePtrType->IsPointer())
  6729. {
  6730. bool wantsRefThis = dwUsePtrType->WantsRefThis();
  6731. dwUsePtrType = dwUsePtrType->GetDbgModule()->GetPointerType(dwUsePtrType);
  6732. if (wantsRefThis)
  6733. ptrUseDataStr += "*";
  6734. }
  6735. String ptrUseDataTypeStr = dwUsePtrType->ToStringRaw();
  6736. ptrUseDataStr += StrFormat("(%s)", ptrUseDataTypeStr.c_str()) + EncodeDataPtr(dataPtr, true);
  6737. if ((origTypedValue.mSrcAddress == -1) && (origTypedValue.mVariable != NULL))
  6738. {
  6739. ptrDataStr = origTypedValue.mVariable->mName;
  6740. if (!origTypedValue.mType->RemoveModifiers()->Equals(origTypedValue.mVariable->mType->RemoveModifiers()))
  6741. {
  6742. //ptrDataStr = StrFormat("(%s)%s", origTypedValue.mType->ToString().c_str(), origTypedValue.mVariable->mName);
  6743. ptrDataStr = expr;
  6744. }
  6745. ptrUseDataStr = ptrDataStr;
  6746. }
  6747. bool isNull = wasPtr && (dataPtr == 0);
  6748. bool isBadSrc = !wasPtr && (dataPtr == 0) && (!dwValueType->IsValuelessType());
  6749. if ((ptrVal == 0) && (dwValueType->IsTypedPrimitive()))
  6750. {
  6751. DbgTypedValue rawVal;
  6752. rawVal.mInt64 = origTypedValue.mInt64;
  6753. rawVal.mType = dwValueType->GetRootBaseType();
  6754. ptrDataStr = "(" + dwUseType->ToStringRaw() + ")";
  6755. ptrDataStr += DbgTypedValueToString(rawVal, expr, formatInfo, optEvaluator, fullPrecision);
  6756. int editValIdx = ptrDataStr.IndexOf(":editVal");
  6757. if (editValIdx != -1)
  6758. ptrDataStr.Remove(0, editValIdx + 9);
  6759. int crPos = (int)ptrDataStr.IndexOf('\n');
  6760. if (crPos != -1)
  6761. ptrDataStr.RemoveToEnd(crPos);
  6762. ptrUseDataStr = ptrDataStr;
  6763. if ((origTypedValue.mRegNum != -1) && (!expr.IsEmpty()) && (!formatInfo.mExplicitThis))
  6764. {
  6765. // There's no address, use direct local identifier
  6766. ptrDataStr = expr;
  6767. ptrUseDataStr = expr;
  6768. }
  6769. // This keeps 'function' types from showing null as "<null parent>"
  6770. isBadSrc = false;
  6771. }
  6772. else if ((ptrVal == 0) && (dwValueType->IsCompositeType()))
  6773. {
  6774. }
  6775. DbgTypedValue useTypedValue = typedValue;
  6776. if ((origHadRef) || ((typedValue.mType->HasPointer()) && (!dwUseType->HasPointer())))
  6777. {
  6778. useTypedValue.mSrcAddress = useTypedValue.mPtr;
  6779. useTypedValue.mPtr = 0;
  6780. if (dwUseType->IsTypedPrimitive())
  6781. {
  6782. int byteCount = dwUseType->GetByteCount();
  6783. if (byteCount <= sizeof(intptr))
  6784. {
  6785. ReadMemory(useTypedValue.mSrcAddress, byteCount, &useTypedValue.mPtr);
  6786. }
  6787. }
  6788. }
  6789. useTypedValue.mType = dwUseType;
  6790. if ((!formatInfo.mNoVisualizers) && (!isNull) && (!isBadSrc))
  6791. {
  6792. if (language == DbgLanguage_Beef)
  6793. dwUseType->FixName();
  6794. debugVis = FindVisualizerForType(dwUseType, &dbgVisWildcardCaptures);
  6795. }
  6796. bool hadCustomDisplayString = false;
  6797. if (debugVis != NULL)
  6798. {
  6799. auto& displayStringList = formatInfo.mRawString ? debugVis->mStringViews : debugVis->mDisplayStrings;
  6800. for (auto displayEntry : displayStringList)
  6801. {
  6802. if (!displayEntry->mCondition.empty())
  6803. {
  6804. if (!EvalCondition(debugVis, dbgCompileUnit, useTypedValue, formatInfo, displayEntry->mCondition, dbgVisWildcardCaptures, displayString))
  6805. continue;
  6806. }
  6807. hadCustomDisplayString = true;
  6808. String displayStr = mDebugManager->mDebugVisualizers->DoStringReplace(displayEntry->mString, dbgVisWildcardCaptures);
  6809. if (displayString.length() > 0)
  6810. displayString += " ";
  6811. ProcessEvalString(dbgCompileUnit, useTypedValue, displayStr, displayString, formatInfo, debugVis, true);
  6812. if (formatInfo.mRawString)
  6813. return displayString;
  6814. break;
  6815. }
  6816. if ((!debugVis->mExpandItems.empty()) || (debugVis->mCollectionType != DebugVisualizerEntry::CollectionType_None))
  6817. {
  6818. wantsCustomExpandedItems = true;
  6819. }
  6820. }
  6821. if (formatInfo.mRawString)
  6822. return "";
  6823. bool isTuple = (dwUseType->mName != NULL) && (dwUseType->mName[0] == '(') && (language == DbgLanguage_Beef);
  6824. if (isBadSrc)
  6825. {
  6826. displayString += "<null parent>";
  6827. }
  6828. else if ((!isNull) && (!formatInfo.mNoVisualizers) && (!hadCustomDisplayString))
  6829. {
  6830. // Create our own custom display
  6831. String firstRet;
  6832. String bigRet = isTuple ? "(" : "{ ";
  6833. int memberIdx = 0;
  6834. DbgType* summaryType = dwUseType;
  6835. bool summaryDone = false;
  6836. bool truncatedMemberList = false;
  6837. DbgTypedValue summaryTypedValue = useTypedValue;
  6838. String summaryDataStr = ptrDataStr;
  6839. String splatStr;
  6840. if (dataPtr == -1)
  6841. splatStr = expr;
  6842. while (summaryType != NULL)
  6843. {
  6844. summaryType->PopulateType();
  6845. if ((summaryType->IsTypedPrimitive()) &&
  6846. ((summaryType->mBaseTypes.IsEmpty()) || (!summaryType->mBaseTypes.front()->mBaseType->IsTypedPrimitive())))
  6847. {
  6848. if (formatInfo.mTotalSummaryLength + (int)displayString.length() > 255)
  6849. {
  6850. truncatedMemberList = true;
  6851. summaryDone = true;
  6852. bigRet += "...";
  6853. }
  6854. else
  6855. {
  6856. DwFormatInfo displayStrFormatInfo = formatInfo;
  6857. displayStrFormatInfo.mExpandItemDepth = 1;
  6858. displayStrFormatInfo.mTotalSummaryLength += (int)displayString.length();
  6859. displayStrFormatInfo.mHidePointers = false;
  6860. DbgType* primType = summaryType->mTypeParam;
  6861. String result;
  6862. if (primType->IsInteger())
  6863. formatInfo.mTypeKindFlags = (DbgTypeKindFlags)(formatInfo.mTypeKindFlags | DbgTypeKindFlag_Int);
  6864. if ((dataPtr != 0) && (dataPtr != -1))
  6865. {
  6866. String evalString = "(" + primType->ToString() + ")" + ptrDataStr;
  6867. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, origTypedValue, evalString, &displayStrFormatInfo);
  6868. if (evalResult)
  6869. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  6870. }
  6871. else
  6872. {
  6873. DbgTypedValue evalResult = origTypedValue;
  6874. evalResult.mType = primType;
  6875. String evalString = "(" + primType->ToString() + ")" + expr;
  6876. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  6877. }
  6878. if (formatInfo.mRawString)
  6879. return result;
  6880. int crPos = result.IndexOf('\n');
  6881. if (crPos != -1)
  6882. result.RemoveToEnd(crPos);
  6883. if (memberIdx == 0)
  6884. firstRet = result;
  6885. bigRet += result;
  6886. memberIdx++;
  6887. }
  6888. }
  6889. for (auto member : summaryType->mMemberList)
  6890. {
  6891. if (!member->mIsStatic)
  6892. {
  6893. if (formatInfo.mTotalSummaryLength + retVal.length() + bigRet.length() > 255)
  6894. {
  6895. truncatedMemberList = true;
  6896. summaryDone = true;
  6897. bigRet += "...";
  6898. break;
  6899. }
  6900. if (member->mName != NULL)
  6901. {
  6902. if (member->mName[0] == '$')
  6903. continue;
  6904. if (!isdigit(*member->mName))
  6905. {
  6906. if (memberIdx != 0)
  6907. bigRet += isTuple ? ", " : " ";
  6908. if ((!isTuple) || (member->mName[0] != '_'))
  6909. {
  6910. bigRet += String(member->mName);
  6911. bigRet += isTuple ? ":" : "=";
  6912. }
  6913. }
  6914. else
  6915. {
  6916. if (memberIdx != 0)
  6917. bigRet += ", ";
  6918. }
  6919. DwFormatInfo displayStrFormatInfo = formatInfo;
  6920. displayStrFormatInfo.mExpandItemDepth = 1;
  6921. displayStrFormatInfo.mHidePointers = false;
  6922. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + retVal.length() + bigRet.length();
  6923. String evalString;
  6924. if (dataPtr != -1)
  6925. {
  6926. if ((member->mName[0] >= '0') && (member->mName[0] <= '9'))
  6927. evalString += "this.";
  6928. evalString += String(member->mName); // +", this=" + summaryDataStr;
  6929. }
  6930. else
  6931. {
  6932. evalString = "(";
  6933. evalString += splatStr;
  6934. evalString += ").";
  6935. evalString += member->mName;
  6936. }
  6937. String referenceId;
  6938. String result;
  6939. if (!member->mType->IsValuelessType())
  6940. {
  6941. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, summaryTypedValue, evalString, &displayStrFormatInfo, &referenceId);
  6942. if (evalResult)
  6943. {
  6944. displayStrFormatInfo.mReferenceId = referenceId;
  6945. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  6946. int crPos = result.IndexOf('\n');
  6947. if (crPos != -1)
  6948. result.RemoveToEnd(crPos);
  6949. }
  6950. else
  6951. result = "???";
  6952. }
  6953. if (member->mType->IsInteger())
  6954. formatInfo.mTypeKindFlags = (DbgTypeKindFlags)(formatInfo.mTypeKindFlags | DbgTypeKindFlag_Int);
  6955. if (formatInfo.mRawString)
  6956. return result;
  6957. if (memberIdx == 0)
  6958. firstRet = result;
  6959. bigRet += result;
  6960. //formatInfo.mEmbeddedDisplayCount = displayStrFormatInfo.mEmbeddedDisplayCount;
  6961. memberIdx++;
  6962. }
  6963. else
  6964. {
  6965. //TODO: Handle C++ unions?
  6966. }
  6967. }
  6968. }
  6969. if (truncatedMemberList)
  6970. break;
  6971. // Find first base class with members
  6972. DbgType* nextSummaryType = NULL;
  6973. for (auto checkBase : summaryType->mBaseTypes)
  6974. {
  6975. auto checkBaseType = checkBase->mBaseType;
  6976. checkBaseType = checkBaseType->GetPrimaryType();
  6977. checkBaseType->PopulateType();
  6978. if ((checkBaseType->GetByteCount() > 0) || (checkBaseType->IsPrimitiveType()))
  6979. {
  6980. if (!splatStr.empty())
  6981. {
  6982. splatStr = "(" + checkBaseType->ToString() + ")" + splatStr;
  6983. }
  6984. else
  6985. {
  6986. summaryTypedValue.mType = checkBaseType;
  6987. }
  6988. nextSummaryType = checkBaseType;
  6989. break;
  6990. }
  6991. }
  6992. summaryType = nextSummaryType;
  6993. if (summaryType == NULL)
  6994. break;
  6995. // Don't add the Object members
  6996. if ((summaryType->GetBaseType() == NULL) && (summaryType->IsBfObject()))
  6997. break;
  6998. // If we don't have many members then find a base class with some members to show
  6999. if ((memberIdx != 0) && (displayString.length() >= 255))
  7000. {
  7001. truncatedMemberList = true;
  7002. bigRet += "...";
  7003. break;
  7004. }
  7005. }
  7006. bigRet += isTuple ? ")" : " }";
  7007. if (displayString.length() > 0)
  7008. displayString += " ";
  7009. if ((memberIdx == 1) && (!truncatedMemberList) && (firstRet.IndexOf('{') == -1) && (!isTuple))
  7010. displayString += "{ " + firstRet + " }";
  7011. else
  7012. displayString += bigRet;
  7013. }
  7014. DbgType* memberListType = actualType;
  7015. bool memberListForceCast = false;
  7016. if (actualType != NULL)
  7017. {
  7018. String valTypeName = displayType->ToString();
  7019. String actualTypeName = actualType->ToString(DbgLanguage_Unknown, true);
  7020. String actualUseTypeName = actualTypeName;
  7021. if ((int)actualTypeName.IndexOf('^') != -1)
  7022. useActualRawType = true;
  7023. if (useActualRawType)
  7024. actualUseTypeName = actualType->ToStringRaw();
  7025. if (displayString.empty())
  7026. {
  7027. // Nothing to display
  7028. }
  7029. else
  7030. {
  7031. if (!retVal.empty())
  7032. retVal += " ";
  7033. retVal += displayString;
  7034. }
  7035. retVal += "\n" + valTypeName;
  7036. if ((innerType->IsBaseBfObject()) || (innerType->IsInterface()))
  7037. {
  7038. if (actualType != innerType)
  7039. {
  7040. retVal += " {" + actualTypeName + "}";
  7041. memberListForceCast = true;
  7042. }
  7043. }
  7044. else
  7045. {
  7046. if (actualType != innerType)
  7047. {
  7048. retVal += " {" + actualTypeName + "}";
  7049. retVal += "\n";
  7050. if (!wantsCustomExpandedItems)
  7051. {
  7052. retVal += "[" + actualTypeName + "]\t((" + actualUseTypeName;
  7053. if (!actualType->IsBfObject())
  7054. retVal += "*";
  7055. retVal += ")this), nd, na, nv, this=" + ptrDataStr;
  7056. memberListType = innerType;
  7057. }
  7058. }
  7059. }
  7060. }
  7061. else
  7062. {
  7063. if ((formatInfo.mHidePointers) && (formatInfo.mIgnoreDerivedClassInfo))
  7064. {
  7065. displayType = innerType;
  7066. if (displayString.empty())
  7067. retVal += displayType->ToString(DbgLanguage_Unknown, true);
  7068. }
  7069. if (!displayString.empty())
  7070. {
  7071. if (!retVal.empty())
  7072. retVal += " ";
  7073. retVal += displayString;
  7074. }
  7075. else
  7076. {
  7077. if (formatInfo.mRawString)
  7078. return "";
  7079. }
  7080. retVal += "\n" + displayType->ToString(DbgLanguage_Unknown, true);
  7081. memberListType = innerType;
  7082. }
  7083. if ((isBfObject) && (mDebugTarget->mBfObjectHasFlags) && (!formatInfo.mNoVisualizers) && (!formatInfo.mRawString))
  7084. {
  7085. int stackTraceLen = 1;
  7086. addr_target stackTraceAddr = ptrVal + sizeof(addr_target);
  7087. if ((bfObjectFlags & BfObjectFlag_AllocInfo) != 0)
  7088. {
  7089. addr_target objectSize = ReadMemory<addr_target>(ptrVal + sizeof(addr_target));
  7090. addr_target largeAllocInfo = ReadMemory<addr_target>(ptrVal + objectSize);
  7091. stackTraceLen = largeAllocInfo & 0xFFFF;
  7092. stackTraceAddr = ptrVal + objectSize + sizeof(addr_target);
  7093. }
  7094. else if ((bfObjectFlags & BfObjectFlag_AllocInfo_Short) != 0)
  7095. {
  7096. addr_target dbgAllocInfo = ReadMemory<addr_target>(ptrVal + sizeof(addr_target));
  7097. stackTraceLen = dbgAllocInfo & 0xFF;
  7098. stackTraceAddr = ptrVal + (dbgAllocInfo >> 16);
  7099. }
  7100. if (stackTraceLen == 1)
  7101. {
  7102. retVal += StrFormat("\n[AllocStackTrace]\t*(System.CallStackAddr*)%s, nm", EncodeDataPtr(stackTraceAddr, true).c_str());
  7103. }
  7104. else if (stackTraceLen > 0)
  7105. {
  7106. retVal += StrFormat("\n[AllocStackTrace]\t(System.CallStackAddr*)%s, %d, na", EncodeDataPtr(stackTraceAddr, true).c_str(), stackTraceLen);
  7107. }
  7108. }
  7109. retVal += StrFormat("\n:language\t%d", language);
  7110. if (formatInfo.mNoMembers)
  7111. {
  7112. //
  7113. }
  7114. else if (wantsCustomExpandedItems)
  7115. {
  7116. HandleCustomExpandedItems(retVal, dbgCompileUnit, debugVis, dwUseType, dwValueType, ptrUseDataStr, ptrDataStr, useTypedValue, dbgVisWildcardCaptures, formatInfo);
  7117. }
  7118. else if ((!isNull) && (!isBadSrc))
  7119. {
  7120. if (dataPtr == -1)
  7121. {
  7122. //String splatName = ((origTypedValue.mSrcAddress == -1) && (origTypedValue.mVariable != NULL)) ? origTypedValue.mVariable->mName : expr;
  7123. String splatName = expr;
  7124. retVal += "\n" + GetMemberList(memberListType, splatName, wasPtr, false, false, true, origTypedValue.mIsReadOnly);
  7125. }
  7126. else
  7127. {
  7128. retVal += "\n" + GetMemberList(memberListType, ptrDataStr, wasPtr, false, memberListForceCast, isCompositeWithoutAddress, origTypedValue.mIsReadOnly);
  7129. }
  7130. }
  7131. if (formatInfo.mExpandItemDepth > 0)
  7132. return retVal;
  7133. if (isAppendBfObject)
  7134. retVal += "\n:appendAlloc";
  7135. if (isStackBfObject)
  7136. retVal += "\n:stack";
  7137. if (isDeletedBfObject)
  7138. retVal += "\n:deleted";
  7139. if ((debugVis != NULL) && (!debugVis->mAction.empty()))
  7140. {
  7141. String rawActionStr = mDebugManager->mDebugVisualizers->DoStringReplace(debugVis->mAction, dbgVisWildcardCaptures);
  7142. String actionStr;
  7143. ProcessEvalString(dbgCompileUnit, useTypedValue, rawActionStr, actionStr, formatInfo, debugVis, true);
  7144. retVal += "\n:action\t" + actionStr;
  7145. }
  7146. if ((!typedValue.mIsLiteral) && (dwValueType->IsPointer()))
  7147. {
  7148. retVal += "\n:editVal\t" + EncodeDataPtr(ptrVal, true);
  7149. }
  7150. return retVal;
  7151. }
  7152. return "Unknown Type\n" + origValueType->ToString();
  7153. }
  7154. void WinDebugger::HandleCustomExpandedItems(String& retVal, DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgType* dwUseType, DbgType* dwValueType, String& ptrUseDataStr, String& ptrDataStr, DbgTypedValue useTypedValue, Array<String>& dbgVisWildcardCaptures, DwFormatInfo& formatInfo)
  7155. {
  7156. auto debugVisualizers = mDebugManager->mDebugVisualizers;
  7157. auto dbgModule = dbgCompileUnit->mDbgModule;
  7158. if (formatInfo.mExpandItemDepth > 10) // Avoid crashing on circular ExpandItems
  7159. return;
  7160. auto language = formatInfo.mLanguage;
  7161. bool isReadOnly = false;
  7162. if (useTypedValue.mIsReadOnly)
  7163. isReadOnly = true;
  7164. for (auto entry : debugVis->mExpandItems)
  7165. {
  7166. if (!entry->mCondition.empty())
  7167. {
  7168. String error;
  7169. if (!EvalCondition(debugVis, dbgCompileUnit, useTypedValue, formatInfo, entry->mCondition, dbgVisWildcardCaptures, error))
  7170. {
  7171. if (!error.empty())
  7172. retVal += "\n" + entry->mName + "\t@!<DbgVis Failed>@!";
  7173. continue;
  7174. }
  7175. }
  7176. String replacedStr = debugVisualizers->DoStringReplace(entry->mValue, dbgVisWildcardCaptures);
  7177. retVal += "\n" + entry->mName + "\t" + replacedStr + ", this=(" + ptrUseDataStr + ")";
  7178. }
  7179. String referenceId = dwUseType->ToString();
  7180. if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_ExpandedItem)
  7181. {
  7182. DbgTypedValue itemValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7183. if (itemValue)
  7184. {
  7185. DwFormatInfo itemFormatInfo = formatInfo;
  7186. itemFormatInfo.mExpandItemDepth++;
  7187. String itemRetVal = DbgTypedValueToString(itemValue, "", itemFormatInfo, NULL);
  7188. int crIdx = (int)itemRetVal.IndexOf('\n');
  7189. if (crIdx != -1)
  7190. {
  7191. crIdx = (int)itemRetVal.IndexOf('\n', crIdx + 1);
  7192. if (crIdx != -1)
  7193. retVal += itemRetVal.Substring(crIdx);
  7194. }
  7195. }
  7196. }
  7197. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Array)
  7198. {
  7199. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7200. Array<int> lowerDimSizes;
  7201. for (auto lowerDim : debugVis->mLowerDimSizes)
  7202. {
  7203. DbgTypedValue lowerDimValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(lowerDim, dbgVisWildcardCaptures), &formatInfo);
  7204. int dimSize = 0;
  7205. if ((lowerDimValue) && (lowerDimValue.mType->IsInteger()))
  7206. dimSize = (int)lowerDimValue.GetInt64();
  7207. dimSize = BF_MAX(dimSize, 1);
  7208. lowerDimSizes.push_back(dimSize);
  7209. }
  7210. if ((sizeValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7211. {
  7212. if (!debugVis->mCondition.IsEmpty())
  7213. {
  7214. int size = (int)sizeValue.GetInt64();
  7215. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7216. DbgTypedValue curNode = headPointer;
  7217. Array<addr_target> parentList;
  7218. String continuationData;
  7219. int totalSize = 2;
  7220. auto valueType = headPointer.mType;
  7221. String addrs = GetArrayItems(dbgCompileUnit, debugVis, valueType, headPointer, totalSize, &continuationData);
  7222. String firstAddr;
  7223. String secondAddr;
  7224. bool hasSecondAddr = valueType == NULL;
  7225. if (addrs.length() > 0)
  7226. {
  7227. const char* addrsPtr = addrs.c_str();
  7228. firstAddr = addrs.Substring(0, sizeof(addr_target) * 2);
  7229. if (hasSecondAddr)
  7230. secondAddr = addrs.Substring(sizeof(addr_target) * 2, sizeof(addr_target) * 2);
  7231. }
  7232. String evalStr;
  7233. if (valueType != NULL)
  7234. {
  7235. evalStr = "(" + valueType->ToStringRaw();
  7236. if (!valueType->IsPointer())
  7237. evalStr += "*";
  7238. evalStr += ")0x{1}";
  7239. }
  7240. else
  7241. {
  7242. evalStr += "({1})0x{2}";
  7243. }
  7244. if (!debugVis->mShowElementAddrs)
  7245. evalStr.Insert(0, "*");
  7246. if (addrs.length() > 0)
  7247. {
  7248. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7249. if (isReadOnly)
  7250. evalStr += ", ne";
  7251. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, BF_MAX(size, 0), 10000) +
  7252. "\t[{0}]\t" + evalStr + "\t" + firstAddr;
  7253. if (hasSecondAddr)
  7254. retVal += "\t" + secondAddr;
  7255. if (size != 0)
  7256. {
  7257. retVal += "\n:addrs\t" + addrs;
  7258. if (valueType == NULL)
  7259. retVal += "\n:addrsEntrySize\t2";
  7260. if (continuationData.length() > 0)
  7261. retVal += "\n:continuation\t" + continuationData;
  7262. }
  7263. }
  7264. }
  7265. else if (lowerDimSizes.size() == 1)
  7266. {
  7267. int dimSize1 = lowerDimSizes[0];
  7268. String evalStr = "(" + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7269. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7270. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7271. if (isReadOnly)
  7272. evalStr += ", ne";
  7273. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64() / dimSize1, 50000) +
  7274. "\t[{0}]\t" + evalStr;
  7275. }
  7276. else if (lowerDimSizes.size() == 2)
  7277. {
  7278. int dimSize1 = lowerDimSizes[0];
  7279. int dimSize2 = lowerDimSizes[1];
  7280. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7281. if ((headPointer.mType != NULL) && (headPointer.mType->IsPointer()))
  7282. {
  7283. String evalStr = StrFormat("((%s[%d]*)", headPointer.mType->mTypeParam->ToStringRaw(language).c_str(), dimSize2) + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7284. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7285. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7286. if (isReadOnly)
  7287. evalStr += ", ne";
  7288. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64() / dimSize1 / dimSize2, 50000) +
  7289. "\t[{0}]\t" + evalStr;
  7290. }
  7291. }
  7292. else if (lowerDimSizes.size() == 3)
  7293. {
  7294. int dimSize1 = lowerDimSizes[0];
  7295. int dimSize2 = lowerDimSizes[1];
  7296. int dimSize3 = lowerDimSizes[2];
  7297. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7298. if ((headPointer.mType != NULL) && (headPointer.mType->IsPointer()))
  7299. {
  7300. String evalStr = StrFormat("((%s[%d][%d]*)", headPointer.mType->mTypeParam->ToStringRaw(language).c_str(), dimSize2, dimSize3) + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7301. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7302. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7303. if (isReadOnly)
  7304. evalStr += ", ne";
  7305. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64() / dimSize1 / dimSize2 / dimSize3, 50000) +
  7306. "\t[{0}]\t" + evalStr;
  7307. }
  7308. }
  7309. else
  7310. {
  7311. String evalStr = "*(" + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) + " + {0}), this=" + ptrUseDataStr;
  7312. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7313. if (isReadOnly)
  7314. evalStr += ", ne";
  7315. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64(), 50000) +
  7316. "\t[{0}]\t" + evalStr;
  7317. }
  7318. }
  7319. }
  7320. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_IndexItems)
  7321. {
  7322. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7323. if ((sizeValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7324. {
  7325. String evalStr = debugVis->mValuePointer + ", this=" + ptrUseDataStr;
  7326. evalStr.Replace("$i", "{0}");
  7327. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7328. if (isReadOnly)
  7329. evalStr += ", ne";
  7330. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64(), 50000) +
  7331. "\t[{0}]\t" + evalStr;
  7332. }
  7333. }
  7334. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_LinkedList)
  7335. {
  7336. DbgType* valueType = NULL;
  7337. if (!debugVis->mValueType.empty())
  7338. {
  7339. valueType = dbgModule->FindType(debugVisualizers->DoStringReplace(debugVis->mValueType, dbgVisWildcardCaptures), dwValueType);
  7340. if (valueType != NULL)
  7341. valueType = valueType->ResolveTypeDef();
  7342. }
  7343. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mHeadPointer, dbgVisWildcardCaptures), &formatInfo);
  7344. if (headPointer)
  7345. {
  7346. DbgTypedValue endPointer;
  7347. if (!debugVis->mEndPointer.empty())
  7348. endPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mEndPointer, dbgVisWildcardCaptures), &formatInfo);
  7349. DbgTypedValue nextPointer = EvaluateInContext(dbgCompileUnit, headPointer, debugVisualizers->DoStringReplace(debugVis->mNextPointer, dbgVisWildcardCaptures), &formatInfo);
  7350. int size = -1;
  7351. if (!debugVis->mSize.empty())
  7352. {
  7353. auto sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7354. if (sizeValue)
  7355. size = (int)sizeValue.GetInt64();
  7356. }
  7357. DbgTypedValue curNode = headPointer;
  7358. Array<addr_target> parentList;
  7359. String continuationData;
  7360. int totalSize = 2;
  7361. String addrs = GetLinkedListItems(dbgCompileUnit, debugVis, endPointer.mPtr, valueType, curNode, totalSize, &continuationData);
  7362. String firstAddr;
  7363. String secondAddr;
  7364. bool hasSecondAddr = valueType == NULL;
  7365. if (addrs.length() > 0)
  7366. {
  7367. const char* addrsPtr = addrs.c_str();
  7368. firstAddr = addrs.Substring(0, sizeof(addr_target)*2);
  7369. if (hasSecondAddr)
  7370. secondAddr = addrs.Substring(sizeof(addr_target)*2, sizeof(addr_target)*2);
  7371. }
  7372. String evalStr;
  7373. if (valueType != NULL)
  7374. {
  7375. evalStr = "(" + valueType->ToStringRaw();
  7376. if (!valueType->IsPointer())
  7377. evalStr += "*";
  7378. evalStr += ")0x{1}";
  7379. }
  7380. else
  7381. {
  7382. evalStr += "({1})0x{2}";
  7383. }
  7384. if (!debugVis->mShowElementAddrs)
  7385. evalStr.Insert(0, "*");
  7386. if (addrs.length() > 0)
  7387. {
  7388. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7389. if (isReadOnly)
  7390. evalStr += ", ne";
  7391. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, size, 10000) +
  7392. "\t[{0}]\t" + evalStr + "\t" + firstAddr;
  7393. if (hasSecondAddr)
  7394. retVal += "\t" + secondAddr;
  7395. if (size != 0)
  7396. {
  7397. retVal += "\n:addrs\t" + addrs;
  7398. if (valueType == NULL)
  7399. retVal += "\n:addrsEntrySize\t2";
  7400. if (continuationData.length() > 0)
  7401. retVal += "\n:continuation\t" + continuationData;
  7402. }
  7403. }
  7404. }
  7405. }
  7406. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_TreeItems)
  7407. {
  7408. DbgType* valueType = NULL;
  7409. if (!debugVis->mValueType.empty())
  7410. {
  7411. valueType = dbgModule->FindType(debugVisualizers->DoStringReplace(debugVis->mValueType, dbgVisWildcardCaptures), dwValueType);
  7412. if (valueType != NULL)
  7413. valueType = valueType->ResolveTypeDef();
  7414. }
  7415. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7416. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mHeadPointer, dbgVisWildcardCaptures), &formatInfo);
  7417. if (sizeValue)
  7418. sizeValue.mType = sizeValue.mType->RemoveModifiers();
  7419. if ((sizeValue) && (headPointer) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7420. {
  7421. DbgTypedValue curNode = headPointer;
  7422. Array<addr_target> parentList;
  7423. String continuationData;
  7424. int getItemCount = (int)BF_MIN(sizeValue.GetInt64(), 32LL);
  7425. String addrs = GetTreeItems(dbgCompileUnit, debugVis, parentList, valueType, curNode, getItemCount, &continuationData);
  7426. addr_target firstAddr = 0;
  7427. addr_target secondAddr = 0;
  7428. bool hasSecondAddr = valueType == NULL;
  7429. if (addrs.length() > 0)
  7430. {
  7431. const char* addrsPtr = addrs.c_str();
  7432. firstAddr = DecodeTargetDataPtr(addrsPtr);
  7433. if (hasSecondAddr)
  7434. secondAddr = DecodeTargetDataPtr(addrsPtr);
  7435. }
  7436. String evalStr;
  7437. if (valueType != NULL)
  7438. {
  7439. evalStr = "*(" + valueType->ToStringRaw();
  7440. if (!valueType->IsPointer())
  7441. evalStr += "*";
  7442. evalStr += ")0x{1}";
  7443. }
  7444. else
  7445. {
  7446. evalStr += "*(_T_{1}*)0x{2}";
  7447. }
  7448. int size = (int)sizeValue.GetInt64();
  7449. if (addrs.length() == 0)
  7450. {
  7451. evalStr = ""; // Failed
  7452. }
  7453. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7454. if (isReadOnly)
  7455. evalStr += ", ne";
  7456. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, size, 10000) +
  7457. "\t[{0}]\t" + evalStr + "\t" + EncodeDataPtr(firstAddr, false);
  7458. if (hasSecondAddr)
  7459. retVal += "\t" + EncodeDataPtr(secondAddr, false);
  7460. if (addrs.length() > 0)
  7461. {
  7462. retVal += "\n:addrs\t" + addrs;
  7463. if (continuationData.length() > 0)
  7464. retVal += "\n:continuation\t" + continuationData;
  7465. }
  7466. }
  7467. }
  7468. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Dictionary)
  7469. {
  7470. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7471. DbgTypedValue entriesPtrValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mEntries, dbgVisWildcardCaptures), &formatInfo);
  7472. if (sizeValue)
  7473. sizeValue.mType = sizeValue.mType->RemoveModifiers();
  7474. if ((sizeValue) && (entriesPtrValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7475. {
  7476. String continuationData;
  7477. DbgType* valueType = entriesPtrValue.mType;
  7478. int getItemCount = (int)std::min(sizeValue.GetInt64(), 2LL);
  7479. DbgType* useTypedValType = useTypedValue.mType;
  7480. addr_target useTypedValPtr = useTypedValue.mPtr;
  7481. addr_target useTypedValAddr = useTypedValue.mSrcAddress;
  7482. String addrs = GetDictionaryItems(dbgCompileUnit, debugVis, useTypedValue, 0, -1, getItemCount, &continuationData);
  7483. addr_target firstAddr = 0;
  7484. if (addrs.length() > 0)
  7485. {
  7486. const char* addrsPtr = addrs.c_str();
  7487. firstAddr = DecodeTargetDataPtr(addrsPtr);
  7488. }
  7489. String evalStr = "((" + valueType->ToStringRaw() + ")0x{1}), na";
  7490. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7491. if (isReadOnly)
  7492. evalStr += ", ne";
  7493. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64(), 10000) +
  7494. "\t[{0}]\t" + evalStr + "\t" + EncodeDataPtr(firstAddr, false);
  7495. if (addrs.length() > 0)
  7496. {
  7497. retVal += "\n:addrs\t" + addrs;
  7498. if (continuationData.length() > 0)
  7499. retVal += "\n:continuation\t" + continuationData;
  7500. }
  7501. }
  7502. }
  7503. if (formatInfo.mExpandItemDepth == 0)
  7504. {
  7505. //retVal += "\n[Raw View]\tthis, this=" + ptrDataStr + ", nv";
  7506. retVal += "\n[Raw View]\t" + ptrDataStr + ", nv";
  7507. }
  7508. }
  7509. bool WinDebugger::IsPaused()
  7510. {
  7511. return (mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint) || (mRunState == RunState_Exception) || (mRunState == RunState_DebugEval_Done);
  7512. }
  7513. DbgTypedValue WinDebugger::GetRegister(const StringImpl& regName, DbgLanguage language, CPURegisters* registers, Array<RegForm>* regForms)
  7514. {
  7515. int regNum = -1;
  7516. String lwrRegName(regName);
  7517. _strlwr((char*)lwrRegName.c_str());
  7518. // int regs
  7519. #ifdef BF_DBG_32
  7520. DbgTypeCode regType = DbgType_i32;
  7521. if (lwrRegName == "eax")
  7522. regNum = X86Reg_EAX;
  7523. else if (lwrRegName == "ecx")
  7524. regNum = X86Reg_ECX;
  7525. else if (lwrRegName == "edx")
  7526. regNum = X86Reg_EDX;
  7527. else if (lwrRegName == "ebx")
  7528. regNum = X86Reg_EBX;
  7529. else if (lwrRegName == "esp")
  7530. regNum = X86Reg_ESP;
  7531. else if (lwrRegName == "ebp")
  7532. regNum = X86Reg_EBP;
  7533. else if (lwrRegName == "esi")
  7534. regNum = X86Reg_ESI;
  7535. else if (lwrRegName == "edi")
  7536. regNum = X86Reg_EDI;
  7537. else if (lwrRegName == "eip")
  7538. regNum = X86Reg_EIP;
  7539. else if (lwrRegName == "efl")
  7540. regNum = X86Reg_EFL;
  7541. #else
  7542. DbgTypeCode regType = DbgType_i64;
  7543. if (lwrRegName == "rax")
  7544. regNum = X64Reg_RAX;
  7545. else if (lwrRegName == "rcx")
  7546. regNum = X64Reg_RCX;
  7547. else if (lwrRegName == "rdx")
  7548. regNum = X64Reg_RDX;
  7549. else if (lwrRegName == "rbx")
  7550. regNum = X64Reg_RBX;
  7551. else if (lwrRegName == "rsp")
  7552. regNum = X64Reg_RSP;
  7553. else if (lwrRegName == "rbp")
  7554. regNum = X64Reg_RBP;
  7555. else if (lwrRegName == "rsi")
  7556. regNum = X64Reg_RSI;
  7557. else if (lwrRegName == "rdi")
  7558. regNum = X64Reg_RDI;
  7559. else if (lwrRegName == "rip")
  7560. regNum = X64Reg_RIP;
  7561. else if (lwrRegName == "r8")
  7562. regNum = X64Reg_R8;
  7563. else if (lwrRegName == "r9")
  7564. regNum = X64Reg_R9;
  7565. else if (lwrRegName == "r10")
  7566. regNum = X64Reg_R10;
  7567. else if (lwrRegName == "r11")
  7568. regNum = X64Reg_R11;
  7569. else if (lwrRegName == "r12")
  7570. regNum = X64Reg_R12;
  7571. else if (lwrRegName == "r13")
  7572. regNum = X64Reg_R13;
  7573. else if (lwrRegName == "r14")
  7574. regNum = X64Reg_R14;
  7575. else if (lwrRegName == "r15")
  7576. regNum = X64Reg_R15;
  7577. else
  7578. {
  7579. regType = DbgType_i32;
  7580. if (lwrRegName == "eax")
  7581. regNum = X64Reg_RAX;
  7582. else if (lwrRegName == "ecx")
  7583. regNum = X64Reg_RCX;
  7584. else if (lwrRegName == "edx")
  7585. regNum = X64Reg_RDX;
  7586. else if (lwrRegName == "ebx")
  7587. regNum = X64Reg_RBX;
  7588. else if (lwrRegName == "efl")
  7589. regNum = X64Reg_EFL;
  7590. else if (lwrRegName == "esi")
  7591. regNum = X64Reg_RSI;
  7592. else if (lwrRegName == "edi")
  7593. regNum = X64Reg_RDI;
  7594. else if (lwrRegName == "r8d")
  7595. regNum = X64Reg_R8;
  7596. else if (lwrRegName == "r9d")
  7597. regNum = X64Reg_R9;
  7598. else if (lwrRegName == "r10d")
  7599. regNum = X64Reg_R10;
  7600. else if (lwrRegName == "r11d")
  7601. regNum = X64Reg_R11;
  7602. else if (lwrRegName == "r12d")
  7603. regNum = X64Reg_R12;
  7604. else if (lwrRegName == "r13d")
  7605. regNum = X64Reg_R13;
  7606. else if (lwrRegName == "r14d")
  7607. regNum = X64Reg_R14;
  7608. else if (lwrRegName == "r15d")
  7609. regNum = X64Reg_R15;
  7610. else
  7611. {
  7612. regType = DbgType_i16;
  7613. if (lwrRegName == "ax")
  7614. regNum = X64Reg_RAX;
  7615. else if (lwrRegName == "cx")
  7616. regNum = X64Reg_RCX;
  7617. else if (lwrRegName == "dx")
  7618. regNum = X64Reg_RDX;
  7619. else if (lwrRegName == "bx")
  7620. regNum = X64Reg_RBX;
  7621. else if (lwrRegName == "si")
  7622. regNum = X64Reg_RSI;
  7623. else if (lwrRegName == "di")
  7624. regNum = X64Reg_RDI;
  7625. else if (lwrRegName == "r8w")
  7626. regNum = X64Reg_R8;
  7627. else if (lwrRegName == "r9w")
  7628. regNum = X64Reg_R9;
  7629. else if (lwrRegName == "r10w")
  7630. regNum = X64Reg_R10;
  7631. else if (lwrRegName == "r11w")
  7632. regNum = X64Reg_R11;
  7633. else if (lwrRegName == "r12w")
  7634. regNum = X64Reg_R12;
  7635. else if (lwrRegName == "r13w")
  7636. regNum = X64Reg_R13;
  7637. else if (lwrRegName == "r14w")
  7638. regNum = X64Reg_R14;
  7639. else if (lwrRegName == "r15w")
  7640. regNum = X64Reg_R15;
  7641. else
  7642. {
  7643. regType = DbgType_i8;
  7644. if (lwrRegName == "al")
  7645. regNum = X64Reg_RAX;
  7646. else if (lwrRegName == "cl")
  7647. regNum = X64Reg_RCX;
  7648. else if (lwrRegName == "dl")
  7649. regNum = X64Reg_RDX;
  7650. else if (lwrRegName == "bl")
  7651. regNum = X64Reg_RBX;
  7652. else if (lwrRegName == "sil")
  7653. regNum = X64Reg_RSI;
  7654. else if (lwrRegName == "dil")
  7655. regNum = X64Reg_RDI;
  7656. else if (lwrRegName == "r8b")
  7657. regNum = X64Reg_R8;
  7658. else if (lwrRegName == "r9b")
  7659. regNum = X64Reg_R9;
  7660. else if (lwrRegName == "r10b")
  7661. regNum = X64Reg_R10;
  7662. else if (lwrRegName == "r11b")
  7663. regNum = X64Reg_R11;
  7664. else if (lwrRegName == "r12b")
  7665. regNum = X64Reg_R12;
  7666. else if (lwrRegName == "r13b")
  7667. regNum = X64Reg_R13;
  7668. else if (lwrRegName == "r14b")
  7669. regNum = X64Reg_R14;
  7670. else if (lwrRegName == "r15b")
  7671. regNum = X64Reg_R15;
  7672. }
  7673. }
  7674. }
  7675. #endif
  7676. auto dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  7677. if (regNum != -1)
  7678. {
  7679. DbgTypedValue typedVal;
  7680. typedVal.mType = dbgModule->GetPrimitiveType(regType, language);
  7681. typedVal.mInt64 = registers->mIntRegsArray[regNum];
  7682. typedVal.mRegNum = regNum;
  7683. return typedVal;
  7684. }
  7685. // st regs
  7686. if ((lwrRegName.length() == 3) && (lwrRegName[0] == 's') && (lwrRegName[1] == 't') && (lwrRegName[2] >= '0') && (lwrRegName[2] <= '7'))
  7687. {
  7688. regNum = CPUReg_FPSTREG_FIRST + (lwrRegName[2] - '0');
  7689. }
  7690. if (regNum != -1)
  7691. {
  7692. DbgTypedValue typedVal;
  7693. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Double, language);
  7694. typedVal.mDouble = ConvertFloat80ToDouble(registers->mFpMmRegsArray[regNum - CPUReg_FPSTREG_FIRST].fp.fp80);
  7695. typedVal.mRegNum = regNum;
  7696. return typedVal;
  7697. }
  7698. // mm regs
  7699. if ((lwrRegName.length() == 3) && (lwrRegName[0] == 'm') && (lwrRegName[1] == 'm') && (lwrRegName[2] >= '0') && (lwrRegName[2] <= '7'))
  7700. {
  7701. regNum = CPUReg_MMREG_FIRST + (lwrRegName[2] - '0');
  7702. }
  7703. if (regNum != -1)
  7704. {
  7705. DbgTypedValue typedVal;
  7706. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_i64, language);
  7707. typedVal.mInt64 = registers->mFpMmRegsArray[regNum - CPUReg_MMREG_FIRST].mm;
  7708. typedVal.mRegNum = regNum;
  7709. return typedVal;
  7710. }
  7711. // xmm regs
  7712. #ifdef BF_DBG_32
  7713. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '7') &&
  7714. (lwrRegName[4] == '_') && (lwrRegName[5] >= '0') && (lwrRegName[5] <= '3'))
  7715. {
  7716. regNum = CPUReg_XMMREG_FIRST + ((lwrRegName[3] - '0') * 4) + (lwrRegName[5] - '0');
  7717. }
  7718. #else
  7719. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '9') &&
  7720. (lwrRegName[4] == '_') && (lwrRegName[5] >= '0') && (lwrRegName[5] <= '3'))
  7721. {
  7722. regNum = CPUReg_XMMREG_FIRST + ((lwrRegName[3] - '0') * 4) + (lwrRegName[5] - '0');
  7723. }
  7724. if ((lwrRegName.length() == 7) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] == '1') && (lwrRegName[4] >= '0') && (lwrRegName[4] <= '9') &&
  7725. (lwrRegName[5] == '_') && (lwrRegName[6] >= '0') && (lwrRegName[6] <= '3'))
  7726. {
  7727. regNum = CPUReg_XMMREG_FIRST + ((10 + (lwrRegName[4] - '0')) * 4) + (lwrRegName[6] - '0');
  7728. }
  7729. #endif
  7730. if (regNum != -1)
  7731. {
  7732. int xmmMajor = (regNum - CPUReg_XMMREG_FIRST) >> 2;
  7733. int xmmMinor = (regNum - CPUReg_XMMREG_FIRST) & 3;
  7734. DwMmDisplayType mmDisplayType = GetDisplayInfo(StrFormat("$XMM%d", xmmMajor))->mMmDisplayType;
  7735. RegForm regForm = RegForm_Unknown;
  7736. if (regForms != NULL)
  7737. {
  7738. int regFormIdx = CPUReg_M128_XMMREG_FIRST + xmmMajor;
  7739. if (regFormIdx < (int)regForms->size())
  7740. regForm = (*regForms)[regFormIdx];
  7741. }
  7742. if (mmDisplayType == DwMmDisplayType_Default)
  7743. {
  7744. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2))
  7745. mmDisplayType = DwMmDisplayType_Double;
  7746. else if (regForm == RegForm_Int4)
  7747. mmDisplayType = DwMmDisplayType_Int;
  7748. }
  7749. //TODO: Add int types
  7750. if (mmDisplayType == DwMmDisplayType_Double)
  7751. {
  7752. DbgTypedValue typedVal;
  7753. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Double, language);
  7754. typedVal.mDouble = registers->mXmmDRegsArray[xmmMajor].d[xmmMinor];
  7755. typedVal.mRegNum = regNum;
  7756. return typedVal;
  7757. }
  7758. if ((mmDisplayType == DwMmDisplayType_Byte) || (mmDisplayType == DwMmDisplayType_Short) || (mmDisplayType == DwMmDisplayType_Int))
  7759. {
  7760. DbgTypedValue typedVal;
  7761. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_i32, language);
  7762. typedVal.mInt32 = registers->mXmmIRegsARray[xmmMajor].i[xmmMinor];
  7763. typedVal.mRegNum = regNum;
  7764. return typedVal;
  7765. }
  7766. DbgTypedValue typedVal;
  7767. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Single, language);
  7768. typedVal.mSingle = registers->mXmmRegsArray[xmmMajor].f[xmmMinor];
  7769. typedVal.mRegNum = regNum;
  7770. return typedVal;
  7771. }
  7772. #ifdef BF_DBG_32
  7773. if ((lwrRegName.length() == 4) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '7'))
  7774. {
  7775. regNum = CPUReg_M128_XMMREG_FIRST + (lwrRegName[3] - '0');
  7776. }
  7777. #else
  7778. if ((lwrRegName.length() == 4) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '9'))
  7779. {
  7780. regNum = CPUReg_M128_XMMREG_FIRST + (lwrRegName[3] - '0');
  7781. }
  7782. if ((lwrRegName.length() == 5) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] == '1') && (lwrRegName[4] >= '0') && (lwrRegName[4] <= '5'))
  7783. {
  7784. regNum = CPUReg_M128_XMMREG_FIRST + 10 + (lwrRegName[4] - '0');
  7785. }
  7786. #endif
  7787. if (regNum != -1)
  7788. {
  7789. DbgTypedValue typedVal;
  7790. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_RegGroup, language);
  7791. 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)
  7792. typedVal.mRegNum = regNum;
  7793. return typedVal;
  7794. }
  7795. // flags
  7796. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'f') && (lwrRegName[1] == 'l') && (lwrRegName[2] == 'a') && (lwrRegName[3] == 'g') && (lwrRegName[5] == 'f'))
  7797. {
  7798. switch(lwrRegName[4])
  7799. {
  7800. case 'c': regNum = CPUReg_FLAG_CF_CARRY; break;
  7801. case 'p': regNum = CPUReg_FLAG_PF_PARITY; break;
  7802. case 'a': regNum = CPUReg_FLAG_AF_ADJUST; break;
  7803. case 'z': regNum = CPUReg_FLAG_ZF_ZERO; break;
  7804. case 's': regNum = CPUReg_FLAG_SF_SIGN; break;
  7805. case 'i': regNum = CPUReg_FLAG_IF_INTERRUPT; break;
  7806. case 'd': regNum = CPUReg_FLAG_DF_DIRECTION; break;
  7807. case 'o': regNum = CPUReg_FLAG_OF_OVERFLOW; break;
  7808. default: break;
  7809. }
  7810. }
  7811. if (regNum != -1)
  7812. {
  7813. int flagBit = CPURegisters::GetFlagBitForRegister(regNum);
  7814. BF_ASSERT(flagBit >= 0);
  7815. DbgTypedValue typedVal;
  7816. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Bool, language);
  7817. typedVal.mBool = (registers->mIntRegs.efl & ((uint64)1 << flagBit)) != 0;
  7818. typedVal.mRegNum = regNum;
  7819. return typedVal;
  7820. }
  7821. // categories
  7822. if (lwrRegName == "allregs")
  7823. regNum = CPUReg_CAT_ALLREGS;
  7824. else if (lwrRegName == "iregs")
  7825. regNum = CPUReg_CAT_IREGS;
  7826. else if (lwrRegName == "fpregs")
  7827. regNum = CPUReg_CAT_FPREGS;
  7828. else if (lwrRegName == "mmregs")
  7829. regNum = CPUReg_CAT_MMREGS;
  7830. else if (lwrRegName == "xmmregs")
  7831. regNum = CPUReg_CAT_XMMREGS;
  7832. else if (lwrRegName == "flags")
  7833. regNum = CPUReg_CAT_FLAGS;
  7834. if (regNum != -1)
  7835. {
  7836. DbgTypedValue typedVal;
  7837. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_RegGroup, language);
  7838. 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)
  7839. typedVal.mRegNum = regNum;
  7840. return typedVal;
  7841. }
  7842. return DbgTypedValue();
  7843. }
  7844. DbgModule* WinDebugger::GetCallStackDbgModule(int callStackIdx)
  7845. {
  7846. if ((mRunState == RunState_NotStarted) || (!IsPaused()))
  7847. return mEmptyDebugTarget->GetMainDbgModule();
  7848. if (callStackIdx == -1)
  7849. return mDebugTarget->GetMainDbgModule();
  7850. FixCallStackIdx(callStackIdx);
  7851. if (callStackIdx >= mCallStack.size())
  7852. return mDebugTarget->GetMainDbgModule();
  7853. UpdateCallStackMethod(callStackIdx);
  7854. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  7855. if (subProgram != NULL)
  7856. return subProgram->mCompileUnit->mDbgModule;
  7857. auto dbgModule = mDebugTarget->FindDbgModuleForAddress(mCallStack[callStackIdx]->mRegisters.GetPC());
  7858. if (dbgModule != NULL)
  7859. return dbgModule;
  7860. return mDebugTarget->GetMainDbgModule();
  7861. }
  7862. DbgSubprogram* WinDebugger::GetCallStackSubprogram(int callStackIdx)
  7863. {
  7864. if ((IsInRunState()) || (mRunState == RunState_NotStarted) || (callStackIdx == -1))
  7865. return NULL;
  7866. if (callStackIdx >= (int)mCallStack.size())
  7867. UpdateCallStack();
  7868. if (mCallStack.IsEmpty())
  7869. return NULL;
  7870. if (callStackIdx >= (int)mCallStack.size())
  7871. callStackIdx = 0;
  7872. UpdateCallStackMethod(callStackIdx);
  7873. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  7874. return subProgram;
  7875. }
  7876. DbgCompileUnit* WinDebugger::GetCallStackCompileUnit(int callStackIdx)
  7877. {
  7878. if ((IsInRunState()) || (mRunState == RunState_NotStarted) || (callStackIdx == -1))
  7879. return NULL;
  7880. if (callStackIdx >= (int)mCallStack.size())
  7881. UpdateCallStack();
  7882. if (mCallStack.IsEmpty())
  7883. return NULL;
  7884. if (callStackIdx >= (int)mCallStack.size())
  7885. callStackIdx = 0;
  7886. UpdateCallStackMethod(callStackIdx);
  7887. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  7888. if (subProgram == NULL)
  7889. return NULL;
  7890. return subProgram->mCompileUnit;
  7891. }
  7892. String WinDebugger::EvaluateContinue(DbgPendingExpr* pendingExpr, BfPassInstance& bfPassInstance)
  7893. {
  7894. DbgModule* dbgModule = NULL;
  7895. DbgCompileUnit* dbgCompileUnit = NULL;
  7896. if (pendingExpr->mThreadId == -1)
  7897. {
  7898. if ((pendingExpr->mFormatInfo.mLanguage == DbgLanguage_Beef) && (mDebugTarget != NULL) && (mDebugTarget->mTargetBinary != NULL))
  7899. dbgModule = mDebugTarget->mTargetBinary;
  7900. else
  7901. dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  7902. }
  7903. else
  7904. {
  7905. dbgModule = GetCallStackDbgModule(pendingExpr->mCallStackIdx);
  7906. if ((dbgModule != NULL) &&(!dbgModule->mDebugTarget->mIsEmpty))
  7907. dbgCompileUnit = GetCallStackCompileUnit(pendingExpr->mCallStackIdx);
  7908. }
  7909. if (dbgModule == NULL)
  7910. dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  7911. if (!pendingExpr->mException.empty())
  7912. {
  7913. RestoreAllRegisters();
  7914. return "!" + pendingExpr->mException;
  7915. }
  7916. DwAutoComplete autoComplete;
  7917. if (bfPassInstance.HasFailed())
  7918. {
  7919. // Don't allow pending calls if we've already failed in the calling Evaluate()
  7920. pendingExpr->mExpressionFlags = (DwEvalExpressionFlags)(pendingExpr->mExpressionFlags & ~DwEvalExpressionFlag_AllowCalls);
  7921. }
  7922. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, pendingExpr->mCallStackIdx, pendingExpr->mCursorPos);
  7923. dbgExprEvaluator.mLanguage = pendingExpr->mFormatInfo.mLanguage;
  7924. dbgExprEvaluator.mReferenceId = &pendingExpr->mReferenceId;
  7925. dbgExprEvaluator.mExpressionFlags = pendingExpr->mExpressionFlags;
  7926. dbgExprEvaluator.mExplicitThis = pendingExpr->mFormatInfo.mExplicitThis;
  7927. dbgExprEvaluator.mSubjectExpr = pendingExpr->mFormatInfo.mSubjectExpr;
  7928. dbgExprEvaluator.mNamespaceSearchStr = pendingExpr->mFormatInfo.mNamespaceSearch;
  7929. dbgExprEvaluator.mExpectingTypeName = pendingExpr->mFormatInfo.mExpectedType;
  7930. dbgExprEvaluator.mCallResults = &pendingExpr->mCallResults;
  7931. if ((pendingExpr->mExpressionFlags & DwEvalExpressionFlag_ValidateOnly) != 0)
  7932. {
  7933. dbgExprEvaluator.mValidateOnly = true;
  7934. }
  7935. if (pendingExpr->mCursorPos != -1)
  7936. {
  7937. dbgExprEvaluator.mAutoComplete = &autoComplete;
  7938. }
  7939. dbgExprEvaluator.mDbgCompileUnit = dbgCompileUnit;
  7940. DbgTypedValue exprResult;
  7941. if (pendingExpr->mExplitType != NULL)
  7942. {
  7943. exprResult.mHasNoValue = true;
  7944. exprResult.mType = pendingExpr->mExplitType;
  7945. }
  7946. else if (pendingExpr->mExprNode != NULL)
  7947. {
  7948. exprResult = dbgExprEvaluator.Resolve(pendingExpr->mExprNode);
  7949. }
  7950. if (dbgExprEvaluator.mCreatedPendingCall)
  7951. {
  7952. BF_ASSERT(mRunState == RunState_DebugEval);
  7953. //ContinueDebugEvent();
  7954. return "!pending";
  7955. }
  7956. if (dbgExprEvaluator.mCountResultOverride != -1)
  7957. pendingExpr->mFormatInfo.mOverrideCount = dbgExprEvaluator.mCountResultOverride;
  7958. String val;
  7959. if (bfPassInstance.HasFailed())
  7960. {
  7961. BfLogDbgExpr("Evaluate Failed: %s\n", bfPassInstance.mErrors[0]->mError.c_str());
  7962. val = StrFormat("!%d\t%d\t%s", bfPassInstance.mErrors[0]->GetSrcStart(), bfPassInstance.mErrors[0]->GetSrcLength(), bfPassInstance.mErrors[0]->mError.c_str());
  7963. }
  7964. else if (dbgExprEvaluator.mBlockedSideEffects)
  7965. {
  7966. BfLogDbgExpr("Evaluate blocked side effects\n");
  7967. val = "!sideeffects";
  7968. }
  7969. else if (!exprResult)
  7970. {
  7971. if (exprResult.mType != NULL)
  7972. {
  7973. BfLogDbgExpr("Evaluate success\n");
  7974. String typeName = exprResult.mType->ToString();
  7975. DbgType* rawType = exprResult.mType;
  7976. if (rawType->IsBfObjectPtr())
  7977. rawType = rawType->mTypeParam;
  7978. String typeNameRaw = rawType->ToStringRaw();
  7979. val = typeName + "\n" + typeName;
  7980. val += "\n" + GetMemberList(exprResult.mType, typeNameRaw, false, true, false, false, exprResult.mIsReadOnly);
  7981. if (exprResult.mType->mTypeCode == DbgType_Namespace)
  7982. {
  7983. val += "\n:type\tnamespace";
  7984. }
  7985. else
  7986. {
  7987. auto type = exprResult.mType;
  7988. if (type->IsPointer())
  7989. type = type->mTypeParam;
  7990. if (type->IsBfObject())
  7991. val += "\n:type\tclass";
  7992. else
  7993. val += "\n:type\tvaluetype";
  7994. }
  7995. if (!pendingExpr->mReferenceId.empty())
  7996. val += "\n:referenceId\t" + pendingExpr->mReferenceId;
  7997. }
  7998. else
  7999. val = "!";
  8000. }
  8001. else if ((pendingExpr->mExpressionFlags & (DwEvalExpressionFlag_MemoryAddress)) != 0)
  8002. {
  8003. DbgType* resultType = exprResult.mType->RemoveModifiers();
  8004. if ((resultType->IsInteger()) || (resultType->IsPointerOrRef()))
  8005. {
  8006. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", 0);
  8007. }
  8008. else
  8009. {
  8010. if (exprResult.mSrcAddress != 0)
  8011. val = StrFormat("!Type '%s' is invalid. A pointer or address value is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  8012. else
  8013. val = StrFormat("!Type '%s' is invalid. A pointer or address value is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  8014. }
  8015. }
  8016. else if ((pendingExpr->mExpressionFlags & (DwEvalExpressionFlag_MemoryWatch)) != 0)
  8017. {
  8018. DbgType* resultType = exprResult.mType->RemoveModifiers();
  8019. bool isMemoryWatch = (pendingExpr->mExpressionFlags & DwEvalExpressionFlag_MemoryWatch) != 0;
  8020. if (!resultType->IsPointerOrRef())
  8021. {
  8022. if (exprResult.mSrcAddress != 0)
  8023. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  8024. else
  8025. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  8026. }
  8027. else
  8028. {
  8029. auto innerType = resultType->mTypeParam;
  8030. int byteCount = innerType->GetByteCount();
  8031. if (pendingExpr->mFormatInfo.mArrayLength != -1)
  8032. byteCount *= pendingExpr->mFormatInfo.mArrayLength;
  8033. if (byteCount == 0)
  8034. {
  8035. 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());
  8036. }
  8037. #ifdef BF_DBG_32
  8038. else if ((isMemoryWatch) && (!IsMemoryBreakpointSizeValid(exprResult.mPtr, byteCount)))
  8039. {
  8040. if (innerType->mSize > 16)
  8041. 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);
  8042. else if (!IsMemoryBreakpointSizeValid(0, byteCount))
  8043. 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);
  8044. else
  8045. 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);
  8046. }
  8047. #else
  8048. else if ((isMemoryWatch) && (!IsMemoryBreakpointSizeValid(exprResult.mPtr, byteCount)))
  8049. {
  8050. if (innerType->mSize > 32)
  8051. 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);
  8052. else if (!IsMemoryBreakpointSizeValid(0, byteCount))
  8053. val = StrFormat("!Element size is %d bytes, which is not a supported size for a memory watch. Try casting to an appropriately-sized pointer.", byteCount);
  8054. else
  8055. val = StrFormat("!Element size is %d bytes, which is not a supported size for a memory watch at non-aligned address %@. Try casting to an appropriately-sized pointer.", byteCount, exprResult.mPtr);
  8056. }
  8057. #endif
  8058. else
  8059. {
  8060. auto language = dbgExprEvaluator.GetLanguage();
  8061. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", byteCount) + "\n" + StrFormat("%d\t", language) + innerType->ToStringRaw(language);
  8062. }
  8063. }
  8064. }
  8065. else
  8066. {
  8067. if (pendingExpr->mFormatInfo.mNoEdit)
  8068. exprResult.mIsReadOnly = true;
  8069. if (!pendingExpr->mReferenceId.empty())
  8070. pendingExpr->mFormatInfo.mReferenceId = pendingExpr->mReferenceId;
  8071. val = DbgTypedValueToString(exprResult, pendingExpr->mExprNode->ToString(), pendingExpr->mFormatInfo, &dbgExprEvaluator, (pendingExpr->mExpressionFlags & DwEvalExpressionFlag_FullPrecision) != 0);
  8072. if ((!val.empty()) && (val[0] == '!'))
  8073. return val;
  8074. if (pendingExpr->mFormatInfo.mRawString)
  8075. return val;
  8076. if (exprResult.mIsLiteral)
  8077. val += "\n:literal";
  8078. if (bfPassInstance.HasMessages())
  8079. {
  8080. for (auto error : bfPassInstance.mErrors)
  8081. {
  8082. if (error->mIsWarning)
  8083. {
  8084. val += "\n:warn\t";
  8085. val += error->mError;
  8086. }
  8087. }
  8088. }
  8089. if (!pendingExpr->mFormatInfo.mReferenceId.empty())
  8090. val += "\n:referenceId\t" + pendingExpr->mFormatInfo.mReferenceId;
  8091. if ((exprResult.mSrcAddress != 0) && (HasMemoryBreakpoint(exprResult.mSrcAddress, exprResult.mType->GetByteCount())))
  8092. val += StrFormat("\n:break\t%@", exprResult.mSrcAddress);
  8093. auto checkType = exprResult.mType->RemoveModifiers();
  8094. if (checkType->IsBfObjectPtr())
  8095. val += "\n:type\tobject";
  8096. else if ((checkType->IsPointer()) || (checkType->mTypeCode == DbgType_Subroutine))
  8097. val += "\n:type\tpointer";
  8098. else if (checkType->IsInteger())
  8099. val += "\n:type\tint";
  8100. else if (checkType->IsFloat())
  8101. val += "\n:type\tfloat";
  8102. else if ((exprResult.mRegNum >= X64Reg_M128_XMM0) && (exprResult.mRegNum <= X64Reg_M128_XMM15))
  8103. val += "\n:type\tmm128";
  8104. else
  8105. val += "\n:type\tvaluetype";
  8106. if ((pendingExpr->mFormatInfo.mTypeKindFlags & DbgTypeKindFlag_Int) != 0)
  8107. val += "\n:type\tint";
  8108. if (dbgExprEvaluator.mHadSideEffects)
  8109. val += "\n:sideeffects";
  8110. auto underlyingType = exprResult.mType->RemoveModifiers();
  8111. bool canEdit = true;
  8112. if (pendingExpr->mFormatInfo.mLanguage == DbgLanguage_Beef)
  8113. {
  8114. if (exprResult.mType->IsConst())
  8115. canEdit = false;
  8116. }
  8117. if (pendingExpr->mFormatInfo.mNoEdit)
  8118. canEdit = false;
  8119. if (exprResult.mIsReadOnly)
  8120. canEdit = false;
  8121. if (val[0] == '!')
  8122. {
  8123. // Already has an error embedded, can't edit
  8124. }
  8125. else if ((exprResult.mSrcAddress != 0) && (underlyingType->mTypeCode >= DbgType_i8) && (underlyingType->mTypeCode <= DbgType_Ptr) &&
  8126. (underlyingType->mTypeCode != DbgType_Class) && (underlyingType->mTypeCode != DbgType_Struct))
  8127. {
  8128. if (canEdit)
  8129. val += "\n:canEdit";
  8130. if (exprResult.mType->mTypeCode == DbgType_Ptr)
  8131. {
  8132. val += "\n:editVal\t" + EncodeDataPtr(exprResult.mPtr, true);
  8133. }
  8134. }
  8135. else if ((underlyingType->IsStruct()) && (exprResult.mSrcAddress != 0) && (underlyingType->IsTypedPrimitive()))
  8136. {
  8137. auto primType = underlyingType->GetRootBaseType();
  8138. DbgTypedValue primVal = dbgExprEvaluator.ReadTypedValue(NULL, primType, exprResult.mSrcAddress, DbgAddrType_Target);
  8139. String primResult = DbgTypedValueToString(primVal, "", pendingExpr->mFormatInfo, NULL);
  8140. int crPos = (int)primResult.IndexOf('\n');
  8141. if (crPos != -1)
  8142. primResult.RemoveToEnd(crPos);
  8143. if (canEdit)
  8144. val += "\n:canEdit";
  8145. val += "\n:editVal\t" + primResult;
  8146. }
  8147. else if (exprResult.mRegNum >= 0)
  8148. {
  8149. bool isPseudoReg = ( ((exprResult.mRegNum >= X86Reg_M128_XMMREG_FIRST) && (exprResult.mRegNum <= X86Reg_M128_XMMREG_LAST))
  8150. || ((exprResult.mRegNum >= X86Reg_CAT_FIRST) && (exprResult.mRegNum <= X86Reg_CAT_LAST)) );
  8151. if (!isPseudoReg)
  8152. {
  8153. if (canEdit)
  8154. val += "\n:canEdit";
  8155. }
  8156. }
  8157. }
  8158. if (pendingExpr->mFormatInfo.mRawString)
  8159. return "";
  8160. if (pendingExpr->mCursorPos != -1)
  8161. val += GetAutocompleteOutput(autoComplete);
  8162. return val;
  8163. }
  8164. String WinDebugger::EvaluateContinue()
  8165. {
  8166. BP_ZONE("WinDebugger::EvaluateContinue");
  8167. AutoCrit autoCrit(mDebugManager->mCritSect);
  8168. if (mDebugPendingExpr == NULL)
  8169. return "!Evaluation canceled";
  8170. if (!IsPaused())
  8171. return "!Not paused";
  8172. if (mRunState == RunState_DebugEval_Done)
  8173. mRunState = RunState_Paused;
  8174. BfPassInstance bfPassInstance(mBfSystem);
  8175. String result = EvaluateContinue(mDebugPendingExpr, bfPassInstance);
  8176. if (result != "!pending")
  8177. {
  8178. BfLogDbg("EvaluateContinue finishing pending expr in thread %d\n", mDebugEvalThreadInfo.mThreadId);
  8179. CleanupDebugEval();
  8180. }
  8181. return result;
  8182. }
  8183. void WinDebugger::EvaluateContinueKeep()
  8184. {
  8185. if (mDebugPendingExpr != NULL)
  8186. mDebugPendingExpr->mIdleTicks = 0;
  8187. }
  8188. static void PdbTestFile(WinDebugger* debugger, const StringImpl& path)
  8189. {
  8190. if (!path.EndsWith(".PDB", StringImpl::CompareKind_OrdinalIgnoreCase))
  8191. return;
  8192. OutputDebugStrF("Testing %s\n", path.c_str());
  8193. COFF coffFile(debugger->mDebugTarget);
  8194. uint8 wantGuid[16] = { 0 };
  8195. if (!coffFile.TryLoadPDB(path, wantGuid, -1))
  8196. return;
  8197. if (!coffFile.mIs64Bit)
  8198. return;
  8199. coffFile.ParseTypeData();
  8200. coffFile.ParseSymbolData();
  8201. coffFile.ParseGlobalsData();
  8202. }
  8203. static void PdbTest(WinDebugger* debugger, const StringImpl& path)
  8204. {
  8205. for (auto& fileEntry : FileEnumerator(path, FileEnumerator::Flags_Files))
  8206. {
  8207. String filePath = fileEntry.GetFilePath();
  8208. PdbTestFile(debugger, filePath);
  8209. }
  8210. for (auto& fileEntry : FileEnumerator(path, FileEnumerator::Flags_Directories))
  8211. {
  8212. String childPath = fileEntry.GetFilePath();
  8213. String dirName;
  8214. dirName = GetFileName(childPath);
  8215. PdbTest(debugger, childPath);
  8216. }
  8217. }
  8218. String WinDebugger::Evaluate(const StringImpl& expr, DwFormatInfo formatInfo, int callStackIdx, int cursorPos, int language, DwEvalExpressionFlags expressionFlags)
  8219. {
  8220. BP_ZONE_F("WinDebugger::Evaluate %s", BP_DYN_STR(expr.c_str()));
  8221. AutoCrit autoCrit(mDebugManager->mCritSect);
  8222. if ((expressionFlags & DwEvalExpressionFlag_Symbol) != 0)
  8223. {
  8224. DwAutoComplete autoComplete;
  8225. String retVal;
  8226. retVal += GetAutocompleteOutput(autoComplete);
  8227. return retVal;
  8228. }
  8229. UpdateCallStackMethod(callStackIdx);
  8230. BfLogDbgExpr("Evaluate %s in thread %d\n", expr.c_str(), (mActiveThread != NULL) ? mActiveThread->mThreadId : 0);
  8231. if (language != -1)
  8232. formatInfo.mLanguage = (DbgLanguage)language;
  8233. auto activeThread = mActiveThread;
  8234. if ((!IsPaused()) && (mRunState != RunState_NotStarted) && (mRunState != RunState_DebugEval))
  8235. {
  8236. activeThread = NULL;
  8237. callStackIdx = -1;
  8238. }
  8239. if (mDebugPendingExpr != NULL)
  8240. {
  8241. // We already have a pending call
  8242. expressionFlags = (DwEvalExpressionFlags)(expressionFlags & ~DwEvalExpressionFlag_AllowCalls);
  8243. }
  8244. auto dbgModule = GetCallStackDbgModule(callStackIdx);
  8245. auto dbgSubprogram = GetCallStackSubprogram(callStackIdx);
  8246. DbgCompileUnit* dbgCompileUnit = NULL;
  8247. if (dbgSubprogram != NULL)
  8248. dbgCompileUnit = dbgSubprogram->mCompileUnit;
  8249. auto terminatedExpr = expr + ";";
  8250. if ((expr.length() > 0) && (expr[0] == '!'))
  8251. {
  8252. if (expr.StartsWith("!step "))
  8253. {
  8254. expressionFlags = (DwEvalExpressionFlags)(expressionFlags | DwEvalExpressionFlag_StepIntoCalls);
  8255. for (int i = 0; i < 5; i++)
  8256. terminatedExpr[i] = ' ';
  8257. }
  8258. else
  8259. {
  8260. String cmd = expr;
  8261. int commaPos = (int)cmd.IndexOf(',');
  8262. if (commaPos != -1)
  8263. cmd.RemoveToEnd(commaPos);
  8264. if (cmd == "!info")
  8265. {
  8266. OutputMessage(StrFormat("Module: %s\n", dbgModule->mDisplayName.c_str()));
  8267. if (dbgSubprogram == NULL)
  8268. {
  8269. //
  8270. }
  8271. else if (dbgSubprogram->mLinkName != NULL)
  8272. {
  8273. OutputMessage(StrFormat("Link Name: %s\n", dbgSubprogram->mLinkName));
  8274. }
  8275. else
  8276. {
  8277. String outSymbol;
  8278. if (mDebugTarget->FindSymbolAt(dbgSubprogram->mBlock.mLowPC, &outSymbol))
  8279. {
  8280. OutputMessage(StrFormat("Link Name: %s\n", outSymbol.c_str()));
  8281. }
  8282. }
  8283. return "";
  8284. }
  8285. else if (cmd == "!dbg")
  8286. {
  8287. mDbgBreak = true;
  8288. return "";
  8289. }
  8290. else if (cmd == "!pdbtest")
  8291. {
  8292. PdbTest(this, "c:\\");
  8293. }
  8294. }
  8295. }
  8296. bool valIsAddr = false;
  8297. BfParser* parser = new BfParser(mBfSystem);
  8298. parser->mCompatMode = true;
  8299. BfPassInstance bfPassInstance(mBfSystem);
  8300. if ((terminatedExpr.length() > 2) && (terminatedExpr[0] == '@'))
  8301. {
  8302. if (terminatedExpr[1] == '!') // Return string as error
  8303. {
  8304. int errorEnd = (int)terminatedExpr.IndexOf("@!", 2);
  8305. if (errorEnd != -1)
  8306. return terminatedExpr.Substring(1, errorEnd - 1);
  8307. else
  8308. return terminatedExpr.Substring(1);
  8309. }
  8310. else if (terminatedExpr[1] == '>') // Return string as text
  8311. {
  8312. int errorEnd = (int)terminatedExpr.IndexOf("@>", 2);
  8313. if (errorEnd != -1)
  8314. return terminatedExpr.Substring(2, errorEnd - 1);
  8315. else
  8316. return terminatedExpr.Substring(2);
  8317. }
  8318. else // Look for "@:" or "@Beef:" style
  8319. {
  8320. int colonIdx = terminatedExpr.IndexOf(':');
  8321. if (colonIdx > 0)
  8322. {
  8323. bool isValid = true;
  8324. DbgLanguage language = DbgLanguage_Unknown;
  8325. String lang = terminatedExpr.Substring(1, colonIdx - 1);
  8326. lang = ToUpper(lang);
  8327. if ((lang == "") || (lang == "BEEF"))
  8328. {
  8329. language = DbgLanguage_Beef;
  8330. }
  8331. else if (lang == "C")
  8332. {
  8333. language = DbgLanguage_C;
  8334. }
  8335. if (language != DbgLanguage_Unknown)
  8336. {
  8337. for (int i = 0; i < colonIdx + 1; i++)
  8338. terminatedExpr[i] = ' ';
  8339. DbgLanguage curLanguage = DbgLanguage_Unknown;
  8340. if (dbgSubprogram != NULL)
  8341. curLanguage = dbgSubprogram->GetLanguage();
  8342. if (language != curLanguage)
  8343. {
  8344. dbgModule = mDebugTarget->mTargetBinary;
  8345. dbgSubprogram = NULL;
  8346. formatInfo.mLanguage = language;
  8347. callStackIdx = -1;
  8348. }
  8349. }
  8350. }
  8351. }
  8352. }
  8353. parser->SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  8354. parser->Parse(&bfPassInstance);
  8355. BfReducer bfReducer;
  8356. bfReducer.mAlloc = parser->mAlloc;
  8357. bfReducer.mSystem = mBfSystem;
  8358. bfReducer.mPassInstance = &bfPassInstance;
  8359. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser->mRootNode);
  8360. bfReducer.mVisitorPos.MoveNext();
  8361. bfReducer.mCompatMode = parser->mCompatMode;
  8362. bfReducer.mSource = parser;
  8363. auto exprNode = bfReducer.CreateExpression(parser->mRootNode->mChildArr.GetAs<BfAstNode*>(0));
  8364. parser->Close();
  8365. formatInfo.mCallStackIdx = callStackIdx;
  8366. if ((formatInfo.mLanguage == DbgLanguage_Unknown) && (dbgSubprogram != NULL))
  8367. formatInfo.mLanguage = dbgSubprogram->GetLanguage();
  8368. DbgPendingExpr* pendingExpr = new DbgPendingExpr();
  8369. if (activeThread != NULL)
  8370. pendingExpr->mThreadId = activeThread->mThreadId;
  8371. pendingExpr->mParser = parser;
  8372. pendingExpr->mCallStackIdx = callStackIdx;
  8373. pendingExpr->mCursorPos = cursorPos;
  8374. pendingExpr->mExpressionFlags = expressionFlags;
  8375. pendingExpr->mExprNode = exprNode;
  8376. DbgType* explicitType = NULL;
  8377. String formatFlags;
  8378. String assignExpr;
  8379. int assignExprOffset = -1;
  8380. if ((exprNode != NULL) && (exprNode->GetSrcEnd() < (int)expr.length()))
  8381. {
  8382. int formatOffset = exprNode->GetSrcEnd();
  8383. while (formatOffset < (int)expr.length())
  8384. {
  8385. char c = expr[formatOffset];
  8386. if (c == ' ')
  8387. formatOffset++;
  8388. else
  8389. break;
  8390. }
  8391. formatFlags = Trim(expr.Substring(formatOffset));
  8392. bool isComplexType = false;
  8393. for (char c : formatFlags)
  8394. if (c == '>')
  8395. isComplexType = true;
  8396. if (isComplexType)
  8397. {
  8398. explicitType = dbgModule->FindType(expr);
  8399. }
  8400. if ((explicitType == NULL) && (formatFlags.length() > 0))
  8401. {
  8402. String errorString = "Invalid expression";
  8403. if (!ParseFormatInfo(dbgModule, formatFlags, &formatInfo, &bfPassInstance, &assignExprOffset, &assignExpr, &errorString))
  8404. {
  8405. if (formatInfo.mRawString)
  8406. return "";
  8407. bfPassInstance.FailAt(errorString, parser->mSourceData, exprNode->GetSrcEnd(), (int) expr.length() - exprNode->GetSrcEnd());
  8408. formatFlags = "";
  8409. }
  8410. if (assignExprOffset != -1)
  8411. assignExprOffset += formatOffset;
  8412. }
  8413. }
  8414. if (assignExpr.length() > 0)
  8415. {
  8416. String newEvalStr = exprNode->ToString() + " = ";
  8417. int errorOffset = (int)newEvalStr.length();
  8418. newEvalStr += assignExpr;
  8419. String result = Evaluate(newEvalStr, formatInfo, callStackIdx, cursorPos, language, expressionFlags);
  8420. if (result[0] == '!')
  8421. {
  8422. int tabPos = (int)result.IndexOf('\t');
  8423. if (tabPos > 0)
  8424. {
  8425. int errorStart = atoi(result.Substring(1, tabPos - 1).c_str());
  8426. if (errorStart >= errorOffset)
  8427. {
  8428. result = StrFormat("!%d", errorStart - errorOffset + assignExprOffset) + result.Substring(tabPos);
  8429. }
  8430. }
  8431. }
  8432. return result;
  8433. }
  8434. pendingExpr->mExplitType = explicitType;
  8435. pendingExpr->mFormatInfo = formatInfo;
  8436. String result = EvaluateContinue(pendingExpr, bfPassInstance);
  8437. if (result == "!pending")
  8438. {
  8439. BF_ASSERT(mDebugPendingExpr == NULL);
  8440. if (mDebugPendingExpr != NULL)
  8441. {
  8442. return "!retry"; // We already have a pending
  8443. }
  8444. mDebugPendingExpr = pendingExpr;
  8445. mDebugEvalThreadInfo = *mActiveThread;
  8446. mActiveThread->mIsAtBreakpointAddress = 0;
  8447. mActiveThread->mStoppedAtAddress = 0;
  8448. mActiveThread->mBreakpointAddressContinuing = 0;
  8449. }
  8450. else
  8451. delete pendingExpr;
  8452. return result;
  8453. }
  8454. String WinDebugger::Evaluate(const StringImpl& expr, int callStackIdx, int cursorPos, int language, DwEvalExpressionFlags expressionFlags)
  8455. {
  8456. DwFormatInfo formatInfo;
  8457. return Evaluate(expr, formatInfo, callStackIdx, cursorPos, language, expressionFlags);
  8458. }
  8459. static void ConvertDoubleToFloat80(double d, byte fp80[10])
  8460. {
  8461. uint64 di = *reinterpret_cast<uint64*>(&d);
  8462. uint64 m = di & (((uint64)1 << 52) - 1);
  8463. uint64 e = (di >> 52) & 0x7ff;
  8464. memset(fp80, 0, 10);
  8465. // sign bit is directly transferred
  8466. if (di & ((uint64)1 << 63))
  8467. fp80[9] |= 0x80;
  8468. if (!e && !m)
  8469. return; // zero
  8470. fp80[7] |= 0x80; // leading integer bit in mantissa (always 1 in normalized numbers)
  8471. if (e == 0x7ff)
  8472. {
  8473. fp80[9] |= 0x7f;
  8474. fp80[8] = 0xff;
  8475. if (m == 0)
  8476. return; // inf
  8477. fp80[7] |= 0x3f; // any nonzero value will be a NaN (SNaN or QNaN)
  8478. if (m & ((uint64)1 << 51))
  8479. fp80[7] |= 0x40; // QNaN
  8480. return;
  8481. }
  8482. int useExponent = (int)e - 1023;
  8483. if (!e)
  8484. {
  8485. // denormal; can renormalize though since fp80 supports lower exponents
  8486. BF_ASSERT(m != 0); // we should have trapped zero above
  8487. while (!(m & ((uint64)1 << 51)))
  8488. {
  8489. m <<= 1;
  8490. --useExponent;
  8491. }
  8492. // finally we have our leading 1 bit; strip that off and we have a normalized number again
  8493. m <<= 1;
  8494. --useExponent;
  8495. m &= (((uint64)1 << 52) - 1);
  8496. }
  8497. useExponent += 16383;
  8498. BF_ASSERT((useExponent > 0) && (useExponent < 0x7fff));
  8499. *reinterpret_cast<uint16*>(&fp80[8]) |= (uint16)useExponent;
  8500. *reinterpret_cast<uint64*>(&fp80[0]) |= (m << 11);
  8501. }
  8502. bool WinDebugger::AssignToReg(int callStackIdx, DbgTypedValue regVal, DbgTypedValue value, String& outError)
  8503. {
  8504. BF_ASSERT(regVal.mRegNum >= 0);
  8505. if (mCallStack.size() == 0)
  8506. {
  8507. outError = "No call stack";
  8508. return false;
  8509. }
  8510. if (callStackIdx >= (int)mCallStack.size())
  8511. {
  8512. outError = "Invalid call stack index";
  8513. return false;
  8514. }
  8515. auto registers = &mCallStack[callStackIdx]->mRegisters;
  8516. void* regPtr = NULL;
  8517. #ifdef BF_DBG_32
  8518. if ((regVal.mRegNum >= X86Reg_INTREG_FIRST) && (regVal.mRegNum <= X86Reg_INTREG_LAST))
  8519. {
  8520. BF_ASSERT(regVal.mType->mSize == sizeof(int32));
  8521. registers->mIntRegsArray[regVal.mRegNum - X86Reg_INTREG_FIRST] = (uint64)value.mUInt32; // don't sign-extend
  8522. }
  8523. else if ((regVal.mRegNum >= X86Reg_FPSTREG_FIRST) && (regVal.mRegNum <= X86Reg_FPSTREG_LAST))
  8524. {
  8525. BF_ASSERT(regVal.mType->mSize == sizeof(float) || regVal.mType->mSize == sizeof(double));
  8526. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X86Reg_FPSTREG_FIRST];
  8527. double d;
  8528. if (regVal.mType->mSize == sizeof(float))
  8529. d = (double)value.mSingle;
  8530. else
  8531. d = value.mDouble;
  8532. ConvertDoubleToFloat80(d, reg->fp.fp80);
  8533. }
  8534. else if ((regVal.mRegNum >= X86Reg_MMREG_FIRST) && (regVal.mRegNum <= X86Reg_MMREG_LAST))
  8535. {
  8536. BF_ASSERT(regVal.mType->mSize == sizeof(int32) || regVal.mType->mSize == sizeof(int64));
  8537. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X86Reg_MMREG_FIRST];
  8538. if (regVal.mType->mSize == sizeof(int32))
  8539. reg->mm = (uint64)value.mUInt32; // don't sign-extend
  8540. else if (regVal.mType->mSize == sizeof(int64))
  8541. reg->mm = value.mInt64;
  8542. // 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
  8543. reg->fp.fp80[8] = reg->fp.fp80[9] = 0xFF;
  8544. }
  8545. else if ((regVal.mRegNum >= X86Reg_XMMREG_FIRST) && (regVal.mRegNum <= X86Reg_XMMREG_LAST))
  8546. {
  8547. int xmmMajor = (regVal.mRegNum - X86Reg_XMMREG_FIRST) >> 2;
  8548. int xmmMinor = (regVal.mRegNum - X86Reg_XMMREG_FIRST) & 3;
  8549. registers->mXmmRegsArray[xmmMajor].f[xmmMinor] = value.mSingle;
  8550. }
  8551. else if ((regVal.mRegNum >= X86Reg_M128_XMMREG_FIRST) && (regVal.mRegNum <= X86Reg_M128_XMMREG_LAST))
  8552. {
  8553. outError = "Cannot write directly to 128-bit XMM register, please use inner float components";
  8554. return false;
  8555. }
  8556. else if ((regVal.mRegNum >= X86Reg_FLAG_FIRST) && (regVal.mRegNum <= X86Reg_FLAG_LAST))
  8557. {
  8558. int flagBit = CPURegisters::GetFlagBitForRegister(regVal.mRegNum);
  8559. if (flagBit >= 0)
  8560. {
  8561. if (value.mBool)
  8562. registers->mIntRegs.efl |= ((uint64)1 << flagBit);
  8563. else
  8564. registers->mIntRegs.efl &= ~((uint64)1 << flagBit);
  8565. }
  8566. else
  8567. {
  8568. outError = "Unrecognized flag";
  8569. return false;
  8570. }
  8571. }
  8572. else if ((regVal.mRegNum >= X86Reg_CAT_FIRST) && (regVal.mRegNum <= X86Reg_CAT_LAST))
  8573. {
  8574. outError = "Cannot write directly to register categories, please use inner float components";
  8575. return false;
  8576. }
  8577. #else
  8578. if ((regVal.mRegNum >= X64Reg_INTREG_FIRST) && (regVal.mRegNum <= X64Reg_INTREG_LAST))
  8579. {
  8580. //BF_ASSERT(regVal.mType->mSize == sizeof(addr_target));
  8581. registers->mIntRegsArray[regVal.mRegNum - X64Reg_INTREG_FIRST] = value.GetInt64(); // don't sign-extend
  8582. regPtr = &registers->mIntRegsArray[regVal.mRegNum - X64Reg_INTREG_FIRST];
  8583. }
  8584. else if ((regVal.mRegNum >= X64Reg_FPSTREG_FIRST) && (regVal.mRegNum <= X64Reg_FPSTREG_LAST))
  8585. {
  8586. BF_ASSERT(regVal.mType->mSize == sizeof(float) || regVal.mType->mSize == sizeof(double));
  8587. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X64Reg_FPSTREG_FIRST];
  8588. double d;
  8589. if (regVal.mType->mSize == sizeof(float))
  8590. d = (double)value.mSingle;
  8591. else
  8592. d = value.mDouble;
  8593. ConvertDoubleToFloat80(d, reg->fp.fp80);
  8594. regPtr = reg;
  8595. }
  8596. else if ((regVal.mRegNum >= X64Reg_MMREG_FIRST) && (regVal.mRegNum <= X64Reg_MMREG_LAST))
  8597. {
  8598. BF_ASSERT(regVal.mType->mSize == sizeof(int32) || regVal.mType->mSize == sizeof(int64));
  8599. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X64Reg_MMREG_FIRST];
  8600. if (regVal.mType->mSize == sizeof(int32))
  8601. reg->mm = (uint64)value.mUInt32; // don't sign-extend
  8602. else if (regVal.mType->mSize == sizeof(int64))
  8603. reg->mm = value.mInt64;
  8604. // 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
  8605. reg->fp.fp80[8] = reg->fp.fp80[9] = 0xFF;
  8606. regPtr = reg;
  8607. }
  8608. else if ((regVal.mRegNum >= X64Reg_XMMREG_FIRST) && (regVal.mRegNum <= X64Reg_XMMREG_LAST))
  8609. {
  8610. int xmmMajor = (regVal.mRegNum - X64Reg_XMMREG_FIRST) >> 2;
  8611. int xmmMinor = (regVal.mRegNum - X64Reg_XMMREG_FIRST) & 3;
  8612. if (value.mType->GetByteCount() == 4)
  8613. registers->mXmmRegsArray[xmmMajor].f[xmmMinor] = value.mSingle;
  8614. else if (value.mType->GetByteCount() == 8)
  8615. registers->mXmmDRegsArray[xmmMajor].d[xmmMinor] = value.mDouble;
  8616. else
  8617. BF_FATAL("Invalid XMM set value type");
  8618. regPtr = &registers->mXmmRegsArray[xmmMajor];
  8619. }
  8620. else if ((regVal.mRegNum >= X64Reg_M128_XMMREG_FIRST) && (regVal.mRegNum <= X64Reg_M128_XMMREG_LAST))
  8621. {
  8622. outError = "Cannot write directly to 128-bit XMM register, please use inner float components";
  8623. return false;
  8624. }
  8625. else if ((regVal.mRegNum >= X64Reg_FLAG_FIRST) && (regVal.mRegNum <= X64Reg_FLAG_LAST))
  8626. {
  8627. int flagBit = CPURegisters::GetFlagBitForRegister(regVal.mRegNum);
  8628. if (flagBit >= 0)
  8629. {
  8630. if (value.mBool)
  8631. registers->mIntRegs.efl |= ((uint64)1 << flagBit);
  8632. else
  8633. registers->mIntRegs.efl &= ~((uint64)1 << flagBit);
  8634. regPtr = &registers->mIntRegs.efl;
  8635. }
  8636. else
  8637. {
  8638. outError = "Unrecognized flag";
  8639. return false;
  8640. }
  8641. }
  8642. else if ((regVal.mRegNum >= X64Reg_CAT_FIRST) && (regVal.mRegNum <= X64Reg_CAT_LAST))
  8643. {
  8644. outError = "Cannot write directly to register categories, please use inner float components";
  8645. return false;
  8646. }
  8647. else
  8648. BF_FATAL("Not implemented");
  8649. #endif
  8650. if (callStackIdx == 0)
  8651. {
  8652. SetRegisters(&mCallStack[0]->mRegisters);
  8653. return true;
  8654. }
  8655. else
  8656. {
  8657. bool wasSaved = false;
  8658. for (int calleeStackIdx = callStackIdx - 1; calleeStackIdx >= 0; calleeStackIdx--)
  8659. {
  8660. auto calleeRegisters = &mCallStack[calleeStackIdx]->mRegisters;
  8661. if (!mDebugTarget->PropogateRegisterUpCallStack(registers, calleeRegisters, regPtr, wasSaved))
  8662. {
  8663. outError = "Failed to set register";
  8664. return false;
  8665. }
  8666. if (wasSaved)
  8667. return true;
  8668. }
  8669. // This register wasn't saved, so commit it to the callstack top
  8670. return AssignToReg(0, regVal, value, outError);
  8671. }
  8672. }
  8673. String WinDebugger::GetAutocompleteOutput(DwAutoComplete& autoComplete)
  8674. {
  8675. String val = "\n:autocomplete\n";
  8676. if (autoComplete.mInsertStartIdx != -1)
  8677. {
  8678. val += StrFormat("insertRange\t%d %d\n", autoComplete.mInsertStartIdx, autoComplete.mInsertEndIdx);
  8679. }
  8680. Array<AutoCompleteEntry*> entries;
  8681. for (auto& entry : autoComplete.mEntriesSet)
  8682. {
  8683. entries.Add(&entry);
  8684. }
  8685. std::sort(entries.begin(), entries.end(), [](AutoCompleteEntry* lhs, AutoCompleteEntry* rhs)
  8686. {
  8687. return stricmp(lhs->mDisplay, rhs->mDisplay) < 0;
  8688. });
  8689. for (auto entry : entries)
  8690. {
  8691. val += String(entry->mEntryType);
  8692. val += "\t";
  8693. val += String(entry->mDisplay);
  8694. val += "\n";
  8695. }
  8696. /*if (autoComplete.mEntries.size() != 0)
  8697. {
  8698. for (auto& entry : autoComplete.mEntries)
  8699. {
  8700. val += String(entry.mEntryType) + "\t" + String(entry.mDisplay) + "\n";
  8701. }
  8702. }*/
  8703. return val;
  8704. }
  8705. String WinDebugger::EvaluateToAddress(const StringImpl& expr, int callStackIdx, int cursorPos)
  8706. {
  8707. AutoCrit autoCrit(mDebugManager->mCritSect);
  8708. if (IsInRunState())
  8709. return "!Target not paused";
  8710. auto dbgModule = GetCallStackDbgModule(callStackIdx);
  8711. auto dbgCompileUnit = GetCallStackCompileUnit(callStackIdx);
  8712. BfParser parser(mBfSystem);
  8713. parser.mCompatMode = true;
  8714. BfPassInstance bfPassInstance(mBfSystem);
  8715. auto terminatedExpr = expr + ";";
  8716. parser.SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  8717. parser.Parse(&bfPassInstance);
  8718. BfReducer bfReducer;
  8719. bfReducer.mAlloc = parser.mAlloc;
  8720. bfReducer.mSystem = mBfSystem;
  8721. bfReducer.mPassInstance = &bfPassInstance;
  8722. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser.mRootNode);
  8723. bfReducer.mVisitorPos.MoveNext();
  8724. bfReducer.mSource = &parser;
  8725. auto exprNode = bfReducer.CreateExpression(parser.mRootNode->GetFirst());
  8726. parser.Close();
  8727. DwAutoComplete autoComplete;
  8728. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, callStackIdx, cursorPos);
  8729. if (cursorPos != -1)
  8730. dbgExprEvaluator.mAutoComplete = &autoComplete;
  8731. dbgExprEvaluator.mDbgCompileUnit = dbgCompileUnit;
  8732. DwFormatInfo formatInfo;
  8733. formatInfo.mCallStackIdx = callStackIdx;
  8734. DbgTypedValue exprResult;
  8735. if (exprNode != NULL)
  8736. exprResult = dbgExprEvaluator.Resolve(exprNode);
  8737. DbgType* resultType = exprResult.mType->RemoveModifiers();
  8738. String val;
  8739. if (bfPassInstance.HasFailed())
  8740. {
  8741. val = StrFormat("!%d\t%d\t%s", bfPassInstance.mErrors[0]->mSrcStart, bfPassInstance.mErrors[0]->GetSrcLength(), bfPassInstance.mErrors[0]->mError.c_str());
  8742. }
  8743. else if (exprResult.mType == NULL)
  8744. {
  8745. val = "!Invalid expression";
  8746. }
  8747. else if (!resultType->IsPointerOrRef())
  8748. {
  8749. if (exprResult.mSrcAddress != 0)
  8750. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  8751. else
  8752. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  8753. }
  8754. else
  8755. {
  8756. auto innerType = resultType->mTypeParam;
  8757. int byteCount = innerType->GetByteCount();
  8758. if (byteCount == 0)
  8759. {
  8760. 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());
  8761. }
  8762. #ifdef BF_DBG_32
  8763. else if ((byteCount != 1) && (byteCount != 2) && (byteCount != 4))
  8764. {
  8765. 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);
  8766. }
  8767. #else
  8768. else if ((byteCount != 1) && (byteCount != 2) && (byteCount != 4) && (byteCount != 8))
  8769. {
  8770. 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);
  8771. }
  8772. #endif
  8773. else
  8774. {
  8775. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", byteCount);
  8776. }
  8777. }
  8778. if (cursorPos != -1)
  8779. val += GetAutocompleteOutput(autoComplete);
  8780. return val;
  8781. }
  8782. // This is currently only used for autocomplete during conditional breakpoint expression entry.
  8783. // If we want to use it for more than that then remove DwEvalExpressionFlags_ValidateOnly
  8784. String WinDebugger::EvaluateAtAddress(const StringImpl& expr, intptr atAddr, int cursorPos)
  8785. {
  8786. AutoCrit autoCrit(mDebugManager->mCritSect);
  8787. if (IsInRunState())
  8788. return "!Target not paused";
  8789. if (!IsPaused())
  8790. return "!Target not running";
  8791. WdStackFrame stackFrame;
  8792. memset(&stackFrame.mRegisters, 0, sizeof(stackFrame.mRegisters));
  8793. stackFrame.mHasGottenSubProgram = true;
  8794. *stackFrame.mRegisters.GetPCRegisterRef() = (intptr_target)atAddr;
  8795. stackFrame.mSubProgram = mDebugTarget->FindSubProgram((addr_target)atAddr);
  8796. if (stackFrame.mSubProgram == NULL)
  8797. return "!Invalid address";
  8798. mCallStack.push_back(&stackFrame);
  8799. int callStackIdx = (int)mCallStack.size() - 1;
  8800. String val = Evaluate(expr, callStackIdx, cursorPos, -1, DwEvalExpressionFlag_ValidateOnly);
  8801. mCallStack.pop_back();
  8802. return val;
  8803. }
  8804. String WinDebugger::GetAutoExpressions(int callStackIdx, uint64 memoryRangeStart, uint64 memoryRangeLen)
  8805. {
  8806. BP_ZONE("WinDebugger::GetAutoExpressions");
  8807. AutoCrit autoCrit(mDebugManager->mCritSect);
  8808. if (IsInRunState())
  8809. return "!Not paused";
  8810. if (!IsPaused())
  8811. return "!Not running";
  8812. if (!FixCallStackIdx(callStackIdx))
  8813. return "";
  8814. CPUStackFrame* stackFrame = (callStackIdx >= 0) ? mCallStack[callStackIdx] : mCallStack.front();
  8815. String result;
  8816. DbgAutoValueMapType dwarfAutos;
  8817. mDebugTarget->GetAutoValueNames(dwarfAutos, stackFrame, memoryRangeStart, memoryRangeLen);
  8818. for (auto const &a : dwarfAutos)
  8819. {
  8820. std::pair<uint64, uint64> varRange = a.mValue;
  8821. if (varRange.first != 0)
  8822. result += StrFormat("&%s\t%llu\t%llu\n", a.mKey.c_str(), varRange.second, varRange.first);
  8823. else
  8824. result += StrFormat("?%s\t%llu\n", a.mKey.c_str(), varRange.second);
  8825. }
  8826. #ifdef BF_DBG_64
  8827. // add int regs
  8828. const char* regStrs[] = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "rip", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", 0 };
  8829. #else
  8830. // add int regs
  8831. const char* regStrs[] = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "eip", 0 };
  8832. #endif
  8833. for (const char** p = regStrs; *p; ++p)
  8834. result += StrFormat("$%s\t%d\n", *p, sizeof(addr_target));
  8835. if (callStackIdx < (int)mCallStack.size() - 2)
  8836. {
  8837. WdStackFrame* prevStackFrame = mCallStack[callStackIdx + 1];
  8838. // Inlined methods have no stack frame
  8839. int stackSize = prevStackFrame->mRegisters.GetSP() - stackFrame->mRegisters.GetSP();
  8840. result += StrFormat("&$StackFrame\t%llu\t%llu\n", stackSize, stackFrame->mRegisters.GetSP());
  8841. }
  8842. return result;
  8843. }
  8844. String WinDebugger::GetAutoLocals(int stackFrameIdx, bool showRegs)
  8845. {
  8846. BP_ZONE("WinDebugger::GetAutoExpressions");
  8847. AutoCrit autoCrit(mDebugManager->mCritSect);
  8848. if (IsInRunState())
  8849. return "";
  8850. if (!IsPaused())
  8851. return "";
  8852. if (mCallStack.size() == 0)
  8853. UpdateCallStack();
  8854. String result;
  8855. Array<String> localList;
  8856. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  8857. UpdateCallStackMethod(actualStackFrameIdx);
  8858. if (actualStackFrameIdx >= mCallStack.size())
  8859. return "";
  8860. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  8861. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  8862. if (dwSubprogram == NULL)
  8863. return "";
  8864. auto langage = dwSubprogram->GetLanguage();
  8865. DbgLineData* dwLineData = FindLineDataInSubprogram(wdStackFrame->GetSourcePC(), dwSubprogram);
  8866. if (dwLineData == NULL)
  8867. return "";
  8868. dwSubprogram->PopulateSubprogram();
  8869. mDebugTarget->GetAutoLocalsInBlock(localList, dwSubprogram, &dwSubprogram->mBlock, wdStackFrame, dwLineData);
  8870. String lastLocal;
  8871. for (auto local : localList)
  8872. {
  8873. if (langage == DbgLanguage_C)
  8874. {
  8875. if ((local == "this") && (strncmp(dwSubprogram->mName, "<lambda_", 8) == 0))
  8876. {
  8877. // Use explicit "$this" so we can see the actual capture
  8878. result += "$this\n";
  8879. continue;
  8880. }
  8881. }
  8882. bool wasAlias = false;
  8883. for (int i = 0; i < (int)local.length() - 1; i++)
  8884. {
  8885. if ((local[i] == '$') && (local[i + 1] == 'a'))
  8886. {
  8887. // Alias
  8888. wasAlias = true;
  8889. String localName = local.Substring(0, i) + "\n";
  8890. if (localName != lastLocal)
  8891. {
  8892. result += localName;
  8893. lastLocal = localName;
  8894. }
  8895. break;
  8896. }
  8897. }
  8898. if (!wasAlias)
  8899. result += local + "\n";
  8900. }
  8901. if (showRegs)
  8902. {
  8903. result += "$FLAGS\n";
  8904. UpdateRegisterUsage(stackFrameIdx);
  8905. for (int regIdx = 0; regIdx < (int)wdStackFrame->mRegForms.size(); regIdx++)
  8906. {
  8907. if (wdStackFrame->mRegForms[regIdx] != RegForm_Invalid)
  8908. result += "$" + String(CPURegisters::GetRegisterName(regIdx)) + "\n";
  8909. }
  8910. }
  8911. return result;
  8912. }
  8913. String WinDebugger::CompactChildExpression(const StringImpl& expr, const StringImpl& parentExpr, int callStackIdx)
  8914. {
  8915. DbgCompileUnit* compileUnit = GetCallStackCompileUnit(callStackIdx);
  8916. DbgModule* dbgModule = GetCallStackDbgModule(callStackIdx);
  8917. if (dbgModule == NULL)
  8918. return "!failed";
  8919. DbgLanguage language = DbgLanguage_Unknown;
  8920. if (compileUnit != NULL)
  8921. language = compileUnit->mLanguage;
  8922. BfPassInstance bfPassInstance(mBfSystem);
  8923. BfParser parser(mBfSystem);
  8924. parser.mCompatMode = language != DbgLanguage_Beef;
  8925. auto terminatedExpr = expr + ";";
  8926. parser.SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  8927. parser.Parse(&bfPassInstance);
  8928. BfParser parentParser(mBfSystem);
  8929. auto terminatedParentExpr = parentExpr + ";";
  8930. parentParser.mCompatMode = language != DbgLanguage_Beef;
  8931. parentParser.SetSource(terminatedParentExpr.c_str(), terminatedParentExpr.length());
  8932. parentParser.Parse(&bfPassInstance);
  8933. BfReducer bfReducer;
  8934. bfReducer.mCompatMode = true;
  8935. bfReducer.mAlloc = parser.mAlloc;
  8936. bfReducer.mSystem = mBfSystem;
  8937. bfReducer.mPassInstance = &bfPassInstance;
  8938. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser.mRootNode);
  8939. bfReducer.mVisitorPos.MoveNext();
  8940. bfReducer.mSource = &parser;
  8941. auto exprNode = bfReducer.CreateExpression(parser.mRootNode->GetFirst());
  8942. bfReducer.mAlloc = parentParser.mAlloc;
  8943. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parentParser.mRootNode);
  8944. bfReducer.mVisitorPos.MoveNext();
  8945. auto parentExprNode = bfReducer.CreateExpression(parentParser.mRootNode->GetFirst());
  8946. parser.Close();
  8947. if ((exprNode == NULL) || (parentExprNode == NULL))
  8948. return "!failed";
  8949. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, callStackIdx, -1);
  8950. DwFormatInfo formatInfo;
  8951. formatInfo.mCallStackIdx = callStackIdx;
  8952. String formatFlags;
  8953. String assignExpr;
  8954. if ((exprNode != NULL) && (exprNode->GetSrcEnd() < (int) expr.length()))
  8955. {
  8956. formatFlags = Trim(expr.Substring(exprNode->GetSrcEnd()));
  8957. if (formatFlags.length() > 0)
  8958. {
  8959. String errorString = "Invalid expression";
  8960. if (!ParseFormatInfo(dbgModule, formatFlags, &formatInfo, &bfPassInstance, NULL, &assignExpr, &errorString))
  8961. {
  8962. bfPassInstance.FailAt(errorString, parser.mSourceData, exprNode->GetSrcEnd(), (int) expr.length() - exprNode->GetSrcEnd());
  8963. formatFlags = "";
  8964. }
  8965. }
  8966. }
  8967. dbgExprEvaluator.mExplicitThis = formatInfo.mExplicitThis;
  8968. dbgExprEvaluator.mExplicitThisExpr = parentExprNode;
  8969. DbgTypedValue exprResult = dbgExprEvaluator.Resolve(exprNode);
  8970. BfAstNode* headNode = dbgExprEvaluator.FinalizeExplicitThisReferences(exprNode);
  8971. BfPrinter printer(parser.mRootNode, NULL, NULL);
  8972. printer.mIgnoreTrivia = true;
  8973. printer.mReformatting = true;
  8974. printer.VisitChild(headNode);
  8975. auto result = printer.mOutString;
  8976. if (formatInfo.mNoVisualizers)
  8977. result += ", nv";
  8978. if (formatInfo.mNoMembers)
  8979. result += ", nm";
  8980. if (formatInfo.mNoEdit)
  8981. result += ", ne";
  8982. if (formatInfo.mIgnoreDerivedClassInfo)
  8983. result += ", nd";
  8984. if (formatInfo.mDisplayType == DwDisplayType_Ascii)
  8985. result += ", s";
  8986. if (formatInfo.mDisplayType == DwDisplayType_Utf8)
  8987. result += ", s8";
  8988. if (formatInfo.mDisplayType == DwDisplayType_Utf16)
  8989. result += ", s16";
  8990. if (formatInfo.mDisplayType == DwDisplayType_Utf32)
  8991. result += ", s32";
  8992. return result;
  8993. }
  8994. String WinDebugger::GetProcessInfo()
  8995. {
  8996. AutoCrit autoCrit(mDebugManager->mCritSect);
  8997. if ((mActiveThread == NULL) && (!mIsRunning))
  8998. return "";
  8999. SYSTEM_INFO sysinfo = { 0 };
  9000. GetSystemInfo(&sysinfo);
  9001. FILETIME creationTime = { 0 };
  9002. FILETIME exitTime = { 0 };
  9003. FILETIME kernelTime = { 0 };
  9004. FILETIME userTime = { 0 };
  9005. ::GetProcessTimes(mProcessInfo.hProcess, &creationTime, &exitTime, &kernelTime, &userTime);
  9006. String retStr;
  9007. PROCESS_MEMORY_COUNTERS memInfo = { 0 };
  9008. ::GetProcessMemoryInfo(mProcessInfo.hProcess, &memInfo, sizeof(PROCESS_MEMORY_COUNTERS));
  9009. FILETIME currentTime = { 0 };
  9010. ::GetSystemTimeAsFileTime(&currentTime);
  9011. retStr += StrFormat("VirtualMemory\t%d\n", memInfo.PagefileUsage);
  9012. retStr += StrFormat("WorkingMemory\t%d\n", memInfo.WorkingSetSize);
  9013. retStr += StrFormat("RunningTime\t%lld\n", *(int64*)&currentTime - *(int64*)&creationTime);
  9014. retStr += StrFormat("KernelTime\t%lld\n", *(int64*)&kernelTime / sysinfo.dwNumberOfProcessors);
  9015. retStr += StrFormat("UserTime\t%lld\n", *(int64*)&userTime / sysinfo.dwNumberOfProcessors);
  9016. return retStr;
  9017. }
  9018. String WinDebugger::GetThreadInfo()
  9019. {
  9020. AutoCrit autoCrit(mDebugManager->mCritSect);
  9021. String retStr;
  9022. if ((mActiveThread == NULL) && (!mIsRunning))
  9023. {
  9024. retStr = "";
  9025. }
  9026. else
  9027. {
  9028. if (mActiveThread != NULL)
  9029. retStr = StrFormat("%d", mActiveThread->mThreadId);
  9030. for (auto threadInfo : mThreadList)
  9031. {
  9032. SetAndRestoreValue<WdThreadInfo*> prevThread(mActiveThread, threadInfo);
  9033. retStr += "\n";
  9034. for (int pass = 0; pass < 2; pass++)
  9035. {
  9036. CPURegisters registers;
  9037. PopulateRegisters(&registers);
  9038. String locString = EncodeDataPtr((addr_target)registers.GetPC(), true);
  9039. TryGetThreadName(threadInfo);
  9040. bool hadThreadName = true;
  9041. String threadName = threadInfo->mName;
  9042. if (threadName.IsEmpty())
  9043. {
  9044. hadThreadName = false;
  9045. if (threadInfo->mThreadId == mProcessInfo.dwThreadId)
  9046. threadName = "Main Thread";
  9047. else
  9048. threadName = "Worker Thread";
  9049. }
  9050. bool isInvalid = false;
  9051. addr_target appendAddr = 0;
  9052. for (int stackIdx = 0; true; stackIdx++)
  9053. {
  9054. auto subProgram = mDebugTarget->FindSubProgram(registers.GetPC(), DbgOnDemandKind_LocalOnly);
  9055. if (subProgram != NULL)
  9056. {
  9057. if (subProgram->mLineInfo != NULL)
  9058. {
  9059. DbgModule* module = subProgram->mCompileUnit->mDbgModule;
  9060. DbgModule* linkedModule = module->GetLinkedModule();
  9061. if (linkedModule->mDisplayName.length() > 0)
  9062. {
  9063. locString = linkedModule->mDisplayName + "!" + subProgram->ToString();
  9064. if (!hadThreadName)
  9065. threadName = module->mDisplayName + " thread";
  9066. }
  9067. else
  9068. {
  9069. locString = subProgram->ToString();
  9070. }
  9071. appendAddr = 0;
  9072. break;
  9073. }
  9074. }
  9075. DbgModule* module = mDebugTarget->FindDbgModuleForAddress(registers.GetPC());
  9076. if (module == NULL)
  9077. {
  9078. isInvalid = true;
  9079. break;
  9080. }
  9081. DbgModule* linkedModule = module->GetLinkedModule();
  9082. appendAddr = (addr_target)registers.GetPC();
  9083. locString = linkedModule->mDisplayName + "!" + EncodeDataPtr((addr_target)registers.GetPC(), true);
  9084. if (!hadThreadName)
  9085. threadName = linkedModule->mDisplayName + " thread";
  9086. if ((mActiveThread == mExplicitStopThread) && (mActiveBreakpoint != NULL))
  9087. {
  9088. if ((subProgram == NULL) ||
  9089. (mActiveBreakpoint->mAddr < subProgram->mBlock.mLowPC) ||
  9090. (mActiveBreakpoint->mAddr >= subProgram->mBlock.mHighPC))
  9091. break;
  9092. }
  9093. if (pass == 1) // Just take the first item
  9094. break;
  9095. if (stackIdx == 128)
  9096. break; // Too many!
  9097. addr_target returnAddr;
  9098. if (!mDebugTarget->RollBackStackFrame(&registers, &returnAddr, true))
  9099. {
  9100. isInvalid = true;
  9101. break;
  9102. }
  9103. }
  9104. if ((isInvalid) && (pass == 0))
  9105. continue;
  9106. if (appendAddr != 0)
  9107. {
  9108. String symbolName;
  9109. addr_target offset;
  9110. DbgModule* dwarf;
  9111. if (mDebugTarget->FindSymbolAt(appendAddr, &symbolName, &offset, &dwarf))
  9112. {
  9113. DbgModule* linkedModule = dwarf->GetLinkedModule();
  9114. String demangledName = BfDemangler::Demangle(symbolName, DbgLanguage_Unknown);
  9115. if (!linkedModule->mDisplayName.empty())
  9116. {
  9117. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  9118. }
  9119. locString = demangledName + StrFormat("+0x%X", offset);
  9120. }
  9121. }
  9122. retStr += StrFormat("%d\t%s\t%s", threadInfo->mThreadId, threadName.c_str(), locString.c_str());
  9123. String attrs;
  9124. if (threadInfo->mFrozen)
  9125. {
  9126. attrs += "Fr";
  9127. }
  9128. if (!attrs.IsEmpty())
  9129. {
  9130. retStr += "\t";
  9131. retStr += attrs;
  9132. }
  9133. break;
  9134. }
  9135. }
  9136. }
  9137. return retStr;
  9138. }
  9139. void WinDebugger::SetActiveThread(int threadId)
  9140. {
  9141. AutoCrit autoCrit(mDebugManager->mCritSect);
  9142. if (mThreadMap.TryGetValue(threadId, &mActiveThread))
  9143. {
  9144. BfLogDbg("SetActiveThread %d\n", threadId);
  9145. ClearCallStack();
  9146. }
  9147. else
  9148. {
  9149. BfLogDbg("SetActiveThread %d FAILED\n", threadId);
  9150. }
  9151. }
  9152. int WinDebugger::GetActiveThread()
  9153. {
  9154. AutoCrit autoCrit(mDebugManager->mCritSect);
  9155. if (mActiveThread == NULL)
  9156. return -1;
  9157. return mActiveThread->mThreadId;
  9158. }
  9159. void WinDebugger::FreezeThread(int threadId)
  9160. {
  9161. AutoCrit autoCrit(mDebugManager->mCritSect);
  9162. BF_ASSERT(!IsInRunState());
  9163. auto thread = mThreadMap[threadId];
  9164. if (!thread->mFrozen)
  9165. {
  9166. thread->mFrozen = true;
  9167. ::SuspendThread(thread->mHThread);
  9168. BfLogDbg("SuspendThread %d from FreezeThread\n", thread->mThreadId);
  9169. }
  9170. }
  9171. void WinDebugger::ThawThread(int threadId)
  9172. {
  9173. AutoCrit autoCrit(mDebugManager->mCritSect);
  9174. BF_ASSERT(!IsInRunState());
  9175. auto thread = mThreadMap[threadId];
  9176. if (thread->mFrozen)
  9177. {
  9178. thread->mFrozen = false;
  9179. ::ResumeThread(thread->mHThread);
  9180. BfLogDbg("ResumeThread %d from ThawThread\n", thread->mThreadId);
  9181. }
  9182. }
  9183. bool WinDebugger::IsActiveThreadWaiting()
  9184. {
  9185. AutoCrit autoCrit(mDebugManager->mCritSect);
  9186. return mActiveThread == mDebuggerWaitingThread;
  9187. }
  9188. void WinDebugger::ClearCallStack()
  9189. {
  9190. AutoCrit autoCrit(mDebugManager->mCritSect);
  9191. BfLogDbg("ClearCallstack\n");
  9192. BF_ASSERT(mRunState != RunState_DebugEval);
  9193. for (auto wdStackFrame : mCallStack)
  9194. delete wdStackFrame;
  9195. mCallStack.Clear();
  9196. mIsPartialCallStack = true;
  9197. }
  9198. void WinDebugger::UpdateCallStack(bool slowEarlyOut)
  9199. {
  9200. AutoCrit autoCrit(mDebugManager->mCritSect);
  9201. if (!mIsPartialCallStack)
  9202. return;
  9203. BF_ASSERT(!IsInRunState());
  9204. uint32 tickStart = BFTickCount();
  9205. CPURegisters registers;
  9206. if (mCallStack.size() > 0)
  9207. {
  9208. WdStackFrame* wdStackFrame = mCallStack.back();
  9209. if (wdStackFrame->mIsEnd)
  9210. {
  9211. return;
  9212. }
  9213. memcpy(&registers, &wdStackFrame->mRegisters, sizeof(registers));
  9214. bool regsRolledBack = RollBackStackFrame(&registers, mCallStack.size() == 1);
  9215. // If we can't roll them back then mIsEnd should have been set for the previous frame
  9216. BF_ASSERT(regsRolledBack);
  9217. }
  9218. else
  9219. {
  9220. BF_ASSERT(mIsPartialCallStack);
  9221. mCallStack.Reserve(1024);
  9222. PopulateRegisters(&registers);
  9223. BfLogDbg("UpdateCallStack starting. Thread=%d PC=0x%p\n", mActiveThread->mThreadId, registers.GetPC());
  9224. }
  9225. bool isPartial = false;
  9226. // Incrementally fill callstack structure to avoid stepping slowdown during deep nesting
  9227. for (int fillIdx = 0; fillIdx < (slowEarlyOut ? 10000 : 100000); fillIdx++)
  9228. {
  9229. WdStackFrame* wdStackFrame = new WdStackFrame();
  9230. memcpy(&wdStackFrame->mRegisters, &registers, sizeof(registers));
  9231. wdStackFrame->mIsStart = mCallStack.size() == 0;
  9232. wdStackFrame->mIsEnd = false;
  9233. bool rollbackSuccess = false;
  9234. for (int tryCount = 0; tryCount < 16; tryCount++)
  9235. {
  9236. if (!RollBackStackFrame(&registers, wdStackFrame->mIsStart))
  9237. {
  9238. break;
  9239. }
  9240. if (registers.GetPC() > 0xFFFF)
  9241. {
  9242. rollbackSuccess = true;
  9243. break;
  9244. }
  9245. if (mCallStack.size() > 0)
  9246. break; // Only retry for the first frame
  9247. }
  9248. if (!rollbackSuccess)
  9249. wdStackFrame->mIsEnd = true;
  9250. if (registers.GetSP() <= wdStackFrame->mRegisters.GetSP())
  9251. {
  9252. // SP went the wrong direction, stop rolling back
  9253. wdStackFrame->mIsEnd = true;
  9254. }
  9255. mCallStack.push_back(wdStackFrame);
  9256. if (IsMiniDumpDebugger())
  9257. {
  9258. // Make sure to queue up any debug stuff we need
  9259. UpdateCallStackMethod((int)mCallStack.size() - 1);
  9260. }
  9261. if (wdStackFrame->mIsEnd)
  9262. break;
  9263. // Time-limit callstack generation. Most useful for debug mode.
  9264. if ((slowEarlyOut) && ((fillIdx % 100) == 0))
  9265. {
  9266. uint32 tickEnd = BFTickCount();
  9267. if (tickEnd - tickStart >= 10)
  9268. {
  9269. isPartial = true;
  9270. break;
  9271. }
  9272. }
  9273. }
  9274. if (!isPartial)
  9275. mIsPartialCallStack = false;
  9276. }
  9277. int WinDebugger::GetCallStackCount()
  9278. {
  9279. AutoCrit autoCrit(mDebugManager->mCritSect);
  9280. return (int)mCallStack.size();
  9281. }
  9282. int WinDebugger::GetRequestedStackFrameIdx()
  9283. {
  9284. AutoCrit autoCrit(mDebugManager->mCritSect);
  9285. if ((mActiveThread == mExplicitStopThread) && (mRequestedStackFrameIdx >= -1))
  9286. {
  9287. if (mActiveBreakpoint != NULL)
  9288. mRequestedStackFrameIdx = GetBreakStackFrameIdx();
  9289. if (mRequestedStackFrameIdx == -1)
  9290. mRequestedStackFrameIdx = 0;
  9291. return mRequestedStackFrameIdx;
  9292. }
  9293. int newCallStackIdx = 0;
  9294. while (true)
  9295. {
  9296. if (newCallStackIdx >= (int)mCallStack.size() - 1)
  9297. UpdateCallStack();
  9298. if (newCallStackIdx >= (int)mCallStack.size() - 1)
  9299. break;
  9300. intptr addr;
  9301. String file;
  9302. int hotIdx;
  9303. int defLineStart;
  9304. int defLineEnd;
  9305. int line;
  9306. int column;
  9307. int language;
  9308. int stackSize;
  9309. int8 flags;
  9310. GetStackFrameInfo(newCallStackIdx, &addr, &file, &hotIdx, &defLineStart, &defLineEnd, &line, &column, &language, &stackSize, &flags);
  9311. if (!file.empty())
  9312. return newCallStackIdx;
  9313. newCallStackIdx++;
  9314. }
  9315. return 0;
  9316. }
  9317. int WinDebugger::GetBreakStackFrameIdx()
  9318. {
  9319. AutoCrit autoCrit(mDebugManager->mCritSect);
  9320. if ((mActiveBreakpoint == NULL) || (mRunState != RunState_Breakpoint))
  9321. return -1;
  9322. if ((mBreakStackFrameIdx != -1) || (mActiveThread != mExplicitStopThread))
  9323. return mBreakStackFrameIdx;
  9324. mBreakStackFrameIdx = 0;
  9325. BF_ASSERT(mActiveBreakpoint != NULL);
  9326. if (mCallStack.IsEmpty())
  9327. UpdateCallStack();
  9328. if (!mCallStack.IsEmpty())
  9329. {
  9330. UpdateCallStackMethod(0);
  9331. for (int stackIdx = 0; stackIdx < (int)mCallStack.size(); stackIdx++)
  9332. {
  9333. auto callStackEntry = mCallStack[stackIdx];
  9334. if (callStackEntry->mSubProgram == NULL)
  9335. break;
  9336. if ((mActiveBreakpoint->mAddr < callStackEntry->mSubProgram->mBlock.mLowPC) ||
  9337. (mActiveBreakpoint->mAddr >= callStackEntry->mSubProgram->mBlock.mHighPC))
  9338. break;
  9339. DbgSubprogram* specificSubprogram = callStackEntry->mSubProgram;
  9340. auto dwLineData = callStackEntry->mSubProgram->FindClosestLine(mActiveBreakpoint->mAddr, &specificSubprogram);
  9341. if (dwLineData == NULL)
  9342. break;
  9343. if (mActiveBreakpoint->mLineData == dwLineData)
  9344. {
  9345. mBreakStackFrameIdx = stackIdx;
  9346. break;
  9347. }
  9348. }
  9349. }
  9350. return mBreakStackFrameIdx;
  9351. }
  9352. static const char* SafeString(const char* str)
  9353. {
  9354. if (str == NULL)
  9355. return "???";
  9356. return str;
  9357. }
  9358. void WinDebugger::UpdateRegisterUsage(int stackFrameIdx)
  9359. {
  9360. WdStackFrame* wdStackFrame = mCallStack[stackFrameIdx];
  9361. if (wdStackFrame->mRegForms.size() != 0)
  9362. return;
  9363. auto dwSubprogram = wdStackFrame->mSubProgram;
  9364. if (dwSubprogram == NULL)
  9365. return;
  9366. addr_target addr = dwSubprogram->mBlock.mLowPC;
  9367. const uint8* baseOp = nullptr;
  9368. while (addr < dwSubprogram->mBlock.mHighPC)
  9369. {
  9370. CPUInst inst;
  9371. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  9372. break;
  9373. bool overrideForm = inst.mAddress <= (addr_target)wdStackFrame->mRegisters.GetPC();
  9374. inst.MarkRegsUsed(wdStackFrame->mRegForms, overrideForm);
  9375. addr += inst.GetLength();
  9376. }
  9377. }
  9378. // It's safe to pass an invalid idx in here
  9379. void WinDebugger::UpdateCallStackMethod(int stackFrameIdx)
  9380. {
  9381. if (mCallStack.empty())
  9382. return;
  9383. int startIdx = std::min(stackFrameIdx, (int)mCallStack.size() - 1);
  9384. while (startIdx >= 0)
  9385. {
  9386. WdStackFrame* wdStackFrame = mCallStack[startIdx];
  9387. if (wdStackFrame->mHasGottenSubProgram)
  9388. break;
  9389. startIdx--;
  9390. }
  9391. startIdx++;
  9392. for (int checkFrameIdx = startIdx; checkFrameIdx <= stackFrameIdx; checkFrameIdx++)
  9393. {
  9394. //BF_ASSERT(checkFrameIdx < mCallStack.size());
  9395. if (checkFrameIdx >= mCallStack.size())
  9396. break;
  9397. WdStackFrame* wdStackFrame = mCallStack[checkFrameIdx];
  9398. wdStackFrame->mHasGottenSubProgram = true;
  9399. addr_target pcAddress = (addr_target)wdStackFrame->GetSourcePC();
  9400. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress, DbgOnDemandKind_LocalOnly);
  9401. wdStackFrame->mHasGottenSubProgram = true;
  9402. wdStackFrame->mSubProgram = dwSubprogram;
  9403. if ((dwSubprogram == NULL) && (IsMiniDumpDebugger()))
  9404. {
  9405. // FindSymbolAt will queue up debug info if necessary...
  9406. String symbolName;
  9407. addr_target offset;
  9408. DbgModule* dbgModule;
  9409. mDebugTarget->FindSymbolAt(pcAddress, &symbolName, &offset, &dbgModule);
  9410. }
  9411. // Insert inlines
  9412. int insertIdx = checkFrameIdx + 1;
  9413. while ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL))
  9414. {
  9415. WdStackFrame* inlineStackFrame = new WdStackFrame();
  9416. *inlineStackFrame = *wdStackFrame;
  9417. inlineStackFrame->mInInlineMethod = true;
  9418. wdStackFrame->mInInlineCall = true;
  9419. inlineStackFrame->mSubProgram = dwSubprogram->mInlineeInfo->mInlineParent;
  9420. mCallStack.Insert(insertIdx, inlineStackFrame);
  9421. dwSubprogram = dwSubprogram->mInlineeInfo->mInlineParent;
  9422. insertIdx++;
  9423. checkFrameIdx++;
  9424. }
  9425. }
  9426. }
  9427. void WinDebugger::GetCodeAddrInfo(intptr addr, String* outFile, int* outHotIdx, int* outDefLineStart, int* outDefLineEnd, int* outLine, int* outColumn)
  9428. {
  9429. AutoCrit autoCrit(mDebugManager->mCritSect);
  9430. DbgSubprogram* subProgram = NULL;
  9431. DbgLineData* callingLineData = FindLineDataAtAddress((addr_target)addr, &subProgram);
  9432. if (subProgram != NULL)
  9433. {
  9434. *outHotIdx = subProgram->mCompileUnit->mDbgModule->mHotIdx;
  9435. *outFile = subProgram->GetLineSrcFile(*callingLineData)->GetLocalPath();
  9436. *outLine = callingLineData->mLine;
  9437. *outColumn = callingLineData->mColumn;
  9438. FixupLineDataForSubprogram(subProgram);
  9439. DbgLineData* dwStartLineData = NULL;
  9440. DbgLineData* dwEndLineData = NULL;
  9441. if (subProgram->mLineInfo != NULL)
  9442. {
  9443. if (subProgram->mLineInfo->mLines.size() > 0)
  9444. {
  9445. dwStartLineData = &subProgram->mLineInfo->mLines[0];
  9446. dwEndLineData = &subProgram->mLineInfo->mLines.back();
  9447. }
  9448. }
  9449. else
  9450. {
  9451. if (subProgram->mInlineeInfo != NULL)
  9452. {
  9453. dwStartLineData = &subProgram->mInlineeInfo->mFirstLineData;
  9454. dwEndLineData = &subProgram->mInlineeInfo->mLastLineData;
  9455. }
  9456. }
  9457. if (dwEndLineData != NULL)
  9458. {
  9459. *outDefLineStart = dwStartLineData->mLine;
  9460. *outDefLineEnd = dwEndLineData->mLine;
  9461. }
  9462. }
  9463. }
  9464. void WinDebugger::GetStackAllocInfo(intptr addr, int* outThreadId, int* outStackIdx)
  9465. {
  9466. AutoCrit autoCrit(mDebugManager->mCritSect);
  9467. *outThreadId = 0;
  9468. if (outStackIdx != NULL)
  9469. *outStackIdx = -1;
  9470. if (!IsPaused())
  9471. return;
  9472. for (auto thread : mThreadList)
  9473. {
  9474. NT_TIB64 tib = { 0 };
  9475. if (!ReadMemory((intptr)thread->mThreadLocalBase, sizeof(tib), &tib))
  9476. continue;
  9477. MEMORY_BASIC_INFORMATION stackInfo = { 0 };
  9478. if (VirtualQueryEx(mProcessInfo.hProcess, (void*)(tib.StackBase - 1), &stackInfo, sizeof(MEMORY_BASIC_INFORMATION)) == 0)
  9479. continue;
  9480. if ((addr >= (intptr)stackInfo.AllocationBase) && (addr < (intptr)tib.StackBase))
  9481. {
  9482. *outThreadId = thread->mThreadId;
  9483. if (outStackIdx == NULL)
  9484. return;
  9485. if (mActiveThread == thread)
  9486. {
  9487. UpdateCallStack(false);
  9488. for (int callStackIdx = 0; callStackIdx < (int)mCallStack.size(); callStackIdx++)
  9489. {
  9490. UpdateCallStackMethod(callStackIdx);
  9491. auto stackFrame = mCallStack[callStackIdx];
  9492. if (addr >= (intptr)stackFrame->mRegisters.GetSP())
  9493. {
  9494. *outStackIdx = callStackIdx;
  9495. }
  9496. }
  9497. }
  9498. return;
  9499. }
  9500. }
  9501. }
  9502. String WinDebugger::GetStackFrameInfo(int stackFrameIdx, intptr* addr, String* outFile, int* outHotIdx, int* outDefLineStart, int* outDefLineEnd,
  9503. int* outLine, int* outColumn, int* outLanguage, int* outStackSize, int8* outFlags)
  9504. {
  9505. enum FrameFlags
  9506. {
  9507. FrameFlags_Optimized = 1,
  9508. FrameFlags_HasPendingDebugInfo = 2,
  9509. FrameFlags_CanGetOldSource = 4,
  9510. FrameFlags_WasHotReplaced = 8,
  9511. };
  9512. AutoCrit autoCrit(mDebugManager->mCritSect);
  9513. if (mCallStack.size() == 0)
  9514. UpdateCallStack();
  9515. *addr = 0;
  9516. *outFile = "";
  9517. *outHotIdx = 0;
  9518. *outDefLineStart = -1;
  9519. *outDefLineEnd = -1;
  9520. *outLine = -1;
  9521. *outColumn = 0;
  9522. *outLanguage = 0;
  9523. *outStackSize = 0;
  9524. *outFlags = 0;
  9525. UpdateCallStackMethod(stackFrameIdx);
  9526. if (stackFrameIdx >= mCallStack.size())
  9527. {
  9528. return "";
  9529. }
  9530. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9531. UpdateCallStackMethod(actualStackFrameIdx);
  9532. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9533. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  9534. if (stackFrameIdx == -1)
  9535. pcAddress = mShowPCOverride;
  9536. *addr = pcAddress;
  9537. if (actualStackFrameIdx < (int)mCallStack.size() - 2)
  9538. {
  9539. WdStackFrame* prevStackFrame = mCallStack[actualStackFrameIdx + 1];
  9540. // Inlined methods have no stack frame
  9541. *outStackSize = prevStackFrame->mRegisters.GetSP() - wdStackFrame->mRegisters.GetSP();
  9542. }
  9543. const auto& _CheckHashSrcFile = [&](String& outStr, DbgModule* dbgModule, DbgSrcFile* srcFile)
  9544. {
  9545. if (srcFile->mHashKind != DbgHashKind_None)
  9546. {
  9547. outStr += "#";
  9548. srcFile->GetHash(outStr);
  9549. }
  9550. };
  9551. auto _SetFlags = [&](DbgSubprogram* dwSubprogram)
  9552. {
  9553. DbgModule* dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  9554. if (dwSubprogram->mIsOptimized)
  9555. *outFlags |= FrameFlags_Optimized;
  9556. if (dbgModule->HasPendingDebugInfo())
  9557. *outFlags |= FrameFlags_HasPendingDebugInfo;
  9558. if (dbgModule->CanGetOldSource())
  9559. *outFlags |= FrameFlags_CanGetOldSource;
  9560. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) || (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid))
  9561. *outFlags |= FrameFlags_WasHotReplaced;
  9562. };
  9563. if (wdStackFrame->mInInlineMethod)
  9564. {
  9565. WdStackFrame* nextStackFrame = mCallStack[actualStackFrameIdx - 1];
  9566. auto subProgram = nextStackFrame->mSubProgram;
  9567. _SetFlags(subProgram);
  9568. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  9569. DbgSubprogram* parentSubprogram = subProgram->mInlineeInfo->mInlineParent; // Require it be in the inline parent
  9570. auto foundLine = parentSubprogram->FindClosestLine(subProgram->mBlock.mLowPC, &parentSubprogram);
  9571. if (foundLine != NULL)
  9572. {
  9573. auto srcFile = parentSubprogram->GetLineSrcFile(*foundLine);
  9574. *outFile = srcFile->GetLocalPath();
  9575. _CheckHashSrcFile(*outFile, subProgram->mCompileUnit->mDbgModule, srcFile);
  9576. *outLine = foundLine->mLine;
  9577. }
  9578. *outLanguage = subProgram->GetLanguage();
  9579. *outHotIdx = subProgram->mCompileUnit->mDbgModule->mHotIdx;
  9580. *outColumn = -1;
  9581. DbgSubprogram* callingSubProgram = NULL;
  9582. DbgLineData* callingLineData = FindLineDataAtAddress(nextStackFrame->mSubProgram->mBlock.mLowPC - 1, &callingSubProgram);
  9583. if ((callingLineData != NULL) && (callingSubProgram == wdStackFrame->mSubProgram))
  9584. {
  9585. auto callingSrcFile = callingSubProgram->GetLineSrcFile(*callingLineData);
  9586. *outLanguage = callingSubProgram->mCompileUnit->mLanguage;
  9587. auto srcFile = callingSrcFile;
  9588. *outFile = srcFile->GetLocalPath();
  9589. _CheckHashSrcFile(*outFile, subProgram->mCompileUnit->mDbgModule, srcFile);
  9590. if (*outLine == callingLineData->mLine)
  9591. *outColumn = callingLineData->mColumn;
  9592. }
  9593. String name = wdStackFrame->mSubProgram->ToString();
  9594. DbgModule* dbgModule = wdStackFrame->mSubProgram->mCompileUnit->mDbgModule;
  9595. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  9596. if (!linkedModule->mDisplayName.empty())
  9597. name = linkedModule->mDisplayName + "!" + name;
  9598. return name;
  9599. }
  9600. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  9601. if (dwSubprogram != NULL)
  9602. {
  9603. String demangledName;
  9604. if ((dwSubprogram->mName != NULL) && (strncmp(dwSubprogram->mName, ":Sep@", 5) == 0))
  9605. {
  9606. char* p;
  9607. auto addr = strtoll(dwSubprogram->mName + 5, &p, 16);
  9608. if (addr != 0)
  9609. {
  9610. auto parentSubprogram = mDebugTarget->FindSubProgram(addr);
  9611. if (parentSubprogram != NULL)
  9612. demangledName = parentSubprogram->ToString();
  9613. }
  9614. }
  9615. if (demangledName.IsEmpty())
  9616. {
  9617. dwSubprogram->ToString(demangledName, true);
  9618. }
  9619. DbgSrcFile* dwSrcFile = NULL;
  9620. DbgLineData* dwLineData = NULL;
  9621. FixupLineDataForSubprogram(dwSubprogram);
  9622. addr_target findAddress = wdStackFrame->GetSourcePC();
  9623. DbgSubprogram* specificSubprogram = dwSubprogram;
  9624. dwLineData = dwSubprogram->FindClosestLine(findAddress, &specificSubprogram);
  9625. if (dwLineData != NULL)
  9626. dwSrcFile = dwSubprogram->GetLineSrcFile(*dwLineData);
  9627. DbgLineData* dwStartLineData = NULL;
  9628. DbgLineData* dwEndLineData = NULL;
  9629. if (dwSubprogram->mLineInfo != NULL)
  9630. {
  9631. if (dwSubprogram->mLineInfo->mLines.size() > 0)
  9632. {
  9633. dwStartLineData = &dwSubprogram->mLineInfo->mLines[0];
  9634. dwEndLineData = &dwSubprogram->mLineInfo->mLines.back();
  9635. }
  9636. }
  9637. else
  9638. {
  9639. if (dwSubprogram->mInlineeInfo != NULL)
  9640. {
  9641. dwStartLineData = &dwSubprogram->mInlineeInfo->mFirstLineData;
  9642. dwEndLineData = &dwSubprogram->mInlineeInfo->mLastLineData;
  9643. }
  9644. }
  9645. DbgModule* dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  9646. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  9647. if (!linkedModule->mDisplayName.empty())
  9648. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  9649. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) || (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid))
  9650. demangledName = "#" + demangledName;
  9651. _SetFlags(dwSubprogram);
  9652. if ((dwLineData != NULL) && (dwSrcFile != NULL))
  9653. {
  9654. *outFile = dwSrcFile->GetLocalPath();
  9655. _CheckHashSrcFile(*outFile, dbgModule, dwSrcFile);
  9656. *outHotIdx = dbgModule->mHotIdx;
  9657. *outLine = dwLineData->mLine;
  9658. *outColumn = dwLineData->mColumn;
  9659. *outLanguage = (int)dwSubprogram->mCompileUnit->mLanguage;
  9660. if (dwEndLineData != NULL)
  9661. {
  9662. *outDefLineStart = dwStartLineData->mLine;
  9663. *outDefLineEnd = dwEndLineData->mLine;
  9664. }
  9665. return demangledName;
  9666. }
  9667. else
  9668. {
  9669. return demangledName + StrFormat("+0x%X", pcAddress - dwSubprogram->mBlock.mLowPC);
  9670. }
  9671. }
  9672. else
  9673. {
  9674. String symbolName;
  9675. addr_target offset;
  9676. DbgModule* dbgModule;
  9677. if (mDebugTarget->FindSymbolAt(pcAddress, &symbolName, &offset, &dbgModule))
  9678. {
  9679. if (dbgModule->HasPendingDebugInfo())
  9680. {
  9681. *outFlags |= FrameFlags_HasPendingDebugInfo;
  9682. if (mPendingDebugInfoLoad.ContainsKey(dbgModule))
  9683. {
  9684. String outName = EncodeDataPtr(pcAddress, true);
  9685. if ((dbgModule != NULL) && (!dbgModule->mDisplayName.empty()))
  9686. outName = dbgModule->mDisplayName + "!<Loading...>" + outName;
  9687. return outName;
  9688. }
  9689. }
  9690. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  9691. String demangledName = BfDemangler::Demangle(symbolName, DbgLanguage_Unknown);
  9692. if (!linkedModule->mDisplayName.empty())
  9693. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  9694. return demangledName + StrFormat("+0x%X", offset);
  9695. }
  9696. }
  9697. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress(pcAddress);
  9698. DbgModule* linkedModule = NULL;
  9699. if (dbgModule != NULL)
  9700. {
  9701. linkedModule = dbgModule->GetLinkedModule();
  9702. if (dbgModule->HasPendingDebugInfo())
  9703. *outFlags |= FrameFlags_HasPendingDebugInfo;
  9704. }
  9705. String outName = EncodeDataPtr(pcAddress, true);
  9706. if ((linkedModule != NULL) && (!linkedModule->mDisplayName.empty()))
  9707. outName = linkedModule->mDisplayName + "!" + outName;
  9708. return outName;
  9709. }
  9710. String WinDebugger::Callstack_GetStackFrameOldFileInfo(int stackFrameIdx)
  9711. {
  9712. AutoCrit autoCrit(mDebugManager->mCritSect);
  9713. if (!FixCallStackIdx(stackFrameIdx))
  9714. return "";
  9715. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9716. UpdateCallStackMethod(actualStackFrameIdx);
  9717. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9718. DbgModule* dbgModule = NULL;
  9719. DbgSrcFile* dbgSrcFile = NULL;
  9720. if (wdStackFrame->mInInlineMethod)
  9721. {
  9722. WdStackFrame* nextStackFrame = mCallStack[actualStackFrameIdx - 1];
  9723. auto subProgram = nextStackFrame->mSubProgram;
  9724. dbgModule = subProgram->mCompileUnit->mDbgModule;
  9725. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  9726. DbgSubprogram* parentSubprogram = subProgram->mInlineeInfo->mInlineParent; // Require it be in the inline parent
  9727. auto foundLine = parentSubprogram->FindClosestLine(subProgram->mBlock.mLowPC, &parentSubprogram);
  9728. if (foundLine != NULL)
  9729. dbgSrcFile = parentSubprogram->GetLineSrcFile(*foundLine);
  9730. DbgSubprogram* callingSubProgram = NULL;
  9731. DbgLineData* callingLineData = FindLineDataAtAddress(nextStackFrame->mSubProgram->mBlock.mLowPC - 1, &callingSubProgram);
  9732. if ((callingLineData != NULL) && (callingSubProgram == wdStackFrame->mSubProgram))
  9733. dbgSrcFile = callingSubProgram->GetLineSrcFile(*callingLineData);
  9734. }
  9735. else
  9736. {
  9737. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  9738. if (dwSubprogram != NULL)
  9739. {
  9740. FixupLineDataForSubprogram(dwSubprogram);
  9741. addr_target findAddress = wdStackFrame->GetSourcePC();
  9742. DbgSubprogram* dbgSubprogram = NULL;
  9743. DbgLineData* dwLineData = dwSubprogram->FindClosestLine(findAddress, &dbgSubprogram, &dbgSrcFile);
  9744. dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  9745. }
  9746. }
  9747. if (dbgSrcFile != NULL)
  9748. {
  9749. // Note: we must use mFilePath here, make sure we don't use GetLocalPath()
  9750. return dbgModule->GetOldSourceCommand(dbgSrcFile->mFilePath);
  9751. }
  9752. return "";
  9753. }
  9754. int WinDebugger::GetJmpState(int stackFrameIdx)
  9755. {
  9756. AutoCrit autoCrit(mDebugManager->mCritSect);
  9757. if (!FixCallStackIdx(stackFrameIdx))
  9758. return -1;
  9759. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9760. UpdateCallStackMethod(actualStackFrameIdx);
  9761. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9762. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  9763. CPUInst inst;
  9764. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  9765. return -1;
  9766. return inst.GetJmpState(wdStackFrame->mRegisters.mIntRegs.efl);
  9767. }
  9768. intptr WinDebugger::GetStackFrameCalleeAddr(int stackFrameIdx)
  9769. {
  9770. AutoCrit autoCrit(mDebugManager->mCritSect);
  9771. if (!FixCallStackIdx(stackFrameIdx))
  9772. return -1;
  9773. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9774. UpdateCallStackMethod(actualStackFrameIdx);
  9775. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9776. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  9777. if (stackFrameIdx == -1)
  9778. pcAddress = mShowPCOverride;
  9779. if (wdStackFrame->mInInlineMethod)
  9780. {
  9781. WdStackFrame* inlineStackFrame = mCallStack[actualStackFrameIdx - 1];
  9782. return inlineStackFrame->mSubProgram->mBlock.mLowPC - 1;
  9783. }
  9784. return pcAddress - 1;
  9785. }
  9786. String WinDebugger::GetStackMethodOwner(int stackFrameIdx, int& language)
  9787. {
  9788. AutoCrit autoCrit(mDebugManager->mCritSect);
  9789. if (!FixCallStackIdx(stackFrameIdx))
  9790. return "";
  9791. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9792. if (actualStackFrameIdx >= (int)mCallStack.size())
  9793. actualStackFrameIdx = 0;
  9794. UpdateCallStackMethod(actualStackFrameIdx);
  9795. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9796. if (wdStackFrame->mSubProgram == NULL)
  9797. return "";
  9798. auto parentType = wdStackFrame->mSubProgram->GetParent();
  9799. if (parentType == NULL)
  9800. return "";
  9801. parentType = parentType->GetPrimaryType();
  9802. language = (int)parentType->GetLanguage();
  9803. return parentType->ToString();
  9804. }
  9805. String WinDebugger::FindCodeAddresses(const StringImpl& fileName, int line, int column, bool allowAutoResolve)
  9806. {
  9807. String result;
  9808. if (mDebugTarget == NULL)
  9809. return "";
  9810. DbgSrcFile* srcFile = mDebugTarget->GetSrcFile(fileName);
  9811. if (srcFile == NULL)
  9812. return result;
  9813. bool foundInSequence = false;
  9814. WdBreakpoint* prevBreakpoint = NULL;
  9815. int bestLineOffset = 0x7FFFFFFF;
  9816. for (auto dbgSubprogram : srcFile->mLineDataRefs)
  9817. {
  9818. for (auto& lineData : dbgSubprogram->mLineInfo->mLines)
  9819. {
  9820. auto lineSrcFile = dbgSubprogram->GetLineSrcFile(lineData);
  9821. if (lineSrcFile != srcFile)
  9822. continue;
  9823. int lineOffset = lineData.mLine - line;
  9824. if ((lineOffset >= 0) && (lineOffset <= 12) && (lineOffset <= bestLineOffset))
  9825. {
  9826. if (lineOffset < bestLineOffset)
  9827. {
  9828. bestLineOffset = lineOffset;
  9829. result = "";
  9830. }
  9831. if (!foundInSequence)
  9832. {
  9833. auto addr = dbgSubprogram->GetLineAddr(lineData);
  9834. result += EncodeDataPtr(addr, false) + "\t" + dbgSubprogram->ToString() + "\n";
  9835. }
  9836. }
  9837. // New sequence?
  9838. if (!lineData.IsStackFrameSetup())
  9839. foundInSequence = false;
  9840. }
  9841. }
  9842. return result;
  9843. }
  9844. String WinDebugger::GetAddressSourceLocation(intptr address)
  9845. {
  9846. DbgSubprogram* subProgram = NULL;
  9847. DbgLineData* lineData = FindLineDataAtAddress(address, &subProgram);
  9848. if (lineData != NULL)
  9849. return StrFormat("%s:%d:%d", subProgram->GetLineSrcFile(*lineData)->GetLocalPath().c_str(), lineData->mLine + 1, lineData->mColumn + 1);
  9850. String outSymbol;
  9851. addr_target offset = 0;
  9852. DbgModule* dbgModule;
  9853. if (mDebugTarget->FindSymbolAt(address, &outSymbol, &offset, &dbgModule))
  9854. {
  9855. if (offset < 0x10000)
  9856. {
  9857. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9858. if (offset > 0)
  9859. outSymbol += StrFormat("+%x", offset);
  9860. return outSymbol;
  9861. }
  9862. }
  9863. return StrFormat("0x%@", address);
  9864. }
  9865. String WinDebugger::GetAddressSymbolName(intptr address, bool demangle)
  9866. {
  9867. String outSymbol;
  9868. addr_target offset = 0;
  9869. DbgModule* dbgModule;
  9870. if (mDebugTarget->FindSymbolAt(address, &outSymbol, &offset, &dbgModule))
  9871. {
  9872. if (offset < 0x10000)
  9873. {
  9874. if (demangle)
  9875. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9876. if (offset > 0)
  9877. outSymbol += StrFormat("+%x", offset);
  9878. return outSymbol;
  9879. }
  9880. }
  9881. return StrFormat("0x%@", address);
  9882. }
  9883. String WinDebugger::DisassembleAtRaw(intptr inAddress)
  9884. {
  9885. addr_target address = (addr_target)inAddress;
  9886. const int addrBorder = 1024;
  9887. for (int offset = 0; offset < 8; offset++)
  9888. {
  9889. String result;
  9890. bool addOffset = true;
  9891. bool hadAddr = false;
  9892. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress(address);
  9893. DbgModuleMemoryCache* memCache = NULL;
  9894. defer
  9895. (
  9896. if (dbgModule == NULL)
  9897. delete memCache;
  9898. );
  9899. if ((dbgModule != NULL) && (dbgModule->mOrigImageData == NULL))
  9900. dbgModule = NULL;
  9901. result += "R\n"; // Raw
  9902. addr_target addrStart = address;
  9903. if (dbgModule != NULL)
  9904. {
  9905. dbgModule->ParseSymbolData();
  9906. memCache = dbgModule->mOrigImageData;
  9907. addrStart = BF_MAX((addr_target)dbgModule->mImageBase, address - addrBorder - offset);
  9908. }
  9909. else
  9910. {
  9911. memCache = new DbgModuleMemoryCache(addrStart & (4096 - 1), 4096 * 2);
  9912. }
  9913. //addr_target imageBase = dbgModule->mImageBase;
  9914. //int imageSize = dbgModule->mImageSize;
  9915. addr_target dataAddr = addrStart;
  9916. addr_target addrEnd = addrStart + addrBorder * 2 + 16;
  9917. while (dataAddr < addrEnd)
  9918. {
  9919. if (dataAddr == address)
  9920. hadAddr = true;
  9921. if (dataAddr > address)
  9922. {
  9923. if (!hadAddr)
  9924. {
  9925. if (offset == 7)
  9926. {
  9927. dataAddr = address;
  9928. }
  9929. break;
  9930. }
  9931. }
  9932. String outSymbol;
  9933. addr_target symOffset = 0;
  9934. DbgModule* symDWARF;
  9935. if (mDebugTarget->FindSymbolAt(dataAddr, &outSymbol, &symOffset, &symDWARF))
  9936. {
  9937. if (symOffset == 0)
  9938. {
  9939. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9940. if ((symDWARF != NULL) && (!symDWARF->mDisplayName.empty()))
  9941. outSymbol = symDWARF->GetLinkedModule()->mDisplayName + "!" + outSymbol;
  9942. result += "T " + outSymbol + ":\n";
  9943. }
  9944. }
  9945. CPUInst inst;
  9946. if (!mCPU->Decode(dataAddr, memCache, &inst))
  9947. {
  9948. if ((offset == 7) && (!hadAddr))
  9949. {
  9950. uint8 instData[1];
  9951. memCache->Read(dataAddr, instData, 1);
  9952. int instLen = 1;
  9953. #ifdef BF_DBG_32
  9954. result += StrFormat("D %08X: ", dataAddr);
  9955. #else
  9956. result += StrFormat("D %@: ", dataAddr);
  9957. #endif
  9958. for (int i = 0; i < instLen; i++)
  9959. result += StrFormat("%02X ", instData[i]);
  9960. for (int i = instLen; i < 8; i++)
  9961. result += " ";
  9962. result += "\n";
  9963. dataAddr++;
  9964. continue;
  9965. }
  9966. break;
  9967. }
  9968. int instLen = inst.GetLength();
  9969. #ifdef BF_DBG_32
  9970. result += StrFormat("D %08X: ", dataAddr);
  9971. #else
  9972. result += StrFormat("D %@: ", dataAddr);
  9973. #endif
  9974. uint8 instData[32];
  9975. int showInstLen = BF_MIN(32, instLen);
  9976. memCache->Read(dataAddr, instData, showInstLen);
  9977. for (int i = 0; i < showInstLen; i++)
  9978. result += StrFormat("%02X ", instData[i]);
  9979. for (int i = instLen; i < 8; i++)
  9980. result += " ";
  9981. result += mCPU->InstructionToString(&inst, dataAddr);
  9982. if ((inst.IsCall()) || (inst.IsBranch()))
  9983. {
  9984. addr_target targetAddr = inst.GetTarget();
  9985. if (targetAddr != 0)
  9986. {
  9987. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &symOffset))
  9988. {
  9989. if (symOffset < 0x10000)
  9990. {
  9991. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9992. result += " ; " + outSymbol;
  9993. if (symOffset > 0)
  9994. result += StrFormat("+%x", symOffset);
  9995. //result += ">";
  9996. }
  9997. }
  9998. }
  9999. }
  10000. result += "\n";
  10001. dataAddr += instLen;
  10002. }
  10003. if (!hadAddr)
  10004. continue;
  10005. return result;
  10006. }
  10007. return "";
  10008. }
  10009. String WinDebugger::DisassembleAt(intptr inAddress)
  10010. {
  10011. BP_ZONE("WinDebugger::DisassembleAt");
  10012. AutoCrit autoCrit(mDebugManager->mCritSect);
  10013. addr_target address = (addr_target)inAddress;
  10014. if (mDebugTarget == NULL)
  10015. return "";
  10016. String result;
  10017. auto dwSubProgram = mDebugTarget->FindSubProgram(address);
  10018. if (dwSubProgram == NULL)
  10019. return DisassembleAtRaw(address);
  10020. dwSubProgram = dwSubProgram->GetRootInlineParent();
  10021. DbgModule* dwarf = dwSubProgram->mCompileUnit->mDbgModule;
  10022. int frameBaseRegister = mDebugTarget->GetFrameBaseRegister(dwSubProgram);
  10023. addr_target addrStart = dwSubProgram->mBlock.mLowPC;
  10024. addr_target addrEnd = dwSubProgram->mBlock.mHighPC;
  10025. auto dwCompileUnit = dwSubProgram->mCompileUnit;
  10026. {
  10027. FixupLineData(dwCompileUnit);
  10028. }
  10029. DbgSrcFile* dwSrcFile = NULL;
  10030. FixupLineDataForSubprogram(dwSubProgram);
  10031. DbgLineData* dwLineData = NULL;
  10032. if (dwSubProgram->mLineInfo != NULL)
  10033. dwLineData = &dwSubProgram->mLineInfo->mLines[0];
  10034. int nextLineDataIdx = 1;
  10035. if (dwSubProgram->mIsOptimized)
  10036. result += "O\n";
  10037. DbgSrcFile* srcFile = NULL;
  10038. int firstLine = 0;
  10039. int curLine = 0;
  10040. if (dwLineData != NULL)
  10041. {
  10042. srcFile = dwSubProgram->GetLineSrcFile(*dwLineData);
  10043. result += "S " + srcFile->GetLocalPath() + "\n";
  10044. if (srcFile->mHashKind != DbgHashKind_None)
  10045. {
  10046. result += "H ";
  10047. srcFile->GetHash(result);
  10048. result += "\n";
  10049. }
  10050. curLine = BF_MAX(0, dwLineData->mLine - 5);
  10051. //for (; curLine <= dwLineData->mLine; curLine++)
  10052. result += StrFormat("L %d %d\n", curLine, dwLineData->mLine - curLine + 1);
  10053. curLine = dwLineData->mLine + 1;
  10054. firstLine = dwLineData->mLine;
  10055. }
  10056. Array<DbgSubprogram*> inlineStack;
  10057. Array<DbgBlock*> blockList;
  10058. blockList.push_back(&dwSubProgram->mBlock);
  10059. addr_target dataAddr = addrStart;
  10060. int decodeFailureCount = 0;
  10061. auto& _PopInlineStack = [&]()
  10062. {
  10063. int depth = inlineStack.size();
  10064. auto curStackEntry = inlineStack.back();
  10065. if (depth > 1)
  10066. result += StrFormat("T <<<%d Inline End ", depth);
  10067. else
  10068. result += "T <<< Inline End ";
  10069. result += curStackEntry->ToString();
  10070. result += "\n";
  10071. inlineStack.pop_back();
  10072. };
  10073. std::function<void(DbgSubprogram* subprogram, int depth)> _UpdateInlineStackHelper = [&](DbgSubprogram* subprogram, int depth)
  10074. {
  10075. int stackIdx = depth - 1;
  10076. if (stackIdx < inlineStack.size())
  10077. {
  10078. auto curStackEntry = inlineStack[stackIdx];
  10079. if (curStackEntry != subprogram)
  10080. _PopInlineStack();
  10081. }
  10082. if (depth > 1)
  10083. {
  10084. _UpdateInlineStackHelper(subprogram->mInlineeInfo->mInlineParent, depth - 1);
  10085. }
  10086. if (stackIdx >= inlineStack.size())
  10087. {
  10088. if (depth > 1)
  10089. result += StrFormat("T >>>%d Inline ", depth);
  10090. else
  10091. result += "T >>> Inline ";
  10092. result += subprogram->ToString();
  10093. result += "\n";
  10094. inlineStack.push_back(subprogram);
  10095. }
  10096. };
  10097. auto _UpdateInlineStack = [&](DbgSubprogram* subprogram)
  10098. {
  10099. if (subprogram == NULL)
  10100. {
  10101. while (!inlineStack.IsEmpty())
  10102. _PopInlineStack();
  10103. return;
  10104. }
  10105. int inlineDepth = subprogram->GetInlineDepth();
  10106. while (inlineDepth < inlineStack.size())
  10107. _PopInlineStack();
  10108. if (inlineDepth > 0)
  10109. _UpdateInlineStackHelper(subprogram, inlineDepth);
  10110. };
  10111. while (dataAddr < addrEnd)
  10112. {
  10113. // Pop off old scopes
  10114. while (blockList.size() > 0)
  10115. {
  10116. auto lastBlock = blockList.back();
  10117. if (dataAddr < lastBlock->mHighPC)
  10118. break;
  10119. blockList.pop_back();
  10120. }
  10121. // Check entry into new child scopes
  10122. auto lastBlock = blockList.back();
  10123. for (auto checkBlock : lastBlock->mSubBlocks)
  10124. {
  10125. if ((dataAddr >= checkBlock->mLowPC) && (dataAddr < checkBlock->mHighPC))
  10126. {
  10127. blockList.push_back(checkBlock);
  10128. break;
  10129. }
  10130. }
  10131. bool allowSourceJump = false;
  10132. if ((dwLineData != NULL) && (dwLineData->mContribSize != 0) && (dataAddr >= dwSubProgram->GetLineAddr(*dwLineData) + dwLineData->mContribSize))
  10133. {
  10134. DbgSubprogram* inlinedSubprogram = NULL;
  10135. auto inlinedLine = dwSubProgram->FindClosestLine(dataAddr, &inlinedSubprogram);
  10136. _UpdateInlineStack(dwSubProgram);
  10137. }
  10138. // Update line data
  10139. while ((dwLineData != NULL) && (dwSubProgram->GetLineAddr(*dwLineData) <= dataAddr))
  10140. {
  10141. _UpdateInlineStack(dwSubProgram->GetLineInlinee(*dwLineData));
  10142. const int lineLimit = 5; // 15
  10143. if (allowSourceJump)
  10144. curLine = dwLineData->mLine;
  10145. auto lineSrcFile = dwSubProgram->GetLineSrcFile(*dwLineData);
  10146. if (lineSrcFile != srcFile)
  10147. {
  10148. srcFile = lineSrcFile;
  10149. result += "S ";
  10150. result += srcFile->GetLocalPath();
  10151. result += "\n";
  10152. // Just show the one line from the new file
  10153. curLine = dwLineData->mLine;
  10154. }
  10155. if (dwLineData->mLine < curLine - 1)
  10156. {
  10157. // Jumping backwards - possibly into inlined method, or possibly in current method.
  10158. // Show previous 6 lines, for context
  10159. curLine = BF_MAX(0, dwLineData->mLine - lineLimit);
  10160. }
  10161. if ((curLine <= firstLine) && (dwLineData->mLine >= firstLine))
  10162. {
  10163. // Jumping from inlined method (declared above) back into main method
  10164. curLine = dwLineData->mLine;
  10165. }
  10166. if (curLine < dwLineData->mLine - lineLimit)
  10167. {
  10168. // Don't show huge span of source - only show the last 6 lines at maximum
  10169. curLine = dwLineData->mLine - lineLimit;
  10170. }
  10171. //for ( ; curLine <= dwLineData->mLine; curLine++)
  10172. result += StrFormat("L %d %d\n", curLine, dwLineData->mLine - curLine + 1);
  10173. curLine = dwLineData->mLine + 1;
  10174. DbgLineData* nextLineData = NULL;
  10175. while (nextLineDataIdx < dwSubProgram->mLineInfo->mLines.mSize)
  10176. {
  10177. nextLineData = &dwSubProgram->mLineInfo->mLines[nextLineDataIdx];
  10178. //TODO:
  10179. /*{
  10180. result += StrFormat("T LineIdx: %d (%@ to %@)", nextLineDataIdx, dwSubProgram->GetLineAddr(*nextLineData), dwSubProgram->GetLineAddr(*nextLineData) + nextLineData->mContribSize);
  10181. auto inlinee = dwSubProgram->GetLineInlinee(*nextLineData);
  10182. if (inlinee != NULL)
  10183. {
  10184. result += StrFormat(" Inlinee: %s Depth: %d", inlinee->mName, inlinee->GetInlineDepth());
  10185. }
  10186. result += "\n";
  10187. }*/
  10188. auto nextLineAddr = dwSubProgram->GetLineAddr(*nextLineData);
  10189. if (nextLineAddr > dataAddr)
  10190. {
  10191. if (nextLineDataIdx + 1 < dwSubProgram->mLineInfo->mLines.mSize)
  10192. {
  10193. auto peekLineData = &dwSubProgram->mLineInfo->mLines[nextLineDataIdx + 1];
  10194. if (peekLineData->mRelAddress == nextLineData->mRelAddress)
  10195. {
  10196. // Use the later entry
  10197. ++nextLineDataIdx;
  10198. continue;
  10199. }
  10200. }
  10201. break;
  10202. }
  10203. // If we go back to an older entry beacuse of a gap then we need to catch back up...
  10204. ++nextLineDataIdx;
  10205. nextLineData = NULL; // Keep searching...
  10206. }
  10207. dwLineData = nextLineData;
  10208. nextLineDataIdx++;
  10209. }
  10210. // Have we gone off the end of the inline function?
  10211. // We may not have an explicit non-inlined line data at the transition point...
  10212. while (!inlineStack.IsEmpty())
  10213. {
  10214. auto subProgram = inlineStack.back();
  10215. if (dataAddr < subProgram->mBlock.mHighPC)
  10216. break;
  10217. _PopInlineStack();
  10218. }
  10219. bool hadDecodeFailure = false;
  10220. CPUInst inst;
  10221. if (!mCPU->Decode(dataAddr, dwarf->mOrigImageData, &inst))
  10222. hadDecodeFailure = true;
  10223. if ((decodeFailureCount == 8) || ((decodeFailureCount > 0) && (!hadDecodeFailure)))
  10224. {
  10225. for (int i = decodeFailureCount; i < 4 + sizeof(addr_target); i++)
  10226. result += " ";
  10227. result += " ???\n";
  10228. decodeFailureCount = 0;
  10229. }
  10230. if (decodeFailureCount == 0)
  10231. {
  10232. #ifdef BF_DBG_32
  10233. result += StrFormat("D %08X: ", dataAddr);
  10234. #else
  10235. result += StrFormat("D %@: ", dataAddr);
  10236. #endif
  10237. }
  10238. if (hadDecodeFailure)
  10239. {
  10240. uint8 byte = 0;
  10241. dwarf->mOrigImageData->Read(dataAddr, &byte, 1);
  10242. result += StrFormat("%02X ", byte);
  10243. dataAddr++;
  10244. decodeFailureCount++;
  10245. continue;
  10246. }
  10247. int instLen = inst.GetLength();
  10248. uint8 instData[32];
  10249. int showInstLen = BF_MIN(32, instLen);
  10250. dwarf->mOrigImageData->Read(dataAddr, instData, showInstLen);
  10251. for (int i = 0; i < showInstLen; i++)
  10252. result += StrFormat("%02X ", instData[i]);
  10253. for (int i = instLen; i < 4 + sizeof(addr_target); i++)
  10254. result += " ";
  10255. result += " ";
  10256. result += mCPU->InstructionToString(&inst, dataAddr);
  10257. int reg;
  10258. int offset;
  10259. if (inst.GetIndexRegisterAndOffset(&reg, &offset))
  10260. {
  10261. for (int blockIdx = (int)blockList.size() - 1; blockIdx >= 0; blockIdx--)
  10262. {
  10263. auto dwBlock = blockList[blockIdx];
  10264. for (auto variable : dwBlock->mVariables)
  10265. {
  10266. int varRegister;
  10267. int varOffset;
  10268. if (mDebugTarget->GetVariableIndexRegisterAndOffset(variable, &varRegister, &varOffset))
  10269. {
  10270. if (varRegister == -1)
  10271. varRegister = frameBaseRegister;
  10272. if ((reg == varRegister) && (offset == varOffset))
  10273. {
  10274. result += " ; ";
  10275. result += variable->mName;
  10276. break;
  10277. }
  10278. }
  10279. }
  10280. }
  10281. }
  10282. else if ((inst.IsCall()) || (inst.IsBranch()) || (inst.IsLoadAddress()))
  10283. {
  10284. addr_target targetAddr = inst.GetTarget();
  10285. if (targetAddr != 0)
  10286. {
  10287. if ((targetAddr >= addrStart) && (targetAddr < addrEnd))
  10288. {
  10289. result += StrFormat("\nJ %s", EncodeDataPtr(targetAddr, false).c_str());
  10290. }
  10291. else
  10292. {
  10293. String outSymbol;
  10294. addr_target offset = 0;
  10295. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &offset))
  10296. {
  10297. if (offset < 0x10000)
  10298. {
  10299. outSymbol = BfDemangler::Demangle(outSymbol, dwSubProgram->GetLanguage());
  10300. result += " ; " + outSymbol;
  10301. if (offset > 0)
  10302. result += StrFormat("+%x", offset);
  10303. }
  10304. }
  10305. }
  10306. }
  10307. }
  10308. result += "\n";
  10309. dataAddr += instLen;
  10310. }
  10311. // Why did we want to "show lines at end"??
  10312. // Show lines at end
  10313. /*if (curLine > 0)
  10314. {
  10315. for (int i = 0; i < 6; i++, curLine++)
  10316. result += StrFormat("L %d\n", curLine);
  10317. }*/
  10318. return result;
  10319. }
  10320. String WinDebugger::FindLineCallAddresses(intptr inAddress)
  10321. {
  10322. String callAddresses;
  10323. addr_target address = (addr_target)inAddress;
  10324. DbgSubprogram* dwSubprogram = NULL;
  10325. DbgLineData* startLineData = FindLineDataAtAddress(address, &dwSubprogram, NULL);
  10326. if (dwSubprogram == NULL)
  10327. return "";
  10328. CPURegisters registers;
  10329. PopulateRegisters(&registers);
  10330. auto inlinerSubprogram = dwSubprogram->GetRootInlineParent();
  10331. FixupLineDataForSubprogram(inlinerSubprogram);
  10332. if (inlinerSubprogram->mLineInfo->mLines.mSize == 0)
  10333. return "";
  10334. auto lineData = &inlinerSubprogram->mLineInfo->mLines[0];
  10335. addr_target addr = dwSubprogram->mBlock.mLowPC;
  10336. addr_target endAddr = dwSubprogram->mBlock.mHighPC;
  10337. DbgSubprogram* checkSubprogram = dwSubprogram;
  10338. DbgLineData* checkLineData = lineData;
  10339. addr_target checkLineAddr = 0;
  10340. int lineIdx = 0;
  10341. while (checkLineData != NULL)
  10342. {
  10343. //auto nextLineData = dwSubprogram->mCompileUnit->mLineDataMap.GetNext(checkLineData);
  10344. ++lineIdx;
  10345. DbgLineData* nextLineData = NULL;
  10346. addr_target nextLineAddr;
  10347. if (lineIdx < inlinerSubprogram->mLineInfo->mLines.size())
  10348. {
  10349. nextLineData = &inlinerSubprogram->mLineInfo->mLines[lineIdx];
  10350. nextLineAddr = dwSubprogram->GetLineAddr(*nextLineData);
  10351. }
  10352. else
  10353. nextLineAddr = inlinerSubprogram->mBlock.mHighPC;
  10354. // This stuff doesn't make sense...
  10355. DbgSubprogram* nextSubProgram;
  10356. if (nextLineData != NULL)
  10357. {
  10358. if (nextLineAddr > dwSubprogram->mBlock.mHighPC)
  10359. break;
  10360. endAddr = nextLineAddr;
  10361. nextSubProgram = mDebugTarget->FindSubProgram(endAddr);
  10362. if (nextSubProgram != NULL)
  10363. {
  10364. auto dbgModule = nextSubProgram->mCompileUnit->mDbgModule;
  10365. dbgModule->ParseSymbolData();
  10366. }
  10367. }
  10368. else
  10369. {
  10370. nextSubProgram = dwSubprogram;
  10371. endAddr = dwSubprogram->mBlock.mHighPC;
  10372. }
  10373. auto _HandleSection = [&]()
  10374. {
  10375. while (addr < endAddr)
  10376. {
  10377. CPUInst inst;
  10378. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  10379. break;
  10380. *registers.GetPCRegisterRef() = addr;
  10381. if (inst.IsCall())
  10382. {
  10383. bool addSymbol = true;
  10384. if (addr < (addr_target)inAddress)
  10385. callAddresses += "-";
  10386. callAddresses += EncodeDataPtr(addr, false);
  10387. addr_target targetAddr = inst.GetTarget(this, &registers);
  10388. if (targetAddr != 0)
  10389. {
  10390. String outSymbol;
  10391. auto subprogram = mDebugTarget->FindSubProgram(targetAddr);
  10392. if (subprogram != NULL)
  10393. {
  10394. CreateFilterName(outSymbol, subprogram);
  10395. addSymbol = true;
  10396. }
  10397. else
  10398. {
  10399. addr_target offset = 0;
  10400. String fullSymbolName;
  10401. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &offset))
  10402. {
  10403. if (offset < 0x200)
  10404. {
  10405. //outSymbol = BfDemangler::Demangle(outSymbol, dwSubprogram->GetLanguage());
  10406. if (outSymbol == "___chkstk_ms")
  10407. addSymbol = false;
  10408. else
  10409. {
  10410. String demangledName = BfDemangler::Demangle(outSymbol, DbgLanguage_C);
  10411. outSymbol.clear();
  10412. CreateFilterName(outSymbol, demangledName.c_str(), DbgLanguage_C);
  10413. }
  10414. }
  10415. else
  10416. outSymbol.clear();
  10417. }
  10418. }
  10419. if (addSymbol)
  10420. {
  10421. if (outSymbol.empty())
  10422. callAddresses += "\tFunc@" + EncodeDataPtr(targetAddr, false);
  10423. else
  10424. callAddresses += "\t" + outSymbol;
  10425. String attrs;
  10426. bool isFiltered = false;
  10427. if (subprogram != NULL)
  10428. {
  10429. subprogram->PopulateSubprogram();
  10430. isFiltered = subprogram->mIsStepFilteredDefault;
  10431. if (isFiltered)
  10432. attrs += "d"; // 'd' for default filtered
  10433. }
  10434. StepFilter* stepFilterPtr = NULL;
  10435. if (mDebugManager->mStepFilters.TryGetValue(outSymbol, &stepFilterPtr))
  10436. isFiltered = stepFilterPtr->IsFiltered(isFiltered);
  10437. if (isFiltered)
  10438. attrs += "f"; // 'f' for filter
  10439. if (!attrs.IsEmpty())
  10440. callAddresses += "\t" + attrs;
  10441. }
  10442. }
  10443. if (addSymbol)
  10444. callAddresses += "\n";
  10445. }
  10446. inst.PartialSimulate(this, &registers);
  10447. addr += inst.GetLength();
  10448. }
  10449. };
  10450. // For inlining - only add calls that are found either directly in our main block (not an inlined block)
  10451. // But add inlined methods when their parent is our current block
  10452. if ((checkSubprogram == dwSubprogram) && (checkLineData->mLine == startLineData->mLine))
  10453. {
  10454. _HandleSection();
  10455. }
  10456. else if ((checkSubprogram->mInlineeInfo != NULL) && (checkSubprogram->mInlineeInfo->mInlineParent == dwSubprogram))
  10457. {
  10458. if (checkLineAddr == checkSubprogram->mBlock.mLowPC)
  10459. {
  10460. addr_target inlineStartAddr = checkSubprogram->mBlock.mLowPC;
  10461. // Find the calling line
  10462. DbgSubprogram* callingSubprogram = dwSubprogram;
  10463. auto checkLineData = dwSubprogram->FindClosestLine(inlineStartAddr, &callingSubprogram);
  10464. if ((checkLineData != NULL) && (checkLineData->mCtxIdx == startLineData->mCtxIdx) && (checkLineData->mLine == startLineData->mLine))
  10465. {
  10466. if (inlineStartAddr <= (addr_target)inAddress)
  10467. callAddresses += "-";
  10468. callAddresses += EncodeDataPtr(inlineStartAddr, false);
  10469. String outSymbol;
  10470. CreateFilterName(outSymbol, checkSubprogram);
  10471. callAddresses += "\t" + outSymbol;
  10472. bool isFiltered = dwSubprogram->mIsStepFilteredDefault;
  10473. StepFilter* stepFilterPtr;
  10474. if (mDebugManager->mStepFilters.TryGetValue(outSymbol, &stepFilterPtr))
  10475. isFiltered = stepFilterPtr->IsFiltered(isFiltered);
  10476. if (isFiltered)
  10477. callAddresses += "\tf"; // 'f' for filter
  10478. callAddresses += "\n";
  10479. }
  10480. // if (checkSubprogram->mBlock.mHighPC < endAddr)
  10481. // {
  10482. // addr = checkSubprogram->mBlock.mHighPC;
  10483. // _HandleSection();
  10484. // }
  10485. }
  10486. // If we have unattributed data after the end of an inlined method, add that
  10487. if ((endAddr > checkSubprogram->mBlock.mHighPC) && (nextSubProgram == dwSubprogram))
  10488. {
  10489. addr = checkSubprogram->mBlock.mHighPC;
  10490. _HandleSection();
  10491. }
  10492. }
  10493. checkLineData = nextLineData;
  10494. checkSubprogram = nextSubProgram;
  10495. checkLineAddr = nextLineAddr;
  10496. addr = endAddr;
  10497. }
  10498. return callAddresses;
  10499. }
  10500. String WinDebugger::GetCurrentException()
  10501. {
  10502. AutoCrit autoCrit(mDebugManager->mCritSect);
  10503. String result = StrFormat("%s\n%08X",
  10504. EncodeDataPtr((addr_target)(intptr)mCurException.ExceptionAddress, true).c_str(),
  10505. mCurException.ExceptionCode);
  10506. String exStr;
  10507. switch (mCurException.ExceptionCode)
  10508. {
  10509. case EXCEPTION_ACCESS_VIOLATION:
  10510. {
  10511. String accessType;
  10512. if (mCurException.ExceptionInformation[0] == 0)
  10513. accessType = "reading from";
  10514. else if (mCurException.ExceptionInformation[0] == 8)
  10515. accessType = "executing";
  10516. else
  10517. accessType = "writing to";
  10518. exStr = StrFormat("EXCEPTION_ACCESS_VIOLATION %s %s", accessType.c_str(), EncodeDataPtr((addr_target)mCurException.ExceptionInformation[1], true).c_str());
  10519. }
  10520. break;
  10521. case EXCEPTION_DATATYPE_MISALIGNMENT:
  10522. exStr = "EXCEPTION_DATATYPE_MISALIGNMENT";
  10523. case EXCEPTION_SINGLE_STEP:
  10524. exStr = "EXCEPTION_SINGLE_STEP";
  10525. break;
  10526. case EXCEPTION_BREAKPOINT:
  10527. exStr = "EXCEPTION_BREAKPOINT";
  10528. break;
  10529. case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
  10530. exStr = "EXCEPTION_ARRAY_BOUNDS_EXCEEDED";
  10531. break;
  10532. case EXCEPTION_FLT_DENORMAL_OPERAND:
  10533. exStr = "EXCEPTION_FLT_DENORMAL_OPERAND";
  10534. break;
  10535. case EXCEPTION_FLT_DIVIDE_BY_ZERO:
  10536. exStr = "EXCEPTION_FLT_DIVIDE_BY_ZERO";
  10537. break;
  10538. case EXCEPTION_FLT_INEXACT_RESULT:
  10539. exStr = "EXCEPTION_FLT_INEXACT_RESULT";
  10540. break;
  10541. case EXCEPTION_FLT_INVALID_OPERATION:
  10542. exStr = "EXCEPTION_FLT_INVALID_OPERATIO";
  10543. break;
  10544. case EXCEPTION_FLT_OVERFLOW:
  10545. exStr = "EXCEPTION_FLT_OVERFLOW";
  10546. break;
  10547. case EXCEPTION_FLT_STACK_CHECK:
  10548. exStr = "EXCEPTION_FLT_STACK_CHECK";
  10549. break;
  10550. case EXCEPTION_FLT_UNDERFLOW:
  10551. exStr = "EXCEPTION_FLT_UNDERFLOW";
  10552. break;
  10553. case EXCEPTION_INT_DIVIDE_BY_ZERO:
  10554. exStr = "EXCEPTION_INT_DIVIDE_BY_ZERO";
  10555. break;
  10556. case EXCEPTION_INT_OVERFLOW:
  10557. exStr = "EXCEPTION_INT_OVERFLOW";
  10558. break;
  10559. case EXCEPTION_PRIV_INSTRUCTION:
  10560. exStr = "EXCEPTION_PRIV_INSTRUCTION";
  10561. break;
  10562. case EXCEPTION_IN_PAGE_ERROR:
  10563. exStr = "EXCEPTION_IN_PAGE_ERROR";
  10564. break;
  10565. case EXCEPTION_ILLEGAL_INSTRUCTION:
  10566. exStr = "EXCEPTION_ILLEGAL_INSTRUCTION";
  10567. break;
  10568. case EXCEPTION_NONCONTINUABLE_EXCEPTION:
  10569. exStr = "EXCEPTION_NONCONTINUABLE_EXCEPTION";
  10570. break;
  10571. case EXCEPTION_STACK_OVERFLOW:
  10572. exStr = "EXCEPTION_STACK_OVERFLOW";
  10573. break;
  10574. case EXCEPTION_INVALID_DISPOSITION:
  10575. exStr = "EXCEPTION_INVALID_DISPOSITION";
  10576. break;
  10577. case EXCEPTION_GUARD_PAGE:
  10578. exStr = "EXCEPTION_GUARD_PAGE";
  10579. break;
  10580. case EXCEPTION_INVALID_HANDLE:
  10581. exStr = "EXCEPTION_INVALID_HANDLE";
  10582. break;
  10583. case CONTROL_C_EXIT:
  10584. exStr = "CONTROL_C_EXIT";
  10585. break;
  10586. default:
  10587. exStr += StrFormat("EXCEPTION %08X", mCurException.ExceptionCode);
  10588. }
  10589. if (mActiveThread != NULL)
  10590. exStr += StrFormat(" in thread %d", mActiveThread->mThreadId);
  10591. if (!exStr.empty())
  10592. result += "\n" + exStr;
  10593. // After we retrieve the exception then we can go back to just being normal 'paused'
  10594. // This allows us to evaluate stuff, Set Next Statement, etc.
  10595. mRunState = RunState_Paused;
  10596. return result.c_str();
  10597. }
  10598. void WinDebugger::SetAliasPath(const StringImpl& origPath, const StringImpl& localPath)
  10599. {
  10600. AutoCrit autoCrit(mDebugManager->mCritSect);
  10601. String fixedOrigPath = FixPathAndCase(origPath);
  10602. String fixedLocalPath = FixPathAndCase(localPath);
  10603. auto origFile = mDebugTarget->AddSrcFile(origPath);
  10604. origFile->mLocalPath = FixPath(localPath);
  10605. mDebugTarget->mLocalToOrigSrcMap[fixedLocalPath] = fixedOrigPath;
  10606. // We invalidate the step filters, because previously-failing 'CheckSourceFileExist' checks may now succeed
  10607. mDebugManager->mStepFilterVersion++;
  10608. }
  10609. String WinDebugger::GetModulesInfo()
  10610. {
  10611. AutoCrit autoCrit(mDebugManager->mCritSect);
  10612. String str;
  10613. for (auto module : mDebugTarget->mDbgModules)
  10614. {
  10615. COFF* coff = (COFF*)module;
  10616. if (module->mHotIdx > 0)
  10617. continue;
  10618. str += module->mDisplayName;
  10619. str += "\t";
  10620. if (module->mLoadState == DbgModuleLoadState_Loaded)
  10621. {
  10622. str += module->mFilePath;
  10623. }
  10624. else if (module->mLoadState == DbgModuleLoadState_NotLoaded)
  10625. {
  10626. str += module->mFilePath;
  10627. str += " (Loading...)";
  10628. }
  10629. else if (module->mLoadState == DbgModuleLoadState_Failed)
  10630. {
  10631. str += "!";
  10632. str += module->mFilePath;
  10633. }
  10634. if (module->mMappedImageFile != NULL)
  10635. {
  10636. str += " (";
  10637. str += module->mMappedImageFile->mFileName;
  10638. str += ")";
  10639. }
  10640. str += "\t";
  10641. str += coff->mPDBPath;
  10642. str += "\t";
  10643. str += module->mVersion;
  10644. str += StrFormat("\t%@-%@\t%dk\t", module->mImageBase, module->mImageBase + module->mImageSize, module->mImageSize / 1024);
  10645. time_t timestamp = coff->mTimeStamp;
  10646. if (timestamp == 0)
  10647. timestamp = GetFileTimeWrite(coff->mFilePath);
  10648. if (timestamp != 0)
  10649. {
  10650. char timeString[256];
  10651. auto time_info = localtime(&timestamp);
  10652. strftime(timeString, sizeof(timeString), "%D %T", time_info);
  10653. str += timeString;
  10654. }
  10655. str += "\n";
  10656. }
  10657. return str;
  10658. }
  10659. void WinDebugger::CancelSymSrv()
  10660. {
  10661. AutoCrit autoCrit(mDebugManager->mCritSect);
  10662. if (mActiveSymSrvRequest != NULL)
  10663. mActiveSymSrvRequest->Cancel();
  10664. }
  10665. bool WinDebugger::HasPendingDebugLoads()
  10666. {
  10667. AutoCrit autoCrit(mDebugManager->mCritSect);
  10668. return (!mPendingImageLoad.IsEmpty()) || (!mPendingDebugInfoLoad.IsEmpty());
  10669. }
  10670. int WinDebugger::LoadImageForModule(const StringImpl &modulePath, const StringImpl& imagePath)
  10671. {
  10672. AutoCrit autoCrit(mDebugManager->mCritSect);
  10673. for (auto dbgModule : mDebugTarget->mDbgModules)
  10674. {
  10675. if (modulePath.Equals(dbgModule->mFilePath, StringImpl::CompareKind_OrdinalIgnoreCase))
  10676. {
  10677. auto coff = (COFF*)dbgModule;
  10678. if (!coff->LoadModuleImage(imagePath))
  10679. {
  10680. mDebugManager->mOutMessages.push_back("error Failed to load image " + imagePath);
  10681. }
  10682. ModuleChanged(dbgModule);
  10683. return 0;
  10684. }
  10685. }
  10686. return 0;
  10687. }
  10688. int WinDebugger::LoadDebugInfoForModule(DbgModule* dbgModule)
  10689. {
  10690. if (!dbgModule->HasPendingDebugInfo())
  10691. return 0;
  10692. if (dbgModule->RequestDebugInfo())
  10693. {
  10694. ClearCallStack(); // Make this re-resolve with debug info
  10695. return 1;
  10696. }
  10697. DbgPendingDebugInfoLoad* dbgPendingDebugInfoLoad = NULL;
  10698. if (mPendingDebugInfoLoad.TryAdd(dbgModule, NULL, &dbgPendingDebugInfoLoad))
  10699. {
  10700. dbgPendingDebugInfoLoad->mModule = dbgModule;
  10701. dbgPendingDebugInfoLoad->mAllowRemote = true;
  10702. return 2;
  10703. }
  10704. dbgPendingDebugInfoLoad->mAllowRemote = true;
  10705. return 0;
  10706. }
  10707. int WinDebugger::LoadDebugInfoForModule(const StringImpl& moduleName)
  10708. {
  10709. AutoCrit autoCrit(mDebugManager->mCritSect);
  10710. for (auto dbgModule : mDebugTarget->mDbgModules)
  10711. {
  10712. String checkModuleName = GetFileName(dbgModule->mFilePath);
  10713. if (moduleName.Equals(checkModuleName, StringImpl::CompareKind_OrdinalIgnoreCase))
  10714. {
  10715. return LoadDebugInfoForModule(dbgModule);
  10716. }
  10717. }
  10718. return 0;
  10719. }
  10720. int WinDebugger::LoadDebugInfoForModule(const StringImpl& modulePath, const StringImpl& debugFileName)
  10721. {
  10722. AutoCrit autoCrit(mDebugManager->mCritSect);
  10723. for (auto dbgModule : mDebugTarget->mDbgModules)
  10724. {
  10725. if (modulePath.Equals(dbgModule->mFilePath, StringImpl::CompareKind_OrdinalIgnoreCase))
  10726. {
  10727. auto coff = (COFF*)dbgModule;
  10728. String err;
  10729. if (!coff->mPDBLoaded)
  10730. {
  10731. dbgModule->mFailMsgPtr = &err;
  10732. if (coff->TryLoadPDB(debugFileName, coff->mWantPDBGuid, coff->mWantAge))
  10733. {
  10734. ModuleChanged(dbgModule);
  10735. }
  10736. dbgModule->mFailMsgPtr = NULL;
  10737. }
  10738. else
  10739. {
  10740. err = StrFormat("Module '%s' already has debug information loaded", GetFileName(modulePath).c_str());
  10741. }
  10742. if (!err.IsEmpty())
  10743. {
  10744. mDebugManager->mOutMessages.push_back("error " + err);
  10745. }
  10746. return 0;
  10747. }
  10748. }
  10749. return 0;
  10750. }
  10751. void WinDebugger::FixupLineData(DbgCompileUnit* compileUnit)
  10752. {
  10753. if (!compileUnit || !compileUnit->mNeedsLineDataFixup)
  10754. return;
  10755. compileUnit->mNeedsLineDataFixup = false;
  10756. }
  10757. static int CompareLineData(const void* lineDataP1, const void* lineDataP2)
  10758. {
  10759. int cmpResult = (int)(((DbgLineData*)lineDataP1)->mRelAddress - ((DbgLineData*)lineDataP2)->mRelAddress);
  10760. if (cmpResult != 0)
  10761. return cmpResult;
  10762. // A larger contrib size means it's the 'outer' inlinee
  10763. cmpResult = -(((DbgLineData*)lineDataP1)->mContribSize - ((DbgLineData*)lineDataP2)->mContribSize);
  10764. if (cmpResult != 0)
  10765. return cmpResult;
  10766. return -(((DbgLineData*)lineDataP1)->mCtxIdx - ((DbgLineData*)lineDataP2)->mCtxIdx);
  10767. }
  10768. void WinDebugger::FixupLineDataForSubprogram(DbgSubprogram* subProgram)
  10769. {
  10770. if ((subProgram == NULL) || (!subProgram->mNeedLineDataFixup))
  10771. return;
  10772. BP_ZONE("FixupLineDataForSubprogram");
  10773. subProgram->mNeedLineDataFixup = false;
  10774. if (subProgram->mInlineeInfo != NULL)
  10775. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  10776. if ((subProgram->mLineInfo == NULL) || (subProgram->mLineInfo->mLines.mSize == 0))
  10777. return;
  10778. //TODO: I think this was covering up a bug in DWARF line encoding? Figure this out
  10779. // if (subProgram->mLineInfo->mLines.mSize >= 2)
  10780. // {
  10781. // DbgLineData* line0 = &subProgram->mLineInfo->mLines[0];
  10782. // DbgLineData* line1 = &subProgram->mLineInfo->mLines[1];
  10783. //
  10784. //
  10785. // if ((line0->mRelAddress == line1->mRelAddress) && (!line0->IsStackFrameSetup()) && (line1->IsStackFrameSetup()))
  10786. // {
  10787. // CPUInst inst;
  10788. // if (mCPU->Decode(line0->mAddress, subProgram->mCompileUnit->mDbgModule->mOrigImageData, &inst))
  10789. // line1->mAddress += inst.GetLength();
  10790. // }
  10791. // }
  10792. qsort(subProgram->mLineInfo->mLines.mVals, subProgram->mLineInfo->mLines.mSize, sizeof(DbgLineData), CompareLineData);
  10793. // If we have multiple lines with the same line/column/context, merge them
  10794. if (!subProgram->mLineInfo->mLines.IsEmpty())
  10795. {
  10796. auto prevLine = &subProgram->mLineInfo->mLines[0];
  10797. for (int i = 1; i < subProgram->mLineInfo->mLines.mSize; i++)
  10798. {
  10799. auto nextLine = &subProgram->mLineInfo->mLines[i];
  10800. if ((nextLine->mLine == prevLine->mLine) && (nextLine->mColumn == prevLine->mColumn) && (nextLine->mCtxIdx == prevLine->mCtxIdx) &&
  10801. (nextLine->mRelAddress == prevLine->mRelAddress + prevLine->mContribSize))
  10802. {
  10803. prevLine->mContribSize += nextLine->mContribSize;
  10804. // This messed up inline cases because mContribSize actually INCLUDES inlined lines so it caused the address to skip too far
  10805. //nextLine->mRelAddress += nextLine->mContribSize;
  10806. //nextLine->mContribSize = 0;
  10807. }
  10808. else
  10809. {
  10810. prevLine = nextLine;
  10811. }
  10812. }
  10813. }
  10814. }
  10815. void WinDebugger::ReserveHotTargetMemory(int size)
  10816. {
  10817. HotTargetMemory hotTargetMemory;
  10818. hotTargetMemory.mOffset = 0;
  10819. hotTargetMemory.mSize = 0;
  10820. hotTargetMemory.mPtr = NULL;
  10821. if (size > 0)
  10822. {
  10823. // In 64-bit mode we have a reserved region on program load that we commit here because the offsets
  10824. // must be within 32-bits of the original EXE image, but in 32-bit mode we don't reserve anything
  10825. // until here
  10826. #ifdef BF_DBG_32
  10827. //hotTargetMemory.mSize = std::max(1024 * 1024, size);
  10828. BF_ASSERT((size & (mPageSize - 1)) == 0);
  10829. hotTargetMemory.mSize = size;
  10830. hotTargetMemory.mPtr = (addr_target)(intptr)VirtualAllocEx(mProcessInfo.hProcess, NULL, hotTargetMemory.mSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
  10831. mDebugTarget->mHotHeap->AddTrackedRegion(hotTargetMemory.mPtr, hotTargetMemory.mSize);
  10832. #else
  10833. hotTargetMemory.mSize = size;
  10834. hotTargetMemory.mPtr = mDebugTarget->mHotHeap->Alloc(size);
  10835. BF_ASSERT(hotTargetMemory.mPtr != 0);
  10836. auto ptr = ::VirtualAllocEx(mProcessInfo.hProcess, (void*)(intptr)hotTargetMemory.mPtr, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  10837. BF_ASSERT(ptr == (void*)(intptr)hotTargetMemory.mPtr);
  10838. #endif
  10839. }
  10840. BfLogDbg("ReserveHotTargetMemory %p %d", hotTargetMemory.mPtr, hotTargetMemory.mSize);
  10841. int err = GetLastError();
  10842. mHotTargetMemory.push_back(hotTargetMemory);
  10843. }
  10844. addr_target WinDebugger::AllocHotTargetMemory(int size, bool canExecute, bool canWrite, int* outAllocSize)
  10845. {
  10846. int prot = PAGE_READWRITE;
  10847. if (canExecute && canWrite)
  10848. prot = PAGE_EXECUTE_READWRITE;
  10849. else if (canExecute)
  10850. prot = PAGE_EXECUTE_READ;
  10851. auto hotTargetMemory = (HotTargetMemory*)&mHotTargetMemory.back();
  10852. if (hotTargetMemory->mPtr == 0)
  10853. {
  10854. Fail("Failed to allocate memory for hot loading");
  10855. return 0;
  10856. }
  10857. size = (size + (mPageSize - 1)) & ~(mPageSize - 1);
  10858. *outAllocSize = size;
  10859. BF_ASSERT(hotTargetMemory->mOffset + size <= hotTargetMemory->mSize);
  10860. addr_target result = hotTargetMemory->mPtr + hotTargetMemory->mOffset;
  10861. ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)result, size, prot, NULL);
  10862. BfLogDbg("AllocHotTargetMemory: %p %d %d %d\n", result, size, canExecute, canWrite);
  10863. hotTargetMemory->mOffset += size;
  10864. return result;
  10865. }
  10866. void WinDebugger::ReleaseHotTargetMemory(addr_target addr, int size)
  10867. {
  10868. #ifdef BF_DBG_32
  10869. ::VirtualFreeEx(mProcessInfo.hProcess, (void*)(intptr)addr, 0, MEM_RELEASE);
  10870. #else
  10871. mDebugTarget->mHotHeap->Release(addr, size);
  10872. ::VirtualFreeEx(mProcessInfo.hProcess, (void*)(intptr)addr, size, MEM_DECOMMIT);
  10873. #endif
  10874. }
  10875. void WinDebugger::CleanupHotHeap()
  10876. {
  10877. mDebugTarget->mLastHotHeapCleanIdx = mDebugTarget->mHotHeap->mBlockAllocIdx;
  10878. // Our criteria for determining whether a hot loaded file is still being used:
  10879. // 1) If we are currently executing a method from that object file.
  10880. // 2) If the symbol map has a symbol with that address.
  10881. // 3) If the static variable map contains a reference - including a conservative scan of the data
  10882. // This handles vdata references
  10883. // This is a conservative check which won't purge hot reloads that contain deleted
  10884. // methods (for example), but it will purge hot reloads where all the changed
  10885. // data has been overwritten.
  10886. // For delegate bindings, the original module declaring the bind creates a "preserve"
  10887. // global such as "bf_hs_preserve@_ZN5TestO4TestEv", whose preserved symbol ensures it
  10888. // doesn't get unloaded. The current version of that method resides in "_ZN5TestO4TestEv",
  10889. // ensuring that the method pointed to by the global variable is valid
  10890. mDebugTarget->mHotHeap->ClearReferencedFlags();
  10891. addr_target lowAddr = mDebugTarget->mHotHeap->mHotAreaStart;
  10892. addr_target highAddr = lowAddr + mDebugTarget->mHotHeap->mHotAreaSize;
  10893. // Do conservative scan through all thread stacks. Stack traces aren't 100% reliable, so we
  10894. // need to do a full conservative scan of any addresses stored in the stack
  10895. // to ensure we don't miss any return addresses
  10896. for (int threadIdx = 0; threadIdx < (int)mThreadList.size(); threadIdx++)
  10897. {
  10898. WdThreadInfo* threadInfo = mThreadList[threadIdx];
  10899. BF_CONTEXT lcContext;
  10900. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  10901. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  10902. addr_target checkStackAddr = BF_CONTEXT_SP(lcContext);
  10903. checkStackAddr &= ~(sizeof(addr_target) - 1);
  10904. // Conservative check on registers
  10905. for (int regNum = 0; regNum < sizeof(BF_CONTEXT)/sizeof(addr_target); regNum++)
  10906. {
  10907. addr_target checkAddr = ((addr_target*)&lcContext)[regNum];
  10908. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  10909. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  10910. }
  10911. // Conservative check on all stack data
  10912. while (checkStackAddr < threadInfo->mStartSP)
  10913. {
  10914. addr_target checkAddrArr[1024];
  10915. int numAddrsChecking = BF_MIN(1024, (int)((threadInfo->mStartSP - checkStackAddr) / sizeof(addr_target)));
  10916. ReadMemory(checkStackAddr, numAddrsChecking * sizeof(addr_target), checkAddrArr);
  10917. checkStackAddr += numAddrsChecking * sizeof(addr_target);
  10918. for (int addrIdx = 0; addrIdx < numAddrsChecking; addrIdx++)
  10919. {
  10920. addr_target checkAddr = checkAddrArr[addrIdx];
  10921. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  10922. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  10923. }
  10924. }
  10925. }
  10926. auto mainModule = mDebugTarget->mTargetBinary;
  10927. for (auto entry : mainModule->mSymbolNameMap)
  10928. {
  10929. auto dwSymbol = entry->mValue;
  10930. addr_target checkAddr = dwSymbol->mAddress;
  10931. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  10932. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  10933. }
  10934. mDebugTarget->CleanupHotHeap();
  10935. BfLogDbg("Hot load memory used: %dk\n", (int)mDebugTarget->mHotHeap->GetUsedSize() / 1024);
  10936. }
  10937. int WinDebugger::EnableWriting(intptr address, int size)
  10938. {
  10939. DWORD oldProt;
  10940. bool success = ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)address, size, PAGE_READWRITE, &oldProt);
  10941. if (!success)
  10942. {
  10943. int err = GetLastError();
  10944. }
  10945. return (int)oldProt;
  10946. }
  10947. int WinDebugger::SetProtection(intptr address, int size, int prot)
  10948. {
  10949. DWORD oldProt;
  10950. ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)address, size, prot, &oldProt);
  10951. return (int)oldProt;
  10952. }
  10953. void WinDebugger::EnableMemCache()
  10954. {
  10955. mMemCacheAddr = 1;
  10956. }
  10957. void WinDebugger::DisableMemCache()
  10958. {
  10959. mMemCacheAddr = 0;
  10960. }
  10961. bool WinDebugger::ReadMemory(intptr address, uint64 length, void* dest, bool local)
  10962. {
  10963. if (local)
  10964. {
  10965. __try
  10966. {
  10967. memcpy(dest, (void*)address, length);
  10968. return true;
  10969. }
  10970. __except(EXCEPTION_EXECUTE_HANDLER)
  10971. {
  10972. return false;
  10973. }
  10974. }
  10975. if (mMemCacheAddr != 0)
  10976. {
  10977. addr_target targetAddr = (addr_target)address;
  10978. if ((targetAddr >= mMemCacheAddr) && (targetAddr + length <= mMemCacheAddr + WD_MEMCACHE_SIZE) && (mMemCacheAddr > 1))
  10979. {
  10980. memcpy(dest, mMemCacheData + (targetAddr - mMemCacheAddr), length);
  10981. return true;
  10982. }
  10983. // We need a new block
  10984. SIZE_T dwReadBytes;
  10985. if (::ReadProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, mMemCacheData, (SIZE_T)WD_MEMCACHE_SIZE, &dwReadBytes) != 0)
  10986. {
  10987. mMemCacheAddr = targetAddr;
  10988. memcpy(dest, mMemCacheData, length);
  10989. return true;
  10990. }
  10991. // Failed, turn off caching
  10992. mMemCacheAddr = 0;
  10993. }
  10994. SIZE_T dwReadBytes;
  10995. if (::ReadProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, dest, (SIZE_T)length, &dwReadBytes) != 0)
  10996. return true;
  10997. int lastErr = ::GetLastError();
  10998. memset(dest, 0, length);
  10999. return false;
  11000. }
  11001. bool WinDebugger::WriteMemory(intptr address, void* src, uint64 length)
  11002. {
  11003. SIZE_T dwBytesWritten = 0;
  11004. int result = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, src, (SIZE_T)length, &dwBytesWritten);
  11005. return result != 0;
  11006. }
  11007. addr_target WinDebugger::GetTLSOffset(int tlsIndex)
  11008. {
  11009. typedef LONG NTSTATUS;
  11010. typedef DWORD KPRIORITY;
  11011. typedef WORD UWORD;
  11012. enum THREADINFOCLASS
  11013. {
  11014. ThreadBasicInformation,
  11015. };
  11016. struct CLIENT_ID
  11017. {
  11018. HANDLE UniqueProcess;
  11019. HANDLE UniqueThread;
  11020. };
  11021. struct
  11022. {
  11023. NTSTATUS mExitStatus;
  11024. void* mTebBaseAddress;
  11025. CLIENT_ID mClientId;
  11026. KAFFINITY mAffinityMask;
  11027. KPRIORITY mPriority;
  11028. KPRIORITY mBasePriority;
  11029. } threadInfo = { 0 };
  11030. ULONG len = 0;
  11031. bool loadedManually = false;
  11032. static HMODULE module = NULL;
  11033. static NTSTATUS(__stdcall *NtQueryInformationThread)(HANDLE ThreadHandle, THREADINFOCLASS ThreadInformationClass, PVOID ThreadInformation, ULONG ThreadInformationLength, PULONG ReturnLength);
  11034. if (module == NULL)
  11035. {
  11036. module = GetModuleHandleA("ntdll.dll");
  11037. NtQueryInformationThread = reinterpret_cast<decltype(NtQueryInformationThread)>(GetProcAddress(module, "NtQueryInformationThread"));
  11038. }
  11039. if (NtQueryInformationThread == NULL)
  11040. return 0;
  11041. NTSTATUS status = NtQueryInformationThread(mActiveThread->mHThread, (THREADINFOCLASS)0, &threadInfo, sizeof(threadInfo), nullptr);
  11042. if (status < 0)
  11043. return 0;
  11044. #ifdef BF_DBG_32
  11045. addr_target tibAddr = ReadMemory<addr_target>((intptr)threadInfo.mTebBaseAddress + 0x0);
  11046. addr_target tlsTable = ReadMemory<addr_target>((intptr)tibAddr + 0x2C);
  11047. #else
  11048. addr_target tlsTable = ReadMemory<addr_target>((intptr)threadInfo.mTebBaseAddress + 0x58);
  11049. #endif
  11050. return ReadMemory<addr_target>(tlsTable + tlsIndex * sizeof(addr_target));
  11051. }
  11052. bool WinDebugger::WriteInstructions(intptr address, void* src, uint64 length)
  11053. {
  11054. SIZE_T dwBytesWritten = 0;
  11055. bool result = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, src, (SIZE_T)length, &dwBytesWritten) != 0;
  11056. result |= ::FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, (SIZE_T)length) != 0;
  11057. BF_ASSERT(result);
  11058. BfLogDbg("WriteInstructions: %p %d\n", address, length);
  11059. return result;
  11060. }
  11061. DbgMemoryFlags WinDebugger::GetMemoryFlags(intptr address)
  11062. {
  11063. MEMORY_BASIC_INFORMATION memBasicInfo;
  11064. if (::VirtualQueryEx(mProcessInfo.hProcess, (void*)address, &memBasicInfo, sizeof(MEMORY_BASIC_INFORMATION)) == 0)
  11065. {
  11066. //BfLogDbg("VirtualQueryEx failed with %d\n", GetLastError());
  11067. return DbgMemoryFlags_None;
  11068. }
  11069. DbgMemoryFlags flags = DbgMemoryFlags_None;
  11070. if (memBasicInfo.AllocationProtect & PAGE_READWRITE)
  11071. {
  11072. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11073. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11074. }
  11075. if (memBasicInfo.AllocationProtect & PAGE_READONLY)
  11076. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11077. if (memBasicInfo.AllocationProtect & PAGE_WRITECOPY)
  11078. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11079. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE)
  11080. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11081. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_READ)
  11082. {
  11083. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11084. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11085. }
  11086. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_READWRITE)
  11087. {
  11088. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11089. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11090. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11091. }
  11092. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_WRITECOPY)
  11093. {
  11094. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11095. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11096. }
  11097. return flags;
  11098. }
  11099. #ifdef BF_DBG_32
  11100. Debugger* Beefy::CreateDebugger32(DebugManager* debugManager, DbgMiniDump* miniDump)
  11101. #else
  11102. Debugger* Beefy::CreateDebugger64(DebugManager* debugManager, DbgMiniDump* miniDump)
  11103. #endif
  11104. {
  11105. if (miniDump != NULL)
  11106. {
  11107. auto debugger = new MiniDumpDebugger(debugManager, miniDump);
  11108. return debugger;
  11109. }
  11110. return new WinDebugger(debugManager);
  11111. }
  11112. #ifdef BF_DBG_32
  11113. void WdAllocTest()
  11114. {
  11115. Array<BeefyDbg32::WdStackFrame*> stackFrameList;
  11116. for (int i = 0; true; i++)
  11117. {
  11118. WdStackFrame* stackFrame = new WdStackFrame();
  11119. stackFrameList.push_back(stackFrame);
  11120. }
  11121. }
  11122. #endif
  11123. #endif //!defined BF32 || !defined BF_DBG_64