WinDebugger.cpp 377 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934
  1. #pragma warning(disable:4996)
  2. // TODO: Remove for 64-bit
  3. #pragma warning(disable:4244)
  4. #pragma warning(disable:4267)
  5. #define NTDDI_VERSION 0x06020000
  6. #include "WinDebugger.h"
  7. #include "CPU.h"
  8. #include "DbgModule.h"
  9. #include "DebugVisualizers.h"
  10. #include "MiniDumpDebugger.h"
  11. #include "X86.h"
  12. #include "BeefySysLib/Common.h"
  13. #include "BeefySysLib/util/PerfTimer.h"
  14. #include "BeefySysLib/util/BeefPerf.h"
  15. #include "BeefySysLib/util/CritSect.h"
  16. #include "BeefySysLib/util/UTF8.h"
  17. #include "BeefySysLib/FileStream.h"
  18. #include "BeefySysLib/FileHandleStream.h"
  19. #include "BeefySysLib/util/FileEnumerator.h"
  20. #include <inttypes.h>
  21. #include <windows.h>
  22. #include "DbgExprEvaluator.h"
  23. #include "Compiler/BfSystem.h"
  24. #include "Compiler/BfParser.h"
  25. #include "Compiler/BfReducer.h"
  26. #include "Compiler/BfDemangler.h"
  27. #include "Compiler/BfPrinter.h"
  28. #include <Shlobj.h>
  29. #include "NetManager.h"
  30. #include "DebugManager.h"
  31. #include "X86Target.h"
  32. #include "HotHeap.h"
  33. #include "HotScanner.h"
  34. #include "Profiler.h"
  35. #include <float.h>
  36. #include <psapi.h>
  37. #if !defined BF32 || !defined BF_DBG_64
  38. #define STATUS_WX86_CONTINUE 0x4000001DL
  39. #define STATUS_WX86_SINGLE_STEP 0x4000001EL
  40. #define STATUS_WX86_BREAKPOINT 0x4000001FL
  41. #define STATUS_WX86_EXCEPTION_CONTINUE 0x40000020L
  42. #pragma pack(push, 1)
  43. struct HotJumpOp
  44. {
  45. uint8 mOpCode;
  46. int32 mRelTarget;
  47. };
  48. #pragma pack(pop)
  49. #include "BeefySysLib/util/AllocDebug.h"
  50. #include <limits>
  51. USING_NS_BF_DBG;
  52. static void FilterThreadName(String& name)
  53. {
  54. for (int i = 0; i < (int)name.length(); i++)
  55. {
  56. uint8 c = name[i];
  57. if (c == 0)
  58. {
  59. name.RemoveToEnd(i);
  60. return;
  61. }
  62. if (c < 32)
  63. {
  64. name.Remove(i);
  65. i--;
  66. continue;
  67. }
  68. }
  69. }
  70. //////////////////////////////////////////////////////////////////////////
  71. WdBreakpointCondition::~WdBreakpointCondition()
  72. {
  73. delete mDbgEvaluationContext;
  74. }
  75. //////////////////////////////////////////////////////////////////////////
  76. DbgEvaluationContext::DbgEvaluationContext(WinDebugger* winDebugger, DbgModule* dbgModule, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  77. {
  78. Init(winDebugger, dbgModule, expr, formatInfo, contextValue);
  79. }
  80. DbgEvaluationContext::DbgEvaluationContext(WinDebugger* winDebugger, DbgCompileUnit* dbgCompileUnit, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  81. {
  82. DbgModule* dbgModule = NULL;
  83. if (dbgCompileUnit != NULL)
  84. dbgModule = dbgCompileUnit->mDbgModule;
  85. Init(winDebugger, dbgModule, expr, formatInfo, contextValue);
  86. }
  87. void DbgEvaluationContext::Init(WinDebugger* winDebugger, DbgModule* dbgModule, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  88. {
  89. if (expr.empty())
  90. {
  91. mParser = NULL;
  92. mReducer = NULL;
  93. mPassInstance = NULL;
  94. mDbgExprEvaluator = NULL;
  95. mExprNode = NULL;
  96. return;
  97. }
  98. mParser = new BfParser(winDebugger->mBfSystem);
  99. mParser->mCompatMode = true;
  100. mPassInstance = new BfPassInstance(winDebugger->mBfSystem);
  101. auto terminatedExpr = expr + ";";
  102. mParser->SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  103. mParser->Parse(mPassInstance);
  104. mReducer = new BfReducer();
  105. mReducer->mAlloc = mParser->mAlloc;
  106. mReducer->mSystem = winDebugger->mBfSystem;
  107. mReducer->mPassInstance = mPassInstance;
  108. mReducer->mVisitorPos = BfReducer::BfVisitorPos(mParser->mRootNode);
  109. mReducer->mVisitorPos.MoveNext();
  110. mReducer->mCompatMode = mParser->mCompatMode;
  111. mReducer->mSource = mParser;
  112. mExprNode = mReducer->CreateExpression(mParser->mRootNode->GetFirst());
  113. mParser->Close();
  114. mDbgExprEvaluator = new DbgExprEvaluator(winDebugger, dbgModule, mPassInstance, -1, -1);
  115. if ((formatInfo != NULL) && (mExprNode != NULL) && (mExprNode->GetSrcEnd() < (int) expr.length()))
  116. {
  117. String formatFlags = expr.Substring(mExprNode->GetSrcEnd());
  118. String errorString = "Invalid expression";
  119. if (!winDebugger->ParseFormatInfo(dbgModule, formatFlags, formatInfo, mPassInstance, NULL, NULL, &errorString, contextValue))
  120. {
  121. mPassInstance->FailAt(errorString, mParser->mSourceData, mExprNode->GetSrcEnd(), (int)expr.length() - mExprNode->GetSrcEnd());
  122. formatFlags = "";
  123. }
  124. }
  125. if (formatInfo != NULL)
  126. {
  127. mDbgExprEvaluator->mExplicitThis = formatInfo->mExplicitThis;
  128. mDbgExprEvaluator->mCallStackIdx = formatInfo->mCallStackIdx;
  129. mDbgExprEvaluator->mLanguage = formatInfo->mLanguage;
  130. }
  131. }
  132. bool DbgEvaluationContext::HasExpression()
  133. {
  134. return mExprNode != NULL;
  135. }
  136. DbgEvaluationContext::~DbgEvaluationContext()
  137. {
  138. delete mParser;
  139. delete mReducer;
  140. delete mDbgExprEvaluator;
  141. delete mPassInstance;
  142. }
  143. DbgTypedValue DbgEvaluationContext::EvaluateInContext(DbgTypedValue contextTypedValue)
  144. {
  145. if (mExprNode == NULL)
  146. return DbgTypedValue();
  147. mPassInstance->ClearErrors();
  148. if (contextTypedValue)
  149. {
  150. mDbgExprEvaluator->mExplicitThis = contextTypedValue;
  151. if ((mDbgExprEvaluator->mExplicitThis.mType->IsPointer()) && (mDbgExprEvaluator->mExplicitThis.mType->mTypeParam->WantsRefThis()))
  152. {
  153. mDbgExprEvaluator->mExplicitThis.mType = mDbgExprEvaluator->mExplicitThis.mType->mTypeParam;
  154. mDbgExprEvaluator->mExplicitThis.mSrcAddress = mDbgExprEvaluator->mExplicitThis.mPtr;
  155. mDbgExprEvaluator->mExplicitThis.mPtr = 0;
  156. }
  157. if ((mDbgExprEvaluator->mExplicitThis.mType->IsCompositeType()) && (!mDbgExprEvaluator->mExplicitThis.mType->WantsRefThis()))
  158. {
  159. if (mDbgExprEvaluator->mExplicitThis.mSrcAddress != 0)
  160. {
  161. mDbgExprEvaluator->mExplicitThis.mType = mDbgExprEvaluator->mDbgModule->GetPointerType(mDbgExprEvaluator->mExplicitThis.mType);
  162. mDbgExprEvaluator->mExplicitThis.mPtr = mDbgExprEvaluator->mExplicitThis.mSrcAddress;
  163. mDbgExprEvaluator->mExplicitThis.mSrcAddress = 0;
  164. }
  165. }
  166. }
  167. if (contextTypedValue.mType != NULL)
  168. mDbgExprEvaluator->mDbgCompileUnit = contextTypedValue.mType->mCompileUnit;
  169. DbgTypedValue exprResult;
  170. auto result = mDbgExprEvaluator->Resolve(mExprNode);
  171. return result;
  172. }
  173. bool DbgEvaluationContext::HadError()
  174. {
  175. return mPassInstance->mFailedIdx != 0;
  176. }
  177. String DbgEvaluationContext::GetErrorStr()
  178. {
  179. String errorStr = mPassInstance->mErrors[0]->mError;
  180. if (mExprNode != NULL)
  181. {
  182. errorStr += ": ";
  183. errorStr += mExprNode->ToString();
  184. }
  185. return errorStr;
  186. }
  187. //////////////////////////////////////////////////////////////////////////
  188. typedef HRESULT(WINAPI* SetThreadDescription_t)(HANDLE hThread, PCWSTR lpThreadDescription);
  189. typedef HRESULT(WINAPI* GetThreadDescription_t)(HANDLE hThread, PWSTR* lpThreadDescription);
  190. static SetThreadDescription_t gSetThreadDescription = NULL;
  191. static GetThreadDescription_t gGetThreadDescription = NULL;
  192. static HMODULE gKernelDll = NULL;
  193. static void ImportKernel()
  194. {
  195. if (gKernelDll != NULL)
  196. return;
  197. WCHAR path[MAX_PATH];
  198. GetSystemDirectory(path, MAX_PATH);
  199. wcscat(path, L"\\kernel32.dll");
  200. gKernelDll = GetModuleHandle(path);
  201. if (gKernelDll == NULL)
  202. {
  203. return;
  204. }
  205. gSetThreadDescription = (SetThreadDescription_t)GetProcAddress(gKernelDll, "SetThreadDescription");
  206. gGetThreadDescription = (GetThreadDescription_t)GetProcAddress(gKernelDll, "GetThreadDescription");
  207. }
  208. void WinDebugger::TryGetThreadName(WdThreadInfo* threadInfo)
  209. {
  210. if (threadInfo->mHThread == NULL)
  211. return;
  212. ImportKernel();
  213. PWSTR wStr = NULL;
  214. if (gGetThreadDescription != NULL)
  215. {
  216. gGetThreadDescription(threadInfo->mHThread, &wStr);
  217. if (wStr == NULL)
  218. return;
  219. threadInfo->mName = UTF8Encode(wStr);
  220. FilterThreadName(threadInfo->mName);
  221. LocalFree(wStr);
  222. }
  223. }
  224. static void CreateFilterName(String& name, DbgType* type)
  225. {
  226. CreateFilterName(name, type->mParent);
  227. switch (type->mTypeCode)
  228. {
  229. case DbgType_Namespace:
  230. case DbgType_Struct:
  231. case DbgType_Class:
  232. name += type->mName;
  233. break;
  234. }
  235. }
  236. static void CreateFilterName(String& name, const char* srcStr, DbgLanguage language)
  237. {
  238. int chevronDepth = 0;
  239. const char* cPtr = srcStr;
  240. for (; true; cPtr++)
  241. {
  242. char c = *cPtr;
  243. if (c == 0)
  244. break;
  245. if (c == '>')
  246. chevronDepth--;
  247. bool inGeneric = chevronDepth > 0;
  248. if (c == '<')
  249. chevronDepth++;
  250. if (inGeneric) // Bundle all generic instances together
  251. continue;
  252. if (c == '[') // Bundle all arrays together
  253. name.clear();
  254. if (c == '(')
  255. return; // Start of params
  256. if ((c == ':') && (cPtr[1] == ':') && (language == DbgLanguage_Beef))
  257. {
  258. name.Append('.');
  259. cPtr++;
  260. }
  261. else
  262. name.Append(c);
  263. }
  264. }
  265. static void CreateFilterName(String& name, DbgSubprogram* subprogram)
  266. {
  267. auto language = subprogram->GetLanguage();
  268. if (subprogram->mName == NULL)
  269. {
  270. if (subprogram->mLinkName[0] == '<')
  271. {
  272. name += subprogram->mLinkName;
  273. return;
  274. }
  275. name = BfDemangler::Demangle(subprogram->mLinkName, language);
  276. // Strip off the params since we need to generate those ourselves
  277. int parenPos = (int)name.IndexOf('(');
  278. if (parenPos != -1)
  279. name.RemoveToEnd(parenPos);
  280. return;
  281. }
  282. else if (subprogram->mHasQualifiedName)
  283. {
  284. const char* cPtr = subprogram->mName;
  285. if (strncmp(cPtr, "_bf::", 5) == 0)
  286. {
  287. CreateFilterName(name, cPtr + 5, DbgLanguage_Beef);
  288. name.Replace(".__BfStaticCtor", ".this$static");
  289. name.Replace(".__BfCtorClear", ".this$clear");
  290. name.Replace(".__BfCtor", ".this");
  291. }
  292. else
  293. CreateFilterName(name, subprogram->mName, language);
  294. return;
  295. }
  296. else
  297. {
  298. if (subprogram->mParentType != NULL)
  299. {
  300. String parentName = subprogram->mParentType->ToString();
  301. CreateFilterName(name, parentName.c_str(), language);
  302. if (!name.empty())
  303. {
  304. if (language == DbgLanguage_Beef)
  305. name += ".";
  306. else
  307. name += "::";
  308. }
  309. }
  310. if ((language == DbgLanguage_Beef) && (subprogram->mParentType != NULL) && (subprogram->mParentType->mTypeName != NULL) &&
  311. (strcmp(subprogram->mName, subprogram->mParentType->mTypeName) == 0))
  312. name += "this";
  313. else if ((language == DbgLanguage_Beef) && (subprogram->mName[0] == '~'))
  314. name += "~this";
  315. else if (strncmp(subprogram->mName, "_bf::", 5) == 0)
  316. {
  317. CreateFilterName(name, subprogram->mName + 5, DbgLanguage_Beef);
  318. }
  319. else
  320. {
  321. CreateFilterName(name, subprogram->mName, language);
  322. }
  323. }
  324. if (name.empty())
  325. name += "`anon";
  326. if ((name[name.length() - 1] == '!') || (name[0] == '<'))
  327. {
  328. if (language == DbgLanguage_Beef)
  329. {
  330. // It's a mixin - assert that there's no params
  331. //BF_ASSERT(subprogram->mParams.Size() == 0);
  332. }
  333. return;
  334. }
  335. }
  336. //////////////////////////////////////////////////////////////////////////
  337. DbgPendingExpr::DbgPendingExpr()
  338. {
  339. mThreadId = -1;
  340. mCallStackIdx = -1;
  341. mParser = NULL;
  342. mCursorPos = -1;
  343. mExprNode = NULL;
  344. mIdleTicks = 0;
  345. mExplitType = NULL;
  346. mExpressionFlags = DwEvalExpressionFlag_None;
  347. }
  348. DbgPendingExpr::~DbgPendingExpr()
  349. {
  350. delete mParser;
  351. }
  352. // conversion logic based on table at http://en.wikipedia.org/wiki/Extended_precision
  353. //CDH TODO put this somewhere more general
  354. static double ConvertFloat80ToDouble(const byte fp80[10])
  355. {
  356. uint16 e = *((uint16*)&fp80[8]);
  357. uint64 m = *((uint64*)&fp80[0]);
  358. uint64 bit63 = (uint64)1 << 63;
  359. uint64 bit62 = (uint64)1 << 62;
  360. bool isNegative = (e & 0x8000) != 0;
  361. double s = isNegative ? -1.0 : 1.0;
  362. e &= 0x7fff;
  363. if (!e)
  364. {
  365. // the high bit and mantissa content will determine whether it's an actual zero, or a denormal or
  366. // pseudo-denormal number with an effective exponent of -16382. But since that exponent is so far
  367. // below anything we can handle in double-precision (even accounting for denormal bit shifts), we're
  368. // effectively still dealing with zero.
  369. return s * 0.0;
  370. }
  371. else if (e == 0x7fff)
  372. {
  373. if (m & bit63)
  374. {
  375. if (m & bit62)
  376. {
  377. return std::numeric_limits<double>::quiet_NaN();
  378. }
  379. else
  380. {
  381. if (m == bit63)
  382. return s * std::numeric_limits<double>::infinity();
  383. else
  384. return std::numeric_limits<double>::signaling_NaN();
  385. }
  386. }
  387. else
  388. {
  389. return std::numeric_limits<double>::quiet_NaN();
  390. }
  391. }
  392. else
  393. {
  394. if (!(m & bit63))
  395. return std::numeric_limits<double>::quiet_NaN(); // unnormal (we don't handle these since 80387 and later treat them as invalid operands anyway)
  396. // else is a normalized value
  397. }
  398. int useExponent = (int)e - 16383;
  399. if (useExponent < -1022)
  400. return s * 0.0; // we could technically support e from -1023 to -1074 as denormals, but don't bother with that for now.
  401. else if (useExponent > 1023)
  402. return s * HUGE_VAL;
  403. useExponent += 1023;
  404. BF_ASSERT((useExponent > 0) && (useExponent < 0x7ff)); // assume we've filtered for valid exponent range
  405. BF_ASSERT(m & bit63); // assume we've filtered out values that aren't normalized by now
  406. uint64 result = 0;
  407. if (isNegative)
  408. result |= bit63;
  409. result |= (uint64)useExponent << 52;
  410. result |= (m & ~bit63) >> 11;
  411. return *reinterpret_cast<double*>(&result);
  412. }
  413. addr_target NS_BF_DBG::DecodeTargetDataPtr(const char*& strRef)
  414. {
  415. addr_target val = (addr_target)stouln(strRef, sizeof(intptr_target) * 2);
  416. strRef += sizeof(intptr_target) * 2;
  417. return val;
  418. }
  419. WinDebugger::WinDebugger(DebugManager* debugManager) : mDbgSymSrv(this)
  420. {
  421. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  422. mActiveHotIdx = -1;
  423. mGotStartupEvent = false;
  424. mIsContinuingFromException = false;
  425. mDestroying = false;
  426. mDebugManager = debugManager;
  427. mNeedsRehupBreakpoints = false;
  428. mStepInAssembly = false;
  429. mStepSP = 0;
  430. mStepIsRecursing = false;
  431. mStepStopOnNextInstruction = false;
  432. mDebugTarget = NULL;
  433. mShuttingDown = false;
  434. mBfSystem = new BfSystem();
  435. mAtBreakThread = NULL;
  436. mActiveThread = NULL;
  437. mActiveBreakpoint = NULL;
  438. mSteppingThread = NULL;
  439. mExplicitStopThread = NULL;
  440. mStepSwitchedThreads = false;
  441. mIsDebuggerWaiting = false;
  442. mWantsDebugContinue = false;
  443. mContinueFromBreakpointFailed = false;
  444. mIsStepIntoSpecific = false;
  445. mDbgBreak = false;
  446. mDebuggerWaitingThread = NULL;
  447. mStepType = StepType_None;
  448. mOrigStepType = StepType_None;
  449. mLastValidStepIntoPC = 0;
  450. mActiveSymSrvRequest = NULL;
  451. mStoredReturnValueAddr = 0;
  452. #ifdef BF_DBG_32
  453. mCPU = gX86Target->mX86CPU;
  454. #else
  455. mCPU = gX86Target->mX64CPU;
  456. #endif
  457. mRunState = RunState_NotStarted;
  458. mIsRunning = false;
  459. mSavedAtBreakpointAddress = 0;
  460. mSavedBreakpointAddressContinuing = 0;
  461. mRequestedStackFrameIdx = 0;
  462. mShowPCOverride = 0;
  463. mCurNoInfoStepTries = 0;
  464. mDbgAttachFlags = BfDbgAttachFlag_None;
  465. mDbgProcessHandle = 0;
  466. mDbgThreadHandle = 0;
  467. mDbgProcessId = 0;
  468. mDbgHeapData = NULL;
  469. mIsPartialCallStack = true;
  470. for (int i = 0; i < 4; i++)
  471. {
  472. mFreeMemoryBreakIndices.push_back(i);
  473. }
  474. mMemoryBreakpointVersion = 0;
  475. SYSTEM_INFO systemInfo;
  476. GetSystemInfo(&systemInfo);
  477. mPageSize = systemInfo.dwPageSize;
  478. mEmptyDebugTarget = new DebugTarget(this);
  479. mEmptyDebugTarget->CreateEmptyTarget();
  480. mEmptyDebugTarget->mIsEmpty = true;
  481. mDebugTarget = mEmptyDebugTarget;
  482. mDebugPendingExpr = NULL;
  483. mDebugEvalThreadInfo = WdThreadInfo();
  484. mMemCacheAddr = 0;
  485. mDebuggerThreadId = 0;
  486. }
  487. WinDebugger::~WinDebugger()
  488. {
  489. mDestroying = true;
  490. delete gDbgPerfManager;
  491. gDbgPerfManager = NULL;
  492. if ((mDebugTarget != NULL) && (mDebugTarget != mEmptyDebugTarget))
  493. Detach();
  494. for (auto breakpoint : mBreakpoints)
  495. {
  496. auto checkBreakpoint = breakpoint->mLinkedSibling;
  497. while (checkBreakpoint != NULL)
  498. {
  499. auto nextBreakpoint = checkBreakpoint->mLinkedSibling;
  500. delete checkBreakpoint;
  501. checkBreakpoint = nextBreakpoint;
  502. }
  503. delete breakpoint;
  504. }
  505. delete mEmptyDebugTarget;
  506. delete mBfSystem;
  507. for (auto kv : mPendingProfilerMap)
  508. delete kv.mValue;
  509. for (auto profiler : mNewProfilerList)
  510. delete profiler;
  511. delete mDebugPendingExpr;
  512. }
  513. void WinDebugger::Fail(const StringImpl& error)
  514. {
  515. if (mIsRunning)
  516. mDebugManager->mOutMessages.push_back(StrFormat("error %s", error.c_str()));
  517. }
  518. // Leave active thread unpaused
  519. void WinDebugger::ThreadRestorePause(WdThreadInfo* onlyPauseThread, WdThreadInfo* dontPauseThread)
  520. {
  521. BfLogDbg("ThreadRestorePause %d %d\n", (onlyPauseThread != NULL) ? onlyPauseThread->mThreadId : 0, (dontPauseThread != NULL) ? dontPauseThread->mThreadId : 0);
  522. for (auto threadInfo : mThreadList)
  523. {
  524. if (((threadInfo != dontPauseThread) && (!threadInfo->mIsBreakRestorePaused)) &&
  525. ((onlyPauseThread == NULL) || (threadInfo == onlyPauseThread)))
  526. {
  527. BF_ASSERT(!threadInfo->mIsBreakRestorePaused);
  528. BfLogDbg("SuspendThread %d\n", threadInfo->mThreadId);
  529. ::SuspendThread(threadInfo->mHThread);
  530. threadInfo->mIsBreakRestorePaused = true;
  531. }
  532. }
  533. }
  534. void WinDebugger::ThreadRestoreUnpause()
  535. {
  536. BfLogDbg("ThreadRestoreUnpause\n");
  537. for (auto threadInfo : mThreadList)
  538. {
  539. if (threadInfo->mIsBreakRestorePaused)
  540. {
  541. BfLogDbg("ResumeThread %d\n", threadInfo->mThreadId);
  542. ::ResumeThread(threadInfo->mHThread);
  543. threadInfo->mIsBreakRestorePaused = false;
  544. }
  545. }
  546. }
  547. void WinDebugger::UpdateThreadDebugRegisters(WdThreadInfo* threadInfo)
  548. {
  549. if (threadInfo->mMemoryBreakpointVersion == mMemoryBreakpointVersion)
  550. return;
  551. auto threadId = threadInfo->mHThread;
  552. BF_CONTEXT lcContext;
  553. lcContext.ContextFlags = BF_CONTEXT_DEBUG_REGISTERS;
  554. BF_GetThreadContext(threadId, &lcContext);
  555. for (int memoryBreakIdx = 0; memoryBreakIdx < 4; memoryBreakIdx++)
  556. {
  557. WdMemoryBreakpointBind memoryBreakpointBind = mMemoryBreakpoints[memoryBreakIdx];
  558. WdBreakpoint* wdBreakpoint = memoryBreakpointBind.mBreakpoint;
  559. if (wdBreakpoint == NULL)
  560. {
  561. *(&lcContext.Dr0 + memoryBreakIdx) = 0;
  562. lcContext.Dr7 &= ~((1 << (memoryBreakIdx * 2)) | (1 << (16 + memoryBreakIdx * 4)) | (3 << (18 + memoryBreakIdx * 4)));
  563. }
  564. else
  565. {
  566. int sizeCode = 0;
  567. if (memoryBreakpointBind.mByteCount == 2)
  568. sizeCode = 1;
  569. else if (memoryBreakpointBind.mByteCount == 4)
  570. sizeCode = 3;
  571. else if (memoryBreakpointBind.mByteCount == 8)
  572. sizeCode = 2;
  573. addr_target calcAddr = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress + memoryBreakpointBind.mOfs;
  574. BF_ASSERT(calcAddr == memoryBreakpointBind.mAddress);
  575. *(&lcContext.Dr0 + memoryBreakIdx) = calcAddr;
  576. lcContext.Dr7 |= (1 << (memoryBreakIdx * 2)) | (1 << (16 + memoryBreakIdx * 4)) | (sizeCode << (18 + memoryBreakIdx * 4));
  577. }
  578. }
  579. bool worked = BF_SetThreadContext(threadId, &lcContext) != 0;
  580. BF_ASSERT(worked || (mRunState == RunState_Terminating) || (mRunState == RunState_Terminated));
  581. threadInfo->mMemoryBreakpointVersion = mMemoryBreakpointVersion;
  582. }
  583. void WinDebugger::UpdateThreadDebugRegisters()
  584. {
  585. for (auto threadInfo : mThreadList)
  586. {
  587. ::SuspendThread(threadInfo->mHThread);
  588. UpdateThreadDebugRegisters(threadInfo);
  589. ::ResumeThread(threadInfo->mHThread);
  590. }
  591. }
  592. void WinDebugger::PhysSetBreakpoint(addr_target address)
  593. {
  594. BfLogDbg("PhysSetBreakpoint %p\n", address);
  595. uint8 newData = 0xCC;
  596. // This ensure that we have the orig image data cached
  597. DbgMemoryFlags flags = mDebugTarget->ReadOrigImageData(address, NULL, 1);
  598. if ((flags & DbgMemoryFlags_Execute) == 0)
  599. {
  600. BfLogDbg("Breakpoint ignored - execute flag NOT set in breakpoint address\n", address);
  601. BfLogDbg("Memory Flags = %d\n", gDebugger->GetMemoryFlags(address));
  602. return;
  603. }
  604. // Replace it with Breakpoint
  605. SIZE_T dwReadBytes;
  606. BOOL worked = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, &newData, 1, &dwReadBytes);
  607. if (!worked)
  608. {
  609. int err = GetLastError();
  610. BfLogDbg("SetBreakpoint FAILED %p\n", address);
  611. }
  612. FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, 1);
  613. {
  614. uint8 mem = ReadMemory<uint8>(address);
  615. BfLogDbg("Breakpoint byte %X\n", mem);
  616. }
  617. }
  618. void WinDebugger::SetBreakpoint(addr_target address, bool fromRehup)
  619. {
  620. int* countPtr = NULL;
  621. if (mPhysBreakpointAddrMap.TryAdd(address, NULL, &countPtr))
  622. {
  623. BfLogDbg("SetBreakpoint %p\n", address);
  624. *countPtr = 1;
  625. }
  626. else
  627. {
  628. if (fromRehup)
  629. {
  630. BfLogDbg("SetBreakpoint %p Count: %d. Rehup (ignored).\n", address, *countPtr);
  631. return;
  632. }
  633. (*countPtr)++;
  634. BfLogDbg("SetBreakpoint %p Count: %d\n", address, *countPtr);
  635. return;
  636. }
  637. PhysSetBreakpoint(address);
  638. }
  639. void WinDebugger::SetTempBreakpoint(addr_target address)
  640. {
  641. BfLogDbg("SetTempBreakpoint %p\n", address);
  642. mTempBreakpoint.push_back(address);
  643. SetBreakpoint(address);
  644. }
  645. void WinDebugger::PhysRemoveBreakpoint(addr_target address)
  646. {
  647. BfLogDbg("PhysRemoveBreakpoint %p\n", address);
  648. uint8 origData;
  649. DbgMemoryFlags flags = mDebugTarget->ReadOrigImageData(address, &origData, 1);
  650. if ((flags & DbgMemoryFlags_Execute) == 0)
  651. {
  652. //BF_ASSERT("Failed" == 0);
  653. return;
  654. }
  655. SIZE_T dwReadBytes;
  656. if (!WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, &origData, 1, &dwReadBytes))
  657. {
  658. int err = GetLastError();
  659. BfLogDbg("RemoveBreakpoint FAILED %p\n", address);
  660. }
  661. FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, 1);
  662. }
  663. void WinDebugger::RemoveBreakpoint(addr_target address)
  664. {
  665. int* countPtr = NULL;
  666. mPhysBreakpointAddrMap.TryGetValue(address, &countPtr);
  667. // This can happen when we shutdown and we're continuing from a breakpoint
  668. //BF_ASSERT(*countPtr != NULL);
  669. if (countPtr == NULL)
  670. {
  671. BfLogDbg("RemoveBreakpoint %p FAILED\n", address);
  672. return;
  673. }
  674. BfLogDbg("RemoveBreakpoint %p count: %d\n", address, *countPtr);
  675. if (*countPtr > 1)
  676. {
  677. (*countPtr)--;
  678. return;
  679. }
  680. mPhysBreakpointAddrMap.Remove(address);
  681. PhysRemoveBreakpoint(address);
  682. }
  683. void WinDebugger::SingleStepX86()
  684. {
  685. // In what cases did this catch bugs?
  686. // This caused other failures (caught in tests)
  687. // if (mActiveThread->mIsAtBreakpointAddress != 0)
  688. // {
  689. // ContinueFromBreakpoint();
  690. // return;
  691. // }
  692. BfLogDbg("Setup SingleStepX86 ActiveThread: %d\n", (mActiveThread != NULL) ? mActiveThread->mThreadId : -1);
  693. BF_CONTEXT lcContext;
  694. lcContext.ContextFlags = BF_CONTEXT_ALL;
  695. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  696. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  697. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  698. }
  699. bool WinDebugger::IsInRunState()
  700. {
  701. return (mRunState == RunState_Running) || (mRunState == RunState_Running_ToTempBreakpoint);
  702. }
  703. bool WinDebugger::ContinueFromBreakpoint()
  704. {
  705. if (mDebuggerWaitingThread->mFrozen)
  706. {
  707. BfLogDbg("ContinueFromBreakpoint bailout on frozen thread\n");
  708. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  709. mDebuggerWaitingThread->mIsAtBreakpointAddress = 0;
  710. return true;
  711. }
  712. mActiveThread = mDebuggerWaitingThread;
  713. mActiveBreakpoint = NULL;
  714. BfLogDbg("ContinueFromBreakpoint. ActiveThread: %d\n", (mActiveThread != NULL) ? mActiveThread->mThreadId : -1);
  715. BfLogDbg("ResumeThread %d\n", mActiveThread->mThreadId);
  716. BOOL success = ::ResumeThread(mActiveThread->mHThread);
  717. if (success)
  718. {
  719. // It's possible the active thread is suspended - possibly by the GC, so we would deadlock if we
  720. // attempted to pause the other threads
  721. BfLogDbg("SuspendThread %d\n", mActiveThread->mThreadId);
  722. BfLogDbg("Thread already paused!\n");
  723. ::SuspendThread(mActiveThread->mHThread);
  724. return false;
  725. }
  726. ThreadRestorePause(NULL, mActiveThread);
  727. PhysRemoveBreakpoint(mActiveThread->mIsAtBreakpointAddress);
  728. BF_CONTEXT lcContext;
  729. lcContext.ContextFlags = BF_CONTEXT_ALL;
  730. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  731. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  732. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  733. mActiveThread->mStoppedAtAddress = 0;
  734. mActiveThread->mBreakpointAddressContinuing = mActiveThread->mIsAtBreakpointAddress;
  735. mActiveThread->mIsAtBreakpointAddress = 0;
  736. BfLogDbg("ContinueFromBreakpoint set mIsAtBreakpointAddress = 0\n");
  737. return true;
  738. }
  739. void WinDebugger::ValidateBreakpoints()
  740. {
  741. HashSet<addr_target> usedBreakpoints;
  742. std::function<void(WdBreakpoint*)> _AddBreakpoint = [&](WdBreakpoint* breakpoint)
  743. {
  744. if (breakpoint->mAddr != 0)
  745. {
  746. usedBreakpoints.Add(breakpoint->mAddr);
  747. WdBreakpoint* foundBreakpoint = NULL;
  748. auto itr = mBreakpointAddrMap.Find(breakpoint->mAddr);
  749. bool found = false;
  750. while (itr != mBreakpointAddrMap.end())
  751. {
  752. WdBreakpoint* foundBreakpoint = itr->mValue;
  753. found |= foundBreakpoint == breakpoint;
  754. itr.NextWithSameKey(breakpoint->mAddr);
  755. }
  756. BF_ASSERT(found);
  757. }
  758. auto checkSibling = (WdBreakpoint*)breakpoint->mLinkedSibling;
  759. while (checkSibling != NULL)
  760. {
  761. _AddBreakpoint(checkSibling);
  762. checkSibling = (WdBreakpoint*)checkSibling->mLinkedSibling;
  763. }
  764. };
  765. for (auto breakpoint : mBreakpoints)
  766. _AddBreakpoint(breakpoint);
  767. for (auto& entry : mBreakpointAddrMap)
  768. {
  769. BF_ASSERT(usedBreakpoints.Contains(entry.mKey));
  770. }
  771. }
  772. Breakpoint* WinDebugger::FindBreakpointAt(intptr address)
  773. {
  774. #ifdef _DEBUG
  775. //ValidateBreakpoints();
  776. #endif
  777. WdBreakpoint* breakpoint = NULL;
  778. mBreakpointAddrMap.TryGetValue(address, &breakpoint);
  779. return breakpoint;
  780. }
  781. Breakpoint* WinDebugger::GetActiveBreakpoint()
  782. {
  783. if ((mActiveBreakpoint != NULL) && (mActiveBreakpoint->mHead != NULL))
  784. return mActiveBreakpoint->mHead;
  785. return mActiveBreakpoint;
  786. }
  787. void WinDebugger::DebugThreadProc()
  788. {
  789. BpSetThreadName("DebugThread");
  790. BfpThread_SetName(NULL, "DebugThread", NULL);
  791. mDebuggerThreadId = GetCurrentThreadId();
  792. if (!IsMiniDumpDebugger())
  793. {
  794. if (!DoOpenFile(mLaunchPath, mArgs, mWorkingDir, mEnvBlock))
  795. {
  796. if (mDbgProcessId != 0)
  797. OutputRawMessage("error Unable to attach to process");
  798. else
  799. OutputRawMessage(StrFormat("error Failed to launch: %s", mLaunchPath.c_str()));
  800. mShuttingDown = true;
  801. mRunState = RunState_Terminated;
  802. }
  803. }
  804. while (!mShuttingDown)
  805. {
  806. DoUpdate();
  807. }
  808. mIsRunning = false;
  809. for (int i = 0; i < (int) mBreakpoints.size(); i++)
  810. {
  811. WdBreakpoint* wdBreakpoint = mBreakpoints[i];
  812. if (wdBreakpoint->mAddr != 0)
  813. mBreakpointAddrMap.Remove(wdBreakpoint->mAddr, wdBreakpoint);
  814. wdBreakpoint->mAddr = 0;
  815. wdBreakpoint->mLineData = DbgLineDataEx();
  816. wdBreakpoint->mSrcFile = NULL;
  817. if (wdBreakpoint->mLinkedSibling != NULL)
  818. {
  819. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  820. wdBreakpoint->mLinkedSibling = NULL;
  821. }
  822. }
  823. if (!IsMiniDumpDebugger())
  824. {
  825. while (true)
  826. {
  827. if (!mIsDebuggerWaiting)
  828. {
  829. if (!WaitForDebugEvent(&mDebugEvent, 0))
  830. break;
  831. }
  832. if (mDebuggerWaitingThread != NULL)
  833. {
  834. BF_ASSERT_REL((mDebuggerWaitingThread->mIsAtBreakpointAddress == 0) || (mShuttingDown));
  835. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_CONTINUE);
  836. BfLogDbg("::ContinueDebugEvent startup ThreadId:%d\n", mDebuggerWaitingThread->mThreadId);
  837. }
  838. mIsDebuggerWaiting = false;
  839. mDebuggerWaitingThread = NULL;
  840. }
  841. }
  842. mDebuggerThreadId = 0;
  843. }
  844. static void DebugThreadProcThunk(void* winDebugger)
  845. {
  846. ((WinDebugger*) winDebugger)->DebugThreadProc();
  847. }
  848. int WinDebugger::GetAddrSize()
  849. {
  850. return sizeof(addr_target);
  851. }
  852. bool WinDebugger::CanOpen(const StringImpl& fileName, DebuggerResult* outResult)
  853. {
  854. FILE* fp = fopen(fileName.c_str(), "rb");
  855. if (fp == NULL)
  856. {
  857. *outResult = DebuggerResult_CannotOpen;
  858. return false;
  859. }
  860. FileStream fs;
  861. fs.mFP = fp;
  862. *outResult = DebuggerResult_Ok;
  863. bool canRead = DbgModule::CanRead(&fs, outResult);
  864. fclose(fp);
  865. return canRead;
  866. }
  867. void WinDebugger::OpenFile(const StringImpl& launchPath, const StringImpl& targetPath, const StringImpl& args, const StringImpl& workingDir, const Array<uint8>& envBlock, bool hotSwapEnabled)
  868. {
  869. BF_ASSERT(!mIsRunning);
  870. mLaunchPath = launchPath;
  871. mTargetPath = targetPath;
  872. mArgs = args;
  873. mWorkingDir = workingDir;
  874. mEnvBlock = envBlock;
  875. mHotSwapEnabled = hotSwapEnabled;
  876. mDebugTarget = new DebugTarget(this);
  877. }
  878. bool WinDebugger::Attach(int processId, BfDbgAttachFlags attachFlags)
  879. {
  880. BF_ASSERT(!mIsRunning);
  881. mDbgAttachFlags = attachFlags;
  882. mDbgProcessHandle = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)processId);
  883. if (mDbgProcessHandle == 0)
  884. return false;
  885. BOOL is32Bit = false;
  886. if (!IsWow64Process(mDbgProcessHandle, &is32Bit))
  887. {
  888. mDbgProcessHandle = 0;
  889. ::CloseHandle(mDbgProcessHandle);
  890. return false;
  891. }
  892. bool want32Bit = sizeof(intptr_target) == 4;
  893. if (want32Bit != (is32Bit != 0))
  894. {
  895. mDbgProcessHandle = 0;
  896. ::CloseHandle(mDbgProcessHandle);
  897. return false;
  898. }
  899. HMODULE mainModule = 0;
  900. DWORD memNeeded = 0;
  901. ::EnumProcessModules(mDbgProcessHandle, &mainModule, sizeof(HMODULE), &memNeeded);
  902. WCHAR fileName[MAX_PATH] = {0};
  903. GetModuleFileNameExW(mDbgProcessHandle, mainModule, fileName, MAX_PATH);
  904. mLaunchPath = UTF8Encode(fileName);
  905. mTargetPath = mLaunchPath;
  906. mDbgProcessId = processId;
  907. mDbgProcessHandle = 0;
  908. ::CloseHandle(mDbgProcessHandle);
  909. mDebugTarget = new DebugTarget(this);
  910. return true;
  911. }
  912. void WinDebugger::Run()
  913. {
  914. mIsRunning = true;
  915. DWORD localThreadId;
  916. HANDLE hThread = ::CreateThread(NULL, 64 * 1024, (LPTHREAD_START_ROUTINE) &DebugThreadProcThunk, (void*)this, 0, &localThreadId);
  917. CloseHandle(hThread);
  918. }
  919. void WinDebugger::HotLoad(const Array<String>& objectFiles, int hotIdx)
  920. {
  921. AutoCrit autoCrit(mDebugManager->mCritSect);
  922. if (mDebugTarget->mTargetBinary == NULL)
  923. {
  924. Fail("Hot swapping failed because the hot target binary has not yet been loaded.");
  925. return;
  926. }
  927. if (mDebugTarget->mHotHeap == NULL)
  928. {
  929. Fail("There is no hot heap space available for hot swapping.");
  930. return;
  931. }
  932. BfLogDbg("WinDebugger::HotLoad Start %d\n", hotIdx);
  933. SetAndRestoreValue<int> prevHotIdx(mActiveHotIdx, hotIdx);
  934. BF_ASSERT(mHotThreadStates.empty());
  935. mHotThreadStates.Resize(mThreadList.size());
  936. for (int threadIdx = 0; threadIdx < (int)mThreadList.size(); threadIdx++)
  937. {
  938. WdThreadInfo* threadInfo = mThreadList[threadIdx];
  939. SetAndRestoreValue<WdThreadInfo*> prevActiveThread(mActiveThread, threadInfo);
  940. BfLogDbg("SuspendThread %d\n", threadInfo->mThreadId);
  941. ::SuspendThread(threadInfo->mHThread);
  942. mHotThreadStates[threadIdx].mThreadId = threadInfo->mThreadId;
  943. PopulateRegisters(&mHotThreadStates[threadIdx].mRegisters);
  944. }
  945. for (auto address : mTempBreakpoint)
  946. RemoveBreakpoint(address);
  947. mTempBreakpoint.Clear();
  948. mStepBreakpointAddrs.Clear();
  949. for (auto breakpoint : mBreakpoints)
  950. {
  951. DetachBreakpoint(breakpoint);
  952. }
  953. int startingModuleIdx = (int)mDebugTarget->mDbgModules.size();
  954. bool failed = false;
  955. for (auto fileName : objectFiles)
  956. {
  957. BfLogDbg("WinDebugger::HotLoad: %s\n", fileName.c_str());
  958. DbgModule* newBinary = mDebugTarget->HotLoad(fileName, hotIdx);
  959. if ((newBinary != NULL) && (newBinary->mFailed))
  960. failed = true;
  961. }
  962. for (int moduleIdx = startingModuleIdx; moduleIdx < (int)mDebugTarget->mDbgModules.size(); moduleIdx++)
  963. {
  964. auto dbgModule = mDebugTarget->mDbgModules[moduleIdx];
  965. BF_ASSERT(dbgModule->IsObjectFile());
  966. BF_ASSERT(dbgModule->mHotIdx == hotIdx);
  967. dbgModule->FinishHotSwap();
  968. }
  969. for (auto dwarf : mDebugTarget->mDbgModules)
  970. dwarf->RevertWritingEnable();
  971. int blockAllocSinceClean = mDebugTarget->mHotHeap->mBlockAllocIdx - mDebugTarget->mLastHotHeapCleanIdx;
  972. // Clean up the hot heap every 64MB
  973. int blocksBetweenCleans = (64 * 1024 * 1024) / HotHeap::BLOCK_SIZE;
  974. #ifdef _DEBUG
  975. //TODO: This is just for testing
  976. blocksBetweenCleans = 1;
  977. #endif
  978. //TODO: Put this back after we fix the cleanup
  979. if (blockAllocSinceClean >= blocksBetweenCleans)
  980. CleanupHotHeap();
  981. mDebugTarget->RehupSrcFiles();
  982. for (int breakIdx = 0; breakIdx < (int)mBreakpoints.size(); breakIdx++)
  983. {
  984. auto breakpoint = mBreakpoints[breakIdx];
  985. CheckBreakpoint(breakpoint);
  986. }
  987. for (int hotThreadIdx = 0; hotThreadIdx < (int)mHotThreadStates.size(); hotThreadIdx++)
  988. {
  989. auto& hotThreadState = mHotThreadStates[hotThreadIdx];
  990. WdThreadInfo* threadInfo = NULL;
  991. if (!mThreadMap.TryGetValue((uint32)hotThreadState.mThreadId, &threadInfo))
  992. continue;
  993. BfLogDbg("ResumeThread %d\n", threadInfo->mThreadId);
  994. ::ResumeThread(threadInfo->mHThread);
  995. }
  996. mHotThreadStates.Clear();
  997. if (IsPaused())
  998. {
  999. ClearCallStack();
  1000. UpdateCallStack();
  1001. }
  1002. }
  1003. void WinDebugger::InitiateHotResolve(DbgHotResolveFlags flags)
  1004. {
  1005. AutoCrit autoCrit(mDebugManager->mCritSect);
  1006. delete mHotResolveData;
  1007. mHotResolveData = NULL;
  1008. mHotResolveData = new DbgHotResolveData();
  1009. DbgHotScanner* hotScanner = new DbgHotScanner(this);
  1010. hotScanner->Scan(flags);
  1011. delete hotScanner;
  1012. }
  1013. intptr WinDebugger::GetDbgAllocHeapSize()
  1014. {
  1015. if (mDbgHeapData == NULL)
  1016. {
  1017. Beefy::String memName = StrFormat("BFGC_stats_%d", mProcessInfo.dwProcessId);
  1018. mDbgHeapData = new WinDbgHeapData();
  1019. mDbgHeapData->mFileMapping = ::OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, memName.c_str());
  1020. if (mDbgHeapData->mFileMapping == 0)
  1021. {
  1022. delete mDbgHeapData;
  1023. mDbgHeapData = NULL;
  1024. return 0;
  1025. }
  1026. mDbgHeapData->mStats = (WinDbgHeapData::Stats*)MapViewOfFile(mDbgHeapData->mFileMapping, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(WinDbgHeapData::Stats));
  1027. }
  1028. if (mDbgHeapData->mStats == NULL)
  1029. return 0;
  1030. return mDbgHeapData->mStats->mHeapSize;
  1031. }
  1032. String WinDebugger::GetDbgAllocInfo()
  1033. {
  1034. AutoCrit autoCrit(mDebugManager->mCritSect);
  1035. for (auto threadInfo : mThreadList)
  1036. ::SuspendThread(threadInfo->mHThread);
  1037. delete mHotResolveData;
  1038. mHotResolveData = NULL;
  1039. mHotResolveData = new DbgHotResolveData();
  1040. DbgHotScanner* hotScanner = new DbgHotScanner(this);
  1041. hotScanner->Scan(DbgHotResolveFlag_Allocations);
  1042. delete hotScanner;
  1043. String result;
  1044. if (mHotResolveData != NULL)
  1045. {
  1046. DbgExprEvaluator exprEvaluator(this, NULL, NULL, -1, -1);
  1047. exprEvaluator.mDebugTarget = mDebugTarget;
  1048. String typeName;
  1049. result += ":types\n";
  1050. for (int typeId = 0; typeId < mHotResolveData->mTypeData.size(); typeId++)
  1051. {
  1052. auto& typeData = mHotResolveData->mTypeData[typeId];
  1053. if (typeData.mCount > 0)
  1054. {
  1055. auto type = exprEvaluator.GetBeefTypeById(typeId);
  1056. typeName.Clear();
  1057. exprEvaluator.BeefTypeToString(type, typeName);
  1058. if (typeName.IsEmpty())
  1059. typeName = StrFormat("Type #%d", typeId);
  1060. result += StrFormat("type\t%d\t%s\t%lld\t%lld\n", typeId, typeName.c_str(), typeData.mCount, typeData.mSize);
  1061. }
  1062. }
  1063. }
  1064. for (auto threadInfo : mThreadList)
  1065. ::ResumeThread(threadInfo->mHThread);
  1066. return result;
  1067. }
  1068. bool WinDebugger::DoOpenFile(const StringImpl& fileName, const StringImpl& args, const StringImpl& workingDir, const Array<uint8>& envBlock)
  1069. {
  1070. BP_ZONE("WinDebugger::DoOpenFile");
  1071. AutoCrit autoCrit(mDebugManager->mCritSect);
  1072. //gDbgPerfManager->StartRecording();
  1073. STARTUPINFOW si;
  1074. ZeroMemory(&si, sizeof(si));
  1075. si.cb = sizeof(si);
  1076. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  1077. if (mDbgProcessId != 0)
  1078. {
  1079. BOOL success = ::DebugActiveProcess(mDbgProcessId);
  1080. if (!success)
  1081. return false;
  1082. mProcessInfo.dwProcessId = mDbgProcessId;
  1083. }
  1084. else
  1085. {
  1086. BP_ZONE("DoOpenFile_CreateProcessW");
  1087. UTF16String envW;
  1088. DWORD flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS | CREATE_DEFAULT_ERROR_MODE;
  1089. void* envPtr = NULL;
  1090. if (!envBlock.IsEmpty())
  1091. {
  1092. //UTF16?
  1093. if (envBlock[1] == 0)
  1094. {
  1095. envPtr = (void*)&envBlock[0];
  1096. flags |= CREATE_UNICODE_ENVIRONMENT;
  1097. }
  1098. else
  1099. {
  1100. String str8((char*)&envBlock[0], (int)envBlock.size());
  1101. envW = UTF8Decode(str8);
  1102. envPtr = (void*)envW.c_str();
  1103. flags |= CREATE_UNICODE_ENVIRONMENT;
  1104. }
  1105. }
  1106. String cmdLine = "\"";
  1107. cmdLine += fileName;
  1108. cmdLine += "\"";
  1109. if (!args.IsEmpty())
  1110. {
  1111. cmdLine += " ";
  1112. cmdLine += args;
  1113. }
  1114. BOOL worked = CreateProcessW(NULL, (WCHAR*)UTF8Decode(cmdLine).c_str(), NULL, NULL, FALSE,
  1115. flags, envPtr, (WCHAR*)UTF8Decode(workingDir).c_str(), &si, &mProcessInfo);
  1116. if (!worked)
  1117. {
  1118. auto lastError = ::GetLastError();
  1119. if (lastError == ERROR_DIRECTORY)
  1120. {
  1121. mDebugManager->mOutMessages.push_back(StrFormat("error Unable to locate specified working directory '%s'", SlashString(workingDir, false, false).c_str()));
  1122. }
  1123. return false;
  1124. }
  1125. WdThreadInfo* threadInfo = new WdThreadInfo();
  1126. threadInfo->mProcessId = mProcessInfo.dwProcessId;
  1127. threadInfo->mThreadId = mProcessInfo.dwThreadId;
  1128. threadInfo->mHThread = mProcessInfo.hThread;
  1129. threadInfo->mThreadLocalBase = NULL;
  1130. threadInfo->mStartAddress = NULL;
  1131. mThreadMap[mProcessInfo.dwThreadId] = threadInfo;
  1132. mThreadList.push_back(threadInfo);
  1133. }
  1134. mRunState = RunState_Running;
  1135. while (true)
  1136. {
  1137. BP_ZONE("DoOpenFile_WaitForImageBase");
  1138. autoCrit.mCritSect->Unlock();
  1139. DoUpdate();
  1140. autoCrit.mCritSect->Lock();
  1141. ContinueDebugEvent();
  1142. if ((mDebugTarget->mLaunchBinary != NULL) && (mDebugTarget->mLaunchBinary->mOrigImageData != NULL))
  1143. break;
  1144. }
  1145. RehupBreakpoints(true);
  1146. //gDbgPerfManager->StopRecording();
  1147. //gDbgPerfManager->DbgPrint();
  1148. return true;
  1149. }
  1150. void WinDebugger::StopDebugging()
  1151. {
  1152. AutoCrit autoCrit(mDebugManager->mCritSect);
  1153. BfLogDbg("WinDebugger::Terminate\n");
  1154. if (mActiveSymSrvRequest != NULL)
  1155. mActiveSymSrvRequest->Cancel();
  1156. if ((mRunState == RunState_NotStarted) || (mRunState == RunState_Terminated) || (mRunState == RunState_Terminating))
  1157. return;
  1158. if ((mDbgProcessId != 0) && ((mDbgAttachFlags & BfDbgAttachFlag_ShutdownOnExit) == 0))
  1159. {
  1160. for (auto address : mTempBreakpoint)
  1161. RemoveBreakpoint(address);
  1162. for (auto breakpoint : mBreakpoints)
  1163. DetachBreakpoint(breakpoint);
  1164. BfLogDbg("StopDebugging\n");
  1165. ::DebugActiveProcessStop(mDbgProcessId);
  1166. mRunState = RunState_Terminated;
  1167. BfLogDbg("mRunState = RunState_Terminated\n");
  1168. }
  1169. else
  1170. {
  1171. TerminateProcess(mProcessInfo.hProcess, 0);
  1172. mRunState = RunState_Terminating;
  1173. BfLogDbg("mRunState = RunState_Terminating\n");
  1174. }
  1175. }
  1176. void WinDebugger::Terminate()
  1177. {
  1178. AutoCrit autoCrit(mDebugManager->mCritSect);
  1179. BfLogDbg("WinDebugger::Terminate\n");
  1180. if (mActiveSymSrvRequest != NULL)
  1181. mActiveSymSrvRequest->Cancel();
  1182. if ((mRunState == RunState_NotStarted) || (mRunState == RunState_Terminated) || (mRunState == RunState_Terminating))
  1183. return;
  1184. TerminateProcess(mProcessInfo.hProcess, 0);
  1185. mRunState = RunState_Terminating;
  1186. BfLogDbg("mRunState = RunState_Terminating\n");
  1187. }
  1188. static int gDebugUpdateCnt = 0;
  1189. void WinDebugger::Detach()
  1190. {
  1191. BfLogDbg("Debugger Detach\n");
  1192. mDebugManager->mNetManager->CancelAll();
  1193. while ((mIsRunning) || (mDebuggerThreadId != 0))
  1194. {
  1195. mShuttingDown = true;
  1196. Sleep(1);
  1197. }
  1198. for (auto profiler : mProfilerSet)
  1199. profiler->Stop();
  1200. BfLogDbg("Debugger Detach - thread finished\n");
  1201. mPendingProfilerMap.Clear();
  1202. for (auto profiler : mNewProfilerList)
  1203. delete profiler;
  1204. mNewProfilerList.Clear();
  1205. mPendingImageLoad.Clear();
  1206. mPendingDebugInfoLoad.Clear();
  1207. RemoveTempBreakpoints();
  1208. mContinueEvent.Reset();
  1209. if (mDebugTarget != mEmptyDebugTarget)
  1210. delete mDebugTarget;
  1211. mDebugTarget = mEmptyDebugTarget;
  1212. mShuttingDown = false;
  1213. mStepSP = 0;
  1214. ClearCallStack();
  1215. mRunState = RunState_NotStarted;
  1216. mStepType = StepType_None;
  1217. mHadImageFindError = false;
  1218. mIsPartialCallStack = true;
  1219. delete mDebugPendingExpr;
  1220. mDebugPendingExpr = NULL;
  1221. for (auto threadPair : mThreadMap)
  1222. {
  1223. auto threadInfo = threadPair.mValue;
  1224. delete threadInfo;
  1225. }
  1226. mThreadMap.Clear();
  1227. mThreadList.Clear();
  1228. mHotTargetMemory.Clear();
  1229. // We don't need to close the hThread when we have attached to a process
  1230. if (mDbgProcessId == 0)
  1231. {
  1232. CloseHandle(mProcessInfo.hThread);
  1233. CloseHandle(mProcessInfo.hProcess);
  1234. }
  1235. for (auto breakpoint : mBreakpoints)
  1236. {
  1237. if (!mDestroying)
  1238. {
  1239. BF_FATAL("Breakpoints should be deleted already");
  1240. }
  1241. if (breakpoint->mMemoryBreakpointInfo != NULL)
  1242. {
  1243. DetachBreakpoint(breakpoint);
  1244. }
  1245. }
  1246. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  1247. mStepBreakpointAddrs.Clear();
  1248. mIsRunning = false;
  1249. mDbgAttachFlags = BfDbgAttachFlag_None;
  1250. mDbgProcessId = 0;
  1251. delete mDbgHeapData;
  1252. mDbgHeapData = NULL;
  1253. mDbgProcessHandle = 0;
  1254. ClearCallStack();
  1255. mWantsDebugContinue = false;
  1256. mAtBreakThread = NULL;
  1257. mActiveThread = NULL;
  1258. mActiveBreakpoint = NULL;
  1259. mSteppingThread = NULL;
  1260. mExplicitStopThread = NULL;
  1261. mIsContinuingFromException = false;
  1262. mGotStartupEvent = false;
  1263. mIsDebuggerWaiting = false;
  1264. mPhysBreakpointAddrMap.Clear();
  1265. mBreakpointAddrMap.Clear();
  1266. gDebugUpdateCnt = 0;
  1267. }
  1268. Profiler* WinDebugger::StartProfiling()
  1269. {
  1270. return new DbgProfiler(this);
  1271. }
  1272. Profiler* WinDebugger::PopProfiler()
  1273. {
  1274. AutoCrit autoCrit(mDebugManager->mCritSect);
  1275. if (mNewProfilerList.IsEmpty())
  1276. return NULL;
  1277. auto profiler = (DbgProfiler*)mNewProfilerList[0];
  1278. mNewProfilerList.erase(mNewProfilerList.begin());
  1279. return profiler;
  1280. }
  1281. void WinDebugger::AddProfiler(DbgProfiler * profiler)
  1282. {
  1283. AutoCrit autoCrit(mDebugManager->mCritSect);
  1284. mProfilerSet.Add(profiler);
  1285. }
  1286. void WinDebugger::RemoveProfiler(DbgProfiler * profiler)
  1287. {
  1288. AutoCrit autoCrit(mDebugManager->mCritSect);
  1289. mProfilerSet.Remove(profiler);
  1290. }
  1291. void WinDebugger::ReportMemory(MemReporter* memReporter)
  1292. {
  1293. mEmptyDebugTarget->ReportMemory(memReporter);
  1294. if (mDebugTarget != mEmptyDebugTarget)
  1295. mDebugTarget->ReportMemory(memReporter);
  1296. }
  1297. void WinDebugger::ModuleChanged(DbgModule* dbgModule)
  1298. {
  1299. mDebugManager->mOutMessages.push_back(String("dbgInfoLoaded ") + dbgModule->mFilePath);
  1300. }
  1301. bool WinDebugger::DoUpdate()
  1302. {
  1303. if ((mDbgProcessId != 0) && ((mDbgAttachFlags & BfDbgAttachFlag_ShutdownOnExit) == 0))
  1304. ::DebugSetProcessKillOnExit(FALSE);
  1305. else
  1306. ::DebugSetProcessKillOnExit(TRUE);
  1307. //
  1308. {
  1309. AutoCrit autoCrit(mDebugManager->mCritSect);
  1310. auto _ModuleChanged = [&](DbgModule* dbgModule)
  1311. {
  1312. ModuleChanged(dbgModule);
  1313. ClearCallStack(); // We may have actual dbgSubprograms and stuff now...
  1314. };
  1315. for (auto dbgModule : mPendingImageLoad)
  1316. {
  1317. dbgModule->PreCacheImage();
  1318. }
  1319. for (auto kv : mPendingDebugInfoLoad)
  1320. {
  1321. kv.mKey->PreCacheDebugInfo();
  1322. }
  1323. while (!mPendingImageLoad.IsEmpty())
  1324. {
  1325. auto dbgModule = mPendingImageLoad.back();
  1326. mPendingImageLoad.pop_back();
  1327. dbgModule->RequestImage();
  1328. _ModuleChanged(dbgModule);
  1329. }
  1330. if (!mPendingDebugInfoLoad.IsEmpty())
  1331. {
  1332. Array<DbgPendingDebugInfoLoad> pendingList;
  1333. for (auto kv : mPendingDebugInfoLoad)
  1334. pendingList.Add(kv.mValue);
  1335. mPendingDebugInfoLoad.Clear();
  1336. for (auto& entry : pendingList)
  1337. {
  1338. auto dbgModule = entry.mModule;
  1339. entry.mModule->RequestDebugInfo(entry.mAllowRemote);
  1340. // We do a "_ModuleChanged" even if the load failed, so we rehup the callstack and stop
  1341. // saying "<Loading...>"
  1342. _ModuleChanged(entry.mModule);
  1343. }
  1344. }
  1345. }
  1346. if (IsMiniDumpDebugger())
  1347. {
  1348. //
  1349. {
  1350. AutoCrit autoCrit(mDebugManager->mCritSect);
  1351. if (mRunState == RunState_Terminating)
  1352. {
  1353. mRunState = RunState_Terminated;
  1354. return false;
  1355. }
  1356. }
  1357. Sleep(20);
  1358. return false;
  1359. }
  1360. if (mIsDebuggerWaiting)
  1361. {
  1362. if ((IsInRunState()) || (mRunState == RunState_Terminating) || (mRunState == RunState_DebugEval))
  1363. ContinueDebugEvent();
  1364. if (mContinueEvent.WaitFor(8))
  1365. {
  1366. BF_ASSERT(!mWantsDebugContinue); // mWantsDebugContinue should already been reset
  1367. BfLogDbg("::ContinueDebugEvent 1 ThreadId:%d\n", mDebuggerWaitingThread->mThreadId);
  1368. BF_ASSERT_REL(mDebuggerWaitingThread->mIsAtBreakpointAddress == 0);
  1369. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, mIsContinuingFromException ? DBG_EXCEPTION_NOT_HANDLED : DBG_CONTINUE);
  1370. mIsContinuingFromException = false;
  1371. mIsDebuggerWaiting = false;
  1372. mDebuggerWaitingThread = NULL;
  1373. }
  1374. else
  1375. return false;
  1376. }
  1377. if (!WaitForDebugEvent(&mDebugEvent, 8))
  1378. return false;
  1379. gDebugUpdateCnt++;
  1380. static const char* eventNames[] = { "DBG_EVENT ?",
  1381. "EXCEPTION_DEBUG_EVENT",
  1382. "CREATE_THREAD_DEBUG_EVENT",
  1383. "CREATE_PROCESS_DEBUG_EVENT",
  1384. "EXIT_THREAD_DEBUG_EVENT",
  1385. "EXIT_PROCESS_DEBUG_EVENT",
  1386. "LOAD_DLL_DEBUG_EVENT",
  1387. "UNLOAD_DLL_DEBUG_EVENT",
  1388. "OUTPUT_DEBUG_STRING_EVENT",
  1389. "RIP_EVENT"};
  1390. BfLogDbg("WaitForDebugEvent %s ThreadId:%d\n", eventNames[mDebugEvent.dwDebugEventCode], mDebugEvent.dwThreadId);
  1391. BP_ZONE(eventNames[mDebugEvent.dwDebugEventCode]);
  1392. AutoCrit autoCrit(mDebugManager->mCritSect);
  1393. mActiveBreakpoint = NULL;
  1394. mIsDebuggerWaiting = true;
  1395. mWantsDebugContinue = true;
  1396. mRequestedStackFrameIdx = 0;
  1397. mBreakStackFrameIdx = 0;
  1398. mShowPCOverride = 0;
  1399. WdThreadInfo* threadInfo = NULL;
  1400. mThreadMap.TryGetValue(mDebugEvent.dwThreadId, &threadInfo);
  1401. mDebuggerWaitingThread = threadInfo;
  1402. mExplicitStopThread = mDebuggerWaitingThread;
  1403. switch (mDebugEvent.dwDebugEventCode)
  1404. {
  1405. case CREATE_PROCESS_DEBUG_EVENT:
  1406. {
  1407. if (threadInfo == NULL)
  1408. {
  1409. BF_ASSERT(mThreadMap.size() == 0);
  1410. WdThreadInfo* newThreadInfo = new WdThreadInfo();
  1411. newThreadInfo->mProcessId = mDebugEvent.dwProcessId;
  1412. newThreadInfo->mThreadId = mDebugEvent.dwThreadId;
  1413. newThreadInfo->mHThread = mDebugEvent.u.CreateProcessInfo.hThread;
  1414. newThreadInfo->mThreadLocalBase = mDebugEvent.u.CreateProcessInfo.lpThreadLocalBase;
  1415. newThreadInfo->mStartAddress = (void*)mDebugEvent.u.CreateProcessInfo.lpStartAddress;
  1416. BF_CONTEXT lcContext;
  1417. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1418. BF_GetThreadContext(newThreadInfo->mHThread, &lcContext);
  1419. newThreadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1420. mThreadMap[mDebugEvent.dwThreadId] = newThreadInfo;
  1421. mDebuggerWaitingThread = newThreadInfo;
  1422. mThreadList.push_back(mDebuggerWaitingThread);
  1423. UpdateThreadDebugRegisters();
  1424. OutputMessage(StrFormat("Creating thread from CREATE_PROCESS_DEBUG_EVENT %d\n", mDebugEvent.dwThreadId));
  1425. threadInfo = mDebuggerWaitingThread;
  1426. mProcessInfo.dwThreadId = threadInfo->mThreadId;
  1427. mProcessInfo.hThread = threadInfo->mHThread;
  1428. mProcessInfo.hProcess = mDebugEvent.u.CreateProcessInfo.hProcess;
  1429. }
  1430. else
  1431. {
  1432. threadInfo->mThreadLocalBase = mDebugEvent.u.CreateProcessInfo.lpThreadLocalBase;
  1433. threadInfo->mStartAddress = (void*)mDebugEvent.u.CreateProcessInfo.lpStartAddress;
  1434. }
  1435. BF_CONTEXT lcContext;
  1436. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1437. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1438. threadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1439. DbgModule* launchBinary = mDebugTarget->Init(mLaunchPath, mTargetPath, (addr_target)(intptr)mDebugEvent.u.CreateProcessInfo.lpBaseOfImage);
  1440. addr_target gotImageBase = (addr_target)(intptr)mDebugEvent.u.CreateProcessInfo.lpBaseOfImage;
  1441. if (launchBinary->mImageBase != gotImageBase)
  1442. {
  1443. BF_FATAL("Image base didn't match");
  1444. }
  1445. launchBinary->mImageBase = gotImageBase;
  1446. launchBinary->mImageSize = (int)launchBinary->GetImageSize();
  1447. launchBinary->mOrigImageData = new DbgModuleMemoryCache(launchBinary->mImageBase, launchBinary->mImageSize);
  1448. if (launchBinary == mDebugTarget->mTargetBinary)
  1449. mDebugTarget->SetupTargetBinary();
  1450. if (mDebugEvent.u.CreateProcessInfo.hFile != NULL)
  1451. CloseHandle(mDebugEvent.u.CreateProcessInfo.hFile);
  1452. mDbgProcessHandle = mDebugEvent.u.CreateProcessInfo.hProcess;
  1453. mDbgThreadHandle = mDebugEvent.u.CreateProcessInfo.hThread;
  1454. mGotStartupEvent = true;
  1455. mDebugManager->mOutMessages.push_back("modulesChanged");
  1456. }
  1457. break;
  1458. case EXIT_PROCESS_DEBUG_EVENT:
  1459. {
  1460. BfLogDbg("EXIT_PROCESS_DEBUG_EVENT\n");
  1461. DWORD exitCode = mDebugEvent.u.ExitProcess.dwExitCode;
  1462. String exitMessage;
  1463. switch (exitCode)
  1464. {
  1465. case STATUS_DLL_NOT_FOUND:
  1466. exitMessage = "STATUS_DLL_NOT_FOUND";
  1467. break;
  1468. case STATUS_DLL_INIT_FAILED:
  1469. exitMessage = "STATUS_DLL_INIT_FAILED";
  1470. break;
  1471. case STATUS_ENTRYPOINT_NOT_FOUND:
  1472. exitMessage = "STATUS_ENTRYPOINT_NOT_FOUND";
  1473. break;
  1474. }
  1475. String exitCodeStr;
  1476. if ((exitCode >= 0x10000000) && (exitCode <= 0xF7000000))
  1477. exitCodeStr = StrFormat("0x%X", exitCode);
  1478. else
  1479. exitCodeStr = StrFormat("%d", exitCode);
  1480. if (!exitMessage.IsEmpty())
  1481. OutputMessage(StrFormat("Process terminated. ExitCode: %s (%s).\n", exitCodeStr.c_str(), exitMessage.c_str()));
  1482. else
  1483. OutputMessage(StrFormat("Process terminated. ExitCode: %s.\n", exitCodeStr.c_str()));
  1484. mRunState = RunState_Terminated;
  1485. mDebugManager->mOutMessages.push_back("modulesChanged");
  1486. }
  1487. break;
  1488. case LOAD_DLL_DEBUG_EVENT:
  1489. {
  1490. WCHAR moduleNameStr[MAX_PATH] = { 0 };
  1491. GetFinalPathNameByHandleW(mDebugEvent.u.LoadDll.hFile, moduleNameStr, MAX_PATH, FILE_NAME_NORMALIZED);
  1492. std::wstring wow64Dir;
  1493. std::wstring systemDir;
  1494. PWSTR wow64DirPtr = NULL;
  1495. SHGetKnownFolderPath(FOLDERID_SystemX86, KF_FLAG_NO_ALIAS, NULL, &wow64DirPtr);
  1496. if (wow64DirPtr != NULL)
  1497. {
  1498. wow64Dir = wow64DirPtr;
  1499. CoTaskMemFree(wow64DirPtr);
  1500. }
  1501. PWSTR systemDirPtr = NULL;
  1502. SHGetKnownFolderPath(FOLDERID_System, KF_FLAG_NO_ALIAS, NULL, &systemDirPtr);
  1503. if (systemDirPtr != NULL)
  1504. {
  1505. systemDir = systemDirPtr;
  1506. CoTaskMemFree(systemDirPtr);
  1507. }
  1508. if ((mDebugEvent.u.LoadDll.lpImageName != 0) && (mDebugEvent.u.LoadDll.fUnicode))
  1509. {
  1510. addr_target strAddr = ReadMemory<addr_target>((addr_target)(intptr)mDebugEvent.u.LoadDll.lpImageName);
  1511. for (int i = 0; i < MAX_PATH - 1; i++)
  1512. {
  1513. WCHAR c = ReadMemory<WCHAR>(strAddr + i*2);
  1514. moduleNameStr[i] = (WCHAR)c;
  1515. if (c == 0)
  1516. break;
  1517. }
  1518. }
  1519. String origModuleName = UTF8Encode(moduleNameStr);
  1520. String moduleName = origModuleName;
  1521. String loadMsg;
  1522. HANDLE altFileHandle = INVALID_HANDLE_VALUE;
  1523. if (moduleName != origModuleName)
  1524. {
  1525. loadMsg = StrFormat("Loading DLL: %s(%s) @ %s", origModuleName.c_str(), moduleName.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.LoadDll.lpBaseOfDll, true).c_str());
  1526. altFileHandle = ::CreateFileW(UTF8Decode(moduleName).c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  1527. }
  1528. else
  1529. {
  1530. loadMsg = StrFormat("Loading DLL: %s @ %s", moduleName.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.LoadDll.lpBaseOfDll, true).c_str());
  1531. }
  1532. BfLogDbg("LOAD_DLL_DEBUG_EVENT %s\n", moduleName.c_str());
  1533. bool skipLoad = false;
  1534. #ifdef BF_DBG_32
  1535. if (((uintptr)mDebugEvent.u.LoadDll.lpBaseOfDll & 0xFFFFFFFF00000000LL) != 0)
  1536. {
  1537. skipLoad = true;
  1538. loadMsg += " - Skipped";
  1539. }
  1540. #endif
  1541. if (!skipLoad)
  1542. {
  1543. FileHandleStream stream;
  1544. stream.mFileHandle = mDebugEvent.u.LoadDll.hFile;
  1545. if (altFileHandle != INVALID_HANDLE_VALUE)
  1546. stream.mFileHandle = altFileHandle;
  1547. if (mDebugTarget->SetupDyn(moduleName, &stream, (intptr)mDebugEvent.u.LoadDll.lpBaseOfDll) == NULL)
  1548. loadMsg += " - Failed to load";
  1549. stream.mFileHandle = 0;
  1550. }
  1551. OutputMessage(loadMsg + "\n");
  1552. if (altFileHandle != INVALID_HANDLE_VALUE)
  1553. ::CloseHandle(altFileHandle);
  1554. ::CloseHandle(mDebugEvent.u.LoadDll.hFile);
  1555. // Try to bind any breakpoints tied to this DLL
  1556. RehupBreakpoints(true);
  1557. mDebugManager->mOutMessages.push_back("modulesChanged");
  1558. }
  1559. break;
  1560. case UNLOAD_DLL_DEBUG_EVENT:
  1561. {
  1562. bool needsBreakpointRehup = false;
  1563. String name = "???";
  1564. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress((addr_target)(intptr)mDebugEvent.u.UnloadDll.lpBaseOfDll);
  1565. if (dbgModule != NULL)
  1566. {
  1567. name = dbgModule->mFilePath;
  1568. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  1569. {
  1570. auto breakpoint = mBreakpoints[i];
  1571. auto checkBreakpoint = breakpoint;
  1572. bool hasAddr = false;
  1573. while (checkBreakpoint != NULL)
  1574. {
  1575. if ((checkBreakpoint->mAddr >= dbgModule->mImageBase) && (checkBreakpoint->mAddr < dbgModule->mImageBase + dbgModule->mImageSize))
  1576. hasAddr = true;
  1577. checkBreakpoint = (WdBreakpoint*)checkBreakpoint->mLinkedSibling;
  1578. }
  1579. if (hasAddr)
  1580. {
  1581. DetachBreakpoint(breakpoint);
  1582. needsBreakpointRehup = true;
  1583. }
  1584. }
  1585. mDebugTarget->UnloadDyn(dbgModule->mImageBase);
  1586. if (needsBreakpointRehup)
  1587. RehupBreakpoints(true);
  1588. mPendingDebugInfoLoad.Remove(dbgModule);
  1589. mPendingDebugInfoRequests.Remove(dbgModule);
  1590. mDebugManager->mOutMessages.push_back("modulesChanged");
  1591. }
  1592. if (!name.empty())
  1593. OutputMessage(StrFormat("Unloading DLL: %s @ %0s\n", name.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.UnloadDll.lpBaseOfDll, true).c_str()));
  1594. BfLogDbg("UNLOAD_DLL_DEBUG_EVENT %s\n", name.c_str());
  1595. }
  1596. break;
  1597. case OUTPUT_DEBUG_STRING_EVENT:
  1598. {
  1599. const int maxChars = 1024 * 1024;
  1600. int len = BF_MIN(maxChars, (int)mDebugEvent.u.DebugString.nDebugStringLength); // 1MB max
  1601. char* message = new char[len + 1];
  1602. message[0] = 0;
  1603. message[len] = 0;
  1604. ReadMemory((addr_target)(intptr)mDebugEvent.u.DebugString.lpDebugStringData, len, message);
  1605. if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId == mDebugEvalThreadInfo.mThreadId))
  1606. mDebugManager->mOutMessages.push_back(String("dbgEvalMsg ") + message);
  1607. else
  1608. mDebugManager->mOutMessages.push_back(String("msg ") + message);
  1609. BfLogDbg("OUTPUT_DEBUG_STRING_EVENT (BreakAddr:%@): %s\n", threadInfo->mIsAtBreakpointAddress, message);
  1610. BF_ASSERT_REL(threadInfo->mIsAtBreakpointAddress == 0);
  1611. delete [] message;
  1612. }
  1613. break;
  1614. case CREATE_THREAD_DEBUG_EVENT:
  1615. {
  1616. WdThreadInfo* threadInfo = new WdThreadInfo();
  1617. threadInfo->mProcessId = mDebugEvent.dwProcessId;
  1618. threadInfo->mThreadId = mDebugEvent.dwThreadId;
  1619. threadInfo->mHThread = mDebugEvent.u.CreateThread.hThread;
  1620. threadInfo->mThreadLocalBase = mDebugEvent.u.CreateThread.lpThreadLocalBase;
  1621. threadInfo->mStartAddress = (void*)mDebugEvent.u.CreateThread.lpStartAddress;
  1622. BF_CONTEXT lcContext;
  1623. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1624. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1625. threadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1626. mThreadMap[mDebugEvent.dwThreadId] = threadInfo;
  1627. mDebuggerWaitingThread = threadInfo;
  1628. mThreadList.push_back(mDebuggerWaitingThread);
  1629. UpdateThreadDebugRegisters();
  1630. OutputMessage(StrFormat("Creating thread %d\n", mDebugEvent.dwThreadId));
  1631. }
  1632. break;
  1633. case EXIT_THREAD_DEBUG_EVENT:
  1634. {
  1635. OutputMessage(StrFormat("Exiting thread %d\n", mDebugEvent.dwThreadId));
  1636. if (mSteppingThread == threadInfo)
  1637. {
  1638. // We were attempting stepping on this thread, but not anymore!
  1639. ClearStep();
  1640. }
  1641. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_CONTINUE);
  1642. mIsDebuggerWaiting = false;
  1643. mWantsDebugContinue = false;
  1644. if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId == mDebugEvalThreadInfo.mThreadId))
  1645. {
  1646. // Thread terminated while evaluating! Is there a more graceful way of handling this?
  1647. CleanupDebugEval(false);
  1648. mRunState = RunState_Running;
  1649. }
  1650. mThreadList.Remove(mDebuggerWaitingThread);
  1651. delete mDebuggerWaitingThread;
  1652. mDebuggerWaitingThread = NULL;
  1653. mThreadMap.Remove(mDebugEvent.dwThreadId);
  1654. return true;
  1655. }
  1656. break;
  1657. case RIP_EVENT:
  1658. OutputMessage("RIP Event\n");
  1659. break;
  1660. case EXCEPTION_DEBUG_EVENT:
  1661. {
  1662. auto exceptionRecord = &mDebugEvent.u.Exception.ExceptionRecord;
  1663. switch (exceptionRecord->ExceptionCode)
  1664. {
  1665. case STATUS_WX86_BREAKPOINT:
  1666. case EXCEPTION_BREAKPOINT:
  1667. {
  1668. if (mRunState == RunState_Terminating)
  1669. {
  1670. BfLogDbg("Ignoring event because of RunState_Terminating\n");
  1671. break;
  1672. }
  1673. mAtBreakThread = threadInfo;
  1674. mActiveThread = mAtBreakThread;
  1675. bool isHighAddr = false;
  1676. #ifdef BF_DBG_32
  1677. if (((uintptr)exceptionRecord->ExceptionAddress & 0xFFFFFFFF00000000) != 0)
  1678. {
  1679. if (mActiveThread == mThreadList.front())
  1680. {
  1681. // Skip the initial Wow64 ntdll.dll!LdrpDoDebuggerBreak
  1682. mRunState = RunState_Running;
  1683. break;
  1684. }
  1685. isHighAddr = true;
  1686. }
  1687. #endif
  1688. addr_target pcAddress = (addr_target)(intptr)exceptionRecord->ExceptionAddress;
  1689. if (isHighAddr)
  1690. pcAddress = (addr_target)-1;
  1691. //mStoppedAtAddress = pcAddress;
  1692. bool isStepOut = false;
  1693. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto))
  1694. {
  1695. isStepOut = mStepBreakpointAddrs.Contains(pcAddress);
  1696. }
  1697. BF_CONTEXT lcContext;
  1698. lcContext.ContextFlags = BF_CONTEXT_ALL;
  1699. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1700. BfLogDbg("EXCEPTION_BREAKPOINT Thread:%d %p SP:%p\n", mActiveThread->mThreadId, pcAddress, BF_CONTEXT_SP(lcContext));
  1701. uint8 origImageData = 0xCC;
  1702. mDebugTarget->ReadOrigImageData(pcAddress, &origImageData, 1);
  1703. bool wasDebugBreakpoint = origImageData != 0xCC;
  1704. DbgSubprogram* dwSubprogram = NULL;
  1705. DbgLineData* dwLineData = NULL;
  1706. if (!isStepOut)
  1707. {
  1708. dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  1709. if (dwSubprogram == NULL)
  1710. dwSubprogram = mDebugTarget->FindSubProgram(pcAddress, DbgOnDemandKind_LocalOnly);
  1711. }
  1712. bool isLineStart = (dwLineData != NULL) && (dwSubprogram->GetLineAddr(*dwLineData) == pcAddress);
  1713. bool isNonDebuggerBreak = false;
  1714. if (wasDebugBreakpoint)
  1715. {
  1716. // Go ahead and set EIP back one instruction
  1717. BF_CONTEXT_IP(lcContext)--;
  1718. BF_SetThreadContext(threadInfo->mHThread, &lcContext);
  1719. if ((dwSubprogram != NULL) && (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid) &&
  1720. (pcAddress == dwSubprogram->mBlock.mLowPC))
  1721. {
  1722. BfLogDbg("Hit HotReplaceKind_Invalid breakpoint\n");
  1723. mRunState = RunState_Paused;
  1724. mDebugManager->mOutMessages.push_back("error This lambda was replaced by a new version that has incompatible captures. A program restart is required.");
  1725. PhysRemoveBreakpoint(pcAddress);
  1726. break;
  1727. }
  1728. }
  1729. else
  1730. {
  1731. // This was an actual "break" instruction
  1732. BfLogDbg("Non-debugger break\n");
  1733. isNonDebuggerBreak = true;
  1734. auto prevState = mRunState;
  1735. // Make it an "auto" stop, so for example when we have an assert/retry we won't stop inside assembly
  1736. mRequestedStackFrameIdx = -2;
  1737. mRunState = RunState_Paused;
  1738. CheckNonDebuggerBreak();
  1739. if (IsInRunState())
  1740. {
  1741. BF_ASSERT((prevState == RunState_Running) || (prevState == RunState_DebugEval));
  1742. mRunState = prevState;
  1743. break; // Continue as if nothing happened
  1744. }
  1745. if (prevState == RunState_DebugEval)
  1746. mRequestedStackFrameIdx = -1; // Don't show a rolled back stack idx if a debug eval fails
  1747. ClearStep();
  1748. }
  1749. if (threadInfo->mIsBreakRestorePaused)
  1750. {
  1751. // The thread is supposed to be paused, but the IP has been reset
  1752. // so just break here so we'll hit that breakpoint again once we're
  1753. // actually unpaused properly
  1754. BfLogDbg("Ignoring EXCEPTION_BREAKPOINT\n", threadInfo->mThreadId);
  1755. break;
  1756. }
  1757. if ((mRunState == RunState_DebugEval) || (mRunState == RunState_HotStep))
  1758. {
  1759. // If we hit a breakpoint while doing a debug eval, we just remove the breakpoint
  1760. // and expect to reinstate it during a rehup after the evaluation has completed
  1761. WdBreakpoint* breakpoint = (WdBreakpoint*)FindBreakpointAt((uintptr_t) exceptionRecord->ExceptionAddress);
  1762. if (breakpoint != NULL)
  1763. {
  1764. mNeedsRehupBreakpoints = true;
  1765. RemoveBreakpoint(breakpoint->mLineData.GetAddress());
  1766. }
  1767. break;
  1768. }
  1769. bool isDeeper = false;
  1770. int stepBreakAddrIdx = (int)mStepBreakpointAddrs.IndexOf(pcAddress);
  1771. WdBreakpoint* breakpoint = NULL;
  1772. bool ignoreBreakpoint = false;
  1773. if ((mStepType != StepType_None) && (mSteppingThread == mAtBreakThread))
  1774. {
  1775. if (mStepType == StepType_ToTempBreakpoint)
  1776. {
  1777. RemoveTempBreakpoints();
  1778. mRunState = RunState_Paused;
  1779. break;
  1780. }
  1781. if (mContinueFromBreakpointFailed)
  1782. {
  1783. BfLogDbg("Continuing from ContinueFromBreakpointFailed\n");
  1784. SetupStep(mStepType);
  1785. mRunState = RunState_Running;
  1786. break;
  1787. }
  1788. if (!isStepOut)
  1789. breakpoint = (WdBreakpoint*)FindBreakpointAt(pcAddress);
  1790. // Ignore breakpoint if it's on the line we're stepping off of
  1791. if ((breakpoint != NULL) && (breakpoint->mAddr == mStepPC) &&
  1792. (mStepSP == BF_CONTEXT_SP(lcContext)))
  1793. {
  1794. ignoreBreakpoint = true;
  1795. }
  1796. else if ((breakpoint != NULL) && (stepBreakAddrIdx == -1) && (!CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress)))
  1797. {
  1798. ignoreBreakpoint = true;
  1799. }
  1800. if ((stepBreakAddrIdx == -1) && (breakpoint == NULL) && (!isNonDebuggerBreak))
  1801. {
  1802. // If a breakpoint is removed in a prior thread
  1803. BfLogDbg("Ignoring step break (old breakpoint)\n");
  1804. if ((mSteppingThread == mAtBreakThread) && (mStepSwitchedThreads))
  1805. {
  1806. SetupStep(mStepType);
  1807. }
  1808. break;
  1809. }
  1810. if ((stepBreakAddrIdx != -1) && (breakpoint == NULL) && (mSteppingThread != mActiveThread))
  1811. {
  1812. BfLogDbg("Ignoring break (wrong thread)\n");
  1813. ThreadRestorePause(mSteppingThread, mActiveThread);
  1814. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1815. break;
  1816. }
  1817. isDeeper = mStepSP > BF_CONTEXT_SP(lcContext);
  1818. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto))
  1819. {
  1820. isDeeper = mStepSP >= BF_CONTEXT_SP(lcContext);
  1821. BfLogDbg("StepOut Iteration SP:%p StartSP:%p IsDeeper:%d\n", BF_CONTEXT_SP(lcContext), mStepSP, isDeeper);
  1822. }
  1823. if (((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto)) && (breakpoint == NULL) && (isDeeper))
  1824. {
  1825. // We're encountered recursion
  1826. // Make sure we don't already have one of these stored
  1827. BF_ASSERT(mStoredReturnValueAddr == 0);
  1828. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1829. break; // Don't fall through, we don't want to set mIsAtBreakpointAddress
  1830. }
  1831. if (isStepOut)
  1832. {
  1833. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1834. if (mStepType == StepType_StepOut_ThenInto)
  1835. {
  1836. dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  1837. if ((dwLineData != NULL) && (pcAddress == dwSubprogram->GetLineAddr(*dwLineData)))
  1838. {
  1839. // Our step out from a filtered function put us at the start of a new line. Stop here
  1840. // <do nothing>
  1841. }
  1842. else
  1843. {
  1844. // .. otherwise keep going until we get to the start of a new line
  1845. SetupStep(StepType_StepInto);
  1846. mRunState = RunState_Running;
  1847. break;
  1848. }
  1849. }
  1850. if (!mStepInAssembly)
  1851. {
  1852. // Keep stepping out until we find a frame that we have source for
  1853. DbgSubprogram* dwSubprogram = NULL;
  1854. DbgLineData* dwLineData = FindLineDataAtAddress(BF_CONTEXT_IP(lcContext), &dwSubprogram);
  1855. if (dwLineData == NULL)
  1856. {
  1857. SetupStep(StepType_StepOut);
  1858. break;
  1859. }
  1860. if ((dwLineData->mColumn == -1) && (!dwSubprogram->HasValidLines()))
  1861. {
  1862. // This is a method we don't actually want to be in, it has no valid lines!
  1863. SetupStep(StepType_StepOut);
  1864. break;
  1865. }
  1866. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  1867. {
  1868. // We've stepped out, but right into the start of an inlined method, so step out of this inlined method now...
  1869. SetupStep(StepType_StepOut);
  1870. break;
  1871. }
  1872. }
  1873. ClearStep();
  1874. mRunState = RunState_Paused;
  1875. threadInfo->mStoppedAtAddress = pcAddress;
  1876. break;
  1877. }
  1878. mRunState = RunState_Paused;
  1879. if (breakpoint != NULL)
  1880. {
  1881. // While stepping we hit a legit breakpoint
  1882. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  1883. // Ignore breakpoint on return statement if we're return-stepping
  1884. mRunState = RunState_Breakpoint;
  1885. }
  1886. if ((mStepType == StepType_StepInto) && (dwSubprogram != NULL))
  1887. {
  1888. // Don't filter out the current subprogram (would break cases where we explicitly stepped into or hit breakpoint in a filtered subprogram)
  1889. bool isInStartSubprogram = (mStepStartPC >= dwSubprogram->mBlock.mLowPC) && (mStepStartPC < dwSubprogram->mBlock.mHighPC);
  1890. if ((!isInStartSubprogram) && (IsStepFiltered(dwSubprogram, dwLineData)))
  1891. {
  1892. BfLogDbg("Hit step filter\n");
  1893. mRunState = RunState_Running;
  1894. SetupStep(StepType_StepOut_ThenInto);
  1895. break;
  1896. }
  1897. }
  1898. if ((mStepType == StepType_StepOver) && (stepBreakAddrIdx == 0) && (mStepBreakpointAddrs[0] != 0) && (mStepBreakpointAddrs.size() > 1))
  1899. {
  1900. // Break was on the 'call' instruction, not the instruction after it -- means recursion
  1901. BfLogDbg("StepOver detected recursing\n");
  1902. mStepIsRecursing = true;
  1903. if (mTempBreakpoint.Remove(mStepBreakpointAddrs[0]))
  1904. {
  1905. RemoveBreakpoint(mStepBreakpointAddrs[0]);
  1906. }
  1907. mStepBreakpointAddrs[0] = 0;
  1908. mRunState = RunState_Running;
  1909. break;
  1910. }
  1911. if ((mStepType == StepType_StepOver) && (stepBreakAddrIdx > 0) && (mStepBreakpointAddrs[0] != 0) && (isDeeper))
  1912. {
  1913. // This is the first time we've hit the target breakpoint.
  1914. if (HasSteppedIntoCall())
  1915. {
  1916. mStepIsRecursing = true;
  1917. RemoveBreakpoint(mStepBreakpointAddrs[0]);
  1918. mStepBreakpointAddrs[0] = 0;
  1919. //mStepBreakpointAddrs.erase(mStepBreakpointAddrs.begin());
  1920. }
  1921. }
  1922. if ((mStepType == StepType_StepOver) && (mStepIsRecursing) && (stepBreakAddrIdx != -1) && (isDeeper))
  1923. {
  1924. // Decrement so the equality test on "step out" marks us as not being deeper when we
  1925. // hit the expected SP
  1926. BfLogDbg("Converting StepOver to StepOut\n");
  1927. mStepSP--;
  1928. mStepType = StepType_StepOut_ThenInto;
  1929. //SetupStep(StepType_StepOut);
  1930. mRunState = RunState_Running;
  1931. break;
  1932. }
  1933. if ((mStepType == StepType_StepOver) && (!ignoreBreakpoint) && (breakpoint == NULL) && (!mStepInAssembly))
  1934. {
  1935. // Test for stepping over inline method
  1936. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  1937. // mTempBreakpoints will have 2 entries if we are on a 'call' line. If we have an inlined call immediately following a call, then we
  1938. // assume we're hitting a return break
  1939. /*if ((dwSubprogram != NULL) && (dwSubprogram->mInlineParent != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC) && (mTempBreakpoint.size() < 2))
  1940. {
  1941. BfLogDbg("Attempting StepOver of inlined method\n");
  1942. SetupStep(StepType_StepOut);
  1943. mRunState = RunState_Running;
  1944. break;
  1945. } */
  1946. //TODO: The previous logic with the "(mTempBreakpoint.size() < 2)" was causing Try!(Method()); stepovers to enter into Try!. What did we mean by
  1947. // "assume we're hitting a return break"?
  1948. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  1949. {
  1950. RemoveTempBreakpoints();
  1951. BfLogDbg("Attempting StepOver of inlined method\n");
  1952. SetupStep(StepType_StepOut);
  1953. mRunState = RunState_Running;
  1954. break;
  1955. }
  1956. }
  1957. if (mStepType == StepType_StepOut_Inline)
  1958. {
  1959. if (mOrigStepType == StepType_StepOver)
  1960. {
  1961. // For the step over, if we are still inside the source line after an inline then step over again...
  1962. DbgSubprogram* origSubprogram = NULL;
  1963. auto origLineData = FindLineDataAtAddress(mStepStartPC, &origSubprogram);
  1964. DbgSubprogram* curSubprogram = NULL;
  1965. auto curLineData = FindLineDataAtAddress(pcAddress, &curSubprogram);
  1966. if ((origLineData != NULL) &&
  1967. ((origLineData == curLineData) ||
  1968. ((origSubprogram == curSubprogram) && (origLineData->mLine == curLineData->mLine))))
  1969. {
  1970. mRunState = RunState_Running;
  1971. SetupStep(StepType_StepOver);
  1972. break;
  1973. }
  1974. }
  1975. ClearStep();
  1976. break;
  1977. }
  1978. if ((mStepType != StepType_None) && (ignoreBreakpoint) && (!mStepInAssembly) && (stepBreakAddrIdx == -1))
  1979. {
  1980. // Ignore breakpoint by just continuing...
  1981. mRunState = RunState_Running;
  1982. break;
  1983. }
  1984. RemoveTempBreakpoints();
  1985. if ((mStepType != StepType_None) && (!mStepInAssembly) && (!isLineStart) && (stepBreakAddrIdx != -1))
  1986. {
  1987. SetupStep(mStepType);
  1988. mRunState = RunState_Running;
  1989. }
  1990. else
  1991. {
  1992. //if (mStepType != StepType_Return)
  1993. if (stepBreakAddrIdx != -1)
  1994. {
  1995. // Even if we've detected we're at a breakpoint, we mark ourselves as just stepping if we also
  1996. // have a step breakpoint here
  1997. StepLineTryPause(pcAddress, true);
  1998. }
  1999. if (mRunState == RunState_Paused)
  2000. ClearStep();
  2001. }
  2002. if (ignoreBreakpoint)
  2003. {
  2004. SetupStep(mStepType);
  2005. mRunState = RunState_Running;
  2006. }
  2007. if ((mRunState == RunState_Paused) && (breakpoint != NULL))
  2008. {
  2009. // Just do the 'check' here so we can do the logging/condition stuff
  2010. CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress);
  2011. }
  2012. }
  2013. else
  2014. {
  2015. breakpoint = (WdBreakpoint*)FindBreakpointAt((uintptr_t)exceptionRecord->ExceptionAddress);
  2016. if ((breakpoint != NULL) && (!CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress)))
  2017. {
  2018. ClearCallStack();
  2019. BfLogDbg("Skipping conditional breakpoint. Setting mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  2020. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  2021. mRunState = RunState_Running;
  2022. break;
  2023. }
  2024. if (breakpoint != NULL)
  2025. {
  2026. BfLogDbg("Breakpoint hit. mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  2027. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  2028. mRunState = RunState_Breakpoint;
  2029. }
  2030. else if ((stepBreakAddrIdx != -1) || (isNonDebuggerBreak))
  2031. {
  2032. if (mRunState != RunState_DebugEval)
  2033. {
  2034. // Was in mStepBreakpointAddrs list
  2035. if ((isNonDebuggerBreak) || (mStepType == StepType_None) || (mSteppingThread == mAtBreakThread))
  2036. {
  2037. BfLogDbg("Hit mStepBreakpointAddrs breakpoint\n");
  2038. mRunState = RunState_Paused;
  2039. }
  2040. else
  2041. {
  2042. BfLogDbg("Ignored mStepBreakpointAddrs breakpoint (wrong thread)\n");
  2043. mRunState = RunState_Running;
  2044. }
  2045. }
  2046. }
  2047. else
  2048. {
  2049. BfLogDbg("Ignoring break (old or ignored breakpoint)\n");
  2050. mRunState = RunState_Running;
  2051. }
  2052. }
  2053. if ((breakpoint != NULL) && (!ignoreBreakpoint))
  2054. {
  2055. mActiveBreakpoint = breakpoint;
  2056. mBreakStackFrameIdx = -1;
  2057. }
  2058. if ((mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint))
  2059. threadInfo->mStoppedAtAddress = pcAddress;
  2060. }
  2061. break;
  2062. case STATUS_WX86_SINGLE_STEP:
  2063. case EXCEPTION_SINGLE_STEP:
  2064. {
  2065. if (mRunState == RunState_Terminating)
  2066. {
  2067. BfLogDbg("Ignoring event because of RunState_Terminating\n");
  2068. break;
  2069. }
  2070. if ((mStepSwitchedThreads) && (mActiveThread == mSteppingThread) && (mActiveThread->mIsAtBreakpointAddress != NULL))
  2071. {
  2072. ContinueFromBreakpoint();
  2073. break;
  2074. }
  2075. if (mRunState == RunState_HotStep)
  2076. {
  2077. BF_ASSERT(mActiveThread == mDebuggerWaitingThread);
  2078. mRunState = RunState_Paused;
  2079. break;
  2080. }
  2081. mActiveThread = mDebuggerWaitingThread;
  2082. BF_CONTEXT lcContext;
  2083. lcContext.ContextFlags = BF_CONTEXT_ALL;
  2084. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  2085. addr_target pcAddress = BF_CONTEXT_IP(lcContext);
  2086. bool wasUnfilteredStep = mStepType == StepType_StepInto_Unfiltered;
  2087. if (mStepType == StepType_StepInto_UnfilteredSingle)
  2088. {
  2089. wasUnfilteredStep = true;
  2090. mStepType = StepType_StepInto;
  2091. mStepStartPC = pcAddress;
  2092. }
  2093. BfLogDbg("EXCEPTION_SINGLE_STEP Thread:%d PC:%p\n", mActiveThread->mThreadId, exceptionRecord->ExceptionAddress);
  2094. if (lcContext.Dr6 & 0x0F) // Memory breakpoint hit
  2095. {
  2096. WdBreakpoint* foundBreakpoint = NULL;
  2097. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  2098. {
  2099. if ((lcContext.Dr6 & ((intptr_target)1 << memoryWatchSlot)) != 0)
  2100. {
  2101. foundBreakpoint = mMemoryBreakpoints[memoryWatchSlot].mBreakpoint;
  2102. break;
  2103. }
  2104. }
  2105. BF_ASSERT(foundBreakpoint != NULL);
  2106. DbgSubprogram* subprogram = mDebugTarget->FindSubProgram(pcAddress);
  2107. if (CheckConditionalBreakpoint(foundBreakpoint, subprogram, pcAddress))
  2108. {
  2109. if (foundBreakpoint != NULL)
  2110. {
  2111. mDebugManager->mOutMessages.push_back(StrFormat("memoryBreak %s", EncodeDataPtr(foundBreakpoint->mMemoryBreakpointInfo->mMemoryAddress, false).c_str()));
  2112. mRunState = RunState_Paused;
  2113. }
  2114. mActiveBreakpoint = foundBreakpoint;
  2115. mBreakStackFrameIdx = -1;
  2116. RemoveTempBreakpoints();
  2117. BfLogDbg("Memory breakpoint hit: %p\n", foundBreakpoint);
  2118. }
  2119. else
  2120. ClearCallStack();
  2121. break;
  2122. }
  2123. if ((mRunState == RunState_DebugEval) && (mDebugEvalThreadInfo.mThreadId == mDebuggerWaitingThread->mThreadId))
  2124. {
  2125. if ((addr_target)(intptr)exceptionRecord->ExceptionAddress == mDebugEvalSetRegisters.GetPC())
  2126. {
  2127. // This indicates we are returning from kernel mode and our registers are clobbered
  2128. SetRegisters(&mDebugEvalSetRegisters);
  2129. }
  2130. break;
  2131. }
  2132. bool hadBreakpointContinue = true;
  2133. if (threadInfo->mBreakpointAddressContinuing != 0)
  2134. {
  2135. bool wantsBreakpoint = WantsBreakpointAt(threadInfo->mBreakpointAddressContinuing);
  2136. BfLogDbg("Continuing breakpoint at %p WantsReset:%d\n", threadInfo->mBreakpointAddressContinuing, wantsBreakpoint);
  2137. if (wantsBreakpoint)
  2138. {
  2139. PhysSetBreakpoint(threadInfo->mBreakpointAddressContinuing);
  2140. }
  2141. threadInfo->mBreakpointAddressContinuing = NULL;
  2142. hadBreakpointContinue = true;
  2143. ThreadRestoreUnpause();
  2144. }
  2145. if ((mSteppingThread != NULL) && (mSteppingThread != mActiveThread))
  2146. {
  2147. // This SINGLE_STEP happened in the wrong thread - we need the stepping thread to do the stepping!
  2148. // Try again.
  2149. mActiveThread = mSteppingThread;
  2150. SingleStepX86();
  2151. break;
  2152. }
  2153. bool isDeeper = mStepSP > BF_CONTEXT_SP(lcContext);
  2154. if ((mStepSwitchedThreads) && (mStepType == StepType_StepOver) && (isDeeper))
  2155. {
  2156. if (HasSteppedIntoCall())
  2157. {
  2158. // Since we switched threads, we needed to do a hardware step which has placed us inside a
  2159. // call, so we need to step out of that now...
  2160. SetupStep(StepType_StepOut_NoFrame);
  2161. break;
  2162. }
  2163. }
  2164. // If we don't have a mStepBreakpointAddrs set, that means we're stepping through individual instructions --
  2165. // so process the new location here
  2166. if (((mStepType == StepType_StepInto) || (mStepType == StepType_StepInto_Unfiltered) || (mStepType == StepType_StepOver)) && (mStepBreakpointAddrs.size() == 0))
  2167. {
  2168. DbgSubprogram* dwSubprogram = NULL;
  2169. DbgLineData* dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  2170. if ((dwSubprogram != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC) && (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced))
  2171. {
  2172. BfLogDbg("Stepping through hot thunk\n");
  2173. mRunState = RunState_Running;
  2174. SingleStepX86();
  2175. break;
  2176. }
  2177. if ((mStepType == StepType_StepOver) && (!mStepInAssembly))
  2178. {
  2179. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  2180. {
  2181. BfLogDbg("Attempting StepOver of inlined method - SingleStep\n");
  2182. SetupStep(StepType_StepOut);
  2183. mRunState = RunState_Running;
  2184. break;
  2185. }
  2186. }
  2187. // Column of -1 means "Illegal", keep stepping!
  2188. if ((mStepInAssembly) ||
  2189. ((dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dwLineData->mColumn >= 0) &&
  2190. ((dwSubprogram->GetLineAddr(*dwLineData) == pcAddress) || (mStepStopOnNextInstruction))))
  2191. {
  2192. // Hit a line while stepping, we're done!
  2193. mRunState = RunState_Paused;
  2194. StepLineTryPause(pcAddress, false);
  2195. if (mRunState == RunState_Paused)
  2196. {
  2197. if ((mStepType == StepType_StepInto) && (!wasUnfilteredStep) && (!mStepInAssembly) && (dwSubprogram != NULL))
  2198. {
  2199. // Don't filter out the current subprogram (would break cases where we explicitly stepped into or hit breakpoint in a filtered subprogram)
  2200. bool isInStartSubprogram = (mStepStartPC >= dwSubprogram->mBlock.mLowPC) && (mStepStartPC < dwSubprogram->mBlock.mHighPC);
  2201. if ((!isInStartSubprogram) && (IsStepFiltered(dwSubprogram, dwLineData)))
  2202. {
  2203. BfLogDbg("Hit step filter (2)\n");
  2204. mRunState = RunState_Running;
  2205. SetupStep(StepType_StepOut_ThenInto);
  2206. break;
  2207. }
  2208. }
  2209. ClearStep();
  2210. mCurNoInfoStepTries = 0; // Reset
  2211. }
  2212. else
  2213. SetupStep(mStepType);
  2214. }
  2215. else if (dwSubprogram != NULL)
  2216. {
  2217. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && ((mStepType == StepType_StepInto) || (mStepType == StepType_StepInto_Unfiltered)))
  2218. {
  2219. SingleStepX86();
  2220. }
  2221. else
  2222. {
  2223. // Inside a line's instruction, keep going
  2224. SetupStep(mStepType);
  2225. mCurNoInfoStepTries = 0; // Reset
  2226. }
  2227. }
  2228. else if (mStepType == StepType_StepInto_Unfiltered)
  2229. {
  2230. CPUInst inst;
  2231. if (mDebugTarget->DecodeInstruction(pcAddress, &inst))
  2232. {
  2233. if (inst.IsBranch())
  2234. {
  2235. auto target = inst.GetTarget();
  2236. if (target != 0)
  2237. {
  2238. DbgSubprogram* destSubprogram = mDebugTarget->FindSubProgram(target);
  2239. if ((destSubprogram != NULL) && (target == destSubprogram->mBlock.mLowPC))
  2240. {
  2241. // We're jumping to an actual subprogram, so continue stepping here
  2242. mStepType = StepType_StepInto_UnfilteredSingle;
  2243. SingleStepX86();
  2244. break;
  2245. }
  2246. }
  2247. }
  2248. }
  2249. // We requested to step into this method so stop here even if we don't have source
  2250. mRunState = RunState_Paused;
  2251. }
  2252. else
  2253. {
  2254. // No debug info!
  2255. bool doStepOut = false;
  2256. if (mCurNoInfoStepTries < 16)
  2257. {
  2258. mCurNoInfoStepTries++;
  2259. BfLogDbg("NoInfoStepTries: %d\n", mCurNoInfoStepTries);
  2260. if (!SetupStep(mStepType))
  2261. doStepOut = true;
  2262. }
  2263. else
  2264. doStepOut = true;
  2265. if (doStepOut)
  2266. {
  2267. // Step out of current call.
  2268. mStepSP = 0;
  2269. SetupStep(StepType_StepOut_NoFrame);
  2270. // Aggressive stepout - don't monitor BP
  2271. mStepSP = 0;
  2272. }
  2273. }
  2274. }
  2275. else if (!hadBreakpointContinue)
  2276. {
  2277. BF_DBG_FATAL("EXCEPTION_SINGLE_STEP bad debugger state");
  2278. }
  2279. if (mRunState == RunState_Paused)
  2280. threadInfo->mStoppedAtAddress = pcAddress;
  2281. }
  2282. break;
  2283. default:
  2284. {
  2285. bool isSystemException =
  2286. (exceptionRecord->ExceptionCode >= STATUS_ACCESS_VIOLATION) &&
  2287. (exceptionRecord->ExceptionCode <= STATUS_ASSERTION_FAILURE);
  2288. bool isFirstChance = mDebugEvent.u.Exception.dwFirstChance != 0;
  2289. bool handled = false;
  2290. //TODO: Use a user-defined filter here to determine whether to stop or continue
  2291. if ((!isSystemException) && (isFirstChance))
  2292. {
  2293. if (exceptionRecord->ExceptionCode == 0x406D1388) // Visual C
  2294. {
  2295. if ((int32)exceptionRecord->ExceptionInformation[0] == 0x1000)
  2296. {
  2297. struct THREADNAME_INFO
  2298. {
  2299. DWORD dwType; // Must be 0x1000.
  2300. LPCSTR szName; // Pointer to name (in user addr space).
  2301. DWORD dwThreadID; // Thread ID (-1=caller thread).
  2302. DWORD dwFlags; // Reserved for future use, must be zero.
  2303. };
  2304. THREADNAME_INFO* threadNameInfo = (THREADNAME_INFO*)exceptionRecord->ExceptionInformation;
  2305. DwFormatInfo formatInfo;
  2306. formatInfo.mRawString = true;
  2307. String nameStr = ReadString(DbgType_SChar, (intptr)threadNameInfo->szName, false, 1024, formatInfo);
  2308. WdThreadInfo* namingThreadInfo = threadInfo;
  2309. if (threadNameInfo->dwThreadID != (DWORD)-1)
  2310. {
  2311. namingThreadInfo = NULL;
  2312. mThreadMap.TryGetValue(threadNameInfo->dwThreadID, &namingThreadInfo);
  2313. }
  2314. if (namingThreadInfo != NULL)
  2315. {
  2316. namingThreadInfo->mName = nameStr;
  2317. FilterThreadName(namingThreadInfo->mName);
  2318. }
  2319. }
  2320. else if (((int32)exceptionRecord->ExceptionInformation[0] == 0x1001) && ((int32)exceptionRecord->ExceptionInformation[1] == 0x1002))
  2321. {
  2322. struct FailMessage
  2323. {
  2324. addr_target mPtr0; // Unknown
  2325. addr_target mPtr1; // 0
  2326. addr_target mPtr2; // 0
  2327. addr_target mPtr3; // Unknown
  2328. addr_target mErrorStr;
  2329. };
  2330. FailMessage failMessage = ReadMemory<FailMessage>(exceptionRecord->ExceptionInformation[2]);
  2331. DwFormatInfo formatInfo;
  2332. String failStr = ReadString(DbgType_SChar16, failMessage.mErrorStr, false, 8192, formatInfo);
  2333. mDebugManager->mOutMessages.push_back(StrFormat("error Run-Time Check Failure %d - %s", exceptionRecord->ExceptionInformation[6], failStr.c_str()));
  2334. mRunState = RunState_Paused;
  2335. mRequestedStackFrameIdx = -2; // -2 = "auto"
  2336. handled = true;
  2337. }
  2338. }
  2339. if (!handled)
  2340. {
  2341. OutputMessage(StrFormat("Skipping first chance exception %08X at address %@ in thread %d\n", exceptionRecord->ExceptionCode, exceptionRecord->ExceptionAddress, threadInfo->mThreadId));
  2342. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_EXCEPTION_NOT_HANDLED);
  2343. mIsDebuggerWaiting = false;
  2344. }
  2345. }
  2346. else
  2347. {
  2348. BfLogDbg("EXCEPTION in thread %d at %p\n", threadInfo->mThreadId, exceptionRecord->ExceptionAddress);
  2349. OutputDebugStrF("EXCEPTION\n");
  2350. mActiveThread = threadInfo;
  2351. memcpy(&mCurException, exceptionRecord, sizeof(EXCEPTION_RECORD));
  2352. if (mRunState == RunState_DebugEval)
  2353. {
  2354. if ((intptr)mCurException.ExceptionAddress == 42)
  2355. {
  2356. BfLogDbg("RunState_DebugEval_Done\n");
  2357. OutputDebugStrF(" RunState_DebugEval_Done\n");
  2358. }
  2359. else
  2360. {
  2361. BfLogDbg("Exception at 0x%@ in thread %d, exception code 0x%08X",
  2362. mCurException.ExceptionAddress, mActiveThread->mThreadId, mCurException.ExceptionCode);
  2363. mDebugPendingExpr->mException = StrFormat("Exception at 0x%@ in thread %d, exception code 0x%08X",
  2364. mCurException.ExceptionAddress, mActiveThread->mThreadId, mCurException.ExceptionCode);
  2365. }
  2366. mRunState = RunState_DebugEval_Done;
  2367. mExplicitStopThread = mActiveThread;
  2368. mRequestedStackFrameIdx = mDebugPendingExpr->mCallStackIdx;
  2369. }
  2370. else
  2371. {
  2372. mRunState = RunState_Exception;
  2373. }
  2374. }
  2375. }
  2376. break;
  2377. }
  2378. }
  2379. break;
  2380. }
  2381. if ((mDebugEvalThreadInfo.mThreadId != 0) && (mRunState != RunState_DebugEval) && (mRunState != RunState_DebugEval_Done))
  2382. {
  2383. CleanupDebugEval();
  2384. }
  2385. // Stepping done?
  2386. if (mStepType == StepType_None)
  2387. {
  2388. mLastValidStepIntoPC = 0;
  2389. }
  2390. BF_ASSERT(mDebuggerWaitingThread != NULL);
  2391. return true;
  2392. }
  2393. void WinDebugger::Update()
  2394. {
  2395. AutoCrit autoCrit(mDebugManager->mCritSect);
  2396. // if (mRunState == RunState_DebugEval)
  2397. // ContinueDebugEvent();
  2398. if (mRunState == RunState_DebugEval_Done)
  2399. {
  2400. if (mDebugPendingExpr != NULL)
  2401. {
  2402. mDebugPendingExpr->mIdleTicks++;
  2403. if (mDebugPendingExpr->mIdleTicks >= 2)
  2404. {
  2405. BfLogDbg("Finishing pending expr in thread %d\n", mDebugEvalThreadInfo.mThreadId);
  2406. mRunState = RunState_Paused;
  2407. CleanupDebugEval();
  2408. }
  2409. }
  2410. }
  2411. else if (mDebugPendingExpr != NULL)
  2412. {
  2413. mDebugPendingExpr->mIdleTicks = 0;
  2414. }
  2415. }
  2416. void WinDebugger::ContinueDebugEvent()
  2417. {
  2418. AutoCrit autoCrit(mDebugManager->mCritSect);
  2419. BF_ASSERT(mRunState != RunState_DebugEval_Done);
  2420. if (!mWantsDebugContinue)
  2421. return;
  2422. if (!TryRunContinue())
  2423. return;
  2424. // if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId != mDebugEvalThreadInfo.mThreadId))
  2425. // {
  2426. // // Don't process the 'mIsAtBreakpointAddress' stuff
  2427. // mWantsDebugContinue = false;
  2428. // mContinueEvent.Set();
  2429. // return;
  2430. // }
  2431. if ((mDebuggerWaitingThread->mIsAtBreakpointAddress == 0) && (mDebuggerWaitingThread->mStoppedAtAddress != 0))
  2432. {
  2433. auto breakpoint = FindBreakpointAt(mDebuggerWaitingThread->mStoppedAtAddress);
  2434. if (breakpoint != NULL)
  2435. {
  2436. mDebuggerWaitingThread->mIsAtBreakpointAddress = mDebuggerWaitingThread->mStoppedAtAddress;
  2437. }
  2438. }
  2439. if (mDebuggerWaitingThread->mIsAtBreakpointAddress != 0)
  2440. {
  2441. if (!ContinueFromBreakpoint())
  2442. {
  2443. BfLogDbg("ContinueFromBreakpoint failed\n");
  2444. ClearCallStack();
  2445. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  2446. mDebuggerWaitingThread->mIsAtBreakpointAddress = 0;
  2447. mWantsDebugContinue = false;
  2448. mContinueFromBreakpointFailed = true;
  2449. mContinueEvent.Set();
  2450. return;
  2451. }
  2452. }
  2453. if ((mRunState == RunState_Breakpoint) || (mRunState == RunState_Paused))
  2454. {
  2455. ClearCallStack();
  2456. mRunState = RunState_Running;
  2457. }
  2458. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  2459. mWantsDebugContinue = false;
  2460. BF_ASSERT_REL(mDebuggerWaitingThread->mIsAtBreakpointAddress == 0);
  2461. mContinueEvent.Set();
  2462. }
  2463. static BOOL CALLBACK WdEnumWindowsProc(HWND hwnd, LPARAM lParam)
  2464. {
  2465. HWND owner = GetWindow(hwnd, GW_OWNER);
  2466. if (!IsWindowVisible(hwnd))
  2467. return TRUE;
  2468. DWORD processId = 0;
  2469. DWORD threadId = GetWindowThreadProcessId(hwnd, &processId);
  2470. if (processId != ((WinDebugger*)gDebugger)->mProcessInfo.dwProcessId)
  2471. return TRUE;
  2472. SetForegroundWindow(hwnd);
  2473. return TRUE;
  2474. }
  2475. void WinDebugger::ForegroundTarget()
  2476. {
  2477. EnumWindows(WdEnumWindowsProc, 0);
  2478. }
  2479. static int gFindLineDataAt = 0;
  2480. DbgLineData* WinDebugger::FindLineDataAtAddress(addr_target address, DbgSubprogram** outSubProgram, DbgSrcFile** outSrcFile, int* outLineIdx, DbgOnDemandKind onDemandKind)
  2481. {
  2482. gFindLineDataAt++;
  2483. BP_ZONE("WinDebugger::FindLineDataAtAddress");
  2484. auto dwSubprogram = mDebugTarget->FindSubProgram((addr_target)address, onDemandKind);
  2485. if (dwSubprogram == NULL)
  2486. return NULL;
  2487. FixupLineDataForSubprogram(dwSubprogram);
  2488. auto lineData = dwSubprogram->FindClosestLine(address, outSubProgram, outSrcFile, outLineIdx);
  2489. return lineData;
  2490. }
  2491. DbgLineData* WinDebugger::FindLineDataInSubprogram(addr_target address, DbgSubprogram* dwSubprogram)
  2492. {
  2493. auto dwCompileUnit = dwSubprogram->mCompileUnit;
  2494. FixupLineDataForSubprogram(dwSubprogram);
  2495. auto lineData = dwSubprogram->FindClosestLine(address);
  2496. return lineData;
  2497. }
  2498. bool WinDebugger::IsStepFiltered(DbgSubprogram* dbgSubprogram, DbgLineData* dbgLineData)
  2499. {
  2500. if (mIsStepIntoSpecific)
  2501. return false;
  2502. if (dbgSubprogram->mStepFilterVersion != mDebugManager->mStepFilterVersion)
  2503. {
  2504. String filterName;
  2505. CreateFilterName(filterName, dbgSubprogram);
  2506. dbgSubprogram->PopulateSubprogram();
  2507. bool doDefault = false;
  2508. StepFilter* stepFilterPtr;
  2509. if (mDebugManager->mStepFilters.TryGetValue(filterName, &stepFilterPtr))
  2510. {
  2511. switch (stepFilterPtr->mFilterKind)
  2512. {
  2513. case BfStepFilterKind_Default:
  2514. doDefault = true;
  2515. break;
  2516. case BfStepFilterKind_Filtered:
  2517. dbgSubprogram->mIsStepFiltered = true;
  2518. break;
  2519. case BfStepFilterKind_NotFiltered:
  2520. dbgSubprogram->mIsStepFiltered = false;
  2521. break;
  2522. }
  2523. }
  2524. else
  2525. {
  2526. doDefault = true;
  2527. }
  2528. if (doDefault)
  2529. {
  2530. dbgSubprogram->mIsStepFiltered = dbgSubprogram->mIsStepFilteredDefault;
  2531. }
  2532. dbgSubprogram->mStepFilterVersion = mDebugManager->mStepFilterVersion;
  2533. }
  2534. if (!dbgSubprogram->mIsStepFiltered)
  2535. {
  2536. if (dbgLineData != NULL)
  2537. {
  2538. auto dbgSrcFile = dbgSubprogram->GetLineSrcFile(*dbgLineData);
  2539. if (dbgSrcFile->mStepFilterVersion != mDebugManager->mStepFilterVersion)
  2540. {
  2541. dbgSrcFile->mFileExistKind = dbgSubprogram->mCompileUnit->mDbgModule->CheckSourceFileExist(dbgSrcFile->GetLocalPath());
  2542. dbgSrcFile->mStepFilterVersion = mDebugManager->mStepFilterVersion;
  2543. }
  2544. switch (dbgSrcFile->mFileExistKind)
  2545. {
  2546. case DbgFileExistKind_NotFound:
  2547. return true;
  2548. case DbgFileExistKind_HasOldSourceCommand:
  2549. if (mDebugManager->mStepOverExternalFiles)
  2550. return true;
  2551. }
  2552. }
  2553. }
  2554. return dbgSubprogram->mIsStepFiltered;
  2555. }
  2556. void WinDebugger::RemoveTempBreakpoints()
  2557. {
  2558. BfLogDbg("RemoveTempBreakpoints\n");
  2559. for (auto address : mTempBreakpoint)
  2560. {
  2561. RemoveBreakpoint(address);
  2562. // if (FindBreakpointAt(address) == NULL)
  2563. // {
  2564. // RemoveBreakpoint(address);
  2565. // }
  2566. // else
  2567. // {
  2568. // BfLogDbg("Ignoring remove on temp breakpoint %p\n", address);
  2569. // }
  2570. }
  2571. mTempBreakpoint.Clear();
  2572. mStepBreakpointAddrs.Clear();
  2573. }
  2574. void WinDebugger::RehupBreakpoints(bool doFlush)
  2575. {
  2576. BfLogDbg("RehupBreakpoints\n");
  2577. // First pass- detach breakpoints that need to be rebound
  2578. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  2579. {
  2580. auto breakpoint = mBreakpoints[i];
  2581. while (breakpoint != NULL)
  2582. {
  2583. if (((breakpoint->mSrcFile != NULL) && (breakpoint->mSrcFile->mDeferredRefs.size() > 0)) ||
  2584. (!breakpoint->mSymbolName.IsEmpty()))
  2585. {
  2586. // This breakpoint was already bound, but we loaded a debug module that also had this file so rebind it
  2587. DetachBreakpoint(breakpoint);
  2588. }
  2589. breakpoint = (WdBreakpoint*)breakpoint->mLinkedSibling;
  2590. }
  2591. }
  2592. // Second pass- actually set breakpoints
  2593. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  2594. {
  2595. auto breakpoint = mBreakpoints[i];
  2596. while (breakpoint != NULL)
  2597. {
  2598. CheckBreakpoint(breakpoint);
  2599. if (breakpoint->mAddr != 0)
  2600. SetBreakpoint(breakpoint->mAddr, true);
  2601. breakpoint = (WdBreakpoint*)breakpoint->mLinkedSibling;
  2602. }
  2603. }
  2604. mNeedsRehupBreakpoints = false;
  2605. }
  2606. bool WinDebugger::WantsBreakpointAt(addr_target address)
  2607. {
  2608. if (mTempBreakpoint.Contains(address))
  2609. return true;
  2610. for (auto breakpoint : mBreakpoints)
  2611. {
  2612. WdBreakpoint* checkBreakpoint = breakpoint;
  2613. while (checkBreakpoint != NULL)
  2614. {
  2615. if (address == checkBreakpoint->mAddr)
  2616. return true;
  2617. checkBreakpoint = (WdBreakpoint*)checkBreakpoint->mLinkedSibling;
  2618. }
  2619. }
  2620. return false;
  2621. }
  2622. void WinDebugger::CheckBreakpoint(WdBreakpoint* wdBreakpoint, DbgSrcFile* srcFile, int lineNum, int hotIdx)
  2623. {
  2624. BP_ZONE("WinDebugger::CheckBreakpoint:atLoc");
  2625. if (hotIdx == -1)
  2626. {
  2627. BF_ASSERT(wdBreakpoint->mPendingHotBindIdx == -1);
  2628. }
  2629. WdBreakpoint* headBreakpoint = wdBreakpoint;
  2630. headBreakpoint->mPendingHotBindIdx = -1;
  2631. bool foundInSequence = false;
  2632. DbgSubprogram* lastFoundSubprogram = NULL;
  2633. int highestHotIdx = -1;
  2634. bool foundLine = false;
  2635. int bestLineNum = -1;
  2636. int bestLineOffset = 0x7FFFFFFF;
  2637. auto _CheckLineInfo = [&](DbgSubprogram* dbgSubprogram, DbgLineInfo* dbgLineInfo)
  2638. {
  2639. // Scan first so we can determine if we want to do fix up line data or not.
  2640. bool hasNear = false;
  2641. int maxLineDist = 6;
  2642. for (int lineIdx = 0; lineIdx < dbgLineInfo->mLines.mSize; lineIdx++)
  2643. {
  2644. auto lineData = &dbgLineInfo->mLines[lineIdx];
  2645. auto& ctx = dbgLineInfo->mContexts[lineData->mCtxIdx];
  2646. if (ctx.mSrcFile != srcFile)
  2647. continue;
  2648. int lineOffset = lineData->mLine - lineNum;
  2649. if ((lineOffset >= 0) && (lineOffset <= maxLineDist))
  2650. hasNear = true;
  2651. }
  2652. if (!hasNear)
  2653. return;
  2654. FixupLineDataForSubprogram(dbgSubprogram);
  2655. for (int lineIdx = 0; lineIdx < dbgLineInfo->mLines.mSize; lineIdx++)
  2656. {
  2657. //TODO: Do fixup lineData... ?
  2658. auto lineData = &dbgLineInfo->mLines[lineIdx];
  2659. auto& ctx = dbgLineInfo->mContexts[lineData->mCtxIdx];
  2660. if (ctx.mSrcFile != srcFile)
  2661. continue;
  2662. // if (ctx.mInlinee != NULL)
  2663. // {
  2664. // if (lineIdx + 1 < dbgLineInfo->mLines.mSize)
  2665. // {
  2666. // auto nextLineData = &dbgLineInfo->mLines[lineIdx + 1];
  2667. // if (nextLineData->mRelAddress == lineData->mRelAddress)
  2668. // {
  2669. // // Use the later entry (same logic from DisassembleAt)
  2670. // continue;
  2671. // }
  2672. // }
  2673. // }
  2674. if ((lineData->mColumn == -1) && (wdBreakpoint->mInstrOffset == -1))
  2675. continue;
  2676. int lineOffset = lineData->mLine - lineNum;
  2677. if (lineOffset == 0)
  2678. {
  2679. foundLine = true;
  2680. auto address = dbgSubprogram->GetLineAddr(*lineData);
  2681. auto subProgram = mDebugTarget->FindSubProgram(address);
  2682. if (subProgram->mNeedLineDataFixup)
  2683. FixupLineDataForSubprogram(subProgram);
  2684. if (subProgram != NULL)
  2685. highestHotIdx = BF_MAX(highestHotIdx, subProgram->mCompileUnit->mDbgModule->mHotIdx);
  2686. if ((foundInSequence) && (subProgram != lastFoundSubprogram))
  2687. foundInSequence = false;
  2688. if ((subProgram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && (address < subProgram->mBlock.mLowPC + sizeof(HotJumpOp)))
  2689. {
  2690. // If this breakpoint ends up on the hot jmp instruction
  2691. continue;
  2692. }
  2693. if (!foundInSequence)
  2694. {
  2695. lastFoundSubprogram = subProgram;
  2696. if ((subProgram != NULL) && (subProgram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && (address == subProgram->mBlock.mLowPC))
  2697. {
  2698. // This instruction is actually the hot jump, we don't need a breakpoint here
  2699. foundInSequence = true;
  2700. continue;
  2701. }
  2702. if (wdBreakpoint->mSrcFile != NULL)
  2703. {
  2704. wdBreakpoint = new WdBreakpoint();
  2705. // Insert at head
  2706. wdBreakpoint->mLinkedSibling = headBreakpoint->mLinkedSibling;
  2707. headBreakpoint->mLinkedSibling = wdBreakpoint;
  2708. wdBreakpoint->mRequestedLineNum = headBreakpoint->mRequestedLineNum;
  2709. wdBreakpoint->mLineNum = headBreakpoint->mLineNum;
  2710. wdBreakpoint->mColumn = headBreakpoint->mColumn;
  2711. wdBreakpoint->mInstrOffset = headBreakpoint->mInstrOffset;
  2712. wdBreakpoint->mIsLinkedSibling = true;
  2713. wdBreakpoint->mHead = headBreakpoint;
  2714. }
  2715. if (wdBreakpoint->mInstrOffset > 0)
  2716. {
  2717. for (int instIdx = 0; instIdx < wdBreakpoint->mInstrOffset; instIdx++)
  2718. {
  2719. CPUInst inst;
  2720. if (!mDebugTarget->DecodeInstruction(address, &inst))
  2721. break;
  2722. address += inst.mSize;
  2723. }
  2724. }
  2725. wdBreakpoint->mSrcFile = ctx.mSrcFile;
  2726. wdBreakpoint->mLineData = DbgLineDataEx(lineData, subProgram);
  2727. wdBreakpoint->mBreakpointType = BreakpointType_User;
  2728. wdBreakpoint->mAddr = address;
  2729. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mStoppedAtAddress == address))
  2730. {
  2731. BfLogDbg("CheckBreakpoint setting mIsAtBreakpointAddress = %p\n", address);
  2732. mDebuggerWaitingThread->mIsAtBreakpointAddress = address;
  2733. }
  2734. BfLogDbg("Breakpoint %p found at %s in %s\n", wdBreakpoint, subProgram->mName, GetFileName(subProgram->mCompileUnit->mDbgModule->mFilePath).c_str());
  2735. mBreakpointAddrMap.ForceAdd(address, wdBreakpoint);
  2736. SetBreakpoint(address);
  2737. foundInSequence = true;
  2738. }
  2739. }
  2740. else
  2741. {
  2742. //TODO: We didn't have this here, but if we don't have this then there are some cases where the method-closing brace generates code in
  2743. // multiple places so we need to ensure this will break on them all
  2744. foundInSequence = false;
  2745. }
  2746. if ((lineOffset >= 0) && (lineOffset <= maxLineDist) && (lineOffset <= bestLineOffset))
  2747. {
  2748. if (lineOffset < bestLineOffset)
  2749. {
  2750. bestLineNum = lineData->mLine;
  2751. bestLineOffset = lineOffset;
  2752. }
  2753. }
  2754. }
  2755. };
  2756. for (int pass = 0; pass < 2; pass++)
  2757. {
  2758. if (lineNum == -1)
  2759. break;
  2760. bestLineNum = -1;
  2761. bestLineOffset = 0x7FFFFFFF;
  2762. if (hotIdx >= 0)
  2763. {
  2764. if (hotIdx >= srcFile->mHotReplacedDbgLineInfo.size())
  2765. return;
  2766. auto hotReplacedLineInfo = srcFile->mHotReplacedDbgLineInfo[hotIdx];
  2767. for (auto& hotReplacedEntry : hotReplacedLineInfo->mEntries)
  2768. {
  2769. _CheckLineInfo(hotReplacedEntry.mSubprogram, hotReplacedEntry.mLineInfo);
  2770. }
  2771. }
  2772. else
  2773. {
  2774. for (auto subprogram : srcFile->mLineDataRefs)
  2775. _CheckLineInfo(subprogram, subprogram->mLineInfo);
  2776. }
  2777. if (foundLine)
  2778. break;
  2779. // Don't allow the breakpoint to be inexactly bound -- only match on pass 0
  2780. if (hotIdx != -1)
  2781. break;
  2782. if (bestLineNum == -1)
  2783. break;
  2784. lineNum = bestLineNum;
  2785. wdBreakpoint->mLineNum = bestLineNum;
  2786. }
  2787. int highestCheckHotIdx = highestHotIdx - 1;
  2788. if (hotIdx != -1)
  2789. highestCheckHotIdx = hotIdx - 1;
  2790. for (int hotFileIdx = highestCheckHotIdx; hotFileIdx >= 0; hotFileIdx--)
  2791. {
  2792. auto& hotReplacedDbgLineData = wdBreakpoint->mSrcFile->mHotReplacedDbgLineInfo;
  2793. // Only try to bind to an old hot version if we haven't unloaded the hot module
  2794. if ((hotFileIdx < (int)hotReplacedDbgLineData.size()) && (hotReplacedDbgLineData[hotFileIdx]->mEntries.size() > 0))
  2795. {
  2796. headBreakpoint->mPendingHotBindIdx = hotFileIdx;
  2797. break;
  2798. }
  2799. }
  2800. }
  2801. void WinDebugger::HotBindBreakpoint(Breakpoint* breakpoint, int lineNum, int hotIdx)
  2802. {
  2803. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  2804. CheckBreakpoint(wdBreakpoint, wdBreakpoint->mSrcFile, lineNum, hotIdx);
  2805. }
  2806. void WinDebugger::CheckBreakpoint(WdBreakpoint* wdBreakpoint)
  2807. {
  2808. if (!mGotStartupEvent)
  2809. return;
  2810. if (wdBreakpoint->mThreadId == 0) // Not bound to threadId yet...
  2811. {
  2812. return;
  2813. }
  2814. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  2815. {
  2816. if (wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap != 0)
  2817. return;
  2818. if (mFreeMemoryBreakIndices.size() == 0)
  2819. return;
  2820. if ((IsInRunState()) || (mActiveThread == NULL))
  2821. return;
  2822. int wantBytes[4];
  2823. int wantBindCount = 0;
  2824. int bytesLeft = wdBreakpoint->mMemoryBreakpointInfo->mByteCount;
  2825. addr_target curAddr = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress;
  2826. while (bytesLeft > 0)
  2827. {
  2828. if (wantBindCount >= mFreeMemoryBreakIndices.size())
  2829. return;
  2830. int curByteCount = 1;
  2831. #ifdef BF_DBG_64
  2832. if ((bytesLeft >= 8) && ((curAddr & 7) == 0))
  2833. curByteCount = 8;
  2834. else
  2835. #endif
  2836. if ((bytesLeft >= 4) && ((curAddr & 3) == 0))
  2837. curByteCount = 4;
  2838. else if ((bytesLeft >= 2) && ((curAddr & 1) == 0))
  2839. curByteCount = 2;
  2840. wantBytes[wantBindCount++] = curByteCount;
  2841. bytesLeft -= curByteCount;
  2842. curAddr += curByteCount;
  2843. }
  2844. addr_target curOfs = 0;
  2845. for (int i = 0; i < wantBindCount; i++)
  2846. {
  2847. int memoryBreakIdx = mFreeMemoryBreakIndices.back();
  2848. mFreeMemoryBreakIndices.pop_back();
  2849. mMemoryBreakpoints[memoryBreakIdx].mBreakpoint = wdBreakpoint;
  2850. mMemoryBreakpoints[memoryBreakIdx].mAddress = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress + curOfs;
  2851. mMemoryBreakpoints[memoryBreakIdx].mByteCount = wantBytes[i];
  2852. mMemoryBreakpoints[memoryBreakIdx].mOfs = curOfs;
  2853. curOfs += wantBytes[i];
  2854. mMemoryBreakpointVersion++;
  2855. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap |= 1<<memoryBreakIdx;
  2856. }
  2857. UpdateThreadDebugRegisters();
  2858. }
  2859. if (wdBreakpoint->mAddr != 0)
  2860. return;
  2861. if (!wdBreakpoint->mSymbolName.IsEmpty())
  2862. {
  2863. auto headBreakpoint = wdBreakpoint->GetHeadBreakpoint();
  2864. String symbolName = wdBreakpoint->mSymbolName;
  2865. bool onlyBindFirst = false;
  2866. if (symbolName.StartsWith("-"))
  2867. {
  2868. symbolName.Remove(0);
  2869. onlyBindFirst = true;
  2870. }
  2871. for (auto dbgModule : mDebugTarget->mDbgModules)
  2872. {
  2873. dbgModule->ParseSymbolData();
  2874. addr_target targetAddr = -1;
  2875. auto entry = dbgModule->mSymbolNameMap.Find(symbolName.c_str());
  2876. if (entry != NULL)
  2877. {
  2878. DbgSymbol* dwSymbol = entry->mValue;
  2879. targetAddr = dwSymbol->mAddress;
  2880. }
  2881. if (targetAddr == -1)
  2882. {
  2883. if (symbolName == ".")
  2884. {
  2885. targetAddr = mDebugTarget->mLaunchBinary->mImageBase + mDebugTarget->mLaunchBinary->mEntryPoint;
  2886. onlyBindFirst = true;
  2887. }
  2888. }
  2889. if (targetAddr != -1)
  2890. {
  2891. if (wdBreakpoint->mAddr == 0)
  2892. {
  2893. wdBreakpoint->mAddr = targetAddr;
  2894. wdBreakpoint->mBreakpointType = BreakpointType_User;
  2895. mBreakpointAddrMap.ForceAdd(wdBreakpoint->mAddr, wdBreakpoint);
  2896. SetBreakpoint(wdBreakpoint->mAddr);
  2897. }
  2898. else
  2899. {
  2900. wdBreakpoint = new WdBreakpoint();
  2901. // Insert at head
  2902. wdBreakpoint->mLinkedSibling = headBreakpoint->mLinkedSibling;
  2903. headBreakpoint->mLinkedSibling = wdBreakpoint;
  2904. wdBreakpoint->mSymbolName = headBreakpoint->mSymbolName;
  2905. wdBreakpoint->mIsLinkedSibling = true;
  2906. wdBreakpoint->mHead = headBreakpoint;
  2907. }
  2908. if (onlyBindFirst)
  2909. break;
  2910. }
  2911. }
  2912. return;
  2913. }
  2914. BP_ZONE("WinDebugger::CheckBreakpoint");
  2915. // Rehup if we load a DLL that also uses this file we bound to (thus the mDeferredRefs check)
  2916. if (wdBreakpoint->mSrcFile == NULL)
  2917. {
  2918. DbgSrcFile* srcFile = mDebugTarget->GetSrcFile(wdBreakpoint->mFilePath);
  2919. if (srcFile == NULL)
  2920. return;
  2921. for (auto& deferredSrcFileRef : srcFile->mDeferredRefs)
  2922. {
  2923. deferredSrcFileRef.mDbgModule->ParseCompileUnit(deferredSrcFileRef.mCompileUnitId);
  2924. }
  2925. srcFile->mDeferredRefs.Clear();
  2926. CheckBreakpoint(wdBreakpoint, srcFile, wdBreakpoint->mRequestedLineNum, -1);
  2927. }
  2928. }
  2929. bool WinDebugger::IsMemoryBreakpointSizeValid(addr_target addr, int size)
  2930. {
  2931. int wantBindCount = 0;
  2932. int bytesLeft = size;
  2933. addr_target curAddr = addr;
  2934. for (int i = 0; i < 4; i++)
  2935. {
  2936. int curByteCount = 1;
  2937. #ifdef BF_DBG_64
  2938. if ((bytesLeft >= 8) && ((curAddr & 7) == 0))
  2939. curByteCount = 8;
  2940. else
  2941. #endif
  2942. if ((bytesLeft >= 4) && ((curAddr & 3) == 0))
  2943. curByteCount = 4;
  2944. else if ((bytesLeft >= 2) && ((curAddr & 1) == 0))
  2945. curByteCount = 2;
  2946. bytesLeft -= curByteCount;
  2947. curAddr += curByteCount;
  2948. if (bytesLeft == 0)
  2949. return true;
  2950. }
  2951. return false;
  2952. }
  2953. bool WinDebugger::HasMemoryBreakpoint(addr_target addr, int size)
  2954. {
  2955. for (int i = 0; i < 4; i++)
  2956. {
  2957. if ((mMemoryBreakpoints[i].mAddress == addr) &&
  2958. (mMemoryBreakpoints[i].mOfs == 0) &&
  2959. (mMemoryBreakpoints[i].mBreakpoint->mMemoryBreakpointInfo->mByteCount == size))
  2960. return true;
  2961. }
  2962. return false;
  2963. }
  2964. Breakpoint* WinDebugger::CreateBreakpoint(const StringImpl& fileName, int lineNum, int wantColumn, int instrOffset)
  2965. {
  2966. AutoCrit autoCrit(mDebugManager->mCritSect);
  2967. BfLogDbg("CreateBreakpoint %s %d %d\n", fileName.c_str(), lineNum, wantColumn);
  2968. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  2969. wdBreakpoint->mFilePath = FixPathAndCase(fileName);
  2970. wdBreakpoint->mRequestedLineNum = lineNum;
  2971. wdBreakpoint->mLineNum = lineNum;
  2972. wdBreakpoint->mColumn = wantColumn;
  2973. wdBreakpoint->mInstrOffset = instrOffset;
  2974. mBreakpoints.push_back(wdBreakpoint);
  2975. BfLogDbg("CreateBreakpoint Created %p\n", wdBreakpoint);
  2976. return wdBreakpoint;
  2977. }
  2978. void WinDebugger::CheckBreakpoint(Breakpoint* checkBreakpoint)
  2979. {
  2980. AutoCrit autoCrit(mDebugManager->mCritSect);
  2981. CheckBreakpoint((WdBreakpoint*)checkBreakpoint);
  2982. }
  2983. Breakpoint* WinDebugger::CreateMemoryBreakpoint(intptr addr, int byteCount)
  2984. {
  2985. AutoCrit autoCrit(mDebugManager->mCritSect);
  2986. BfLogDbg("CreateMemoryBreakpoint %p %d\n", addr, byteCount);
  2987. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  2988. WdMemoryBreakpointInfo* memoryBreakInfo = new WdMemoryBreakpointInfo();
  2989. memoryBreakInfo->mMemoryAddress = addr;
  2990. memoryBreakInfo->mByteCount = byteCount;
  2991. wdBreakpoint->mMemoryBreakpointInfo = memoryBreakInfo;
  2992. mBreakpoints.push_back(wdBreakpoint);
  2993. CheckBreakpoint(wdBreakpoint);
  2994. return wdBreakpoint;
  2995. }
  2996. Breakpoint* WinDebugger::CreateSymbolBreakpoint(const StringImpl& symbolName)
  2997. {
  2998. AutoCrit autoCrit(mDebugManager->mCritSect);
  2999. BfLogDbg("CreateSymbolBreakpoint %s\n", symbolName.c_str());
  3000. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  3001. wdBreakpoint->mSymbolName = symbolName;
  3002. mBreakpoints.push_back(wdBreakpoint);
  3003. CheckBreakpoint(wdBreakpoint);
  3004. return wdBreakpoint;
  3005. }
  3006. Breakpoint* WinDebugger::CreateAddressBreakpoint(intptr inAddress)
  3007. {
  3008. AutoCrit autoCrit(mDebugManager->mCritSect);
  3009. BfLogDbg("CreateAddressBreakpoint %p\n", inAddress);
  3010. addr_target address = (addr_target)inAddress;
  3011. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  3012. wdBreakpoint->mAddr = address;
  3013. mBreakpointAddrMap.ForceAdd(wdBreakpoint->mAddr, wdBreakpoint);
  3014. SetBreakpoint(address);
  3015. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mStoppedAtAddress == address))
  3016. {
  3017. BfLogDbg("CreateAddressBreakpoint setting mIsAtBreakpointAddress = %p\n", address);
  3018. mDebuggerWaitingThread->mIsAtBreakpointAddress = address;
  3019. }
  3020. mBreakpoints.push_back(wdBreakpoint);
  3021. return wdBreakpoint;
  3022. }
  3023. void WinDebugger::DeleteBreakpoint(Breakpoint* breakpoint)
  3024. {
  3025. AutoCrit autoCrit(mDebugManager->mCritSect);
  3026. if (breakpoint == mActiveBreakpoint)
  3027. mActiveBreakpoint = NULL;
  3028. BfLogDbg("WinDebugger::DeleteBreakpoint %p Count:%d\n", breakpoint, mBreakpoints.size());
  3029. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3030. if (wdBreakpoint->mCondition != NULL)
  3031. {
  3032. if (!wdBreakpoint->mIsLinkedSibling)
  3033. delete wdBreakpoint->mCondition;
  3034. }
  3035. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  3036. {
  3037. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  3038. {
  3039. if (mMemoryBreakpoints[memoryWatchSlot].mBreakpoint == wdBreakpoint)
  3040. {
  3041. mFreeMemoryBreakIndices.push_back(memoryWatchSlot);
  3042. mMemoryBreakpoints[memoryWatchSlot] = WdMemoryBreakpointBind();
  3043. mMemoryBreakpointVersion++;
  3044. UpdateThreadDebugRegisters();
  3045. }
  3046. }
  3047. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap = 0;
  3048. }
  3049. if (wdBreakpoint->mAddr != 0)
  3050. {
  3051. mBreakpointAddrMap.Remove(wdBreakpoint->mAddr, wdBreakpoint);
  3052. RemoveBreakpoint(wdBreakpoint->mAddr);
  3053. for (auto thread : mThreadList)
  3054. {
  3055. if (thread->mIsAtBreakpointAddress == wdBreakpoint->mAddr)
  3056. thread->mIsAtBreakpointAddress = NULL;
  3057. if (thread->mBreakpointAddressContinuing == wdBreakpoint->mAddr)
  3058. thread->mBreakpointAddressContinuing = NULL;
  3059. }
  3060. }
  3061. if (!wdBreakpoint->mIsLinkedSibling)
  3062. {
  3063. mBreakpoints.Remove(wdBreakpoint);
  3064. }
  3065. if (wdBreakpoint->mLinkedSibling != NULL)
  3066. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  3067. delete wdBreakpoint;
  3068. }
  3069. void WinDebugger::DetachBreakpoint(Breakpoint* breakpoint)
  3070. {
  3071. AutoCrit autoCrit(mDebugManager->mCritSect);
  3072. BfLogDbg("WinDebugger::DetachBreakpoint %p\n", breakpoint);
  3073. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3074. if (wdBreakpoint->mAddr != 0)
  3075. {
  3076. mBreakpointAddrMap.Remove(wdBreakpoint->mAddr, wdBreakpoint);
  3077. RemoveBreakpoint(wdBreakpoint->mAddr);
  3078. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mIsAtBreakpointAddress == wdBreakpoint->mAddr))
  3079. mDebuggerWaitingThread->mIsAtBreakpointAddress = NULL;
  3080. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mBreakpointAddressContinuing == wdBreakpoint->mAddr))
  3081. mDebuggerWaitingThread->mBreakpointAddressContinuing = NULL;
  3082. wdBreakpoint->mLineData = DbgLineDataEx();
  3083. wdBreakpoint->mAddr = 0;
  3084. }
  3085. if (wdBreakpoint->mCondition != NULL)
  3086. {
  3087. delete wdBreakpoint->mCondition->mDbgEvaluationContext;
  3088. wdBreakpoint->mCondition->mDbgEvaluationContext = NULL;
  3089. }
  3090. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  3091. {
  3092. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  3093. {
  3094. if (mMemoryBreakpoints[memoryWatchSlot].mBreakpoint == wdBreakpoint)
  3095. {
  3096. mFreeMemoryBreakIndices.push_back(memoryWatchSlot);
  3097. mMemoryBreakpoints[memoryWatchSlot] = WdMemoryBreakpointBind();
  3098. mMemoryBreakpointVersion++;
  3099. UpdateThreadDebugRegisters();
  3100. }
  3101. }
  3102. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap = 0;
  3103. }
  3104. if (wdBreakpoint->mLinkedSibling != NULL)
  3105. {
  3106. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  3107. wdBreakpoint->mLinkedSibling = NULL;
  3108. }
  3109. wdBreakpoint->mSrcFile = NULL;
  3110. wdBreakpoint->mPendingHotBindIdx = -1;
  3111. }
  3112. void WinDebugger::MoveBreakpoint(Breakpoint* breakpoint, int lineNum, int wantColumn, bool rebindNow)
  3113. {
  3114. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3115. AutoCrit autoCrit(mDebugManager->mCritSect);
  3116. DetachBreakpoint(wdBreakpoint);
  3117. //TODO: This doesn't actually rebind correctly while the app is running
  3118. if ((lineNum != -1) && (wantColumn != -1))
  3119. {
  3120. wdBreakpoint->mRequestedLineNum = lineNum;
  3121. wdBreakpoint->mLineNum = lineNum;
  3122. wdBreakpoint->mColumn = wantColumn;
  3123. }
  3124. if (rebindNow)
  3125. CheckBreakpoint(wdBreakpoint);
  3126. }
  3127. void WinDebugger::MoveMemoryBreakpoint(Breakpoint* breakpoint, intptr addr, int byteCount)
  3128. {
  3129. AutoCrit autoCrit(mDebugManager->mCritSect);
  3130. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3131. DetachBreakpoint(wdBreakpoint);
  3132. wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress = addr;
  3133. wdBreakpoint->mMemoryBreakpointInfo->mByteCount = byteCount;
  3134. CheckBreakpoint(wdBreakpoint);
  3135. }
  3136. void WinDebugger::DisableBreakpoint(Breakpoint* breakpoint)
  3137. {
  3138. AutoCrit autoCrit(mDebugManager->mCritSect);
  3139. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3140. DetachBreakpoint(wdBreakpoint);
  3141. delete wdBreakpoint->mMemoryBreakpointInfo;
  3142. wdBreakpoint->mMemoryBreakpointInfo = NULL;
  3143. }
  3144. void WinDebugger::SetBreakpointCondition(Breakpoint* breakpoint, const StringImpl& conditionExpr)
  3145. {
  3146. AutoCrit autoCrit(mDebugManager->mCritSect);
  3147. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3148. BF_ASSERT(!wdBreakpoint->mIsLinkedSibling);
  3149. if (conditionExpr.empty())
  3150. {
  3151. delete wdBreakpoint->mCondition;
  3152. WdBreakpoint* curBreakpoint = wdBreakpoint;
  3153. wdBreakpoint->mCondition = NULL;
  3154. }
  3155. else
  3156. {
  3157. delete wdBreakpoint->mCondition;
  3158. auto condition = new WdBreakpointCondition();
  3159. condition->mExpr = conditionExpr;
  3160. wdBreakpoint->mCondition = condition;
  3161. }
  3162. }
  3163. void WinDebugger::SetBreakpointLogging(Breakpoint* breakpoint, const StringImpl& logging, bool breakAfterLogging)
  3164. {
  3165. AutoCrit autoCrit(mDebugManager->mCritSect);
  3166. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3167. BF_ASSERT(!wdBreakpoint->mIsLinkedSibling);
  3168. wdBreakpoint->mLogging = logging;
  3169. wdBreakpoint->mBreakAfterLogging = breakAfterLogging;
  3170. }
  3171. bool WinDebugger::CheckConditionalBreakpoint(WdBreakpoint* breakpoint, DbgSubprogram* dbgSubprogram, addr_target pcAddress)
  3172. {
  3173. // What was this assertion for?
  3174. //BF_ASSERT(mCallStack.size() == 0);
  3175. auto headBreakpoint = breakpoint->GetHeadBreakpoint();
  3176. if (headBreakpoint->mThreadId != -1)
  3177. {
  3178. if ((mActiveThread != NULL) && (mActiveThread->mThreadId != headBreakpoint->mThreadId))
  3179. return false;
  3180. }
  3181. auto _SplitExpr = [&](const StringImpl& expr, StringImpl& outExpr, StringImpl& outSubject)
  3182. {
  3183. int crPos = expr.IndexOf('\n');
  3184. if (crPos != -1)
  3185. {
  3186. outExpr += expr.Substring(0, crPos);
  3187. outSubject += expr.Substring(crPos + 1);
  3188. }
  3189. else
  3190. {
  3191. outExpr += expr;
  3192. }
  3193. };
  3194. if (headBreakpoint->mCondition != NULL)
  3195. {
  3196. ClearCallStack();
  3197. auto conditional = headBreakpoint->mCondition;
  3198. if (conditional->mDbgEvaluationContext == NULL)
  3199. {
  3200. CPURegisters registers;
  3201. PopulateRegisters(&registers);
  3202. auto pcAddress = registers.GetPC();
  3203. DbgSubprogram* subprogram = mDebugTarget->FindSubProgram(pcAddress);
  3204. if (subprogram == NULL)
  3205. {
  3206. return false;
  3207. }
  3208. StringT<256> expr;
  3209. StringT<256> subjectExpr;
  3210. if (breakpoint->mMemoryBreakpointInfo != NULL)
  3211. {
  3212. subjectExpr += "*";
  3213. }
  3214. _SplitExpr(conditional->mExpr, expr, subjectExpr);
  3215. DbgLanguage language = DbgLanguage_Unknown;
  3216. if (expr.StartsWith("@Beef:"))
  3217. {
  3218. expr.Remove(0, 6);
  3219. language = DbgLanguage_Beef;
  3220. }
  3221. else if (expr.StartsWith("@C:"))
  3222. {
  3223. expr.Remove(0, 3);
  3224. language = DbgLanguage_C;
  3225. }
  3226. conditional->mDbgEvaluationContext = new DbgEvaluationContext(this, subprogram->mCompileUnit->mDbgModule, expr);
  3227. if (language != DbgLanguage_Unknown)
  3228. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mLanguage = language;
  3229. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mSubjectExpr = subjectExpr;
  3230. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mDbgCompileUnit = subprogram->mCompileUnit;
  3231. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mCallStackIdx = 0;
  3232. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mExpressionFlags = (DwEvalExpressionFlags)(DwEvalExpressionFlag_AllowSideEffects);
  3233. }
  3234. WdStackFrame* wdStackFrame = new WdStackFrame();
  3235. PopulateRegisters(&wdStackFrame->mRegisters);
  3236. mCallStack.Add(wdStackFrame);
  3237. DbgTypedValue result = conditional->mDbgEvaluationContext->EvaluateInContext(DbgTypedValue());
  3238. ClearCallStack();
  3239. if ((result.mType != NULL) && (result.mType->mTypeCode == DbgType_Bitfield))
  3240. result.mType = result.mType->mTypeParam;
  3241. if (conditional->mDbgEvaluationContext->mPassInstance->HasFailed())
  3242. {
  3243. String errorStr = "FAILED";
  3244. for (auto error : conditional->mDbgEvaluationContext->mPassInstance->mErrors)
  3245. {
  3246. if (!error->mIsWarning)
  3247. errorStr = error->mError;
  3248. }
  3249. String condError = StrFormat("error Conditional breakpoint expression '%s' failed: %s", conditional->mExpr.c_str(), errorStr.c_str());
  3250. mDebugManager->mOutMessages.push_back(condError);
  3251. return true;
  3252. }
  3253. else if (conditional->mDbgEvaluationContext->mDbgExprEvaluator->mBlockedSideEffects)
  3254. {
  3255. mDebugManager->mOutMessages.push_back(StrFormat("error Conditional breakpoint expression '%s' contained function calls, which is not allowed", conditional->mExpr.c_str()));
  3256. return true;
  3257. }
  3258. else if ((!result) || (!result.mType->IsBoolean()))
  3259. {
  3260. mDebugManager->mOutMessages.push_back(StrFormat("error Conditional breakpoint expression '%s' must result in a boolean value", conditional->mExpr.c_str()));
  3261. return true;
  3262. }
  3263. else if (!result.mBool)
  3264. return false;
  3265. }
  3266. headBreakpoint->mHitCount++;
  3267. switch (headBreakpoint->mHitCountBreakKind)
  3268. {
  3269. case DbgHitCountBreakKind_Equals:
  3270. if (headBreakpoint->mHitCount != headBreakpoint->mTargetHitCount)
  3271. return false;
  3272. break;
  3273. case DbgHitCountBreakKind_GreaterEquals:
  3274. if (headBreakpoint->mHitCount < headBreakpoint->mTargetHitCount)
  3275. return false;
  3276. break;
  3277. case DbgHitCountBreakKind_Multiple:
  3278. if ((headBreakpoint->mHitCount % headBreakpoint->mTargetHitCount) != 0)
  3279. return false;
  3280. break;
  3281. }
  3282. mActiveBreakpoint = breakpoint;
  3283. mBreakStackFrameIdx = -1;
  3284. if (!headBreakpoint->mLogging.IsEmpty())
  3285. {
  3286. ClearCallStack();
  3287. DwFormatInfo formatInfo;
  3288. formatInfo.mCallStackIdx = 0;
  3289. DbgCompileUnit* dbgCompileUnit = NULL;
  3290. if (dbgSubprogram == NULL)
  3291. dbgSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3292. if (dbgSubprogram != NULL)
  3293. {
  3294. dbgCompileUnit = dbgSubprogram->mCompileUnit;
  3295. formatInfo.mLanguage = dbgSubprogram->GetLanguage();
  3296. }
  3297. auto prevRunState = mRunState;
  3298. mRunState = RunState_Paused; // We need to be paused to avoid certain errors in the eval
  3299. String displayString;
  3300. String expr;
  3301. _SplitExpr(headBreakpoint->mLogging, expr, formatInfo.mSubjectExpr);
  3302. if (expr.StartsWith("@Beef:"))
  3303. {
  3304. expr.Remove(0, 6);
  3305. formatInfo.mLanguage = DbgLanguage_Beef;
  3306. }
  3307. else if (expr.StartsWith("@C:"))
  3308. {
  3309. expr.Remove(0, 3);
  3310. formatInfo.mLanguage = DbgLanguage_C;
  3311. }
  3312. ProcessEvalString(dbgCompileUnit, DbgTypedValue(), expr, displayString, formatInfo, NULL, false);
  3313. mRunState = prevRunState;
  3314. displayString.Insert(0, "log ");
  3315. displayString.Append("\n");
  3316. mDebugManager->mOutMessages.push_back(displayString);
  3317. if (!headBreakpoint->mBreakAfterLogging)
  3318. return false;
  3319. }
  3320. return true;
  3321. }
  3322. void WinDebugger::CleanupDebugEval(bool restoreRegisters)
  3323. {
  3324. BfLogDbg("CleanupDebugEval ThreadId=%d\n", mDebugEvalThreadInfo.mThreadId);
  3325. WdThreadInfo* evalThreadInfo = NULL;
  3326. if (mThreadMap.TryGetValue(mDebugEvalThreadInfo.mThreadId, &evalThreadInfo))
  3327. {
  3328. if ((restoreRegisters) && (!mDbgBreak))
  3329. {
  3330. SetAndRestoreValue<WdThreadInfo*> activeThread(mActiveThread, evalThreadInfo);
  3331. RestoreAllRegisters();
  3332. // if (mRunState == RunState_Running_ToTempBreakpoint)
  3333. // mRunState = RunState_Paused;
  3334. }
  3335. evalThreadInfo->mStartSP = mDebugEvalThreadInfo.mStartSP;
  3336. evalThreadInfo->mStoppedAtAddress = mDebugEvalThreadInfo.mStoppedAtAddress;
  3337. evalThreadInfo->mIsAtBreakpointAddress = mDebugEvalThreadInfo.mIsAtBreakpointAddress;
  3338. evalThreadInfo->mBreakpointAddressContinuing = mDebugEvalThreadInfo.mBreakpointAddressContinuing;
  3339. }
  3340. delete mDebugPendingExpr;
  3341. mDebugPendingExpr = NULL;
  3342. mDebugEvalThreadInfo = WdThreadInfo();
  3343. OutputRawMessage("rehupLoc");
  3344. }
  3345. bool WinDebugger::FixCallStackIdx(int& callStackIdx)
  3346. {
  3347. callStackIdx = BF_MAX(callStackIdx, 0);
  3348. if (mCallStack.IsEmpty())
  3349. UpdateCallStack();
  3350. int stackSize = (int)mCallStack.size();
  3351. while (callStackIdx >= mCallStack.size())
  3352. {
  3353. UpdateCallStack();
  3354. if (stackSize == (int)mCallStack.size())
  3355. break; // Didn't change
  3356. stackSize = (int)mCallStack.size();
  3357. }
  3358. if (callStackIdx >= stackSize)
  3359. {
  3360. callStackIdx = 0;
  3361. return false;
  3362. }
  3363. return true;
  3364. }
  3365. bool WinDebugger::HasLineInfoAt(addr_target address)
  3366. {
  3367. BP_ZONE("WinDebugger::HasLineInfoAt");
  3368. DbgSubprogram* dbgSubprogram = NULL;
  3369. auto dwLineData = FindLineDataAtAddress(address, &dbgSubprogram);
  3370. return (dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dbgSubprogram->GetLineAddr(*dwLineData) == address);
  3371. }
  3372. void WinDebugger::StepLineTryPause(addr_target address, bool requireExactMatch)
  3373. {
  3374. if (mStepInAssembly)
  3375. return;
  3376. if (mStepLineData.mLineData != NULL)
  3377. {
  3378. DbgSubprogram* dbgSubprogram = NULL;
  3379. DbgSrcFile* dbgSrcFile = NULL;
  3380. auto dwLineData = FindLineDataAtAddress(address, &dbgSubprogram, &dbgSrcFile);
  3381. if ((dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && ((!requireExactMatch) || (dbgSubprogram->GetLineAddr(*dwLineData) == address)))
  3382. {
  3383. // "Invalid" line
  3384. if (dwLineData->mColumn == -1)
  3385. {
  3386. SetupStep(mStepType);
  3387. mRunState = RunState_Running;
  3388. return;
  3389. }
  3390. // If we're on the same line but a different column or a <= address then keep it keep looking
  3391. if ((dbgSrcFile == mStepLineData.GetSrcFile()) &&
  3392. ((!requireExactMatch) || (dwLineData != mStepLineData.mLineData) || (address <= mStepStartPC)) &&
  3393. (dwLineData->mLine == mStepLineData.mLineData->mLine))
  3394. {
  3395. SetupStep(mStepType);
  3396. mRunState = RunState_Running;
  3397. return;
  3398. }
  3399. }
  3400. }
  3401. mRunState = RunState_Paused;
  3402. }
  3403. void WinDebugger::BreakAll()
  3404. {
  3405. AutoCrit autoCrit(mDebugManager->mCritSect);
  3406. ::DebugBreakProcess(mProcessInfo.hProcess);
  3407. }
  3408. void WinDebugger::StepInto(bool inAssembly)
  3409. {
  3410. AutoCrit autoCrit(mDebugManager->mCritSect);
  3411. if (!TryRunContinue())
  3412. return;
  3413. BfLogDbg("StepInto\n");
  3414. mCurNoInfoStepTries = 0; // Reset
  3415. mStepInAssembly = inAssembly;
  3416. SetupStep(StepType_StepInto);
  3417. ContinueDebugEvent();
  3418. }
  3419. void WinDebugger::StepIntoSpecific(intptr inAddr)
  3420. {
  3421. addr_target addr = (addr_target)inAddr;
  3422. AutoCrit autoCrit(mDebugManager->mCritSect);
  3423. if (!TryRunContinue())
  3424. return;
  3425. BfLogDbg("StepIntoSpecific %p\n", addr);
  3426. mCurNoInfoStepTries = 0; // Reset
  3427. mStepInAssembly = false;
  3428. SetupStep(StepType_StepInto);
  3429. mIsStepIntoSpecific = true;
  3430. mStepType = StepType_StepInto_Unfiltered;
  3431. if (mStepStartPC != addr)
  3432. {
  3433. RemoveTempBreakpoints();
  3434. SetTempBreakpoint(addr);
  3435. mStepBreakpointAddrs.push_back(addr);
  3436. }
  3437. ContinueDebugEvent();
  3438. }
  3439. void WinDebugger::PushValue(CPURegisters* registers, int64 val)
  3440. {
  3441. addr_target* regSP = registers->GetSPRegisterRef();
  3442. *regSP -= sizeof(addr_target);
  3443. WriteMemory<addr_target>(*regSP, (addr_target)val);
  3444. }
  3445. void WinDebugger::PushValue(CPURegisters* registers, const DbgTypedValue& typedValue)
  3446. {
  3447. addr_target* regSP = registers->GetSPRegisterRef();
  3448. int byteCount = typedValue.mType->GetByteCount();
  3449. if ((byteCount == 8) || (sizeof(addr_target) == 8))
  3450. {
  3451. *regSP -= sizeof(int64);
  3452. addr_target val = typedValue.mInt64;
  3453. if (typedValue.mType->IsCompositeType())
  3454. val = typedValue.mSrcAddress;
  3455. WriteMemory<int64>(*regSP, val);
  3456. }
  3457. else
  3458. {
  3459. *regSP -= sizeof(int32);
  3460. addr_target val = typedValue.mInt32;
  3461. if (typedValue.mType->IsCompositeType())
  3462. val = typedValue.mSrcAddress;
  3463. WriteMemory<int32>(*regSP, val);
  3464. }
  3465. }
  3466. void WinDebugger::SetThisRegister(CPURegisters* registers, addr_target val)
  3467. {
  3468. #if BF_DBG_32
  3469. registers->mIntRegs.ecx = val;
  3470. #else
  3471. registers->mIntRegs.rcx = val;
  3472. #endif
  3473. }
  3474. void WinDebugger::AddParamValue(int paramIdx, bool hadThis, CPURegisters* registers, const DbgTypedValue& typedValue)
  3475. {
  3476. #if BF_DBG_32
  3477. PushValue(registers, typedValue);
  3478. #else
  3479. int regIdx = paramIdx + (hadThis ? 1 : 0);
  3480. if (typedValue.mType->IsFloat())
  3481. {
  3482. PushValue(registers, typedValue);
  3483. if (regIdx < 4)
  3484. {
  3485. if (typedValue.mType->mTypeCode == DbgType_Single)
  3486. {
  3487. registers->mXmmRegsArray[regIdx].f[0] = typedValue.mSingle;
  3488. }
  3489. else
  3490. {
  3491. registers->mXmmDRegsArray[regIdx].d[0] = typedValue.mDouble;
  3492. }
  3493. }
  3494. }
  3495. else
  3496. {
  3497. PushValue(registers, typedValue);
  3498. if (regIdx < 4)
  3499. {
  3500. int64 val;
  3501. if (typedValue.mType->IsCompositeType())
  3502. val = typedValue.mSrcAddress;
  3503. else
  3504. val = typedValue.mPtr;
  3505. if (regIdx == 0)
  3506. registers->mIntRegs.rcx = val;
  3507. else if (regIdx == 1)
  3508. registers->mIntRegs.rdx = val;
  3509. else if (regIdx == 2)
  3510. registers->mIntRegs.r8 = val;
  3511. else if (regIdx == 3)
  3512. registers->mIntRegs.r9 = val;
  3513. }
  3514. }
  3515. #endif
  3516. }
  3517. bool WinDebugger::CheckNeedsSRetArgument(DbgType* retType)
  3518. {
  3519. if (!retType->IsCompositeType())
  3520. return false;
  3521. if (retType->GetByteCount() == 0)
  3522. return false;
  3523. //TODO: Change when we change the calling convention
  3524. if (retType->GetLanguage() == DbgLanguage_Beef)
  3525. return true;
  3526. int retSize = retType->GetByteCount();
  3527. //TODO: Check for 'POD' type?
  3528. if ((retSize == 1) || (retSize == 2) || (retSize == 4) || (retSize == sizeof(addr_target)))
  3529. return false;
  3530. return true;
  3531. }
  3532. DbgTypedValue WinDebugger::ReadReturnValue(CPURegisters* registers, DbgType* type)
  3533. {
  3534. DbgTypedValue retValue;
  3535. if (type->IsFloat())
  3536. {
  3537. retValue.mType = type;
  3538. #if BF_DBG_32
  3539. retValue.mDouble = ConvertFloat80ToDouble(registers->mFpMmRegsArray[0].fp.fp80);
  3540. if (type->mSize == 4)
  3541. retValue.mSingle = (float)retValue.mDouble;
  3542. #else
  3543. if (retValue.mType->mTypeCode == DbgType_Single)
  3544. retValue.mSingle = registers->mXmmRegsArray[0].f[0];
  3545. else
  3546. retValue.mDouble = registers->mXmmDRegsArray[0].d[0];
  3547. #endif
  3548. }
  3549. else if (type->IsCompositeType())
  3550. {
  3551. retValue.mType = type;
  3552. if (CheckNeedsSRetArgument(type))
  3553. {
  3554. #ifdef BF_DBG_32
  3555. retValue.mSrcAddress = mSavedContext.Esp - BF_ALIGN(type->GetByteCount(), 16);
  3556. #else
  3557. retValue.mSrcAddress = mSavedContext.Rsp - BF_ALIGN(type->GetByteCount(), 16);
  3558. #endif
  3559. }
  3560. else
  3561. {
  3562. #ifdef BF_DBG_32
  3563. retValue.mInt32 = mSavedContext.Eax;
  3564. #else
  3565. retValue.mInt64 = mSavedContext.Rax;
  3566. #endif
  3567. }
  3568. }
  3569. else
  3570. {
  3571. #ifdef BF_DBG_32
  3572. retValue.mType = type;
  3573. retValue.mInt32 = registers->mIntRegs.eax;
  3574. if (type->mSize == 8)
  3575. (&retValue.mInt32)[1] = registers->mIntRegs.edx;
  3576. #else
  3577. retValue.mType = type;
  3578. retValue.mInt64 = registers->mIntRegs.rax;
  3579. #endif
  3580. return retValue;
  3581. }
  3582. return retValue;
  3583. }
  3584. bool WinDebugger::SetRegisters(CPURegisters* registers)
  3585. {
  3586. BF_CONTEXT lcContext;
  3587. lcContext.ContextFlags = BF_CONTEXT_CONTROL | BF_CONTEXT_INTEGER | BF_CONTEXT_FLOATING_POINT | BF_CONTEXT_EXTENDED_REGISTERS | BF_CONTEXT_SEGMENTS;
  3588. lcContext.ContextFlags |= BF_CONTEXT_EXCEPTION_REQUEST;
  3589. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  3590. #ifdef BF_DBG_32
  3591. lcContext.Eax = registers->mIntRegs.eax;
  3592. lcContext.Ecx = registers->mIntRegs.ecx;
  3593. lcContext.Edx = registers->mIntRegs.edx;
  3594. lcContext.Ebx = registers->mIntRegs.ebx;
  3595. lcContext.Esp = registers->mIntRegs.esp;
  3596. lcContext.Ebp = registers->mIntRegs.ebp;
  3597. lcContext.Esi = registers->mIntRegs.esi;
  3598. lcContext.Edi = registers->mIntRegs.edi;
  3599. lcContext.Eip = registers->mIntRegs.eip;
  3600. lcContext.EFlags = registers->mIntRegs.efl;
  3601. BF_ASSERT(sizeof(lcContext.FloatSave.RegisterArea) == sizeof(registers->mFpMmRegsArray));
  3602. memcpy(lcContext.FloatSave.RegisterArea, registers->mFpMmRegsArray, sizeof(lcContext.FloatSave.RegisterArea));
  3603. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 32*sizeof(float));
  3604. memcpy(&lcContext.ExtendedRegisters[160], registers->mXmmRegsArray, sizeof(registers->mXmmRegsArray));
  3605. #else
  3606. lcContext.Rax = registers->mIntRegs.rax;
  3607. lcContext.Rcx = registers->mIntRegs.rcx;
  3608. lcContext.Rdx = registers->mIntRegs.rdx;
  3609. lcContext.Rbx = registers->mIntRegs.rbx;
  3610. lcContext.Rsp = registers->mIntRegs.rsp;
  3611. lcContext.Rbp = registers->mIntRegs.rbp;
  3612. lcContext.Rsi = registers->mIntRegs.rsi;
  3613. lcContext.Rdi = registers->mIntRegs.rdi;
  3614. lcContext.Rip = registers->mIntRegs.rip;
  3615. lcContext.EFlags = (DWORD)registers->mIntRegs.efl;
  3616. lcContext.R8 = registers->mIntRegs.r8;
  3617. lcContext.R9 = registers->mIntRegs.r9;
  3618. lcContext.R10 = registers->mIntRegs.r10;
  3619. lcContext.R11 = registers->mIntRegs.r11;
  3620. lcContext.R12 = registers->mIntRegs.r12;
  3621. lcContext.R13 = registers->mIntRegs.r13;
  3622. lcContext.R14 = registers->mIntRegs.r14;
  3623. lcContext.R15 = registers->mIntRegs.r15;
  3624. for (int i = 0; i < 8; i++)
  3625. {
  3626. memcpy(&lcContext.FltSave.FloatRegisters[i], &registers->mFpMmRegsArray[i], 10);
  3627. }
  3628. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 64 * sizeof(float));
  3629. memcpy(BF_CONTEXT_XMMDATA(lcContext), registers->mXmmRegsArray, sizeof(registers->mXmmRegsArray));
  3630. #endif
  3631. //lcContext.ContextFlags |= BF_CONTEXT_EXCEPTION_REQUEST;
  3632. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  3633. return (lcContext.ContextFlags & (BF_CONTEXT_EXCEPTION_ACTIVE | BF_CONTEXT_SERVICE_ACTIVE)) == 0;
  3634. }
  3635. void WinDebugger::SaveAllRegisters()
  3636. {
  3637. BfLogDbg("SaveAllRegisters setting mSavedAtBreakpointAddress = %p\n", mActiveThread->mIsAtBreakpointAddress);
  3638. mSavedAtBreakpointAddress = mActiveThread->mIsAtBreakpointAddress;
  3639. mSavedBreakpointAddressContinuing = mActiveThread->mBreakpointAddressContinuing;
  3640. mSavedContext.ContextFlags = BF_CONTEXT_ALL;
  3641. BF_GetThreadContext(mActiveThread->mHThread, &mSavedContext);
  3642. }
  3643. void WinDebugger::RestoreAllRegisters()
  3644. {
  3645. BfLogDbg("RestoreAllRegisters setting mIsAtBreakpointAddress = %p\n", mSavedAtBreakpointAddress);
  3646. mActiveThread->mIsAtBreakpointAddress = mSavedAtBreakpointAddress;
  3647. mActiveThread->mBreakpointAddressContinuing = mSavedBreakpointAddressContinuing;
  3648. BF_SetThreadContext(mActiveThread->mHThread, &mSavedContext);
  3649. #ifdef BF_DBG_32
  3650. //TODO: Find the test that this was required for...
  3651. // if (mActiveThread->mIsAtBreakpointAddress == mSavedContext.Eip)
  3652. // {
  3653. // if (mRunState == RunState_Running_ToTempBreakpoint)
  3654. // mRunState = RunState_Paused;
  3655. // }
  3656. // else
  3657. // {
  3658. // SetTempBreakpoint(mSavedContext.Eip);
  3659. // mRunState = RunState_Running_ToTempBreakpoint;
  3660. // mStepType = StepType_ToTempBreakpoint;
  3661. // mSteppingThread = mActiveThread;
  3662. // }
  3663. #endif
  3664. }
  3665. void WinDebugger::OutputMessage(const StringImpl& msg)
  3666. {
  3667. if (this == NULL)
  3668. return;
  3669. AutoCrit autoCrit(mDebugManager->mCritSect);
  3670. mDebugManager->mOutMessages.push_back("msg " + msg);
  3671. }
  3672. void WinDebugger::OutputRawMessage(const StringImpl& msg)
  3673. {
  3674. if (this == NULL)
  3675. return;
  3676. AutoCrit autoCrit(mDebugManager->mCritSect);
  3677. mDebugManager->mOutMessages.push_back(msg);
  3678. }
  3679. void WinDebugger::SetRunState(RunState runState)
  3680. {
  3681. mRunState = runState;
  3682. }
  3683. bool WinDebugger::TryRunContinue()
  3684. {
  3685. if (mRunState == RunState_Exception)
  3686. {
  3687. mIsContinuingFromException = true;
  3688. mRunState = RunState_Paused;
  3689. }
  3690. if (((mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint)) && (mNeedsRehupBreakpoints))
  3691. RehupBreakpoints(true);
  3692. return true;
  3693. }
  3694. void WinDebugger::ClearStep()
  3695. {
  3696. BfLogDbg("ClearStep\n");
  3697. RemoveTempBreakpoints();
  3698. mOrigStepType = StepType_None;
  3699. mStepType = StepType_None;
  3700. mStepStartPC = 0;
  3701. mStepSP = 0;
  3702. mStepPC = 0;
  3703. mIsStepIntoSpecific = false;
  3704. mStepIsRecursing = false;
  3705. mStepStopOnNextInstruction = false;
  3706. mStepLineData = DbgLineDataEx();
  3707. }
  3708. bool WinDebugger::SetupStep(StepType stepType)
  3709. {
  3710. BP_ZONE("SetupStep");
  3711. RemoveTempBreakpoints();
  3712. if (mNeedsRehupBreakpoints)
  3713. RehupBreakpoints(true);
  3714. if (mOrigStepType == StepType_None)
  3715. mOrigStepType = stepType;
  3716. mStepType = stepType;
  3717. mSteppingThread = mActiveThread;
  3718. mStepSwitchedThreads = false;
  3719. mContinueFromBreakpointFailed = false;
  3720. CPURegisters registers;
  3721. PopulateRegisters(&registers);
  3722. addr_target pcAddress = registers.GetPC();
  3723. if (mStepLineData.IsNull())
  3724. {
  3725. DbgSubprogram* dbgSubprogram = NULL;
  3726. auto dbgLineData = FindLineDataAtAddress(pcAddress, &dbgSubprogram);
  3727. mStepLineData = DbgLineDataEx(dbgLineData, dbgSubprogram);
  3728. mStepStartPC = registers.GetPC();
  3729. }
  3730. bool isDeeper = mStepSP > registers.GetSP();
  3731. BfLogDbg("SetupStep %d PC:%p SP:%p StepStartSP:%p Thread:%d\n", stepType, (addr_target)registers.GetPC(), (addr_target)registers.GetSP(), (addr_target)mStepSP, mSteppingThread->mThreadId);
  3732. mStepSP = registers.GetSP();
  3733. mStepPC = registers.GetPC();
  3734. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_NoFrame) || (mStepType == StepType_StepOut_ThenInto))
  3735. {
  3736. if (mStepType != StepType_StepOut_NoFrame)
  3737. {
  3738. // Test for stepping out of an inline method
  3739. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3740. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL))
  3741. {
  3742. DbgSubprogram* topSubprogram = dwSubprogram->GetRootInlineParent();
  3743. if ((mOrigStepType == StepType_StepInto) || (mOrigStepType == StepType_StepInto_Unfiltered))
  3744. {
  3745. mStepType = mOrigStepType;
  3746. }
  3747. else
  3748. {
  3749. mStepType = StepType_StepOut_Inline;
  3750. // Set up pcAddress to detect recursion
  3751. //TODO: We can't set a physical breakpoint here because we will immediately hit it when attempting to step over an inlined method.
  3752. // An inlined method can't recurse anyway, but store the pcAddress in mTempBreakpoints because we still check that for recursion
  3753. // SetTempBreakpoint(pcAddress);
  3754. //mTempBreakpoint.push_back(pcAddress);
  3755. mStepBreakpointAddrs.push_back(pcAddress);
  3756. }
  3757. addr_target endAddress = dwSubprogram->mBlock.mHighPC;
  3758. if (dwSubprogram->mHasLineAddrGaps)
  3759. {
  3760. // Keep bumping out the address as long as we can find lines that contain the nextPC
  3761. addr_target nextAddr = pcAddress;
  3762. for (auto& lineInfo : topSubprogram->mLineInfo->mLines)
  3763. {
  3764. auto lineAddr = topSubprogram->GetLineAddr(lineInfo);
  3765. if ((nextAddr >= lineAddr) && (nextAddr < lineAddr + lineInfo.mContribSize))
  3766. {
  3767. auto ctx = topSubprogram->mLineInfo->mContexts[lineInfo.mCtxIdx];
  3768. if (ctx.mInlinee == dwSubprogram)
  3769. {
  3770. nextAddr = lineAddr + lineInfo.mContribSize;
  3771. }
  3772. }
  3773. }
  3774. if (nextAddr != pcAddress)
  3775. endAddress = nextAddr;
  3776. }
  3777. BfLogDbg("Stepping out of inlined method, end address: %p\n", endAddress);
  3778. SetTempBreakpoint(endAddress);
  3779. mStepBreakpointAddrs.push_back(endAddress);
  3780. addr_target decodeAddress = dwSubprogram->mBlock.mLowPC;
  3781. while (decodeAddress < endAddress)
  3782. {
  3783. CPUInst inst;
  3784. if (!mDebugTarget->DecodeInstruction(decodeAddress, &inst))
  3785. break;
  3786. addr_target targetAddress = inst.GetTarget();
  3787. // We need to find a targetAddress
  3788. if ((targetAddress != 0) &&
  3789. !((targetAddress >= dwSubprogram->mBlock.mLowPC) && (targetAddress < dwSubprogram->mBlock.mHighPC)) &&
  3790. ((targetAddress >= topSubprogram->mBlock.mLowPC) && (targetAddress < topSubprogram->mBlock.mHighPC)))
  3791. {
  3792. BfLogDbg("Stepping out of inlined method, branch address: %p\n", targetAddress);
  3793. SetTempBreakpoint(targetAddress);
  3794. mStepBreakpointAddrs.push_back(targetAddress);
  3795. }
  3796. decodeAddress += inst.GetLength();
  3797. }
  3798. return true;
  3799. }
  3800. }
  3801. if ((mStepType != StepType_StepOut_NoFrame) && (RollBackStackFrame(&registers, true)))
  3802. {
  3803. bool isStackAdjust = false;
  3804. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3805. if (dwSubprogram != NULL)
  3806. {
  3807. if ((strcmp(dwSubprogram->mName, "_chkstk") == 0) ||
  3808. (strcmp(dwSubprogram->mName, "__chkstk") == 0) ||
  3809. (strcmp(dwSubprogram->mName, "_alloca_probe") == 0))
  3810. isStackAdjust = true;
  3811. }
  3812. pcAddress = registers.GetPC();
  3813. if (isStackAdjust)
  3814. {
  3815. // We set it to zero so we never detect an "isDeeper" condition which would skip over the return-location breakpoint
  3816. mStepSP = 0;
  3817. }
  3818. else
  3819. {
  3820. addr_target oldAddress = pcAddress;
  3821. CPUInst inst;
  3822. while (true)
  3823. {
  3824. if (mStepInAssembly)
  3825. break;
  3826. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  3827. break;
  3828. if ((inst.IsBranch()) || (inst.IsCall()) || (inst.IsReturn()))
  3829. break;
  3830. #ifdef BF_DBG_32
  3831. if (!inst.StackAdjust(mStepSP))
  3832. break;
  3833. #endif
  3834. DbgSubprogram* checkSubprogram = NULL;
  3835. auto checkLineData = FindLineDataAtAddress(pcAddress, &checkSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  3836. if (checkLineData == NULL)
  3837. break;
  3838. if (checkSubprogram->GetLineAddr(*checkLineData) == pcAddress)
  3839. break;
  3840. pcAddress += inst.GetLength();
  3841. }
  3842. if (pcAddress != oldAddress)
  3843. {
  3844. BfLogDbg("Adjusting stepout address from %p to %p\n", oldAddress, pcAddress);
  3845. }
  3846. }
  3847. BfLogDbg("SetupStep Stepout SetTempBreakpoint %p\n", pcAddress);
  3848. SetTempBreakpoint(pcAddress);
  3849. mStepBreakpointAddrs.push_back(pcAddress);
  3850. if (mStepType != StepType_StepOut_ThenInto)
  3851. mStepType = StepType_StepOut;
  3852. }
  3853. else
  3854. {
  3855. // Try to handle the case where we just entered this call so the return address is the first entry on the stack
  3856. addr_target* regSP = registers.GetSPRegisterRef();
  3857. pcAddress = ReadMemory<addr_target>(*regSP);
  3858. *regSP += sizeof(addr_target);
  3859. if (mDebugTarget->FindSubProgram(pcAddress) != NULL)
  3860. {
  3861. BfLogDbg("SetupStep Stepout SetTempBreakpoint (2) %p\n", pcAddress);
  3862. SetTempBreakpoint(pcAddress);
  3863. mStepBreakpointAddrs.push_back(pcAddress);
  3864. if (mOrigStepType == StepType_StepInto)
  3865. mStepType = StepType_StepInto;
  3866. else
  3867. mStepType = StepType_StepOver;
  3868. return true;
  3869. }
  3870. else
  3871. {
  3872. // Just do stepovers until we eventually step out
  3873. //BF_DBG_FATAL("StepOut Failed");
  3874. BfLogDbg("StepOut Failed\n");
  3875. if (mLastValidStepIntoPC != 0)
  3876. {
  3877. BfLogDbg("Using mLastValidStepIntoPC: %p\n", mLastValidStepIntoPC);
  3878. if (mOrigStepType == StepType_StepInto)
  3879. mStepType = StepType_StepInto;
  3880. else
  3881. mStepType = StepType_StepOver;
  3882. SetTempBreakpoint(mLastValidStepIntoPC);
  3883. mStepBreakpointAddrs.push_back(0);
  3884. mStepBreakpointAddrs.push_back(mLastValidStepIntoPC);
  3885. mLastValidStepIntoPC = 0;
  3886. return true;
  3887. }
  3888. else
  3889. {
  3890. BfLogDbg("Stopping");
  3891. mStepType = StepType_None;
  3892. mRunState = RunState_Paused;
  3893. return true;
  3894. }
  3895. }
  3896. }
  3897. }
  3898. if ((mStepType != StepType_StepOut) && (mStepType != StepType_StepOut_ThenInto))
  3899. {
  3900. if (mDebuggerWaitingThread != mSteppingThread)
  3901. {
  3902. // We've switched threads, so there's a possible race condition:
  3903. // This new thread may already have an EXCEPTION_BREAKPOINT queued up so the PC is actually
  3904. // located one byte past the BREAK instruction, which is one byte into whatever instruction
  3905. // was previously there. We can't insert normal BREAK instructions because we don't know
  3906. // if the current PC is actually at an instruction start, so we do a single step with a
  3907. // slower stack call check to see if we need to step out after a "step over"
  3908. BfLogDbg("Step - switched threads mIsAtBreakpointAddress:%p\n", mSteppingThread->mIsAtBreakpointAddress);
  3909. mStepSwitchedThreads = true;
  3910. SingleStepX86();
  3911. return true;
  3912. }
  3913. bool breakOnNext = false;
  3914. int instIdx = 0;
  3915. for (instIdx = 0; true; instIdx++)
  3916. {
  3917. bool isAtLine = false;
  3918. DbgSubprogram* dwSubprogram = NULL;
  3919. auto dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  3920. isAtLine = (instIdx > 0) && (dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dwSubprogram->GetLineAddr(*dwLineData) == pcAddress);
  3921. // "Never step into" line
  3922. if ((dwLineData != NULL) && (dwLineData->mColumn == -2) && (stepType == StepType_StepInto))
  3923. stepType = StepType_StepOver;
  3924. CPUInst inst;
  3925. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  3926. {
  3927. BfLogDbg("Decode failed, set up SingleStepX86 %p\n", pcAddress);
  3928. SingleStepX86();
  3929. mStepStopOnNextInstruction = true;
  3930. return true;
  3931. }
  3932. if (instIdx > 256)
  3933. {
  3934. BfLogDbg("Too many SetupStep iterations");
  3935. breakOnNext = true;
  3936. }
  3937. if ((inst.IsReturn()) && (instIdx == 0) && (!mStepInAssembly))
  3938. {
  3939. // Do actual STEP OUT so we set up proper "stepping over unimportant post-return instructions"
  3940. if (stepType == StepType_StepInto)
  3941. return SetupStep(StepType_StepOut_ThenInto);
  3942. else
  3943. return SetupStep(StepType_StepOut);
  3944. }
  3945. if ((breakOnNext) || (mStepInAssembly) || (isAtLine) || (inst.IsBranch()) || (inst.IsCall()) || (inst.IsReturn()))
  3946. {
  3947. if (((instIdx == 0) || (mStepInAssembly)) && (!breakOnNext))
  3948. {
  3949. if ((stepType == StepType_StepOver) && (inst.IsCall()))
  3950. {
  3951. // Continue - sets a breakpoint on the call line to detect recursion.
  3952. // The next loop through will set a breakpoint on the line after the return
  3953. BfLogDbg("StepHadCall\n");
  3954. breakOnNext = true;
  3955. BfLogDbg("StepHadCall setting mIsAtBreakpointAddress = %p\n", pcAddress);
  3956. mSteppingThread->mIsAtBreakpointAddress = pcAddress;
  3957. SetTempBreakpoint(pcAddress);
  3958. mStepBreakpointAddrs.push_back(pcAddress);
  3959. }
  3960. else
  3961. {
  3962. if (inst.IsCall())
  3963. {
  3964. if ((mLastValidStepIntoPC == 0) || (dwSubprogram != NULL))
  3965. mLastValidStepIntoPC = pcAddress + inst.mSize;
  3966. }
  3967. if ((dwLineData != NULL) && (inst.IsBranch()))
  3968. {
  3969. addr_target targetAddr = inst.GetTarget();
  3970. if (targetAddr < dwSubprogram->GetLineAddr(*dwLineData))
  3971. {
  3972. // Jumping backwards, stop at next instruction
  3973. mStepStopOnNextInstruction = true;
  3974. }
  3975. }
  3976. bool isPrefixOnly = false;
  3977. if ((mStepInAssembly) && (stepType == StepType_StepOver) && (inst.IsRep(isPrefixOnly)))
  3978. {
  3979. if (isPrefixOnly)
  3980. {
  3981. CPUInst nextInst;
  3982. if (mDebugTarget->DecodeInstruction(pcAddress + inst.GetLength(), &nextInst))
  3983. {
  3984. if (nextInst.IsBranch())
  3985. {
  3986. // repne jmp - this appears in __chkstk (for example)
  3987. // We don't have a good way to "step over" this one, so just do a single step
  3988. }
  3989. else
  3990. {
  3991. // Step over the rep + target instruction
  3992. auto doneAddr = pcAddress + inst.GetLength() + nextInst.GetLength();
  3993. BfLogDbg("SetupStep SetTempBreakpoint %p\n", doneAddr);
  3994. SetTempBreakpoint(doneAddr);
  3995. mStepBreakpointAddrs.push_back(doneAddr);
  3996. break;
  3997. }
  3998. }
  3999. }
  4000. else
  4001. {
  4002. // Step over the instruction
  4003. auto doneAddr = pcAddress + inst.GetLength();
  4004. BfLogDbg("SetupStep SetTempBreakpoint %p\n", doneAddr);
  4005. SetTempBreakpoint(doneAddr);
  4006. mStepBreakpointAddrs.push_back(doneAddr);
  4007. break;
  4008. }
  4009. }
  4010. // Just step a single instruction
  4011. BfLogDbg("SetupStep SingleStepX86 %p\n", pcAddress);
  4012. SingleStepX86();
  4013. if (inst.IsReturn())
  4014. mStepStopOnNextInstruction = true;
  4015. break;
  4016. }
  4017. }
  4018. else
  4019. {
  4020. // Move us to this instruction so we can hardware single-step into it
  4021. BfLogDbg("SetupStep SetTempBreakpoint %p\n", pcAddress);
  4022. SetTempBreakpoint(pcAddress);
  4023. mStepBreakpointAddrs.push_back(pcAddress);
  4024. break;
  4025. }
  4026. }
  4027. // Not an interesting instruction - move to next
  4028. pcAddress += inst.mSize;
  4029. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress >= dwSubprogram->mBlock.mHighPC))
  4030. {
  4031. auto endAddress = dwSubprogram->mBlock.mHighPC;
  4032. BfLogDbg("Stepping past end of inlined method, end address: %p\n", endAddress);
  4033. mStepType = StepType_StepOut_Inline;
  4034. SetTempBreakpoint(endAddress);
  4035. mStepBreakpointAddrs.push_back(endAddress);
  4036. return true;
  4037. }
  4038. }
  4039. if (instIdx > 1)
  4040. BfLogDbg("SetupStep instIdx: %d\n", instIdx);
  4041. }
  4042. return true;
  4043. }
  4044. void WinDebugger::CheckNonDebuggerBreak()
  4045. {
  4046. enum MessageType
  4047. {
  4048. MessageType_None = 0,
  4049. MessageType_Error = 1,
  4050. MessageType_ProfilerCmd = 2
  4051. };
  4052. CPURegisters registers;
  4053. PopulateRegisters(&registers);
  4054. addr_target pcAddress = registers.GetPC();
  4055. addr_target debugMessageDataAddr = (addr_target)-1;
  4056. if (mDebugTarget->mTargetBinary != NULL)
  4057. {
  4058. mDebugTarget->mTargetBinary->ParseSymbolData();
  4059. debugMessageDataAddr = mDebugTarget->FindSymbolAddr("gBfDebugMessageData");
  4060. }
  4061. if (debugMessageDataAddr != (addr_target)-1)
  4062. {
  4063. struct BfDebugMessageData
  4064. {
  4065. int mMessageType; // 0 = none, 1 = error
  4066. int mStackWindbackCount;
  4067. int mBufParamLen;
  4068. addr_target mBufParam;
  4069. addr_target mPCOverride;
  4070. };
  4071. BfDebugMessageData messageData = ReadMemory<BfDebugMessageData>(debugMessageDataAddr);
  4072. WriteMemory<int>(debugMessageDataAddr, 0); // Zero out type so we won't trigger again
  4073. if (messageData.mMessageType != 0)
  4074. {
  4075. llvm::SmallVector<char, 4096> strBuf;
  4076. int strLen = messageData.mBufParamLen;
  4077. strBuf.resize(strLen + 1);
  4078. char* str = &strBuf[0];
  4079. str[strLen] = 0;
  4080. if (ReadMemory(messageData.mBufParam, strLen, str))
  4081. {
  4082. if (messageData.mMessageType == MessageType_Error)
  4083. {
  4084. mRequestedStackFrameIdx = messageData.mStackWindbackCount;
  4085. if (messageData.mPCOverride != 0)
  4086. {
  4087. mShowPCOverride = messageData.mPCOverride;
  4088. mRequestedStackFrameIdx = -2;
  4089. }
  4090. mDebugManager->mOutMessages.push_back(StrFormat("error %s", str));
  4091. }
  4092. else if (messageData.mMessageType == MessageType_ProfilerCmd)
  4093. {
  4094. // It's important to set this here, because we unlock the critSect during StopSampling and we can't have the
  4095. // IDE thinking that we're actually paused when it checks the mRunState
  4096. mRunState = RunState_Running;
  4097. char* cmd = strtok(str, "\t");
  4098. if (strcmp(cmd, "StartSampling") == 0)
  4099. {
  4100. char* sessionIdStr = strtok(NULL, "\t");
  4101. char* threadIdStr = strtok(NULL, "\t");
  4102. char* sampleRateStr = strtok(NULL, "\t");
  4103. char* descStr = strtok(NULL, "\t");
  4104. if (threadIdStr != NULL)
  4105. {
  4106. int threadId = atoi(threadIdStr);
  4107. int sampleRate = atoi(sampleRateStr);
  4108. int sessionId = atoi(sessionIdStr);
  4109. Profiler** profilerPtr;
  4110. if (mPendingProfilerMap.TryAdd(sessionId, NULL, &profilerPtr))
  4111. {
  4112. DbgProfiler* profiler = new DbgProfiler(this);
  4113. if (descStr != NULL)
  4114. profiler->mDescription = descStr;
  4115. if (sampleRate > 0)
  4116. profiler->mSamplesPerSecond = sampleRate;
  4117. profiler->Start();
  4118. *profilerPtr = profiler;
  4119. mDebugManager->mOutMessages.push_back("newProfiler");
  4120. mNewProfilerList.push_back(profiler);
  4121. }
  4122. }
  4123. }
  4124. else if (strcmp(cmd, "StopSampling") == 0)
  4125. {
  4126. char* sessionIdStr = strtok(NULL, "\t");
  4127. if (sessionIdStr != NULL)
  4128. {
  4129. int sessionId = atoi(sessionIdStr);
  4130. Profiler* profiler;
  4131. if (mPendingProfilerMap.Remove(sessionId, &profiler))
  4132. {
  4133. if (profiler->IsSampling())
  4134. {
  4135. // Need to unlock so we don't deadlock
  4136. mDebugManager->mCritSect.Unlock();
  4137. profiler->Stop();
  4138. mDebugManager->mCritSect.Lock();
  4139. }
  4140. }
  4141. }
  4142. }
  4143. else if (strcmp(cmd, "ClearSampling") == 0)
  4144. {
  4145. for (auto& kv : mPendingProfilerMap)
  4146. {
  4147. auto profiler = kv.mValue;
  4148. profiler->Clear();
  4149. }
  4150. }
  4151. else if (strcmp(cmd, "ClearOutput") == 0)
  4152. {
  4153. mDebugManager->mOutMessages.push_back("clearOutput");
  4154. }
  4155. }
  4156. return;
  4157. }
  4158. }
  4159. }
  4160. intptr_target objAddr;
  4161. auto dbgBreakKind = mDebugTarget->GetDbgBreakKind(pcAddress, &registers, &objAddr);
  4162. if (dbgBreakKind == DbgBreakKind_ObjectAccess)
  4163. {
  4164. String errorStr = "error Attempted to access deleted object";
  4165. String objectAddr = EncodeDataPtr((addr_target)objAddr, true);
  4166. errorStr += StrFormat("\x1LEAK\t(System.Object)%s\n (%s)%s\n", objectAddr.c_str(), "System.Object", objectAddr.c_str());
  4167. mDebugManager->mOutMessages.push_back(errorStr);
  4168. return;
  4169. }
  4170. else if (dbgBreakKind == DbgBreakKind_ArithmeticOverflow)
  4171. {
  4172. String errorStr = "error Arithmetic overflow detected";
  4173. mDebugManager->mOutMessages.push_back(errorStr);
  4174. return;
  4175. }
  4176. bool showMainThread = false;
  4177. String symbol;
  4178. addr_target offset;
  4179. DbgModule* dbgModule;
  4180. if (mDebugTarget->FindSymbolAt(pcAddress, &symbol, &offset, &dbgModule))
  4181. {
  4182. if ((symbol == "DbgBreakPoint") || (symbol == "RtlUserThreadStart") || (symbol == "RtlUserThreadStart@8"))
  4183. {
  4184. showMainThread = true;
  4185. }
  4186. }
  4187. #ifdef BF_DBG_32
  4188. else if ((dbgModule != NULL) && (dbgModule->mDisplayName.Equals("kernel32.dll", StringImpl::CompareKind_OrdinalIgnoreCase)))
  4189. {
  4190. showMainThread = true;
  4191. }
  4192. #endif
  4193. if (showMainThread)
  4194. {
  4195. // This is a manual break, show the main thread
  4196. mActiveThread = mThreadList.front();
  4197. if (mDebugPendingExpr != NULL)
  4198. {
  4199. for (auto thread : mThreadList)
  4200. {
  4201. if (thread->mThreadId == mDebugEvalThreadInfo.mThreadId)
  4202. {
  4203. mActiveThread = thread;
  4204. break;
  4205. }
  4206. }
  4207. }
  4208. }
  4209. }
  4210. bool WinDebugger::HasSteppedIntoCall()
  4211. {
  4212. // Some calls (like __chkstk) actually push results to the stack, so we need to check
  4213. // if we're REALLY deeper or not, by rolling back the callstack once
  4214. CPURegisters registers;
  4215. PopulateRegisters(&registers);
  4216. if (RollBackStackFrame(&registers, true))
  4217. {
  4218. // If the previous frames SP is equal or deeper than our step start then we are indeed inside a call!
  4219. if (mStepSP >= registers.GetSP())
  4220. return true;
  4221. }
  4222. return false;
  4223. }
  4224. void WinDebugger::StepOver(bool inAssembly)
  4225. {
  4226. AutoCrit autoCrit(mDebugManager->mCritSect);
  4227. BfLogDbg("StepOver\n");
  4228. if (!TryRunContinue())
  4229. return;
  4230. mCurNoInfoStepTries = 0; // Reset
  4231. mStepInAssembly = inAssembly;
  4232. SetupStep(StepType_StepOver);
  4233. ContinueDebugEvent();
  4234. }
  4235. void WinDebugger::StepOut(bool inAssembly)
  4236. {
  4237. AutoCrit autoCrit(mDebugManager->mCritSect);
  4238. BfLogDbg("StepOut\n");
  4239. if (!TryRunContinue())
  4240. return;
  4241. mCurNoInfoStepTries = 0; // Reset
  4242. mStepInAssembly = inAssembly;
  4243. SetupStep(StepType_StepOut);
  4244. ContinueDebugEvent();
  4245. }
  4246. void WinDebugger::SetNextStatement(bool inAssembly, const StringImpl& fileName, int64 lineNumOrAsmAddr, int wantColumn)
  4247. {
  4248. AutoCrit autoCrit(mDebugManager->mCritSect);
  4249. DbgSubprogram* subProgram = NULL;
  4250. if (!inAssembly)
  4251. {
  4252. if (mCallStack.size() == 0)
  4253. UpdateCallStack();
  4254. if (mCallStack.size() > 0)
  4255. {
  4256. UpdateCallStackMethod(0);
  4257. subProgram = mCallStack[0]->mSubProgram;
  4258. }
  4259. if (subProgram == NULL)
  4260. return;
  4261. }
  4262. DbgSubprogram* rootInlineParent = NULL;
  4263. if (subProgram != NULL)
  4264. rootInlineParent = subProgram->GetRootInlineParent();
  4265. String result;
  4266. if (mDebugTarget == NULL)
  4267. return;
  4268. DbgSrcFile* srcFile = NULL;
  4269. if (!fileName.IsEmpty())
  4270. {
  4271. srcFile = mDebugTarget->GetSrcFile(fileName);
  4272. if (srcFile == NULL)
  4273. return;
  4274. }
  4275. addr_target pcAddress = 0;
  4276. if (inAssembly)
  4277. {
  4278. pcAddress = lineNumOrAsmAddr;
  4279. }
  4280. else
  4281. {
  4282. int lineNum = (int)lineNumOrAsmAddr;
  4283. addr_target bestAddr[2] = { 0, 0 };
  4284. int checkLineNum[2] = { lineNum - 1, lineNum };
  4285. auto _CheckLineInfo = [&](DbgSubprogram* dbgSubprogram, DbgLineInfo* dbgLineInfo)
  4286. {
  4287. for (int iPass = 0; iPass < 2; ++iPass)
  4288. {
  4289. int bestLineOffset = 0x7FFFFFFF;
  4290. for (auto& lineData : dbgLineInfo->mLines)
  4291. {
  4292. auto addr = dbgSubprogram->GetLineAddr(lineData);
  4293. if ((addr < subProgram->mBlock.mLowPC) || (addr >= subProgram->mBlock.mHighPC))
  4294. continue;
  4295. int lineOffset = lineData.mLine - checkLineNum[iPass];
  4296. if ((lineOffset >= 0) && (lineOffset <= 6) && (lineOffset <= bestLineOffset))
  4297. {
  4298. if (lineOffset < bestLineOffset)
  4299. {
  4300. bestLineOffset = lineOffset;
  4301. bestAddr[iPass] = addr;
  4302. }
  4303. }
  4304. }
  4305. }
  4306. };
  4307. for (int checkHotIdx = -1; checkHotIdx < (int)srcFile->mHotReplacedDbgLineInfo.size(); checkHotIdx++)
  4308. {
  4309. if (checkHotIdx >= 0)
  4310. {
  4311. auto hotReplacedLineInfo = srcFile->mHotReplacedDbgLineInfo[checkHotIdx];
  4312. for (auto& hotReplacedEntry : hotReplacedLineInfo->mEntries)
  4313. {
  4314. _CheckLineInfo(hotReplacedEntry.mSubprogram, hotReplacedEntry.mLineInfo);
  4315. }
  4316. }
  4317. else
  4318. {
  4319. for (auto subprogram : srcFile->mLineDataRefs)
  4320. _CheckLineInfo(subprogram, subprogram->mLineInfo);
  4321. }
  4322. if (bestAddr[1] != 0)
  4323. break;
  4324. }
  4325. if (bestAddr[1] != 0)
  4326. {
  4327. const int kMaxAddrDist = 64; // within reasonable range
  4328. if ((bestAddr[0] != 0) && (bestAddr[1] - bestAddr[0] <= kMaxAddrDist))
  4329. {
  4330. addr_target addrStart = bestAddr[0];
  4331. addr_target addrEnd = bestAddr[1];
  4332. addr_target addr = addrStart;
  4333. BF_ASSERT(addrEnd - addr <= kMaxAddrDist);
  4334. addr_target lastOp = 0;
  4335. while (addr < addrEnd)
  4336. {
  4337. CPUInst inst;
  4338. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  4339. break;
  4340. lastOp = addr;
  4341. addr += inst.GetLength();
  4342. }
  4343. }
  4344. pcAddress = (uint64)bestAddr[1];
  4345. }
  4346. }
  4347. if (pcAddress)
  4348. {
  4349. BF_ASSERT(mActiveThread->mBreakpointAddressContinuing == 0);
  4350. mActiveThread->mIsAtBreakpointAddress = 0;
  4351. mActiveThread->mStoppedAtAddress = pcAddress;
  4352. if (mCallStack.size() == 0)
  4353. UpdateCallStack();
  4354. CPURegisters* regs = &mCallStack.front()->mRegisters;
  4355. *regs->GetPCRegisterRef() = pcAddress;
  4356. SetRegisters(regs);
  4357. WdBreakpoint* breakpoint = (WdBreakpoint*)FindBreakpointAt(pcAddress);
  4358. if (breakpoint != NULL)
  4359. {
  4360. BfLogDbg("SetNextStatement setting mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  4361. mActiveThread->mIsAtBreakpointAddress = breakpoint->mAddr;
  4362. }
  4363. }
  4364. }
  4365. bool WinDebugger::PopulateRegisters(CPURegisters* registers, BF_CONTEXT& lcContext)
  4366. {
  4367. #ifdef BF_DBG_32
  4368. registers->mIntRegs.eax = lcContext.Eax;
  4369. registers->mIntRegs.ecx = lcContext.Ecx;
  4370. registers->mIntRegs.edx = lcContext.Edx;
  4371. registers->mIntRegs.ebx = lcContext.Ebx;
  4372. registers->mIntRegs.esp = lcContext.Esp;
  4373. registers->mIntRegs.ebp = lcContext.Ebp;
  4374. registers->mIntRegs.esi = lcContext.Esi;
  4375. registers->mIntRegs.edi = lcContext.Edi;
  4376. registers->mIntRegs.eip = lcContext.Eip;
  4377. registers->mIntRegs.efl = lcContext.EFlags;
  4378. BF_ASSERT(sizeof(lcContext.FloatSave.RegisterArea) == sizeof(registers->mFpMmRegsArray));
  4379. memcpy(registers->mFpMmRegsArray, lcContext.FloatSave.RegisterArea, sizeof(lcContext.FloatSave.RegisterArea));
  4380. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 32 * sizeof(float));
  4381. memcpy(registers->mXmmRegsArray, &lcContext.ExtendedRegisters[160], sizeof(registers->mXmmRegsArray));
  4382. #else
  4383. registers->mIntRegs.rax = lcContext.Rax;
  4384. registers->mIntRegs.rcx = lcContext.Rcx;
  4385. registers->mIntRegs.rdx = lcContext.Rdx;
  4386. registers->mIntRegs.rbx = lcContext.Rbx;
  4387. registers->mIntRegs.rsp = lcContext.Rsp;
  4388. registers->mIntRegs.rbp = lcContext.Rbp;
  4389. registers->mIntRegs.rsi = lcContext.Rsi;
  4390. registers->mIntRegs.rdi = lcContext.Rdi;
  4391. registers->mIntRegs.rip = lcContext.Rip;
  4392. registers->mIntRegs.efl = lcContext.EFlags;
  4393. registers->mIntRegs.r8 = lcContext.R8;
  4394. registers->mIntRegs.r9 = lcContext.R9;
  4395. registers->mIntRegs.r10 = lcContext.R10;
  4396. registers->mIntRegs.r11 = lcContext.R11;
  4397. registers->mIntRegs.r12 = lcContext.R12;
  4398. registers->mIntRegs.r13 = lcContext.R13;
  4399. registers->mIntRegs.r14 = lcContext.R14;
  4400. registers->mIntRegs.r15 = lcContext.R15;
  4401. registers->mIntRegs.gs = lcContext.SegGs;
  4402. for (int i = 0; i < 8; i++)
  4403. {
  4404. memcpy(&registers->mFpMmRegsArray[i], &lcContext.FltSave.FloatRegisters[i], 10);
  4405. }
  4406. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 64 * sizeof(float));
  4407. memcpy(registers->mXmmRegsArray, BF_CONTEXT_XMMDATA(lcContext), sizeof(registers->mXmmRegsArray));
  4408. #endif
  4409. return (lcContext.ContextFlags & (BF_CONTEXT_EXCEPTION_ACTIVE | BF_CONTEXT_SERVICE_ACTIVE)) == 0;
  4410. }
  4411. bool WinDebugger::PopulateRegisters(CPURegisters* registers)
  4412. {
  4413. /*static bool sCheckedProcessorFeatures = false;
  4414. static bool sMmxAvailable = false;
  4415. static bool sXmmAvailable = false;
  4416. if (!sCheckedProcessorFeatures)
  4417. {
  4418. //CDH we don't do anything with these yet since we grab BF_CONTEXT_ALL anyway, but could be useful
  4419. sMmxAvailable = ::IsProcessorFeaturePresent(PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  4420. sXmmAvailable = ::IsProcessorFeaturePresent(PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  4421. sCheckedProcessorFeatures = true;
  4422. }*/
  4423. BF_ASSERT(registers != nullptr);
  4424. BF_CONTEXT lcContext;
  4425. lcContext.ContextFlags = BF_CONTEXT_ALL | BF_CONTEXT_EXCEPTION_REQUEST;
  4426. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4427. return PopulateRegisters(registers, lcContext);
  4428. }
  4429. bool WinDebugger::RollBackStackFrame(CPURegisters* registers, bool isStackStart)
  4430. {
  4431. BF_ASSERT(registers != nullptr);
  4432. return mDebugTarget->RollBackStackFrame(registers, NULL, isStackStart);
  4433. }
  4434. bool WinDebugger::SetHotJump(DbgSubprogram* oldSubprogram, addr_target newTarget, int newTargetSize)
  4435. {
  4436. BfLogDbg("SetHotJump %s %p->%p\n", oldSubprogram->mName, oldSubprogram->mBlock.mLowPC, newTarget);
  4437. //AutoCrit autoCrit(mDebugManager->mCritSect);
  4438. BF_ASSERT(mDebugManager->mCritSect.mLockCount == 1);
  4439. addr_target jmpInstStart = oldSubprogram->mBlock.mLowPC;
  4440. addr_target jmpInstEnd = jmpInstStart + sizeof(HotJumpOp);
  4441. if (jmpInstEnd > oldSubprogram->mBlock.mHighPC)
  4442. {
  4443. if ((oldSubprogram->mBlock.mHighPC - oldSubprogram->mBlock.mLowPC == 1) &&
  4444. (newTargetSize == 1))
  4445. return true; // Special case for just stub 'ret' methods
  4446. String err = StrFormat("Failed to hot replace method, method '%s' too small to insert hot thunk", oldSubprogram->ToString().c_str());
  4447. Fail(err);
  4448. return false;
  4449. }
  4450. if (oldSubprogram->mHotReplaceKind != DbgSubprogram::HotReplaceKind_Replaced)
  4451. {
  4452. for (int hotThreadIdx = 0; hotThreadIdx < (int)mHotThreadStates.size(); hotThreadIdx++)
  4453. {
  4454. auto& hotThreadState = mHotThreadStates[hotThreadIdx];
  4455. WdThreadInfo* threadInfo = NULL;
  4456. if (!mThreadMap.TryGetValue((uint32)hotThreadState.mThreadId, &threadInfo))
  4457. continue;
  4458. int tryStart = GetTickCount();
  4459. while ((hotThreadState.mRegisters.GetPC() >= jmpInstStart) && (hotThreadState.mRegisters.GetPC() < jmpInstEnd))
  4460. {
  4461. if (GetTickCount() - tryStart >= 8000)
  4462. {
  4463. Fail("Failed to hot replace method, can't move past prelude");
  4464. return false;
  4465. }
  4466. BfLogDbg("SetHotJump skipping through %p\n", hotThreadState.mRegisters.GetPC());
  4467. bool removedBreakpoint = false;
  4468. mActiveThread = threadInfo;
  4469. if ((mActiveThread->mStoppedAtAddress >= jmpInstStart) && (mActiveThread->mStoppedAtAddress < jmpInstEnd))
  4470. {
  4471. for (addr_target addr = jmpInstStart; addr < jmpInstEnd; addr++)
  4472. {
  4473. if (mPhysBreakpointAddrMap.ContainsKey(addr))
  4474. {
  4475. removedBreakpoint = true;
  4476. RemoveBreakpoint(addr);
  4477. }
  4478. }
  4479. }
  4480. RunState oldRunState = mRunState;
  4481. mRunState = RunState_HotStep;
  4482. if (mWantsDebugContinue)
  4483. {
  4484. mWantsDebugContinue = false;
  4485. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4486. mContinueEvent.Set();
  4487. }
  4488. BF_CONTEXT lcContext;
  4489. lcContext.ContextFlags = BF_CONTEXT_ALL;
  4490. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4491. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  4492. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  4493. ::ResumeThread(mActiveThread->mHThread);
  4494. BfLogDbg("ResumeThread %d\n", mActiveThread->mThreadId);
  4495. while (mRunState != RunState_Terminated)
  4496. {
  4497. mDebugManager->mCritSect.Unlock();
  4498. Sleep(0);
  4499. mDebugManager->mCritSect.Lock();
  4500. if (IsPaused())
  4501. break;
  4502. if (mWantsDebugContinue)
  4503. {
  4504. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4505. mWantsDebugContinue = false;
  4506. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4507. mContinueEvent.Set();
  4508. }
  4509. }
  4510. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4511. ::SuspendThread(mActiveThread->mHThread);
  4512. BfLogDbg("SuspendThread %d\n", mActiveThread->mThreadId);
  4513. mRunState = oldRunState;
  4514. if ((mRunState != RunState_Terminated) && (mRunState != RunState_Terminating))
  4515. {
  4516. if (!IsPaused())
  4517. {
  4518. BF_ASSERT(mWantsDebugContinue);
  4519. mWantsDebugContinue = false;
  4520. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4521. mContinueEvent.Set();
  4522. }
  4523. }
  4524. PopulateRegisters(&hotThreadState.mRegisters);
  4525. }
  4526. }
  4527. }
  4528. HotJumpOp jumpOp;
  4529. jumpOp.mOpCode = 0xE9;
  4530. jumpOp.mRelTarget = newTarget - oldSubprogram->mBlock.mLowPC - sizeof(HotJumpOp);
  4531. WriteMemory(oldSubprogram->mBlock.mLowPC, jumpOp);
  4532. ::FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)oldSubprogram->mBlock.mLowPC, sizeof(HotJumpOp));
  4533. return true;
  4534. }
  4535. DbgSubprogram* WinDebugger::TryFollowHotJump(DbgSubprogram* subprogram, addr_target addr)
  4536. {
  4537. if (subprogram->mHotReplaceKind != DbgSubprogram::HotReplaceKind_Replaced)
  4538. return subprogram;
  4539. if (addr != subprogram->mBlock.mLowPC)
  4540. return subprogram;
  4541. auto dbgModule = subprogram->mCompileUnit->mDbgModule;
  4542. HotJumpOp jumpOp = ReadMemory<HotJumpOp>(addr);
  4543. if (jumpOp.mOpCode != 0xE9)
  4544. return subprogram;
  4545. addr_target jumpAddr = addr + jumpOp.mRelTarget + sizeof(HotJumpOp);
  4546. auto jumpSubprogram = mDebugTarget->FindSubProgram(jumpAddr);
  4547. if (jumpSubprogram == NULL)
  4548. return subprogram;
  4549. return jumpSubprogram;
  4550. }
  4551. bool WinDebugger::ShouldShowStaticMember(DbgType* dbgType, DbgVariable* member)
  4552. {
  4553. // If locationData is non-null, that means it was added in addition to the static declaration in the CV type info,
  4554. // so only add the names from the type definition
  4555. auto flavor = dbgType->mCompileUnit->mDbgModule->mDbgFlavor;
  4556. return ((((dbgType->IsNamespace()) || (flavor != DbgFlavor_MS)) && ((member->mLocationData != NULL) || member->mIsConst)) ||
  4557. ((flavor == DbgFlavor_MS) && (member->mLocationData == NULL)));
  4558. }
  4559. String WinDebugger::GetMemberList(DbgType* dbgType, const StringImpl& expr, bool isPtr, bool isStatic, bool forceCast, bool isSplat, bool isReadOnly)
  4560. {
  4561. auto dbgModule = dbgType->GetDbgModule();
  4562. dbgType->PopulateType();
  4563. auto language = dbgType->GetLanguage();
  4564. if (!isStatic)
  4565. {
  4566. String retVal;
  4567. bool needsNewline = false;
  4568. bool isBfObject = false;
  4569. if (dbgType->IsBfObjectPtr())
  4570. {
  4571. isBfObject = true;
  4572. dbgType = dbgType->mTypeParam;
  4573. }
  4574. int baseIdx = 0;
  4575. for (auto baseTypeEntry : dbgType->mBaseTypes)
  4576. {
  4577. auto baseType = baseTypeEntry->mBaseType;
  4578. if ((baseType->mSize > 0) || (baseType->mTypeCode != DbgType_Struct) || (strcmp(baseType->mTypeName, "ValueType") != 0))
  4579. {
  4580. String baseTypeStr = baseType->ToStringRaw(language);
  4581. if (baseIdx > 0)
  4582. retVal += "\n";
  4583. if (isSplat)
  4584. retVal += "[base]\t((" + baseTypeStr + ")" + expr + "), nv";
  4585. else if (dbgType->WantsRefThis())
  4586. retVal += "[base]\t((" + baseTypeStr + ")this), nd, na, nv, this=" + expr;
  4587. else
  4588. retVal += "[base]\t((" + baseTypeStr + "*)this), nd, na, nv, this=" + expr;
  4589. if (isReadOnly)
  4590. retVal += ", ne";
  4591. }
  4592. needsNewline = true;
  4593. baseIdx++;
  4594. }
  4595. String thisExpr = expr;
  4596. String castString;
  4597. if (dbgType->IsBfObject())
  4598. {
  4599. auto ptrType = dbgType->GetDbgModule()->GetPointerType(dbgType);
  4600. castString = ptrType->ToStringRaw(language);
  4601. }
  4602. else
  4603. castString = dbgType->ToStringRaw(language);
  4604. bool hadStatics = false;
  4605. for (auto member : dbgType->mMemberList)
  4606. {
  4607. if (member->mMemberOffset < 0)
  4608. continue;
  4609. if (member->mIsStatic)
  4610. {
  4611. if (ShouldShowStaticMember(dbgType, member))
  4612. hadStatics = true;
  4613. }
  4614. else
  4615. {
  4616. bool ignoreMember = false;
  4617. if (member->mName != NULL)
  4618. {
  4619. if ((member->mName[0] == '?') ||
  4620. (member->mName[0] == '$') ||
  4621. (strncmp(member->mName, "_vptr$", 6) == 0))
  4622. ignoreMember = true;
  4623. }
  4624. if (!ignoreMember)
  4625. {
  4626. if (needsNewline)
  4627. retVal += "\n";
  4628. if (member->mName == NULL)
  4629. {
  4630. retVal += GetMemberList(member->mType, expr, isPtr, isStatic, forceCast, isSplat, isReadOnly);
  4631. }
  4632. else
  4633. {
  4634. retVal += String(member->mName);
  4635. if (isSplat)
  4636. {
  4637. retVal += "\t(" + thisExpr + ")." + String(member->mName);
  4638. // We don't want to rely on this being enforced here. For one, ref types shouldn't get ", ne" added,
  4639. // and this doesn't solve the issue of attempting to assign via the Immediate window
  4640. /*if (isReadOnly)
  4641. retVal += ", ne";*/
  4642. }
  4643. else
  4644. {
  4645. if (forceCast)
  4646. retVal += "\t((" + castString + ")this)." + String(member->mName);
  4647. else if ((member->mName[0] >= '0') && (member->mName[0] <= '9')) // Numbered tuple member?
  4648. retVal += "\tthis." + String(member->mName);
  4649. else
  4650. retVal += "\t" + String(member->mName);
  4651. retVal += ", this=" + thisExpr;
  4652. // if (isReadOnly)
  4653. // retVal += ", ne";
  4654. }
  4655. }
  4656. needsNewline = true;
  4657. }
  4658. }
  4659. }
  4660. if (hadStatics)
  4661. {
  4662. if (needsNewline)
  4663. retVal += "\n";
  4664. retVal += "Static values\t" + castString;
  4665. }
  4666. return retVal;
  4667. }
  4668. else
  4669. {
  4670. if (dbgType->IsBfObjectPtr())
  4671. dbgType = dbgType->mTypeParam;
  4672. String retVal;
  4673. String memberPrefix = expr;
  4674. bool needsNewline = false;
  4675. bool hadStatics = false;
  4676. for (auto member : dbgType->mMemberList)
  4677. {
  4678. if (member->mIsStatic)
  4679. {
  4680. if (ShouldShowStaticMember(dbgType, member))
  4681. {
  4682. if (needsNewline)
  4683. retVal += "\n";
  4684. retVal += String(member->mName) + "\t" + memberPrefix + "." + String(member->mName);
  4685. needsNewline = true;
  4686. }
  4687. }
  4688. }
  4689. return retVal;
  4690. }
  4691. return "";
  4692. }
  4693. bool WinDebugger::ParseFormatInfo(DbgModule* dbgModule, const StringImpl& formatInfoStr, DwFormatInfo* formatInfo, BfPassInstance* bfPassInstance, int* assignExprOffset, String* assignExprString, String* errorString, DbgTypedValue contextTypedValue)
  4694. {
  4695. String formatFlags = formatInfoStr;
  4696. if (assignExprOffset != NULL)
  4697. *assignExprOffset = -1;
  4698. while (formatFlags.length() > 0)
  4699. {
  4700. formatFlags = Trim(formatFlags);
  4701. if (formatFlags.IsEmpty())
  4702. break;
  4703. if (formatFlags[0] != ',')
  4704. {
  4705. return false;
  4706. }
  4707. else
  4708. {
  4709. int nextComma = formatFlags.IndexOf(',', 1);
  4710. int quotePos = formatFlags.IndexOf('"', 1);
  4711. if ((quotePos != -1) && (quotePos < nextComma))
  4712. {
  4713. int nextQuotePos = formatFlags.IndexOf('"', quotePos + 1);
  4714. if (nextQuotePos != -1)
  4715. nextComma = formatFlags.IndexOf(',', nextQuotePos + 1);
  4716. }
  4717. if (nextComma == -1)
  4718. nextComma = formatFlags.length();
  4719. String formatCmd = formatFlags.Substring(1, nextComma - 1);
  4720. formatCmd = Trim(formatCmd);
  4721. bool hadError = false;
  4722. if (strncmp(formatCmd.c_str(), "this=", 5) == 0)
  4723. {
  4724. formatCmd = formatFlags.Substring(1);
  4725. formatCmd = Trim(formatCmd);
  4726. String thisExpr = formatCmd.Substring(5);
  4727. if (thisExpr.empty())
  4728. break;
  4729. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, thisExpr, formatInfo);
  4730. formatInfo->mExplicitThis = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4731. if (dbgEvaluationContext.HadError())
  4732. {
  4733. if (errorString != NULL)
  4734. *errorString = dbgEvaluationContext.GetErrorStr();
  4735. return false;
  4736. }
  4737. formatFlags = thisExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4738. continue;
  4739. }
  4740. else if (strncmp(formatCmd.c_str(), "count=", 6) == 0)
  4741. {
  4742. formatCmd = formatFlags.Substring(1);
  4743. formatCmd = Trim(formatCmd);
  4744. String countExpr = formatCmd.Substring(6);
  4745. if (countExpr.empty())
  4746. break;
  4747. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4748. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4749. if ((countValue) && (countValue.mType->IsInteger()))
  4750. formatInfo->mOverrideCount = (intptr)countValue.GetInt64();
  4751. if (dbgEvaluationContext.HadError())
  4752. {
  4753. if (errorString != NULL)
  4754. *errorString = dbgEvaluationContext.GetErrorStr();
  4755. return false;
  4756. }
  4757. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4758. continue;
  4759. }
  4760. else if (strncmp(formatCmd.c_str(), "maxcount=", 9) == 0)
  4761. {
  4762. formatCmd = formatFlags.Substring(1);
  4763. formatCmd = Trim(formatCmd);
  4764. String countExpr = formatCmd.Substring(9);
  4765. if (countExpr.empty())
  4766. break;
  4767. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4768. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4769. if ((countValue) && (countValue.mType->IsInteger()))
  4770. formatInfo->mMaxCount = (intptr)countValue.GetInt64();
  4771. if (dbgEvaluationContext.HadError())
  4772. {
  4773. if (errorString != NULL)
  4774. *errorString = dbgEvaluationContext.GetErrorStr();
  4775. return false;
  4776. }
  4777. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4778. continue;
  4779. }
  4780. else if (strncmp(formatCmd.c_str(), "arraysize=", 10) == 0)
  4781. {
  4782. formatCmd = formatFlags.Substring(1);
  4783. formatCmd = Trim(formatCmd);
  4784. String countExpr = formatCmd.Substring(10);
  4785. if (countExpr.empty())
  4786. break;
  4787. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4788. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4789. if ((countValue) && (countValue.mType->IsInteger()))
  4790. formatInfo->mArrayLength = (intptr)countValue.GetInt64();
  4791. if (dbgEvaluationContext.HadError())
  4792. {
  4793. if (errorString != NULL)
  4794. *errorString = dbgEvaluationContext.GetErrorStr();
  4795. return false;
  4796. }
  4797. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4798. continue;
  4799. }
  4800. else if (strncmp(formatCmd.c_str(), "assign=", 7) == 0)
  4801. {
  4802. formatCmd = formatFlags.Substring(1);
  4803. formatCmd = Trim(formatCmd);
  4804. String assignExpr = formatCmd.Substring(7);
  4805. if (assignExpr.empty())
  4806. break;
  4807. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, assignExpr, formatInfo);
  4808. if (dbgEvaluationContext.HadError())
  4809. {
  4810. if (errorString != NULL)
  4811. *errorString = dbgEvaluationContext.GetErrorStr();
  4812. return false;
  4813. }
  4814. if (assignExprOffset != NULL)
  4815. {
  4816. //TODO: Keep track of the offset directly, this is a hack
  4817. *assignExprOffset = (int)formatInfoStr.IndexOf("assign=") + 7;
  4818. }
  4819. if (assignExprString != NULL)
  4820. *assignExprString = dbgEvaluationContext.mExprNode->ToString();
  4821. formatFlags = assignExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4822. continue;
  4823. }
  4824. else if (strncmp(formatCmd.c_str(), "refid=", 6) == 0)
  4825. {
  4826. formatInfo->mReferenceId = formatCmd.Substring(6);
  4827. if (formatInfo->mReferenceId[0] == '\"')
  4828. formatInfo->mReferenceId = formatInfo->mReferenceId.Substring(1, formatInfo->mReferenceId.length() - 2);
  4829. }
  4830. else if (strncmp(formatCmd.c_str(), "_=", 2) == 0)
  4831. {
  4832. formatInfo->mSubjectExpr = formatCmd.Substring(2);
  4833. if (formatInfo->mSubjectExpr[0] == '\"')
  4834. formatInfo->mSubjectExpr = formatInfo->mSubjectExpr.Substring(1, formatInfo->mSubjectExpr.length() - 2);
  4835. }
  4836. else if (strncmp(formatCmd.c_str(), "expectedType=", 13) == 0)
  4837. {
  4838. formatInfo->mExpectedType = formatCmd.Substring(13);
  4839. if (formatInfo->mExpectedType[0] == '\"')
  4840. formatInfo->mExpectedType = formatInfo->mExpectedType.Substring(1, formatInfo->mExpectedType.length() - 2);
  4841. }
  4842. else if (strncmp(formatCmd.c_str(), "namespaceSearch=", 16) == 0)
  4843. {
  4844. formatInfo->mNamespaceSearch = formatCmd.Substring(16);
  4845. if (formatInfo->mNamespaceSearch[0] == '\"')
  4846. formatInfo->mNamespaceSearch = formatInfo->mNamespaceSearch.Substring(1, formatInfo->mNamespaceSearch.length() - 2);
  4847. }
  4848. else if (formatCmd == "d")
  4849. {
  4850. formatInfo->mDisplayType = DwDisplayType_Decimal;
  4851. }
  4852. else if (formatCmd == "x")
  4853. {
  4854. formatInfo->mDisplayType = DwDisplayType_HexLower;
  4855. }
  4856. else if (formatCmd == "X")
  4857. {
  4858. formatInfo->mDisplayType = DwDisplayType_HexUpper;
  4859. }
  4860. else if (formatCmd == "s")
  4861. {
  4862. formatInfo->mHidePointers = true;
  4863. formatInfo->mDisplayType = DwDisplayType_Ascii;
  4864. }
  4865. else if (formatCmd == "s8")
  4866. {
  4867. formatInfo->mHidePointers = true;
  4868. formatInfo->mDisplayType = DwDisplayType_Utf8;
  4869. }
  4870. else if (formatCmd == "s16")
  4871. {
  4872. formatInfo->mHidePointers = true;
  4873. formatInfo->mDisplayType = DwDisplayType_Utf16;
  4874. }
  4875. else if (formatCmd == "s32")
  4876. {
  4877. formatInfo->mHidePointers = true;
  4878. formatInfo->mDisplayType = DwDisplayType_Utf32;
  4879. }
  4880. else if (formatCmd == "nd")
  4881. {
  4882. formatInfo->mIgnoreDerivedClassInfo = true;
  4883. }
  4884. else if (formatCmd == "na")
  4885. {
  4886. formatInfo->mHidePointers = true;
  4887. }
  4888. else if (formatCmd == "nm")
  4889. {
  4890. formatInfo->mNoMembers = true;
  4891. }
  4892. else if (formatCmd == "ne")
  4893. {
  4894. formatInfo->mNoEdit = true;
  4895. }
  4896. else if (formatCmd == "nv")
  4897. {
  4898. formatInfo->mNoVisualizers = true;
  4899. }
  4900. else if (formatCmd == "rawStr")
  4901. {
  4902. formatInfo->mRawString = true;
  4903. }
  4904. else if (((!formatCmd.IsEmpty()) && ((formatCmd[0] >= '0') && (formatCmd[0] <= '9'))) ||
  4905. (formatCmd.StartsWith("(")))
  4906. {
  4907. String countExpr = formatCmd;
  4908. if (countExpr.empty())
  4909. break;
  4910. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4911. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4912. if ((countValue) && (countValue.mType->IsInteger()))
  4913. formatInfo->mArrayLength = (intptr)countValue.GetInt64();
  4914. if (dbgEvaluationContext.HadError())
  4915. {
  4916. if (errorString != NULL)
  4917. *errorString = dbgEvaluationContext.GetErrorStr();
  4918. return false;
  4919. }
  4920. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4921. continue;
  4922. }
  4923. else
  4924. hadError = true;
  4925. if (hadError)
  4926. {
  4927. if (errorString != NULL)
  4928. *errorString = "Invalid format flags";
  4929. return false;
  4930. }
  4931. formatFlags = formatFlags.Substring(nextComma);
  4932. }
  4933. }
  4934. return true;
  4935. }
  4936. String WinDebugger::MaybeQuoteFormatInfoParam(const StringImpl& str)
  4937. {
  4938. bool needsQuote = false;
  4939. for (int i = 0; i < (int)str.length(); i++)
  4940. {
  4941. char c = str[i];
  4942. if (c == ',')
  4943. needsQuote = true;
  4944. }
  4945. if (!needsQuote)
  4946. return str;
  4947. String qStr = "\"";
  4948. qStr += str;
  4949. qStr += "\"";
  4950. return qStr;
  4951. }
  4952. DbgTypedValue WinDebugger::EvaluateInContext(DbgCompileUnit* dbgCompileUnit, const DbgTypedValue& contextTypedValue, const StringImpl& subExpr, DwFormatInfo* formatInfo, String* outReferenceId, String* outErrors)
  4953. {
  4954. DbgEvaluationContext dbgEvaluationContext(this, dbgCompileUnit->mDbgModule, subExpr, formatInfo, contextTypedValue);
  4955. dbgEvaluationContext.mDbgExprEvaluator->mDbgCompileUnit = dbgCompileUnit;
  4956. if (formatInfo != NULL)
  4957. {
  4958. dbgEvaluationContext.mDbgExprEvaluator->mLanguage = formatInfo->mLanguage;
  4959. dbgEvaluationContext.mDbgExprEvaluator->mSubjectExpr = formatInfo->mSubjectExpr;
  4960. }
  4961. dbgEvaluationContext.mDbgExprEvaluator->mReferenceId = outReferenceId;
  4962. auto result = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4963. if ((formatInfo != NULL) && (dbgEvaluationContext.mDbgExprEvaluator->mCountResultOverride != -1))
  4964. formatInfo->mOverrideCount = dbgEvaluationContext.mDbgExprEvaluator->mCountResultOverride;
  4965. if (dbgEvaluationContext.mPassInstance->HasFailed())
  4966. {
  4967. if (outErrors != NULL)
  4968. {
  4969. int errIdx = 0;
  4970. for (auto err : dbgEvaluationContext.mPassInstance->mErrors)
  4971. {
  4972. if (errIdx > 0)
  4973. (*outErrors) += "\n";
  4974. (*outErrors) += err->mError;
  4975. errIdx++;
  4976. }
  4977. }
  4978. return DbgTypedValue();
  4979. }
  4980. return result;
  4981. }
  4982. void WinDebugger::DbgVisFailed(DebugVisualizerEntry* debugVis, const StringImpl& evalString, const StringImpl& errors)
  4983. {
  4984. bool onlyMemError = errors.StartsWith("Failed to read") && !errors.Contains('\n');
  4985. if ((!debugVis->mShowedError) && (!onlyMemError))
  4986. {
  4987. debugVis->mShowedError = true;
  4988. String errStr = StrFormat("DbgVis '%s' failed while evaluating condition '%s'\n", debugVis->mName.c_str(), evalString.c_str());
  4989. String spacedErrors = errors;
  4990. spacedErrors.Insert(0, " ");
  4991. spacedErrors.Replace("\n", "\n ");
  4992. errStr += spacedErrors;
  4993. OutputMessage(errStr);
  4994. }
  4995. }
  4996. bool WinDebugger::EvalCondition(DebugVisualizerEntry* debugVis, DbgCompileUnit* dbgCompileUnit, DbgTypedValue typedVal, DwFormatInfo& formatInfo, const StringImpl& condition, const Array<String>& dbgVisWildcardCaptures, String& errorStr)
  4997. {
  4998. DwFormatInfo displayStrFormatInfo = formatInfo;
  4999. displayStrFormatInfo.mHidePointers = false;
  5000. displayStrFormatInfo.mRawString = false;
  5001. String errors;
  5002. const String conditionStr = mDebugManager->mDebugVisualizers->DoStringReplace(condition, dbgVisWildcardCaptures);
  5003. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, typedVal, conditionStr, &displayStrFormatInfo, NULL, &errors);
  5004. if ((!evalResult) || (!evalResult.mType->IsBoolean()))
  5005. {
  5006. if (formatInfo.mRawString)
  5007. return false;
  5008. errorStr += "<DbgVis Failed>";
  5009. DbgVisFailed(debugVis, conditionStr, errors);
  5010. return false;
  5011. }
  5012. return evalResult.mBool;
  5013. }
  5014. String WinDebugger::GetArrayItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgType* valueType, DbgTypedValue& curNode, int& count, String* outContinuationData)
  5015. {
  5016. DbgEvaluationContext conditionEvaluationContext(this, dbgCompileUnit, debugVis->mCondition);
  5017. String addrs;
  5018. bool checkLeft = true;
  5019. int usedCount = 0;
  5020. while (usedCount < count)
  5021. {
  5022. DbgTypedValue condVal = conditionEvaluationContext.EvaluateInContext(curNode);
  5023. if (!condVal)
  5024. break;
  5025. if (condVal.mBool)
  5026. {
  5027. auto val = curNode;
  5028. if (valueType == NULL)
  5029. {
  5030. String typeAddr = val.mType->ToStringRaw();
  5031. // RPad
  5032. typeAddr.Append(' ', sizeof(addr_target) * 2 - typeAddr.length());
  5033. addrs += typeAddr;
  5034. }
  5035. String addr = EncodeDataPtr(val.mPtr, false);
  5036. addrs += addr;
  5037. usedCount++;
  5038. }
  5039. curNode.mPtr += curNode.mType->mTypeParam->GetStride();
  5040. }
  5041. count = usedCount;
  5042. if (outContinuationData != NULL)
  5043. {
  5044. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(valueType, false) +
  5045. EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  5046. }
  5047. return addrs;
  5048. }
  5049. String WinDebugger::GetLinkedListItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, addr_target endNodePtr, DbgType* valueType, DbgTypedValue& curNode, int& count, String* outContinuationData)
  5050. {
  5051. DbgEvaluationContext nextEvaluationContext(this, dbgCompileUnit, debugVis->mNextPointer);
  5052. DbgEvaluationContext valueEvaluationContext(this, dbgCompileUnit, debugVis->mValuePointer);
  5053. String addrs;
  5054. bool checkLeft = true;
  5055. int mapIdx;
  5056. for (mapIdx = 0; mapIdx < count; mapIdx++)
  5057. {
  5058. if (curNode.mPtr == endNodePtr)
  5059. break;
  5060. DbgTypedValue val = valueEvaluationContext.EvaluateInContext(curNode);
  5061. if (!val)
  5062. break;
  5063. if (val.mPtr == 0)
  5064. break;
  5065. if (valueType == NULL)
  5066. {
  5067. String typeAddr = val.mType->ToStringRaw();
  5068. // RPad
  5069. typeAddr.Append(' ', sizeof(addr_target)*2 - typeAddr.length());
  5070. addrs += typeAddr;
  5071. }
  5072. String addr = EncodeDataPtr(val.mPtr, false);
  5073. addrs += addr;
  5074. curNode = nextEvaluationContext.EvaluateInContext(curNode);
  5075. }
  5076. count = mapIdx;
  5077. if (outContinuationData != NULL)
  5078. {
  5079. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(endNodePtr, false) + EncodeDataPtr(valueType, false) +
  5080. EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  5081. }
  5082. return addrs;
  5083. }
  5084. String WinDebugger::GetDictionaryItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgTypedValue dictValue, int bucketIdx, int nodeIdx, int& count, String* outContinuationData)
  5085. {
  5086. //DbgEvaluationContext bucketsEvaluationContext(this, dbgModule, debugVis->mBuckets);
  5087. DbgEvaluationContext nextEvaluationContext(this, dbgCompileUnit->mDbgModule, debugVis->mNextPointer);
  5088. DbgTypedValue bucketsPtr = EvaluateInContext(dbgCompileUnit, dictValue, debugVis->mBuckets);
  5089. DbgTypedValue entriesPtr = EvaluateInContext(dbgCompileUnit, dictValue, debugVis->mEntries);
  5090. if ((!bucketsPtr) || (!entriesPtr))
  5091. {
  5092. count = -1;
  5093. return "";
  5094. }
  5095. int entrySize = entriesPtr.mType->mTypeParam->GetStride();
  5096. int bucketIdxSize = bucketsPtr.mType->mTypeParam->GetStride();
  5097. String addrs;
  5098. bool checkLeft = true;
  5099. int encodeCount = 0;
  5100. while (encodeCount < count)
  5101. {
  5102. if (nodeIdx != -1)
  5103. {
  5104. DbgTypedValue entryValue;
  5105. entryValue.mSrcAddress = entriesPtr.mPtr + (nodeIdx * entrySize);
  5106. entryValue.mType = entriesPtr.mType->mTypeParam;
  5107. addrs += EncodeDataPtr(entryValue.mSrcAddress, false);
  5108. DbgTypedValue nextValue = nextEvaluationContext.EvaluateInContext(entryValue);
  5109. if ((!nextValue) || (!nextValue.mType->IsInteger()))
  5110. {
  5111. break;
  5112. }
  5113. nodeIdx = (int)nextValue.GetInt64();
  5114. encodeCount++;
  5115. }
  5116. else
  5117. {
  5118. if (bucketIdxSize == 4)
  5119. nodeIdx = ReadMemory<int>(bucketsPtr.mPtr + bucketIdx * sizeof(int32));
  5120. else
  5121. nodeIdx = (int)ReadMemory<int64>(bucketsPtr.mPtr + bucketIdx * sizeof(int64));
  5122. bucketIdx++;
  5123. }
  5124. }
  5125. count = encodeCount;
  5126. //count = mapIdx;
  5127. if (outContinuationData != NULL)
  5128. {
  5129. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(dictValue.mType, false) + EncodeDataPtr(dictValue.mSrcAddress, false) +
  5130. EncodeDataPtr((addr_target)bucketIdx, false) + EncodeDataPtr((addr_target)nodeIdx, false);
  5131. }
  5132. return addrs;
  5133. }
  5134. String WinDebugger::GetTreeItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, Array<addr_target>& parentList, DbgType*& valueType, DbgTypedValue& curNode, int count, String* outContinuationData)
  5135. {
  5136. DbgEvaluationContext leftEvaluationContext(this, dbgCompileUnit, debugVis->mLeftPointer);
  5137. DbgEvaluationContext rightEvaluationContext(this, dbgCompileUnit, debugVis->mRightPointer);
  5138. DbgEvaluationContext valueEvaluationContext(this, dbgCompileUnit, debugVis->mValuePointer);
  5139. DbgEvaluationContext conditionEvaluationContext(this, dbgCompileUnit, debugVis->mCondition);
  5140. String addrs;
  5141. bool checkLeft = true;
  5142. if ((curNode.mPtr & 2) != 0) // Flag from continuation
  5143. {
  5144. checkLeft = false;
  5145. curNode.mPtr &= (addr_target)~2;
  5146. }
  5147. HashSet<intptr> seenAddrs;
  5148. for (int mapIdx = 0; mapIdx < count; mapIdx++)
  5149. {
  5150. DbgTypedValue readNode;
  5151. while (true)
  5152. {
  5153. bool checkNode = (curNode.mPtr & 1) == 0;
  5154. readNode = curNode;
  5155. readNode.mPtr &= (addr_target)~1;
  5156. if (checkLeft)
  5157. {
  5158. DbgTypedValue leftValue = leftEvaluationContext.EvaluateInContext(readNode);
  5159. bool isEmpty = leftValue.mPtr == NULL;
  5160. if ((leftValue) && (conditionEvaluationContext.HasExpression()))
  5161. {
  5162. auto condValue = conditionEvaluationContext.EvaluateInContext(leftValue);
  5163. if (condValue)
  5164. isEmpty = !condValue.mBool;
  5165. }
  5166. if (isEmpty)
  5167. {
  5168. checkLeft = false;
  5169. break; // Handle node
  5170. }
  5171. parentList.push_back(curNode.mPtr);
  5172. curNode = leftValue;
  5173. }
  5174. else if (checkNode)
  5175. {
  5176. break; // Handle node
  5177. }
  5178. else
  5179. {
  5180. DbgTypedValue rightValue = rightEvaluationContext.EvaluateInContext(readNode);
  5181. bool isEmpty = rightValue.mPtr == NULL;
  5182. if ((rightValue) && (conditionEvaluationContext.HasExpression()))
  5183. {
  5184. auto condValue = conditionEvaluationContext.EvaluateInContext(rightValue);
  5185. if (condValue)
  5186. isEmpty = !condValue.mBool;
  5187. }
  5188. if (!isEmpty)
  5189. {
  5190. curNode = rightValue;
  5191. checkLeft = true;
  5192. }
  5193. else
  5194. {
  5195. if (parentList.size() == 0)
  5196. {
  5197. // Failed
  5198. break;
  5199. }
  5200. curNode.mPtr = parentList.back();
  5201. parentList.pop_back();
  5202. continue; // Don't check against seenAddrs
  5203. }
  5204. }
  5205. if (!seenAddrs.Add(curNode.mPtr))
  5206. {
  5207. // Failed!
  5208. return "";
  5209. }
  5210. }
  5211. DbgTypedValue val = valueEvaluationContext.EvaluateInContext(readNode);
  5212. if (valueType == NULL)
  5213. valueType = val.mType;
  5214. String addr = EncodeDataPtr(val.mPtr, false);
  5215. addrs += addr;
  5216. curNode.mPtr |= 1; // Node handled
  5217. }
  5218. if (!checkLeft)
  5219. curNode.mPtr |= 2;
  5220. if (outContinuationData != NULL)
  5221. {
  5222. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(valueType, false) + EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  5223. for (auto parent : parentList)
  5224. *outContinuationData += EncodeDataPtr(parent, false);
  5225. }
  5226. return addrs;
  5227. }
  5228. String WinDebugger::GetCollectionContinuation(const StringImpl& continuationData, int callStackIdx, int count)
  5229. {
  5230. DbgCompileUnit* dbgCompileUnit = GetCallStackCompileUnit(callStackIdx);;
  5231. if (!IsPaused())
  5232. return "";
  5233. const char* dataPtr = continuationData.c_str();
  5234. DebugVisualizerEntry* debugVis = (DebugVisualizerEntry*)DecodeLocalDataPtr(dataPtr);
  5235. if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_TreeItems)
  5236. {
  5237. DbgType* valueType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5238. DbgTypedValue curNode;
  5239. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5240. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5241. Array<addr_target> parentList;
  5242. String newContinuationData;
  5243. while (*dataPtr != 0)
  5244. parentList.push_back(DecodeTargetDataPtr(dataPtr));
  5245. String retVal = GetTreeItems(dbgCompileUnit, debugVis, parentList, valueType, curNode, count, &newContinuationData);
  5246. retVal += "\n" + newContinuationData;
  5247. return retVal;
  5248. }
  5249. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_LinkedList)
  5250. {
  5251. addr_target endNodePtr = DecodeTargetDataPtr(dataPtr);
  5252. DbgType* valueType = (DbgType*) DecodeLocalDataPtr(dataPtr);
  5253. DbgTypedValue curNode;
  5254. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5255. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5256. String newContinuationData;
  5257. if (count < 0)
  5258. count = 3;
  5259. String retVal = GetLinkedListItems(dbgCompileUnit, debugVis, endNodePtr, valueType, curNode, count, &newContinuationData);
  5260. retVal += "\n" + newContinuationData;
  5261. return retVal;
  5262. }
  5263. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Array)
  5264. {
  5265. DbgType* valueType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5266. DbgTypedValue curNode;
  5267. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5268. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5269. String newContinuationData;
  5270. if (count < 0)
  5271. count = 3;
  5272. String retVal = GetArrayItems(dbgCompileUnit, debugVis, valueType, curNode, count, &newContinuationData);
  5273. retVal += "\n" + newContinuationData;
  5274. return retVal;
  5275. }
  5276. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Dictionary)
  5277. {
  5278. DbgTypedValue dictValue;
  5279. dictValue.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5280. dictValue.mSrcAddress = DecodeTargetDataPtr(dataPtr);
  5281. int bucketIdx = (int)DecodeTargetDataPtr(dataPtr);
  5282. int nodeIdx = (int)DecodeTargetDataPtr(dataPtr);
  5283. String newContinuationData;
  5284. String retVal = GetDictionaryItems(dbgCompileUnit, debugVis, dictValue, bucketIdx, nodeIdx, count, &newContinuationData);
  5285. retVal += "\n" + newContinuationData;
  5286. return retVal;
  5287. }
  5288. return "";
  5289. }
  5290. template <typename T>
  5291. static String IntTypeToString(T val, const StringImpl& name, DwDisplayInfo* displayInfo, DwFormatInfo& formatInfo)
  5292. {
  5293. auto intDisplayType = displayInfo->mIntDisplayType;
  5294. if (formatInfo.mDisplayType == DwDisplayType_Decimal)
  5295. intDisplayType = DwIntDisplayType_Decimal;
  5296. else if (formatInfo.mDisplayType == DwDisplayType_HexUpper)
  5297. intDisplayType = DwIntDisplayType_HexadecimalUpper;
  5298. else if (formatInfo.mDisplayType == DwDisplayType_HexLower)
  5299. intDisplayType = DwIntDisplayType_HexadecimalLower;
  5300. if (intDisplayType == DwIntDisplayType_Binary)
  5301. {
  5302. String binary;
  5303. for (int i = 0; i < sizeof(T) * 8; i++)
  5304. {
  5305. if ((i != 0) && (i % 4 == 0))
  5306. binary = "'" + binary;
  5307. if ((i != 0) && (i % 16 == 0))
  5308. binary = "'" + binary;
  5309. binary = ((val & ((T)1 << i)) ? "1" : "0") + binary;
  5310. }
  5311. return StrFormat("0b'%s\n%s", binary.c_str(), name.c_str());
  5312. }
  5313. if (intDisplayType == DwIntDisplayType_Octal)
  5314. {
  5315. String format;
  5316. if (sizeof(T) == 8)
  5317. {
  5318. format = StrFormat("0o%%lo\n%s", name.c_str());
  5319. }
  5320. else
  5321. format = StrFormat("0o%%0%do\n%s", sizeof(val) * 2, name.c_str());
  5322. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5323. }
  5324. if (intDisplayType == DwIntDisplayType_HexadecimalUpper)
  5325. {
  5326. String format;
  5327. if (sizeof(T) == 8)
  5328. {
  5329. format = StrFormat("0x%%l@\n%s", name.c_str());
  5330. }
  5331. else
  5332. format = StrFormat("0x%%0%dX\n%s", sizeof(val) * 2, name.c_str());
  5333. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5334. }
  5335. //TODO: Implement HexadecimalLower
  5336. if (intDisplayType == DwIntDisplayType_HexadecimalLower)
  5337. {
  5338. String format;
  5339. if (sizeof(T) == 8)
  5340. {
  5341. format = StrFormat("0x%%l@\n%s", name.c_str());
  5342. }
  5343. else
  5344. format = StrFormat("0x%%0%dX\n%s", sizeof(val) * 2, name.c_str());
  5345. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5346. }
  5347. if (std::is_unsigned<T>::value)
  5348. {
  5349. if (sizeof(T) == 8)
  5350. {
  5351. if (val > 0x7FFFFFFFF)
  5352. return StrFormat("%llu\n%s\n:editVal\t%lluUL", val, name.c_str(), val);
  5353. else
  5354. return StrFormat("%llu\n%s", val, name.c_str());
  5355. }
  5356. else
  5357. return StrFormat("%u\n%s", val, name.c_str());
  5358. }
  5359. else
  5360. {
  5361. if (sizeof(T) == 8)
  5362. {
  5363. if ((val > 0x7FFFFFFFF) || (val < -0x80000000LL))
  5364. return StrFormat("%lld\n%s\n:editVal\t%lldL", val, name.c_str(), val);
  5365. else
  5366. return StrFormat("%lld\n%s", val, name.c_str(), val);
  5367. }
  5368. else
  5369. return StrFormat("%d\n%s", val, name.c_str());
  5370. }
  5371. }
  5372. DwDisplayInfo* WinDebugger::GetDisplayInfo(const StringImpl& referenceId)
  5373. {
  5374. DwDisplayInfo* displayInfo = &mDebugManager->mDefaultDisplayInfo;
  5375. if (!referenceId.empty())
  5376. {
  5377. mDebugManager->mDisplayInfos.TryGetValue(referenceId, &displayInfo);
  5378. }
  5379. return displayInfo;
  5380. }
  5381. static String WrapWithModifiers(const StringImpl& origName, DbgType* dbgType, DbgLanguage language)
  5382. {
  5383. if (language == DbgLanguage_Unknown)
  5384. language = dbgType->GetLanguage();
  5385. String name = origName;
  5386. while (true)
  5387. {
  5388. if (dbgType->mTypeCode == DbgType_Const)
  5389. {
  5390. if (language == DbgLanguage_Beef)
  5391. name = "readonly " + name;
  5392. else
  5393. name = "const " + name;
  5394. dbgType = dbgType->mTypeParam;
  5395. }
  5396. else if (dbgType->mTypeCode == DbgType_Volatile)
  5397. {
  5398. name = "volatile " + name;
  5399. dbgType = dbgType->mTypeParam;
  5400. }
  5401. else if (dbgType->mTypeCode == DbgType_TypeDef)
  5402. {
  5403. dbgType = dbgType->mTypeParam;
  5404. }
  5405. else if (dbgType->mTypeCode == DbgType_Ref)
  5406. {
  5407. if (language == DbgLanguage_Beef)
  5408. name = "ref " + name;
  5409. else
  5410. name = name + "&";
  5411. dbgType = dbgType->mTypeParam;
  5412. }
  5413. else if (dbgType->mTypeCode == DbgType_Bitfield)
  5414. {
  5415. return dbgType->ToString(language);
  5416. }
  5417. else
  5418. return name;
  5419. }
  5420. }
  5421. DebugVisualizerEntry* WinDebugger::FindVisualizerForType(DbgType* dbgType, Array<String>* wildcardCaptures)
  5422. {
  5423. auto entry = mDebugManager->mDebugVisualizers->FindEntryForType(dbgType->ToString(DbgLanguage_Unknown, true), dbgType->mCompileUnit->mDbgModule->mDbgFlavor, wildcardCaptures);
  5424. if (entry == NULL)
  5425. {
  5426. dbgType = dbgType->GetPrimaryType();
  5427. dbgType->PopulateType();
  5428. for (auto baseTypeEntry : dbgType->mBaseTypes)
  5429. {
  5430. entry = FindVisualizerForType(baseTypeEntry->mBaseType, wildcardCaptures);
  5431. if (entry != NULL)
  5432. break;
  5433. }
  5434. }
  5435. return entry;
  5436. }
  5437. #define GET_FROM(ptr, T) *((T*)(ptr += sizeof(T)) - 1)
  5438. String WinDebugger::ReadString(DbgTypeCode charType, intptr addr, bool isLocalAddr, intptr maxLength, DwFormatInfo& formatInfo)
  5439. {
  5440. int origMaxLength = maxLength;
  5441. if (addr == 0)
  5442. return "";
  5443. BP_ZONE("WinDebugger::ReadString");
  5444. String retVal = "\"";
  5445. bool wasTerminated = false;
  5446. String valString;
  5447. intptr maxShowSize = 255;
  5448. if (maxLength == -1)
  5449. maxLength = formatInfo.mOverrideCount;
  5450. else if (formatInfo.mOverrideCount != -1)
  5451. maxLength = BF_MIN(formatInfo.mOverrideCount, maxLength);
  5452. if (formatInfo.mMaxCount != -1)
  5453. maxLength = BF_MIN(formatInfo.mMaxCount, maxLength);
  5454. if (maxLength == -1)
  5455. maxLength = 8 * 1024 * 1024; // Is 8MB crazy?
  5456. if (!formatInfo.mRawString)
  5457. maxLength = BF_MIN(maxLength, maxShowSize);
  5458. //EnableMemCache();
  5459. bool readFailed = false;
  5460. intptr strPtr = addr;
  5461. int charLen = 1;
  5462. if ((charType == DbgType_SChar16) || (charType == DbgType_UChar16))
  5463. charLen = 2;
  5464. else if ((charType == DbgType_SChar32) || (charType == DbgType_UChar32))
  5465. charLen = 4;
  5466. bool isUTF8 = formatInfo.mDisplayType == DwDisplayType_Utf8;
  5467. int readSize = BF_MIN(1024, maxLength * charLen);
  5468. uint8 buf[1024];
  5469. uint8* bufPtr = NULL;
  5470. uint8* bufEnd = NULL;
  5471. bool hasHighAscii = false;
  5472. int i;
  5473. for (i = 0; i < maxLength; i++)
  5474. {
  5475. if (bufPtr >= bufEnd)
  5476. {
  5477. while (true)
  5478. {
  5479. if (readSize < charLen)
  5480. {
  5481. readFailed = true;
  5482. break;
  5483. }
  5484. if (ReadMemory(strPtr, readSize, buf, isLocalAddr))
  5485. break;
  5486. readSize /= 2;
  5487. }
  5488. if (readFailed)
  5489. break;
  5490. bufPtr = buf;
  5491. bufEnd = buf + readSize;
  5492. }
  5493. switch (charLen)
  5494. {
  5495. case 1:
  5496. {
  5497. char c = GET_FROM(bufPtr, char);
  5498. if ((c != 0) || (formatInfo.mOverrideCount != -1))
  5499. {
  5500. if ((uint8)c >= 0x80)
  5501. hasHighAscii = true;
  5502. valString.Append(c);
  5503. }
  5504. else
  5505. wasTerminated = true;
  5506. }
  5507. break;
  5508. case 2:
  5509. {
  5510. uint16 c16 = GET_FROM(bufPtr, uint16);
  5511. if ((c16 != 0) || (formatInfo.mOverrideCount != -1))
  5512. {
  5513. char str[8];
  5514. u8_toutf8(str, 8, c16);
  5515. valString += str;
  5516. }
  5517. else
  5518. wasTerminated = true;
  5519. }
  5520. break;
  5521. case 4:
  5522. {
  5523. uint32 c32 = GET_FROM(bufPtr, uint32);
  5524. if ((c32 != 0) || (formatInfo.mOverrideCount != -1))
  5525. {
  5526. char str[8];
  5527. u8_toutf8(str, 8, c32);
  5528. valString += str;
  5529. }
  5530. else
  5531. wasTerminated = true;
  5532. }
  5533. break;
  5534. }
  5535. if ((wasTerminated) && (formatInfo.mOverrideCount != -1))
  5536. {
  5537. valString += '\x00';
  5538. wasTerminated = false;
  5539. }
  5540. if ((wasTerminated) || (readFailed))
  5541. {
  5542. break;
  5543. }
  5544. strPtr += charLen;
  5545. }
  5546. //DisableMemCache();
  5547. if (formatInfo.mOverrideCount != -1)
  5548. {
  5549. if (i == formatInfo.mOverrideCount)
  5550. wasTerminated = true;
  5551. }
  5552. if (strPtr == addr + origMaxLength)
  5553. wasTerminated = true;
  5554. if (valString.length() == formatInfo.mOverrideCount)
  5555. wasTerminated = true;
  5556. // if (formatInfo.mDisplayType == DwDisplayType_Ascii)
  5557. // {
  5558. // // Our encoding for retVal is already assumed to be UTF8, so the special case here actually Ascii
  5559. // valString = UTF8Encode(ToWString(valString));
  5560. // }
  5561. if (formatInfo.mRawString)
  5562. {
  5563. if ((formatInfo.mDisplayType == DwDisplayType_Utf8) || (!hasHighAscii))
  5564. return valString;
  5565. String utf8Str;
  5566. for (int i = 0; i < (int)valString.length(); i++)
  5567. {
  5568. char c = valString[i];
  5569. if ((uint8)c >= 0x80)
  5570. {
  5571. utf8Str += (char)(0xC0 | (((uint8)c & 0xFF) >> 6));
  5572. utf8Str += (char)(0x80 | ((uint8)c & 0x3F));
  5573. }
  5574. else
  5575. utf8Str += c;
  5576. }
  5577. return utf8Str;
  5578. }
  5579. if ((readFailed) && (valString.IsEmpty()))
  5580. return "< Failed to read string >";
  5581. retVal += SlashString(valString, true, true, formatInfo.mLanguage == DbgLanguage_Beef);
  5582. // We could go over 'maxShowSize' if we have a lot of slashed chars. An uninitialized string can be filled with '\xcc' chars
  5583. if ((!formatInfo.mRawString) && ((int)retVal.length() > maxShowSize))
  5584. {
  5585. retVal = retVal.Substring(0, maxShowSize);
  5586. wasTerminated = false;
  5587. }
  5588. if (wasTerminated)
  5589. retVal += "\"";
  5590. else
  5591. retVal += "...";
  5592. return retVal;
  5593. }
  5594. void WinDebugger::ProcessEvalString(DbgCompileUnit* dbgCompileUnit, DbgTypedValue useTypedValue, String& evalStr, String& displayString, DwFormatInfo& formatInfo, DebugVisualizerEntry* debugVis, bool limitLength)
  5595. {
  5596. for (int i = 0; i < (int)evalStr.length(); i++)
  5597. {
  5598. char c = evalStr[i];
  5599. char nextC = 0;
  5600. if (i < (int)evalStr.length() - 1)
  5601. nextC = evalStr[i + 1];
  5602. if ((c == '{') && (nextC != '{'))
  5603. {
  5604. // Evaluate
  5605. int endIdx = i;
  5606. for (; endIdx < (int)evalStr.length(); endIdx++)
  5607. {
  5608. //TODO: Do better parsing - this paren could be inside a string, for example
  5609. if (evalStr[endIdx] == '}')
  5610. break;
  5611. }
  5612. DwFormatInfo displayStrFormatInfo = formatInfo;
  5613. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + (int)displayString.length();
  5614. displayStrFormatInfo.mHidePointers = false;
  5615. if ((limitLength) && (displayStrFormatInfo.mTotalSummaryLength > 255))
  5616. {
  5617. displayString += "...";
  5618. }
  5619. else
  5620. {
  5621. String evalString = evalStr.Substring(i + 1, endIdx - i - 1);
  5622. String errors;
  5623. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, useTypedValue, evalString, &displayStrFormatInfo, NULL, &errors);
  5624. if (evalResult)
  5625. {
  5626. if (displayStrFormatInfo.mNoEdit)
  5627. formatInfo.mNoEdit = true;
  5628. String result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  5629. if ((formatInfo.mRawString) && (limitLength))
  5630. {
  5631. displayString = result;
  5632. return;
  5633. }
  5634. int crPos = result.IndexOf('\n');
  5635. if (crPos != -1)
  5636. displayString += result.Substring(0, crPos);
  5637. else
  5638. displayString += result;
  5639. }
  5640. else if (debugVis != NULL)
  5641. {
  5642. displayString += "<DbgVis Failed>";
  5643. DbgVisFailed(debugVis, evalString, errors);
  5644. }
  5645. else
  5646. {
  5647. displayString += "<Eval Failed>";
  5648. }
  5649. }
  5650. i = endIdx;
  5651. continue;
  5652. }
  5653. else if ((c == '{') && (nextC == '{'))
  5654. {
  5655. // Skip next paren
  5656. i++;
  5657. }
  5658. else if ((c == '}') && (nextC == '}'))
  5659. {
  5660. // Skip next paren
  5661. i++;
  5662. }
  5663. displayString += c;
  5664. }
  5665. }
  5666. static bool IsNormalChar(uint32 c)
  5667. {
  5668. return (c < 0x80);
  5669. }
  5670. String WinDebugger::DbgTypedValueToString(const DbgTypedValue& origTypedValue, const StringImpl& expr, DwFormatInfo& formatInfo, DbgExprEvaluator* optEvaluator, bool fullPrecision)
  5671. {
  5672. BP_ZONE("WinDebugger::DbgTypedValueToString");
  5673. DbgTypedValue typedValue = origTypedValue;
  5674. auto dbgCompileUnit = typedValue.mType->mCompileUnit;
  5675. auto dbgModule = typedValue.mType->GetDbgModule();
  5676. auto language = origTypedValue.mType->GetLanguage();
  5677. if (language == DbgLanguage_Unknown)
  5678. language = formatInfo.mLanguage;
  5679. formatInfo.mLanguage = language;
  5680. bool isBeef = language == DbgLanguage_Beef;
  5681. char str[32];
  5682. bool readFailed = false;
  5683. bool isCompositeType = false;
  5684. bool isSizedArray = false;
  5685. bool isEnum = false;
  5686. int64 enumVal = 0;
  5687. String result;
  5688. DwDisplayInfo* displayInfo = GetDisplayInfo(formatInfo.mReferenceId);
  5689. DbgType* origValueType = typedValue.mType;
  5690. bool origHadRef = false;
  5691. DbgType* dwValueType = typedValue.mType->RemoveModifiers(&origHadRef);
  5692. if (dwValueType == NULL)
  5693. dwValueType = dbgModule->GetPrimitiveType(DbgType_Void, language);
  5694. else
  5695. dwValueType = dwValueType->GetPrimaryType();
  5696. if (dwValueType->mTypeCode == DbgType_TypeDef)
  5697. {
  5698. DbgTypedValue realTypedVal = typedValue;
  5699. realTypedVal.mType = dwValueType->mTypeParam;
  5700. return DbgTypedValueToString(realTypedVal, expr, formatInfo, optEvaluator);
  5701. }
  5702. if (formatInfo.mRawString)
  5703. {
  5704. if ((dwValueType->mTypeCode != DbgType_Struct) && (dwValueType->mTypeCode != DbgType_Class) && (dwValueType->mTypeCode != DbgType_Ptr) && (dwValueType->mTypeCode != DbgType_SizedArray))
  5705. return "";
  5706. }
  5707. auto _ShowArraySummary = [&](String& retVal, addr_target ptrVal, int64 arraySize, DbgType* innerType)
  5708. {
  5709. String displayString;
  5710. displayString += "{";
  5711. for (int idx = 0; idx < arraySize; idx++)
  5712. {
  5713. if (formatInfo.mTotalSummaryLength + retVal.length() + displayString.length() > 255)
  5714. {
  5715. displayString += "...";
  5716. break;
  5717. }
  5718. if ((idx != 0) && (!displayString.EndsWith('{')))
  5719. displayString += ", ";
  5720. DwFormatInfo displayStrFormatInfo = formatInfo;
  5721. displayStrFormatInfo.mExpandItemDepth = 1;
  5722. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + retVal.length() + displayString.length();
  5723. displayStrFormatInfo.mHidePointers = false;
  5724. displayStrFormatInfo.mArrayLength = -1;
  5725. // Why did we have this "na" on here? It made "void*[3]" type things show up as "{,,}"
  5726. //String evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + StrFormat(")[%d], na", idx);
  5727. String evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + StrFormat(")[%lld]", idx);
  5728. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, typedValue, evalStr, &displayStrFormatInfo);
  5729. String result;
  5730. if (evalResult)
  5731. {
  5732. result = DbgTypedValueToString(evalResult, evalStr, displayStrFormatInfo, NULL);
  5733. int crPos = result.IndexOf('\n');
  5734. if (crPos != -1)
  5735. result.RemoveToEnd(crPos);
  5736. }
  5737. else
  5738. result = "???";
  5739. displayString += result;
  5740. }
  5741. displayString += "}";
  5742. retVal += displayString;
  5743. };
  5744. if (formatInfo.mArrayLength != -1)
  5745. {
  5746. if (formatInfo.mRawString)
  5747. return "";
  5748. if (dwValueType->IsPointer())
  5749. {
  5750. String retVal;
  5751. addr_target ptrVal = (addr_target)typedValue.mPtr;
  5752. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  5753. {
  5754. retVal = EncodeDataPtr(ptrVal, true) + " ";
  5755. retVal += dwValueType->mTypeParam->ToString(language);
  5756. retVal += StrFormat("[%lld] ", (int64)formatInfo.mArrayLength);
  5757. }
  5758. _ShowArraySummary(retVal, ptrVal, formatInfo.mArrayLength, dwValueType->mTypeParam);
  5759. String idxStr = "[{0}]";
  5760. DbgType* innerType = dwValueType->mTypeParam;
  5761. retVal += "\n" + dwValueType->ToString(language);
  5762. String evalStr = "*((" + typedValue.mType->ToStringRaw(language) + ")" + EncodeDataPtr(ptrVal, true) + " + {0})";
  5763. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, (int)BF_MAX(formatInfo.mArrayLength, 0), 10000) +
  5764. "\t" + idxStr + "\t" + evalStr;
  5765. return retVal;
  5766. }
  5767. else
  5768. {
  5769. DwFormatInfo newFormatInfo = formatInfo;
  5770. newFormatInfo.mArrayLength = -1;
  5771. String retVal = DbgTypedValueToString(typedValue, expr, newFormatInfo, optEvaluator);
  5772. int crPos = (int)retVal.IndexOf('\n');
  5773. if (crPos != -1)
  5774. retVal = "!Array length flag not valid with this type" + retVal.Substring(crPos);
  5775. return retVal;
  5776. }
  5777. }
  5778. switch (dwValueType->mTypeCode)
  5779. {
  5780. case DbgType_Void:
  5781. return "\nvoid";
  5782. case DbgType_Bool:
  5783. {
  5784. if (typedValue.mUInt8 == 0)
  5785. return "false\n" + WrapWithModifiers("bool", origValueType, language);
  5786. else if (typedValue.mUInt8 == 1)
  5787. return "true\n" + WrapWithModifiers("bool", origValueType, language);
  5788. else
  5789. return StrFormat("true (%d)\n", typedValue.mUInt8) + WrapWithModifiers("bool", origValueType, language);
  5790. }
  5791. break;
  5792. case DbgType_UChar:
  5793. if (language != DbgLanguage_Beef)
  5794. return IntTypeToString<uint8>(typedValue.mUInt8, WrapWithModifiers("uint8_t", origValueType, language), displayInfo, formatInfo);
  5795. case DbgType_SChar:
  5796. {
  5797. if (typedValue.mInt8 != 0)
  5798. {
  5799. char str[2] = {(char)typedValue.mInt8};
  5800. result = SlashString(str, formatInfo.mDisplayType == DwDisplayType_Utf8, true);
  5801. if (!IsNormalChar(typedValue.mUInt8))
  5802. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt8);
  5803. else
  5804. result = StrFormat("'%s'\n", result.c_str());
  5805. }
  5806. else
  5807. result = "'\\0'\n";
  5808. return result + WrapWithModifiers("char", origValueType, language);
  5809. }
  5810. break;
  5811. case DbgType_UChar16:
  5812. if (language != DbgLanguage_Beef)
  5813. return IntTypeToString<int16>(typedValue.mUInt8, WrapWithModifiers("uint16_t", origValueType, language), displayInfo, formatInfo);
  5814. case DbgType_SChar16:
  5815. {
  5816. if (typedValue.mInt16 != 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.mUInt16);
  5822. else
  5823. result = StrFormat("'%s'\n", result.c_str());
  5824. }
  5825. else
  5826. result = "'\\0'\n";
  5827. return result + WrapWithModifiers(isBeef ? "char16" : "int16_t", origValueType, language);
  5828. }
  5829. break;
  5830. case DbgType_UChar32:
  5831. case DbgType_SChar32:
  5832. {
  5833. if (typedValue.mInt32 != 0)
  5834. {
  5835. u8_toutf8(str, 8, typedValue.mUInt32);
  5836. result = SlashString(str, true, true);
  5837. if (!IsNormalChar(typedValue.mUInt32))
  5838. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt32);
  5839. else
  5840. result = StrFormat("'%s'\n", result.c_str());
  5841. }
  5842. else
  5843. result = "'\\0'\n";
  5844. return result + WrapWithModifiers(isBeef ? "char32" : "int32_t", origValueType, language);
  5845. }
  5846. break;
  5847. case DbgType_i8:
  5848. return IntTypeToString<int8>(typedValue.mInt8, WrapWithModifiers(isBeef ? "int8" : "int8_t", origValueType, language), displayInfo, formatInfo);
  5849. case DbgType_u8:
  5850. return IntTypeToString<uint8>(typedValue.mUInt8, WrapWithModifiers(isBeef ? "uint8" : "uint8_t", origValueType, language), displayInfo, formatInfo);
  5851. case DbgType_i16:
  5852. return IntTypeToString<int16>(typedValue.mInt16, WrapWithModifiers(isBeef ? "int16" : "int16_t", origValueType, language), displayInfo, formatInfo);
  5853. case DbgType_u16:
  5854. return IntTypeToString<uint16>(typedValue.mUInt16, WrapWithModifiers(isBeef ? "uint16" : "uint16_t", origValueType, language), displayInfo, formatInfo);
  5855. case DbgType_i32:
  5856. return IntTypeToString<int32>(typedValue.mInt32, WrapWithModifiers(isBeef ? "int32" : "int32_t", origValueType, language), displayInfo, formatInfo);
  5857. case DbgType_u32:
  5858. return IntTypeToString<uint32>(typedValue.mUInt32, WrapWithModifiers(isBeef ? "uint32" : "uint32_t", origValueType, language), displayInfo, formatInfo);
  5859. case DbgType_i64:
  5860. return IntTypeToString<int64>(typedValue.mInt64, WrapWithModifiers(isBeef ? "int64" : "int64_t", origValueType, language), displayInfo, formatInfo);
  5861. case DbgType_u64:
  5862. return IntTypeToString<uint64>(typedValue.mUInt64, WrapWithModifiers(isBeef ? "uint64" : "uint64_t", origValueType, language), displayInfo, formatInfo);
  5863. case DbgType_RegGroup:
  5864. {
  5865. if ((typedValue.mRegNum >= CPUReg_M128_XMMREG_FIRST) && (typedValue.mRegNum <= CPUReg_M128_XMMREG_LAST))
  5866. {
  5867. int callStackIdx = formatInfo.mCallStackIdx;
  5868. FixCallStackIdx(callStackIdx);
  5869. UpdateRegisterUsage(callStackIdx);
  5870. WdStackFrame* wdStackFrame = mCallStack[callStackIdx];
  5871. RegForm regForm = RegForm_Unknown;
  5872. if (typedValue.mRegNum < (int)wdStackFrame->mRegForms.size())
  5873. regForm = wdStackFrame->mRegForms[typedValue.mRegNum];
  5874. int xmmMajor = typedValue.mRegNum - CPUReg_M128_XMMREG_FIRST;
  5875. String headerStr;
  5876. String xmmType = "__m128";
  5877. int xmmCount = 4;
  5878. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2) ||
  5879. (regForm == RegForm_Long) || (regForm == RegForm_Long2) ||
  5880. (regForm == RegForm_ULong) || (regForm == RegForm_ULong2))
  5881. xmmCount = 2;
  5882. //TODO: add byte, short, int, etc...
  5883. if (optEvaluator)
  5884. {
  5885. DwMmDisplayType mmDwMmDisplayType = displayInfo->mMmDisplayType;
  5886. if (mmDwMmDisplayType == DwMmDisplayType_Default)
  5887. {
  5888. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2))
  5889. mmDwMmDisplayType = DwMmDisplayType_Double;
  5890. else if (regForm == RegForm_Int4)
  5891. mmDwMmDisplayType = DwMmDisplayType_Int32;
  5892. }
  5893. if (mmDwMmDisplayType == DwMmDisplayType_Double)
  5894. {
  5895. xmmType = "__m128d";
  5896. xmmCount = 2;
  5897. double xmmRegVals[2];
  5898. CPURegisters* regs = optEvaluator->GetRegisters();
  5899. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5900. {
  5901. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5902. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_Double);
  5903. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5904. xmmRegVals[xmmMinor] = xmmReg.mDouble;
  5905. }
  5906. headerStr = StrFormat("(%f, %f)", xmmRegVals[0], xmmRegVals[1]);
  5907. }
  5908. else if (mmDwMmDisplayType == DwMmDisplayType_UInt8)
  5909. {
  5910. int xmmRegVals[4];
  5911. xmmCount = 16;
  5912. CPURegisters* regs = optEvaluator->GetRegisters();
  5913. for (int xmmMinor = 0; xmmMinor < BF_ARRAY_COUNT(xmmRegVals); ++xmmMinor)
  5914. {
  5915. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5916. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i32);
  5917. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5918. xmmRegVals[xmmMinor] = xmmReg.mInt32;
  5919. }
  5920. headerStr = StrFormat("(%d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d)",
  5921. xmmRegVals[0] & 0xFF, (xmmRegVals[0] >> 8) & 0xFF, (xmmRegVals[0] >> 16) & 0xFF, (xmmRegVals[0] >> 24) & 0xFF,
  5922. xmmRegVals[1] & 0xFF, (xmmRegVals[1] >> 8) & 0xFF, (xmmRegVals[1] >> 16) & 0xFF, (xmmRegVals[1] >> 24) & 0xFF,
  5923. xmmRegVals[2] & 0xFF, (xmmRegVals[2] >> 8) & 0xFF, (xmmRegVals[2] >> 16) & 0xFF, (xmmRegVals[2] >> 24) & 0xFF,
  5924. xmmRegVals[3] & 0xFF, (xmmRegVals[3] >> 8) & 0xFF, (xmmRegVals[3] >> 16) & 0xFF, (xmmRegVals[3] >> 24) & 0xFF);
  5925. }
  5926. else if (mmDwMmDisplayType == DwMmDisplayType_Int16)
  5927. {
  5928. int xmmRegVals[4];
  5929. xmmCount = 8;
  5930. CPURegisters* regs = optEvaluator->GetRegisters();
  5931. for (int xmmMinor = 0; xmmMinor < BF_ARRAY_COUNT(xmmRegVals); ++xmmMinor)
  5932. {
  5933. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5934. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i32);
  5935. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5936. xmmRegVals[xmmMinor] = xmmReg.mInt32;
  5937. }
  5938. headerStr = StrFormat("(%d, %d, %d, %d, %d, %d, %d, %d)",
  5939. xmmRegVals[0] & 0xFFFF, (xmmRegVals[0] >> 16) & 0xFFFF,
  5940. xmmRegVals[1] & 0xFFFF, (xmmRegVals[1] >> 16) & 0xFFFF,
  5941. xmmRegVals[2] & 0xFFFF, (xmmRegVals[2] >> 16) & 0xFFFF,
  5942. xmmRegVals[3] & 0xFFFF, (xmmRegVals[3] >> 16) & 0xFFFF);
  5943. }
  5944. else if (mmDwMmDisplayType == DwMmDisplayType_Int32)
  5945. {
  5946. int xmmRegVals[4];
  5947. xmmCount = 4;
  5948. CPURegisters* regs = optEvaluator->GetRegisters();
  5949. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5950. {
  5951. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5952. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i32);
  5953. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5954. xmmRegVals[xmmMinor] = xmmReg.mInt32;
  5955. }
  5956. headerStr = StrFormat("(%d, %d, %d, %d)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  5957. }
  5958. else if (mmDwMmDisplayType == DwMmDisplayType_Int64)
  5959. {
  5960. int64 xmmRegVals[2];
  5961. xmmCount = 2;
  5962. CPURegisters* regs = optEvaluator->GetRegisters();
  5963. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5964. {
  5965. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5966. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i64);
  5967. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5968. xmmRegVals[xmmMinor] = xmmReg.mInt64;
  5969. }
  5970. headerStr = StrFormat("(%lld, %lld)", xmmRegVals[0], xmmRegVals[1]);
  5971. }
  5972. else // float
  5973. {
  5974. float xmmRegVals[4];
  5975. xmmCount = 4;
  5976. CPURegisters* regs = optEvaluator->GetRegisters();
  5977. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5978. {
  5979. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5980. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_Single);
  5981. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5982. xmmRegVals[xmmMinor] = xmmReg.mSingle;
  5983. }
  5984. headerStr = StrFormat("(%f, %f, %f, %f)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  5985. }
  5986. }
  5987. else
  5988. {
  5989. headerStr = StrFormat("XMM%d", xmmMajor);
  5990. }
  5991. result = headerStr + "\n" + xmmType;
  5992. for (int i = 0; i < xmmCount; i++)
  5993. {
  5994. if (xmmCount == 16)
  5995. result += WrapWithModifiers(StrFormat("\n[%d]\t(uint8)($xmm%d_%d >> %d)", i, xmmMajor, i / 4, (i % 4)*8), origValueType, language);
  5996. else if (xmmCount == 8)
  5997. result += WrapWithModifiers(StrFormat("\n[%d]\t(int16)($xmm%d_%d >> %d)", i, xmmMajor, i / 2, (i % 2)*8), origValueType, language);
  5998. else
  5999. result += WrapWithModifiers(StrFormat("\n[%d]\t$xmm%d_%d", i, xmmMajor, i), origValueType, language);
  6000. }
  6001. return result;
  6002. }
  6003. else
  6004. {
  6005. switch (typedValue.mRegNum)
  6006. {
  6007. case CPUReg_CAT_ALLREGS:
  6008. {
  6009. return "ALLREGS\n__allregs\niregs\t$iregs\nflags\t$flags\nfpregs\t$fpregs\nmmregs\t$mmregs\nxmmregs\t$xmmregs";
  6010. }
  6011. break;
  6012. case CPUReg_CAT_IREGS:
  6013. {
  6014. #ifdef BF_DBG_32
  6015. String headerStr;
  6016. if (optEvaluator)
  6017. {
  6018. CPURegisters* regs = optEvaluator->GetRegisters();
  6019. 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)",
  6020. (uint32)regs->mIntRegs.eax, (uint32)regs->mIntRegs.ebx, (uint32)regs->mIntRegs.ecx, (uint32)regs->mIntRegs.edx,
  6021. (uint32)regs->mIntRegs.esi, (uint32)regs->mIntRegs.edi, (uint32)regs->mIntRegs.esp, (uint32)regs->mIntRegs.ebp,
  6022. (uint32)regs->mIntRegs.eip, (uint32)regs->mIntRegs.efl);
  6023. }
  6024. else
  6025. {
  6026. headerStr = "IREGS";
  6027. }
  6028. 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());
  6029. #else
  6030. String headerStr;
  6031. if (optEvaluator)
  6032. {
  6033. CPURegisters* regs = optEvaluator->GetRegisters();
  6034. 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)",
  6035. (uint64)regs->mIntRegs.rax, (uint64)regs->mIntRegs.rbx, (uint64)regs->mIntRegs.rcx, (uint64)regs->mIntRegs.rdx,
  6036. (uint64)regs->mIntRegs.rsi, (uint64)regs->mIntRegs.rdi, (uint64)regs->mIntRegs.rsp, (uint64)regs->mIntRegs.rbp,
  6037. (uint64)regs->mIntRegs.rip,
  6038. (uint64)regs->mIntRegs.r8, (uint64)regs->mIntRegs.r9, (uint64)regs->mIntRegs.r10, (uint64)regs->mIntRegs.r11,
  6039. (uint64)regs->mIntRegs.r12, (uint64)regs->mIntRegs.r13, (uint64)regs->mIntRegs.r14, (uint64)regs->mIntRegs.r15,
  6040. (uint32)regs->mIntRegs.efl);
  6041. }
  6042. else
  6043. {
  6044. headerStr = "IREGS";
  6045. }
  6046. 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());
  6047. #endif
  6048. }
  6049. break;
  6050. case CPUReg_CAT_FPREGS:
  6051. {
  6052. String headerStr;
  6053. if (optEvaluator)
  6054. {
  6055. CPURegisters* regs = optEvaluator->GetRegisters();
  6056. headerStr = "(";
  6057. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6058. {
  6059. if (i)
  6060. headerStr += ", ";
  6061. double val = ConvertFloat80ToDouble(regs->mFpMmRegsArray[i].fp.fp80);
  6062. headerStr += StrFormat("%f", val);
  6063. }
  6064. headerStr += ")";
  6065. }
  6066. else
  6067. {
  6068. headerStr = "FPREGS";
  6069. }
  6070. result = StrFormat("%s\n__fpregs", headerStr.c_str());
  6071. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6072. result += StrFormat("\n[%d]\t$st%d", i, i);
  6073. return result;
  6074. }
  6075. break;
  6076. case CPUReg_CAT_MMREGS:
  6077. {
  6078. String headerStr;
  6079. if (optEvaluator)
  6080. {
  6081. CPURegisters* regs = optEvaluator->GetRegisters();
  6082. headerStr = "(";
  6083. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6084. {
  6085. if (i)
  6086. headerStr += ", ";
  6087. uint64 val = regs->mFpMmRegsArray[i].mm;
  6088. headerStr += StrFormat("0x%016llx", val);
  6089. }
  6090. headerStr += ")";
  6091. }
  6092. else
  6093. {
  6094. headerStr = "MMREGS";
  6095. }
  6096. result = StrFormat("%s\n__mmregs", headerStr.c_str());
  6097. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6098. result += StrFormat("\n[%d]\t$mm%d", i, i);
  6099. return result;
  6100. }
  6101. break;
  6102. case CPUReg_CAT_XMMREGS:
  6103. {
  6104. String headerStr = StrFormat("XMMREGS[%d]", CPURegisters::kNumXmmRegs); // these are too big to put a useful header for the entire category
  6105. result = StrFormat("%s\n__xmmregs", headerStr.c_str());
  6106. for (int i = 0; i < CPURegisters::kNumXmmRegs; ++i)
  6107. result += StrFormat("\n[%d]\t$xmm%d", i, i);
  6108. return result;
  6109. }
  6110. break;
  6111. case CPUReg_CAT_FLAGS:
  6112. {
  6113. String headerStr;
  6114. if (optEvaluator)
  6115. {
  6116. CPURegisters* regs = optEvaluator->GetRegisters();
  6117. #ifdef BF_DBG_32
  6118. #define FLAGVAR(abbr, name) int flag##abbr = ((regs->mIntRegs.efl & ((uint64)1 << CPURegisters::GetFlagBitForRegister(X86Reg_FLAG_##abbr##_##name))) != 0) ? 1 : 0
  6119. FLAGVAR(CF, CARRY);
  6120. FLAGVAR(PF, PARITY);
  6121. FLAGVAR(AF, ADJUST);
  6122. FLAGVAR(ZF, ZERO);
  6123. FLAGVAR(SF, SIGN);
  6124. FLAGVAR(IF, INTERRUPT);
  6125. FLAGVAR(DF, DIRECTION);
  6126. FLAGVAR(OF, OVERFLOW);
  6127. #undef FLAGVAR
  6128. #else
  6129. #define FLAGVAR(abbr, name) int flag##abbr = ((regs->mIntRegs.efl & ((uint64)1 << CPURegisters::GetFlagBitForRegister(X64Reg_FLAG_##abbr##_##name))) != 0) ? 1 : 0
  6130. FLAGVAR(CF, CARRY);
  6131. FLAGVAR(PF, PARITY);
  6132. FLAGVAR(AF, ADJUST);
  6133. FLAGVAR(ZF, ZERO);
  6134. FLAGVAR(SF, SIGN);
  6135. FLAGVAR(IF, INTERRUPT);
  6136. FLAGVAR(DF, DIRECTION);
  6137. FLAGVAR(OF, OVERFLOW);
  6138. #undef FLAGVAR
  6139. #endif
  6140. headerStr = StrFormat("(CF=%d, PF=%d, AF=%d, ZF=%d, SF=%d, IF=%d, DF=%d, OF=%d)",
  6141. flagCF, flagPF, flagAF, flagZF, flagSF, flagIF, flagDF, flagOF);
  6142. }
  6143. else
  6144. {
  6145. headerStr = "FLAGS";
  6146. }
  6147. 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",
  6148. headerStr.c_str());
  6149. }
  6150. break;
  6151. default:
  6152. BF_ASSERT(false && "unknown category register");
  6153. return "UNKNOWNCATEGORY\n__unknown\n";
  6154. }
  6155. }
  6156. }
  6157. break;
  6158. case DbgType_Single:
  6159. {
  6160. DwFloatDisplayType floatDisplayType = displayInfo->mFloatDisplayType;
  6161. if (floatDisplayType == DwFloatDisplayType_Default)
  6162. floatDisplayType = DwFloatDisplayType_Minimal;
  6163. if (floatDisplayType == DwFloatDisplayType_Minimal)
  6164. ExactMinimalFloatToStr(typedValue.mSingle, str);
  6165. else if (floatDisplayType == DwFloatDisplayType_Full)
  6166. sprintf(str, "%1.9g", typedValue.mSingle);
  6167. else if (floatDisplayType == DwFloatDisplayType_HexUpper)
  6168. sprintf(str, "0x%04X", typedValue.mUInt32);
  6169. else //if (floatDisplayType == DwFloatDisplayType_HexLower)
  6170. sprintf(str, "0x%04x", typedValue.mUInt32);
  6171. return StrFormat("%s\n%s", str, WrapWithModifiers("float", origValueType, language).c_str());
  6172. }
  6173. case DbgType_Double:
  6174. {
  6175. DwFloatDisplayType floatDisplayType = displayInfo->mFloatDisplayType;
  6176. if (floatDisplayType == DwFloatDisplayType_Default)
  6177. floatDisplayType = DwFloatDisplayType_Minimal;
  6178. if (floatDisplayType == DwFloatDisplayType_Minimal)
  6179. ExactMinimalDoubleToStr(typedValue.mDouble, str);
  6180. else if (floatDisplayType == DwFloatDisplayType_Full)
  6181. sprintf(str, "%1.17g", typedValue.mDouble);
  6182. else if (floatDisplayType == DwFloatDisplayType_HexUpper)
  6183. sprintf(str, "0x%08llX", typedValue.mUInt64);
  6184. else //if (floatDisplayType == DwFloatDisplayType_HexLower)
  6185. sprintf(str, "0x%08llx", typedValue.mUInt64);
  6186. return StrFormat("%s\n%s", str, WrapWithModifiers("double", origValueType, language).c_str());
  6187. }
  6188. case DbgType_Subroutine:
  6189. if (typedValue.mCharPtr != NULL)
  6190. return StrFormat("%s\nfunc", typedValue.mCharPtr);
  6191. else
  6192. return "\nfunc";
  6193. case DbgType_RawText:
  6194. return StrFormat("%s\nrawtext", typedValue.mCharPtr);
  6195. case DbgType_Ptr:
  6196. {
  6197. addr_target ptrVal = (addr_target)typedValue.mPtr;
  6198. String retVal;
  6199. DbgType* innerType = dwValueType->mTypeParam;
  6200. if (innerType == NULL)
  6201. return EncodeDataPtr(ptrVal, true) + "\nvoid*";
  6202. bool isChar = false;
  6203. DbgType* unmodInnerType = innerType->RemoveModifiers();
  6204. if (unmodInnerType != NULL)
  6205. {
  6206. if (language == DbgLanguage_Beef)
  6207. {
  6208. if ((unmodInnerType->mTypeCode == DbgType_UChar) ||
  6209. (unmodInnerType->mTypeCode == DbgType_UChar16) ||
  6210. (unmodInnerType->mTypeCode == DbgType_UChar32))
  6211. isChar = true;
  6212. }
  6213. else
  6214. {
  6215. if ((unmodInnerType->mTypeCode == DbgType_SChar) ||
  6216. (unmodInnerType->mTypeCode == DbgType_SChar16) ||
  6217. (unmodInnerType->mTypeCode == DbgType_SChar32))
  6218. isChar = true;
  6219. }
  6220. }
  6221. if ((isChar) && (formatInfo.mArrayLength == -1))
  6222. {
  6223. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6224. retVal = EncodeDataPtr(ptrVal, true);
  6225. int strLen = formatInfo.mOverrideCount;
  6226. if (typedValue.mIsLiteral)
  6227. {
  6228. if (strLen == -1)
  6229. strLen = 0x7FFFFFFF;
  6230. if (typedValue.mDataLen > 0)
  6231. strLen = BF_MIN(strLen, typedValue.mDataLen);
  6232. else
  6233. strLen = BF_MIN(strLen, strlen(typedValue.mCharPtr));
  6234. }
  6235. SetAndRestoreValue<intptr> prevOverrideLen(formatInfo.mOverrideCount, strLen);
  6236. String strResult = ReadString(unmodInnerType->mTypeCode, typedValue.mLocalIntPtr, typedValue.mIsLiteral, strLen, formatInfo);
  6237. if (formatInfo.mRawString)
  6238. return strResult;
  6239. if (!strResult.IsEmpty())
  6240. {
  6241. if (!retVal.IsEmpty())
  6242. retVal += " ";
  6243. retVal += strResult;
  6244. }
  6245. retVal += "\n" + origValueType->ToString(language);
  6246. return retVal;
  6247. }
  6248. else if ((unmodInnerType != NULL) &&
  6249. ((unmodInnerType->mTypeCode == DbgType_Class) || (unmodInnerType->mTypeCode == DbgType_Struct) || (unmodInnerType->mTypeCode == DbgType_Union)))
  6250. {
  6251. isCompositeType = true;
  6252. }
  6253. else if ((unmodInnerType != NULL) && (unmodInnerType->mTypeCode == DbgType_SizedArray))
  6254. {
  6255. isSizedArray = true;
  6256. }
  6257. else if (unmodInnerType->mTypeCode == DbgType_Subroutine)
  6258. {
  6259. if (formatInfo.mRawString)
  6260. return "";
  6261. addr_target funcPtr = (addr_target)typedValue.mPtr;
  6262. String retVal;
  6263. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6264. retVal = EncodeDataPtr(funcPtr, true);
  6265. String symbolName;
  6266. addr_target offset;
  6267. DbgModule* dwarf;
  6268. static String demangledName;
  6269. auto subProgram = mDebugTarget->FindSubProgram(funcPtr);
  6270. if (subProgram != NULL)
  6271. {
  6272. demangledName = subProgram->ToString();
  6273. }
  6274. else if (mDebugTarget->FindSymbolAt(funcPtr, &symbolName, &offset, &dwarf))
  6275. {
  6276. demangledName = BfDemangler::Demangle(symbolName, language);
  6277. if (offset != 0)
  6278. demangledName += StrFormat("+%d", offset);
  6279. }
  6280. else
  6281. {
  6282. auto dbgModule = mDebugTarget->FindDbgModuleForAddress(funcPtr);
  6283. if (dbgModule != NULL)
  6284. demangledName += dbgModule->GetLinkedModule()->mDisplayName + "!";
  6285. demangledName += StrFormat("0x%@", funcPtr);
  6286. }
  6287. retVal += " {";
  6288. retVal += demangledName;
  6289. retVal += "}";
  6290. retVal += "\n" + origValueType->ToString(language);
  6291. return retVal;
  6292. }
  6293. else if (unmodInnerType->mTypeCode == DbgType_Void)
  6294. {
  6295. if (formatInfo.mRawString)
  6296. return "";
  6297. addr_target ptr = (addr_target)typedValue.mPtr;
  6298. String symbolName;
  6299. addr_target offset;
  6300. DbgModule* dwarf;
  6301. String demangledName;
  6302. retVal += demangledName = StrFormat("0x%@", ptr);
  6303. if (mDebugTarget->FindSymbolAt(ptr, &symbolName, &offset, &dwarf))
  6304. {
  6305. if (offset == 0)
  6306. {
  6307. retVal += " {";
  6308. retVal += BfDemangler::Demangle(symbolName, language);
  6309. retVal += "}";
  6310. }
  6311. }
  6312. retVal += "\n" + origValueType->ToString(language);
  6313. return retVal;
  6314. }
  6315. else
  6316. {
  6317. if (formatInfo.mRawString)
  6318. return "";
  6319. addr_target ptrVal = (addr_target)typedValue.mPtr;
  6320. String retVal;
  6321. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6322. retVal = EncodeDataPtr(ptrVal, true);
  6323. if (ptrVal != 0)
  6324. {
  6325. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, NULL, -1, -1);
  6326. DbgTypedValue innerTypedVal = dbgExprEvaluator.ReadTypedValue(NULL, innerType, typedValue.mPtr, DbgAddrType_Target);
  6327. if (innerTypedVal)
  6328. {
  6329. DwFormatInfo defaultFormatInfo;
  6330. defaultFormatInfo.mLanguage = formatInfo.mLanguage;
  6331. defaultFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + 2; // Take into accout the necessary {}'s
  6332. defaultFormatInfo.mExpandItemDepth++;
  6333. String innerStr = DbgTypedValueToString(innerTypedVal, "", defaultFormatInfo, &dbgExprEvaluator);
  6334. int crIdx = innerStr.IndexOf('\n');
  6335. if (crIdx != -1)
  6336. {
  6337. String innerDataStr = innerStr.Substring(0, crIdx);
  6338. if (!innerDataStr.empty())
  6339. {
  6340. if (!retVal.empty())
  6341. retVal += " ";
  6342. retVal += "{" + innerDataStr + "}";
  6343. }
  6344. }
  6345. else
  6346. {
  6347. retVal += "{ ??? }";
  6348. }
  6349. }
  6350. }
  6351. retVal += "\n" + origValueType->ToString(language);
  6352. innerType->PopulateType();
  6353. if ((ptrVal != 0) &&
  6354. ((!innerType->mMemberList.IsEmpty()) || (innerType->mSize > 0) || (innerType->mTypeParam != NULL)))
  6355. {
  6356. String ptrDataStr = StrFormat("(%s)", dwValueType->ToStringRaw(language).c_str()) + EncodeDataPtr(typedValue.mPtr, true);
  6357. retVal += "\n*\t";
  6358. // Why did we have this? It messed up a pointer to sized array
  6359. /*if (language == DbgLanguage_Beef)
  6360. retVal += "this";
  6361. else*/
  6362. retVal += "*this";
  6363. if (!formatInfo.mReferenceId.empty())
  6364. retVal += ", refid=" + MaybeQuoteFormatInfoParam(formatInfo.mReferenceId);
  6365. retVal += ", this=" + ptrDataStr;
  6366. }
  6367. return retVal;
  6368. }
  6369. break;
  6370. }
  6371. case DbgType_Union:
  6372. case DbgType_Class:
  6373. case DbgType_Struct:
  6374. isCompositeType = true;
  6375. break;
  6376. case DbgType_Enum:
  6377. enumVal = typedValue.GetInt64();
  6378. isEnum = true;
  6379. break;
  6380. case DbgType_SizedArray:
  6381. {
  6382. isSizedArray = true;
  6383. }
  6384. break;
  6385. default:
  6386. break;
  6387. }
  6388. if (isSizedArray)
  6389. {
  6390. String retVal;
  6391. addr_target ptrVal = 0;
  6392. DbgType* arrayType = dwValueType;
  6393. DbgType* innerType = dwValueType->mTypeParam;
  6394. if (dwValueType->mTypeCode == DbgType_SizedArray)
  6395. {
  6396. ptrVal = (addr_target)typedValue.mSrcAddress;
  6397. }
  6398. else
  6399. {
  6400. BF_ASSERT(dwValueType->mTypeCode == DbgType_Ptr);
  6401. arrayType = innerType;
  6402. innerType = arrayType->mTypeParam;
  6403. ptrVal = typedValue.mPtr;
  6404. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6405. retVal = EncodeDataPtr(ptrVal, true) + " ";
  6406. }
  6407. if (ptrVal == 0)
  6408. ptrVal = typedValue.mPtr;
  6409. intptr arraySize = 0;
  6410. intptr innerSize = innerType->GetStride();
  6411. if (innerSize > 0)
  6412. arraySize = arrayType->GetStride() / innerSize;
  6413. else
  6414. {
  6415. // Failure!
  6416. }
  6417. String idxStr = "[{0}]";
  6418. if (innerType->IsChar(language))
  6419. {
  6420. String strVal = ReadString(innerType->mTypeCode, typedValue.mSrcAddress, false, arraySize, formatInfo);
  6421. if (formatInfo.mRawString)
  6422. return strVal;
  6423. retVal += strVal;
  6424. }
  6425. else
  6426. {
  6427. if (formatInfo.mRawString)
  6428. return "";
  6429. _ShowArraySummary(retVal, ptrVal, arraySize, innerType);
  6430. }
  6431. retVal += "\n" + origValueType->ToString(language);
  6432. String referenceId = dwValueType->ToString(language);
  6433. String evalStr;
  6434. // Why did we have the "na"? Do we not want to show addresses for all members?
  6435. evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + ")[{0}], refid=" + MaybeQuoteFormatInfoParam(referenceId + ".[]");
  6436. if (typedValue.mIsReadOnly)
  6437. evalStr += ", ne";
  6438. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, (int)BF_MAX(arraySize, 0), 10000) +
  6439. "\t" + idxStr + "\t" + evalStr;
  6440. return retVal;
  6441. }
  6442. dwValueType->PopulateType();
  6443. if (isEnum)
  6444. {
  6445. String retVal;
  6446. int64 bitsLeft = enumVal;
  6447. int valueCount = 0;
  6448. String editVal;
  6449. dwValueType = dwValueType->GetPrimaryType();
  6450. dwValueType->PopulateType();
  6451. while ((bitsLeft != 0) || (valueCount == 0))
  6452. {
  6453. DbgVariable* bestMatch = NULL;
  6454. for (auto member : dwValueType->mMemberList)
  6455. {
  6456. if (member->mConstValue == bitsLeft)
  6457. {
  6458. bestMatch = member;
  6459. break;
  6460. }
  6461. }
  6462. if (bestMatch == NULL)
  6463. {
  6464. for (auto member : dwValueType->mMemberList)
  6465. {
  6466. if ((member->mConstValue != 0) &&
  6467. ((member->mConstValue & bitsLeft) == member->mConstValue))
  6468. {
  6469. bestMatch = member;
  6470. break;
  6471. }
  6472. }
  6473. }
  6474. if (bestMatch == NULL)
  6475. break;
  6476. if (valueCount > 0)
  6477. {
  6478. retVal += " | ";
  6479. if (language == DbgLanguage_C)
  6480. editVal += " | ";
  6481. }
  6482. if (language == DbgLanguage_Beef)
  6483. retVal += ".";
  6484. retVal += bestMatch->mName;
  6485. if (language == DbgLanguage_C)
  6486. {
  6487. if (dwValueType->mParent != NULL)
  6488. {
  6489. editVal += dwValueType->mParent->ToString(language);
  6490. editVal += "::";
  6491. }
  6492. editVal += bestMatch->mName;
  6493. }
  6494. valueCount++;
  6495. bitsLeft &= ~bestMatch->mConstValue;
  6496. }
  6497. if ((valueCount == 0) || (bitsLeft != 0))
  6498. {
  6499. if (valueCount > 0)
  6500. retVal += " | ";
  6501. retVal += StrFormat("%lld", bitsLeft);
  6502. if (language == DbgLanguage_C)
  6503. {
  6504. if (valueCount > 0)
  6505. editVal += " | ";
  6506. editVal += StrFormat("%lld", bitsLeft);
  6507. }
  6508. }
  6509. retVal += "\n" + origValueType->ToString();
  6510. if (language == DbgLanguage_C)
  6511. {
  6512. retVal += "\n:editVal\t";
  6513. retVal += editVal;
  6514. }
  6515. retVal += "\n:canEdit";
  6516. return retVal;
  6517. }
  6518. else if (isCompositeType)
  6519. {
  6520. addr_target ptrVal;
  6521. if (dwValueType->IsPointer())
  6522. ptrVal = (addr_target)typedValue.mPtr;
  6523. else
  6524. ptrVal = (addr_target)typedValue.mSrcAddress;
  6525. String retVal;
  6526. if ((!typedValue.mIsLiteral) && (dwValueType->IsPointer()) &&
  6527. ((!formatInfo.mHidePointers) || (ptrVal == 0)))
  6528. retVal = EncodeDataPtr(ptrVal, true);
  6529. DbgType* innerType = dwValueType;
  6530. bool wasPtr = false;
  6531. if (innerType->mTypeCode == DbgType_Ptr)
  6532. {
  6533. wasPtr = true;
  6534. innerType = dwValueType->mTypeParam;
  6535. innerType = innerType->RemoveModifiers();
  6536. }
  6537. innerType = innerType->GetPrimaryType();
  6538. addr_target dataPtr = wasPtr ? typedValue.mPtr : typedValue.mSrcAddress;
  6539. DbgType* actualType = NULL;
  6540. bool useActualRawType = false;
  6541. bool isBfObject = innerType->IsBfObject();
  6542. bool hasCPPVTable = false;
  6543. if (!isBfObject)
  6544. hasCPPVTable = innerType->HasCPPVTable();
  6545. int bfObjectFlags = 0;
  6546. addr_target classVDataPtr = 0;
  6547. bool isAppendBfObject = false;
  6548. bool isStackBfObject = false;
  6549. bool isDeletedBfObject = false;
  6550. bool isCompositeWithoutAddress = false;
  6551. if (innerType->IsBfPayloadEnum())
  6552. {
  6553. if (formatInfo.mRawString)
  6554. return "";
  6555. auto tagMember = innerType->mMemberList.mTail;
  6556. int tagIdx = 0;
  6557. if (dataPtr == -1)
  6558. {
  6559. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, "(int)" + expr, &formatInfo);
  6560. auto dscValue = dbgEvaluationContext.EvaluateInContext(DbgTypedValue());
  6561. tagIdx = dscValue.mInt32;
  6562. }
  6563. else if (!ReadMemory((intptr)ptrVal + tagMember->mMemberOffset, tagMember->mType->mSize, (void*)&tagIdx))
  6564. {
  6565. return StrFormat("!Failed to read from 0x%@", ptrVal);
  6566. }
  6567. char findStr[16];
  6568. findStr[0] = '_';
  6569. itoa(tagIdx, findStr + 1, 10);
  6570. int len = strlen(findStr);
  6571. findStr[len] = '_';
  6572. len++;
  6573. if (!retVal.empty())
  6574. retVal += " ";
  6575. int startIdx = 0;
  6576. for (auto member : innerType->mMemberList)
  6577. {
  6578. if (strncmp(member->mName, findStr, len) == 0)
  6579. {
  6580. retVal += ".";
  6581. retVal += member->mName + len;
  6582. String tupleExpr;
  6583. DbgTypedValue tupleVal;
  6584. if (dataPtr == -1)
  6585. {
  6586. tupleVal.mSrcAddress = -1;
  6587. tupleVal.mType = member->mType;
  6588. //tupleExpr = "$" + expr + "$u";
  6589. tupleVal.mVariable = typedValue.mVariable;
  6590. tupleExpr = "(" + member->mType->ToStringRaw() + ")(" + expr + ")";
  6591. }
  6592. else
  6593. {
  6594. tupleVal.mType = member->mType;
  6595. tupleVal.mSrcAddress = ptrVal;
  6596. }
  6597. DwFormatInfo displayStrFormatInfo = formatInfo;
  6598. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + (int)retVal.length();
  6599. displayStrFormatInfo.mExpandItemDepth++;
  6600. displayStrFormatInfo.mHidePointers = false;
  6601. retVal += DbgTypedValueToString(tupleVal, tupleExpr, displayStrFormatInfo, NULL);
  6602. int idx = (int)retVal.IndexOf('\n');
  6603. if (idx != -1)
  6604. {
  6605. if ((idx > 2) && (strncmp(retVal.c_str() + idx - 2, "()", 2) == 0))
  6606. {
  6607. // Take off a terminating "()" on the value, if there is one
  6608. retVal.Remove(idx - 2, 2);
  6609. }
  6610. String typeName = innerType->ToString(DbgLanguage_Unknown, true);
  6611. typeName += " ";
  6612. retVal.Insert(idx + 1, typeName);
  6613. }
  6614. return retVal;
  6615. }
  6616. }
  6617. }
  6618. if (isBfObject)
  6619. {
  6620. classVDataPtr = ReadMemory<addr_target>(ptrVal);
  6621. mDebugTarget->GetCompilerSettings();
  6622. if (mDebugTarget->mBfObjectHasFlags)
  6623. {
  6624. bfObjectFlags = ((int)classVDataPtr) & 0xFF;
  6625. if ((bfObjectFlags & BfObjectFlag_Deleted) != 0)
  6626. isDeletedBfObject = true;
  6627. if ((bfObjectFlags & BfObjectFlag_AppendAlloc) != 0)
  6628. isAppendBfObject = true;
  6629. if ((bfObjectFlags & (BfObjectFlag_StackAlloc | BfObjectFlag_Allocated)) == BfObjectFlag_StackAlloc)
  6630. isStackBfObject = true;
  6631. classVDataPtr &= ~0xFF;
  6632. }
  6633. }
  6634. if (!formatInfo.mIgnoreDerivedClassInfo)
  6635. {
  6636. if (isBfObject)
  6637. {
  6638. dbgModule->ParseSymbolData();
  6639. String symbolName;
  6640. addr_target symOffset;
  6641. if ((mDebugTarget->FindSymbolAt(classVDataPtr, &symbolName, &symOffset)) && (symOffset < 0x100))
  6642. {
  6643. String mangledClassName;
  6644. const char* symEnd = "sBfClassVData";
  6645. int symEndLen = strlen(symEnd);
  6646. if (((int)symbolName.length() > symEndLen) && (strstr(symbolName.c_str(), symEnd) != NULL))
  6647. mangledClassName = symbolName;
  6648. // If we have flags then we may be pointing past the _typeData, actually. We could fix this by masking out
  6649. // the flags area, but we need to be sure we are running a build that supports flags
  6650. symEnd = "sBfTypeData";
  6651. symEndLen = strlen(symEnd);
  6652. if (((int) symbolName.length() > symEndLen) && (strstr(symbolName.c_str(), symEnd) != NULL))
  6653. mangledClassName = symbolName;
  6654. if (mangledClassName.length() > 0)
  6655. {
  6656. String className = BfDemangler::Demangle(mangledClassName, innerType->GetLanguage(), BfDemangler::Flag_RawDemangle);
  6657. for (int i = 0; i < className.length() - 3; i++)
  6658. {
  6659. if ((className[i] == 'b') &&
  6660. (className[i + 1] == 'f') &&
  6661. (className[i + 2] == '.'))
  6662. {
  6663. bool matches;
  6664. if (i == 0)
  6665. matches = true;
  6666. else
  6667. {
  6668. char prevC = className[i - 1];
  6669. if ((prevC == ' ') ||
  6670. (prevC == ',') ||
  6671. (prevC == '<'))
  6672. {
  6673. matches = true;
  6674. }
  6675. }
  6676. if (matches)
  6677. className.Remove(i, 3);
  6678. }
  6679. }
  6680. int lastDot = (int)className.LastIndexOf('.');
  6681. if (lastDot > 0)
  6682. className = className.Substring(0, lastDot);
  6683. const char* arrPrefix = "System.Array1<";
  6684. if (strncmp(className.c_str(), arrPrefix, strlen(arrPrefix)) == 0)
  6685. {
  6686. className = className.Substring(strlen(arrPrefix), className.length() - strlen(arrPrefix) - 1);
  6687. className += "[]";
  6688. }
  6689. auto typeEntry = dbgModule->GetLinkedModule()->mTypeMap.Find(className.c_str(), DbgLanguage_BeefUnfixed);
  6690. if (typeEntry != NULL)
  6691. {
  6692. actualType = typeEntry->mValue;
  6693. if (!actualType->IsBfObject())
  6694. {
  6695. if (actualType->mTypeCode == DbgType_Ptr)
  6696. {
  6697. actualType = actualType->mTypeParam;
  6698. }
  6699. }
  6700. }
  6701. }
  6702. }
  6703. }
  6704. else if (hasCPPVTable)
  6705. {
  6706. dbgModule->ParseSymbolData();
  6707. addr_target classVDataPtr = ReadMemory<addr_target>(ptrVal);
  6708. String symbolName;
  6709. addr_target offset = 0;
  6710. if (mDebugTarget->FindSymbolAt(classVDataPtr, &symbolName, &offset, NULL))
  6711. {
  6712. // On GNU, vtable indices can "go negative" for things like RTTI and virtual inheritance, so
  6713. // we can't rely on an exact vtable address lookup
  6714. if (offset < 0x200)
  6715. {
  6716. DbgLanguage lang = innerType->GetLanguage();
  6717. const char* symStart = (innerType->mCompileUnit->mDbgModule->mDbgFlavor == DbgFlavor_GNU) ? "_ZTV" : "??_7";
  6718. if (strncmp(symbolName.c_str(), symStart, strlen(symStart)) == 0)
  6719. {
  6720. //String mangledClassName = symbolName.Substring(1);
  6721. String className = BfDemangler::Demangle(symbolName, lang);
  6722. int vtableNameIdx = (int)className.IndexOf("::`vftable'");
  6723. if (vtableNameIdx != -1)
  6724. className = className.Substring(0, vtableNameIdx);
  6725. auto typeEntry = dbgModule->mTypeMap.Find(className.c_str(), DbgLanguage_C);
  6726. if (typeEntry != NULL)
  6727. {
  6728. actualType = typeEntry->mValue;
  6729. if ((int)className.IndexOf('<') != -1)
  6730. useActualRawType = true;
  6731. int thisOffset = 0;
  6732. if (!DbgExprEvaluator::TypeIsSubTypeOf(actualType, innerType, &thisOffset))
  6733. {
  6734. // This catches virtual inheritance cases where we can't downcast
  6735. actualType = NULL;
  6736. }
  6737. }
  6738. }
  6739. }
  6740. }
  6741. }
  6742. }
  6743. DbgType* displayType = origValueType;
  6744. String displayString;
  6745. bool wantsCustomExpandedItems = false;
  6746. DebugVisualizerEntry* debugVis = NULL;
  6747. Array<String> dbgVisWildcardCaptures;
  6748. DbgType* dwUseType = (actualType != NULL) ? actualType : innerType;
  6749. //auto ptrDataType = dwValueType;
  6750. //TODO: Changed this from the above to account for COFF types where 'this' is always a fwd reference, does this cause any issues?
  6751. auto ptrDataType = innerType;
  6752. String ptrDataStr;
  6753. if (/*(!innerType->IsBfObject()) &&*/ (!ptrDataType->IsPointer()))
  6754. {
  6755. if ((dataPtr != 0) || (ptrDataType->GetByteCount() > sizeof(addr_target)))
  6756. {
  6757. bool wantsRefThis = ptrDataType->WantsRefThis();
  6758. ptrDataType = ptrDataType->GetDbgModule()->GetPointerType(ptrDataType);
  6759. if (wantsRefThis)
  6760. ptrDataStr += "*";
  6761. }
  6762. else
  6763. {
  6764. // Data is inline - must be int-sized or less
  6765. isCompositeWithoutAddress = true;
  6766. dataPtr = typedValue.mPtr;
  6767. }
  6768. }
  6769. String ptrDataTypeStr = ptrDataType->ToStringRaw();
  6770. ptrDataStr += StrFormat("(%s)", ptrDataTypeStr.c_str()) + EncodeDataPtr(dataPtr, true);
  6771. DbgType* dwUsePtrType = dwUseType;
  6772. String ptrUseDataStr;
  6773. if (!dwUsePtrType->IsPointer())
  6774. {
  6775. bool wantsRefThis = dwUsePtrType->WantsRefThis();
  6776. dwUsePtrType = dwUsePtrType->GetDbgModule()->GetPointerType(dwUsePtrType);
  6777. if (wantsRefThis)
  6778. ptrUseDataStr += "*";
  6779. }
  6780. String ptrUseDataTypeStr = dwUsePtrType->ToStringRaw();
  6781. ptrUseDataStr += StrFormat("(%s)", ptrUseDataTypeStr.c_str()) + EncodeDataPtr(dataPtr, true);
  6782. if ((origTypedValue.mSrcAddress == -1) && (origTypedValue.mVariable != NULL))
  6783. {
  6784. ptrDataStr = origTypedValue.mVariable->mName;
  6785. if (!origTypedValue.mType->RemoveModifiers()->Equals(origTypedValue.mVariable->mType->RemoveModifiers()))
  6786. {
  6787. //ptrDataStr = StrFormat("(%s)%s", origTypedValue.mType->ToString().c_str(), origTypedValue.mVariable->mName);
  6788. ptrDataStr = expr;
  6789. }
  6790. ptrUseDataStr = ptrDataStr;
  6791. }
  6792. bool isNull = wasPtr && (dataPtr == 0);
  6793. bool isBadSrc = !wasPtr && (dataPtr == 0) && (!dwValueType->IsValuelessType());
  6794. if ((ptrVal == 0) && (dwValueType->IsTypedPrimitive()))
  6795. {
  6796. DbgTypedValue rawVal;
  6797. rawVal.mInt64 = origTypedValue.mInt64;
  6798. rawVal.mType = dwValueType->GetRootBaseType();
  6799. ptrDataStr = "(" + dwUseType->ToStringRaw() + ")";
  6800. ptrDataStr += DbgTypedValueToString(rawVal, expr, formatInfo, optEvaluator, fullPrecision);
  6801. int editValIdx = ptrDataStr.IndexOf(":editVal");
  6802. if (editValIdx != -1)
  6803. ptrDataStr.Remove(0, editValIdx + 9);
  6804. int crPos = (int)ptrDataStr.IndexOf('\n');
  6805. if (crPos != -1)
  6806. ptrDataStr.RemoveToEnd(crPos);
  6807. ptrUseDataStr = ptrDataStr;
  6808. if ((origTypedValue.mRegNum != -1) && (!expr.IsEmpty()) && (!formatInfo.mExplicitThis))
  6809. {
  6810. // There's no address, use direct local identifier
  6811. ptrDataStr = expr;
  6812. ptrUseDataStr = expr;
  6813. }
  6814. // This keeps 'function' types from showing null as "<null parent>"
  6815. isBadSrc = false;
  6816. }
  6817. else if ((ptrVal == 0) && (dwValueType->IsCompositeType()))
  6818. {
  6819. }
  6820. DbgTypedValue useTypedValue = typedValue;
  6821. if ((origHadRef) || ((typedValue.mType->HasPointer()) && (!dwUseType->HasPointer())))
  6822. {
  6823. useTypedValue.mSrcAddress = useTypedValue.mPtr;
  6824. useTypedValue.mPtr = 0;
  6825. if (dwUseType->IsTypedPrimitive())
  6826. {
  6827. int byteCount = dwUseType->GetByteCount();
  6828. if (byteCount <= sizeof(intptr))
  6829. {
  6830. ReadMemory(useTypedValue.mSrcAddress, byteCount, &useTypedValue.mPtr);
  6831. }
  6832. }
  6833. }
  6834. useTypedValue.mType = dwUseType;
  6835. if ((!formatInfo.mNoVisualizers) && (!isNull) && (!isBadSrc))
  6836. {
  6837. if (language == DbgLanguage_Beef)
  6838. dwUseType->FixName();
  6839. debugVis = FindVisualizerForType(dwUseType, &dbgVisWildcardCaptures);
  6840. }
  6841. bool hadCustomDisplayString = false;
  6842. if (debugVis != NULL)
  6843. {
  6844. auto& displayStringList = formatInfo.mRawString ? debugVis->mStringViews : debugVis->mDisplayStrings;
  6845. for (auto displayEntry : displayStringList)
  6846. {
  6847. if (!displayEntry->mCondition.empty())
  6848. {
  6849. if (!EvalCondition(debugVis, dbgCompileUnit, useTypedValue, formatInfo, displayEntry->mCondition, dbgVisWildcardCaptures, displayString))
  6850. continue;
  6851. }
  6852. hadCustomDisplayString = true;
  6853. String displayStr = mDebugManager->mDebugVisualizers->DoStringReplace(displayEntry->mString, dbgVisWildcardCaptures);
  6854. if (displayString.length() > 0)
  6855. displayString += " ";
  6856. ProcessEvalString(dbgCompileUnit, useTypedValue, displayStr, displayString, formatInfo, debugVis, true);
  6857. if (formatInfo.mRawString)
  6858. return displayString;
  6859. break;
  6860. }
  6861. if ((!debugVis->mExpandItems.empty()) || (debugVis->mCollectionType != DebugVisualizerEntry::CollectionType_None))
  6862. {
  6863. wantsCustomExpandedItems = true;
  6864. }
  6865. }
  6866. if (formatInfo.mRawString)
  6867. return "";
  6868. bool isTuple = (dwUseType->mName != NULL) && (dwUseType->mName[0] == '(') && (language == DbgLanguage_Beef);
  6869. if (isBadSrc)
  6870. {
  6871. displayString += "<null parent>";
  6872. }
  6873. else if ((!isNull) && (!formatInfo.mNoVisualizers) && (!hadCustomDisplayString))
  6874. {
  6875. // Create our own custom display
  6876. String firstRet;
  6877. String bigRet = isTuple ? "(" : "{ ";
  6878. int memberIdx = 0;
  6879. DbgType* summaryType = dwUseType;
  6880. bool summaryDone = false;
  6881. bool truncatedMemberList = false;
  6882. DbgTypedValue summaryTypedValue = useTypedValue;
  6883. String summaryDataStr = ptrDataStr;
  6884. String splatStr;
  6885. if (dataPtr == -1)
  6886. splatStr = expr;
  6887. while (summaryType != NULL)
  6888. {
  6889. summaryType->PopulateType();
  6890. if ((summaryType->IsTypedPrimitive()) &&
  6891. ((summaryType->mBaseTypes.IsEmpty()) || (!summaryType->mBaseTypes.front()->mBaseType->IsTypedPrimitive())))
  6892. {
  6893. if (formatInfo.mTotalSummaryLength + (int)displayString.length() > 255)
  6894. {
  6895. truncatedMemberList = true;
  6896. summaryDone = true;
  6897. bigRet += "...";
  6898. }
  6899. else
  6900. {
  6901. DwFormatInfo displayStrFormatInfo = formatInfo;
  6902. displayStrFormatInfo.mExpandItemDepth = 1;
  6903. displayStrFormatInfo.mTotalSummaryLength += (int)displayString.length();
  6904. displayStrFormatInfo.mHidePointers = false;
  6905. DbgType* primType = summaryType->mTypeParam;
  6906. String result;
  6907. if (primType->IsInteger())
  6908. formatInfo.mTypeKindFlags = (DbgTypeKindFlags)(formatInfo.mTypeKindFlags | DbgTypeKindFlag_Int);
  6909. if ((dataPtr != 0) && (dataPtr != -1))
  6910. {
  6911. String evalString = "(" + primType->ToString() + ")" + ptrDataStr;
  6912. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, origTypedValue, evalString, &displayStrFormatInfo);
  6913. if (evalResult)
  6914. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  6915. }
  6916. else
  6917. {
  6918. DbgTypedValue evalResult = origTypedValue;
  6919. evalResult.mType = primType;
  6920. String evalString = "(" + primType->ToString() + ")" + expr;
  6921. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  6922. }
  6923. if (formatInfo.mRawString)
  6924. return result;
  6925. int crPos = result.IndexOf('\n');
  6926. if (crPos != -1)
  6927. result.RemoveToEnd(crPos);
  6928. if (memberIdx == 0)
  6929. firstRet = result;
  6930. bigRet += result;
  6931. memberIdx++;
  6932. }
  6933. }
  6934. for (auto member : summaryType->mMemberList)
  6935. {
  6936. if (!member->mIsStatic)
  6937. {
  6938. if (formatInfo.mTotalSummaryLength + retVal.length() + bigRet.length() > 255)
  6939. {
  6940. truncatedMemberList = true;
  6941. summaryDone = true;
  6942. bigRet += "...";
  6943. break;
  6944. }
  6945. if (member->mName != NULL)
  6946. {
  6947. if (member->mName[0] == '$')
  6948. continue;
  6949. if (!isdigit(*member->mName))
  6950. {
  6951. if (memberIdx != 0)
  6952. bigRet += isTuple ? ", " : " ";
  6953. if ((!isTuple) || (member->mName[0] != '_'))
  6954. {
  6955. bigRet += String(member->mName);
  6956. bigRet += isTuple ? ":" : "=";
  6957. }
  6958. }
  6959. else
  6960. {
  6961. if (memberIdx != 0)
  6962. bigRet += ", ";
  6963. }
  6964. DwFormatInfo displayStrFormatInfo = formatInfo;
  6965. displayStrFormatInfo.mExpandItemDepth = 1;
  6966. displayStrFormatInfo.mHidePointers = false;
  6967. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + retVal.length() + bigRet.length();
  6968. String evalString;
  6969. if (dataPtr != -1)
  6970. {
  6971. if ((member->mName[0] >= '0') && (member->mName[0] <= '9'))
  6972. evalString += "this.";
  6973. evalString += String(member->mName); // +", this=" + summaryDataStr;
  6974. }
  6975. else
  6976. {
  6977. evalString = "(";
  6978. evalString += splatStr;
  6979. evalString += ").";
  6980. evalString += member->mName;
  6981. }
  6982. String referenceId;
  6983. String result;
  6984. if (!member->mType->IsValuelessType())
  6985. {
  6986. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, summaryTypedValue, evalString, &displayStrFormatInfo, &referenceId);
  6987. if (evalResult)
  6988. {
  6989. displayStrFormatInfo.mReferenceId = referenceId;
  6990. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  6991. int crPos = result.IndexOf('\n');
  6992. if (crPos != -1)
  6993. result.RemoveToEnd(crPos);
  6994. }
  6995. else
  6996. result = "???";
  6997. }
  6998. if (member->mType->IsInteger())
  6999. formatInfo.mTypeKindFlags = (DbgTypeKindFlags)(formatInfo.mTypeKindFlags | DbgTypeKindFlag_Int);
  7000. if (formatInfo.mRawString)
  7001. return result;
  7002. if (memberIdx == 0)
  7003. firstRet = result;
  7004. bigRet += result;
  7005. //formatInfo.mEmbeddedDisplayCount = displayStrFormatInfo.mEmbeddedDisplayCount;
  7006. memberIdx++;
  7007. }
  7008. else
  7009. {
  7010. //TODO: Handle C++ unions?
  7011. }
  7012. }
  7013. }
  7014. if (truncatedMemberList)
  7015. break;
  7016. // Find first base class with members
  7017. DbgType* nextSummaryType = NULL;
  7018. for (auto checkBase : summaryType->mBaseTypes)
  7019. {
  7020. auto checkBaseType = checkBase->mBaseType;
  7021. checkBaseType = checkBaseType->GetPrimaryType();
  7022. checkBaseType->PopulateType();
  7023. if ((checkBaseType->GetByteCount() > 0) || (checkBaseType->IsPrimitiveType()))
  7024. {
  7025. if (!splatStr.empty())
  7026. {
  7027. splatStr = "(" + checkBaseType->ToString() + ")" + splatStr;
  7028. }
  7029. else
  7030. {
  7031. summaryTypedValue.mType = checkBaseType;
  7032. }
  7033. nextSummaryType = checkBaseType;
  7034. break;
  7035. }
  7036. }
  7037. summaryType = nextSummaryType;
  7038. if (summaryType == NULL)
  7039. break;
  7040. // Don't add the Object members
  7041. if ((summaryType->GetBaseType() == NULL) && (summaryType->IsBfObject()))
  7042. break;
  7043. // If we don't have many members then find a base class with some members to show
  7044. if ((memberIdx != 0) && (displayString.length() >= 255))
  7045. {
  7046. truncatedMemberList = true;
  7047. bigRet += "...";
  7048. break;
  7049. }
  7050. }
  7051. bigRet += isTuple ? ")" : " }";
  7052. if (displayString.length() > 0)
  7053. displayString += " ";
  7054. if ((memberIdx == 1) && (!truncatedMemberList) && (firstRet.IndexOf('{') == -1) && (!isTuple))
  7055. displayString += "{ " + firstRet + " }";
  7056. else
  7057. displayString += bigRet;
  7058. }
  7059. DbgType* memberListType = actualType;
  7060. bool memberListForceCast = false;
  7061. if (actualType != NULL)
  7062. {
  7063. String valTypeName = displayType->ToString();
  7064. String actualTypeName = actualType->ToString(DbgLanguage_Unknown, true);
  7065. String actualUseTypeName = actualTypeName;
  7066. if ((int)actualTypeName.IndexOf('^') != -1)
  7067. useActualRawType = true;
  7068. if (useActualRawType)
  7069. actualUseTypeName = actualType->ToStringRaw();
  7070. if (displayString.empty())
  7071. {
  7072. // Nothing to display
  7073. }
  7074. else
  7075. {
  7076. if (!retVal.empty())
  7077. retVal += " ";
  7078. retVal += displayString;
  7079. }
  7080. retVal += "\n" + valTypeName;
  7081. if ((innerType->IsBaseBfObject()) || (innerType->IsInterface()))
  7082. {
  7083. if (actualType != innerType)
  7084. {
  7085. retVal += " {" + actualTypeName + "}";
  7086. memberListForceCast = true;
  7087. }
  7088. }
  7089. else
  7090. {
  7091. if (actualType != innerType)
  7092. {
  7093. retVal += " {" + actualTypeName + "}";
  7094. retVal += "\n";
  7095. if (!wantsCustomExpandedItems)
  7096. {
  7097. retVal += "[" + actualTypeName + "]\t((" + actualUseTypeName;
  7098. if (!actualType->IsBfObject())
  7099. retVal += "*";
  7100. retVal += ")this), nd, na, nv, this=" + ptrDataStr;
  7101. memberListType = innerType;
  7102. }
  7103. }
  7104. }
  7105. }
  7106. else
  7107. {
  7108. if ((formatInfo.mHidePointers) && (formatInfo.mIgnoreDerivedClassInfo))
  7109. {
  7110. displayType = innerType;
  7111. if (displayString.empty())
  7112. retVal += displayType->ToString(DbgLanguage_Unknown, true);
  7113. }
  7114. if (!displayString.empty())
  7115. {
  7116. if (!retVal.empty())
  7117. retVal += " ";
  7118. retVal += displayString;
  7119. }
  7120. else
  7121. {
  7122. if (formatInfo.mRawString)
  7123. return "";
  7124. }
  7125. retVal += "\n" + displayType->ToString(DbgLanguage_Unknown, true);
  7126. memberListType = innerType;
  7127. }
  7128. if ((isBfObject) && (mDebugTarget->mBfObjectHasFlags) && (!formatInfo.mNoVisualizers) && (!formatInfo.mRawString))
  7129. {
  7130. int stackTraceLen = 1;
  7131. addr_target stackTraceAddr = ptrVal + sizeof(addr_target);
  7132. if ((bfObjectFlags & BfObjectFlag_AllocInfo) != 0)
  7133. {
  7134. addr_target objectSize = ReadMemory<addr_target>(ptrVal + sizeof(addr_target));
  7135. addr_target largeAllocInfo = ReadMemory<addr_target>(ptrVal + objectSize);
  7136. stackTraceLen = largeAllocInfo & 0xFFFF;
  7137. stackTraceAddr = ptrVal + objectSize + sizeof(addr_target);
  7138. }
  7139. else if ((bfObjectFlags & BfObjectFlag_AllocInfo_Short) != 0)
  7140. {
  7141. addr_target dbgAllocInfo = ReadMemory<addr_target>(ptrVal + sizeof(addr_target));
  7142. stackTraceLen = dbgAllocInfo & 0xFF;
  7143. stackTraceAddr = ptrVal + (dbgAllocInfo >> 16);
  7144. }
  7145. if (stackTraceLen == 1)
  7146. {
  7147. retVal += StrFormat("\n[AllocStackTrace]\t*(System.CallStackAddr*)%s, nm", EncodeDataPtr(stackTraceAddr, true).c_str());
  7148. }
  7149. else if (stackTraceLen > 0)
  7150. {
  7151. retVal += StrFormat("\n[AllocStackTrace]\t(System.CallStackAddr*)%s, %d, na", EncodeDataPtr(stackTraceAddr, true).c_str(), stackTraceLen);
  7152. }
  7153. }
  7154. retVal += StrFormat("\n:language\t%d", language);
  7155. if (formatInfo.mNoMembers)
  7156. {
  7157. //
  7158. }
  7159. else if (wantsCustomExpandedItems)
  7160. {
  7161. HandleCustomExpandedItems(retVal, dbgCompileUnit, debugVis, dwUseType, dwValueType, ptrUseDataStr, ptrDataStr, useTypedValue, dbgVisWildcardCaptures, formatInfo);
  7162. }
  7163. else if ((!isNull) && (!isBadSrc))
  7164. {
  7165. if (dataPtr == -1)
  7166. {
  7167. //String splatName = ((origTypedValue.mSrcAddress == -1) && (origTypedValue.mVariable != NULL)) ? origTypedValue.mVariable->mName : expr;
  7168. String splatName = expr;
  7169. retVal += "\n" + GetMemberList(memberListType, splatName, wasPtr, false, false, true, origTypedValue.mIsReadOnly);
  7170. }
  7171. else
  7172. {
  7173. retVal += "\n" + GetMemberList(memberListType, ptrDataStr, wasPtr, false, memberListForceCast, isCompositeWithoutAddress, origTypedValue.mIsReadOnly);
  7174. }
  7175. }
  7176. if (formatInfo.mExpandItemDepth > 0)
  7177. return retVal;
  7178. if (isAppendBfObject)
  7179. retVal += "\n:appendAlloc";
  7180. if (isStackBfObject)
  7181. retVal += "\n:stack";
  7182. if (isDeletedBfObject)
  7183. retVal += "\n:deleted";
  7184. if ((debugVis != NULL) && (!debugVis->mAction.empty()))
  7185. {
  7186. String rawActionStr = mDebugManager->mDebugVisualizers->DoStringReplace(debugVis->mAction, dbgVisWildcardCaptures);
  7187. String actionStr;
  7188. ProcessEvalString(dbgCompileUnit, useTypedValue, rawActionStr, actionStr, formatInfo, debugVis, true);
  7189. retVal += "\n:action\t" + actionStr;
  7190. }
  7191. if ((!typedValue.mIsLiteral) && (dwValueType->IsPointer()))
  7192. {
  7193. retVal += "\n:editVal\t" + EncodeDataPtr(ptrVal, true);
  7194. }
  7195. return retVal;
  7196. }
  7197. return "Unknown Type\n" + origValueType->ToString();
  7198. }
  7199. void WinDebugger::HandleCustomExpandedItems(String& retVal, DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgType* dwUseType, DbgType* dwValueType, String& ptrUseDataStr, String& ptrDataStr, DbgTypedValue useTypedValue, Array<String>& dbgVisWildcardCaptures, DwFormatInfo& formatInfo)
  7200. {
  7201. auto debugVisualizers = mDebugManager->mDebugVisualizers;
  7202. auto dbgModule = dbgCompileUnit->mDbgModule;
  7203. if (formatInfo.mExpandItemDepth > 10) // Avoid crashing on circular ExpandItems
  7204. return;
  7205. auto language = formatInfo.mLanguage;
  7206. bool isReadOnly = false;
  7207. if (useTypedValue.mIsReadOnly)
  7208. isReadOnly = true;
  7209. for (auto entry : debugVis->mExpandItems)
  7210. {
  7211. if (!entry->mCondition.empty())
  7212. {
  7213. String error;
  7214. if (!EvalCondition(debugVis, dbgCompileUnit, useTypedValue, formatInfo, entry->mCondition, dbgVisWildcardCaptures, error))
  7215. {
  7216. if (!error.empty())
  7217. retVal += "\n" + entry->mName + "\t@!<DbgVis Failed>@!";
  7218. continue;
  7219. }
  7220. }
  7221. String replacedStr = debugVisualizers->DoStringReplace(entry->mValue, dbgVisWildcardCaptures);
  7222. retVal += "\n" + entry->mName + "\t" + replacedStr + ", this=(" + ptrUseDataStr + ")";
  7223. }
  7224. String referenceId = dwUseType->ToString();
  7225. if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_ExpandedItem)
  7226. {
  7227. DbgTypedValue itemValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7228. if (itemValue)
  7229. {
  7230. DwFormatInfo itemFormatInfo = formatInfo;
  7231. itemFormatInfo.mExpandItemDepth++;
  7232. String itemRetVal = DbgTypedValueToString(itemValue, "", itemFormatInfo, NULL);
  7233. int crIdx = (int)itemRetVal.IndexOf('\n');
  7234. if (crIdx != -1)
  7235. {
  7236. crIdx = (int)itemRetVal.IndexOf('\n', crIdx + 1);
  7237. if (crIdx != -1)
  7238. retVal += itemRetVal.Substring(crIdx);
  7239. }
  7240. }
  7241. }
  7242. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Array)
  7243. {
  7244. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7245. Array<int> lowerDimSizes;
  7246. for (auto lowerDim : debugVis->mLowerDimSizes)
  7247. {
  7248. DbgTypedValue lowerDimValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(lowerDim, dbgVisWildcardCaptures), &formatInfo);
  7249. int dimSize = 0;
  7250. if ((lowerDimValue) && (lowerDimValue.mType->IsInteger()))
  7251. dimSize = (int)lowerDimValue.GetInt64();
  7252. dimSize = BF_MAX(dimSize, 1);
  7253. lowerDimSizes.push_back(dimSize);
  7254. }
  7255. if ((sizeValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7256. {
  7257. if (!debugVis->mCondition.IsEmpty())
  7258. {
  7259. int size = (int)sizeValue.GetInt64();
  7260. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7261. DbgTypedValue curNode = headPointer;
  7262. Array<addr_target> parentList;
  7263. String continuationData;
  7264. int totalSize = 2;
  7265. auto valueType = headPointer.mType;
  7266. String addrs = GetArrayItems(dbgCompileUnit, debugVis, valueType, headPointer, totalSize, &continuationData);
  7267. String firstAddr;
  7268. String secondAddr;
  7269. bool hasSecondAddr = valueType == NULL;
  7270. if (addrs.length() > 0)
  7271. {
  7272. const char* addrsPtr = addrs.c_str();
  7273. firstAddr = addrs.Substring(0, sizeof(addr_target) * 2);
  7274. if (hasSecondAddr)
  7275. secondAddr = addrs.Substring(sizeof(addr_target) * 2, sizeof(addr_target) * 2);
  7276. }
  7277. String evalStr;
  7278. if (valueType != NULL)
  7279. {
  7280. evalStr = "(" + valueType->ToStringRaw();
  7281. if (!valueType->IsPointer())
  7282. evalStr += "*";
  7283. evalStr += ")0x{1}";
  7284. }
  7285. else
  7286. {
  7287. evalStr += "({1})0x{2}";
  7288. }
  7289. if (!debugVis->mShowElementAddrs)
  7290. evalStr.Insert(0, "*");
  7291. if (addrs.length() > 0)
  7292. {
  7293. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7294. if (isReadOnly)
  7295. evalStr += ", ne";
  7296. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, BF_MAX(size, 0), 10000) +
  7297. "\t[{0}]\t" + evalStr + "\t" + firstAddr;
  7298. if (hasSecondAddr)
  7299. retVal += "\t" + secondAddr;
  7300. if (size != 0)
  7301. {
  7302. retVal += "\n:addrs\t" + addrs;
  7303. if (valueType == NULL)
  7304. retVal += "\n:addrsEntrySize\t2";
  7305. if (continuationData.length() > 0)
  7306. retVal += "\n:continuation\t" + continuationData;
  7307. }
  7308. }
  7309. }
  7310. else if (lowerDimSizes.size() == 1)
  7311. {
  7312. int dimSize1 = lowerDimSizes[0];
  7313. String evalStr = "(" + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7314. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7315. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7316. if (isReadOnly)
  7317. evalStr += ", ne";
  7318. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, sizeValue.GetInt64() / dimSize1, 50000) +
  7319. "\t[{0}]\t" + evalStr;
  7320. }
  7321. else if (lowerDimSizes.size() == 2)
  7322. {
  7323. int dimSize1 = lowerDimSizes[0];
  7324. int dimSize2 = lowerDimSizes[1];
  7325. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7326. if ((headPointer.mType != NULL) && (headPointer.mType->IsPointer()))
  7327. {
  7328. String evalStr = StrFormat("((%s[%d]*)", headPointer.mType->mTypeParam->ToStringRaw(language).c_str(), dimSize2) + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7329. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7330. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7331. if (isReadOnly)
  7332. evalStr += ", ne";
  7333. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, sizeValue.GetInt64() / dimSize1 / dimSize2, 50000) +
  7334. "\t[{0}]\t" + evalStr;
  7335. }
  7336. }
  7337. else if (lowerDimSizes.size() == 3)
  7338. {
  7339. int dimSize1 = lowerDimSizes[0];
  7340. int dimSize2 = lowerDimSizes[1];
  7341. int dimSize3 = lowerDimSizes[2];
  7342. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7343. if ((headPointer.mType != NULL) && (headPointer.mType->IsPointer()))
  7344. {
  7345. String evalStr = StrFormat("((%s[%d][%d]*)", headPointer.mType->mTypeParam->ToStringRaw(language).c_str(), dimSize2, dimSize3) + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7346. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7347. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7348. if (isReadOnly)
  7349. evalStr += ", ne";
  7350. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, sizeValue.GetInt64() / dimSize1 / dimSize2 / dimSize3, 50000) +
  7351. "\t[{0}]\t" + evalStr;
  7352. }
  7353. }
  7354. else
  7355. {
  7356. String evalStr = "*(" + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) + " + {0}), this=" + ptrUseDataStr;
  7357. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7358. if (isReadOnly)
  7359. evalStr += ", ne";
  7360. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, sizeValue.GetInt64(), 50000) +
  7361. "\t[{0}]\t" + evalStr;
  7362. }
  7363. }
  7364. }
  7365. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_IndexItems)
  7366. {
  7367. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7368. if ((sizeValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7369. {
  7370. String evalStr = debugVis->mValuePointer + ", this=" + ptrUseDataStr;
  7371. evalStr.Replace("$i", "{0}");
  7372. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7373. if (isReadOnly)
  7374. evalStr += ", ne";
  7375. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, sizeValue.GetInt64(), 50000) +
  7376. "\t[{0}]\t" + evalStr;
  7377. }
  7378. }
  7379. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_LinkedList)
  7380. {
  7381. DbgType* valueType = NULL;
  7382. if (!debugVis->mValueType.empty())
  7383. {
  7384. valueType = dbgModule->FindType(debugVisualizers->DoStringReplace(debugVis->mValueType, dbgVisWildcardCaptures), dwValueType);
  7385. if (valueType != NULL)
  7386. valueType = valueType->ResolveTypeDef();
  7387. }
  7388. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mHeadPointer, dbgVisWildcardCaptures), &formatInfo);
  7389. if (headPointer)
  7390. {
  7391. DbgTypedValue endPointer;
  7392. if (!debugVis->mEndPointer.empty())
  7393. endPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mEndPointer, dbgVisWildcardCaptures), &formatInfo);
  7394. DbgTypedValue nextPointer = EvaluateInContext(dbgCompileUnit, headPointer, debugVisualizers->DoStringReplace(debugVis->mNextPointer, dbgVisWildcardCaptures), &formatInfo);
  7395. int size = -1;
  7396. if (!debugVis->mSize.empty())
  7397. {
  7398. auto sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7399. if (sizeValue)
  7400. size = (int)sizeValue.GetInt64();
  7401. }
  7402. DbgTypedValue curNode = headPointer;
  7403. Array<addr_target> parentList;
  7404. String continuationData;
  7405. int totalSize = 2;
  7406. String addrs = GetLinkedListItems(dbgCompileUnit, debugVis, endPointer.mPtr, valueType, curNode, totalSize, &continuationData);
  7407. String firstAddr;
  7408. String secondAddr;
  7409. bool hasSecondAddr = valueType == NULL;
  7410. if (addrs.length() > 0)
  7411. {
  7412. const char* addrsPtr = addrs.c_str();
  7413. firstAddr = addrs.Substring(0, sizeof(addr_target)*2);
  7414. if (hasSecondAddr)
  7415. secondAddr = addrs.Substring(sizeof(addr_target)*2, sizeof(addr_target)*2);
  7416. }
  7417. String evalStr;
  7418. if (valueType != NULL)
  7419. {
  7420. evalStr = "(" + valueType->ToStringRaw();
  7421. if (!valueType->IsPointer())
  7422. evalStr += "*";
  7423. evalStr += ")0x{1}";
  7424. }
  7425. else
  7426. {
  7427. evalStr += "({1})0x{2}";
  7428. }
  7429. if (!debugVis->mShowElementAddrs)
  7430. evalStr.Insert(0, "*");
  7431. if (addrs.length() > 0)
  7432. {
  7433. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7434. if (isReadOnly)
  7435. evalStr += ", ne";
  7436. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, size, 10000) +
  7437. "\t[{0}]\t" + evalStr + "\t" + firstAddr;
  7438. if (hasSecondAddr)
  7439. retVal += "\t" + secondAddr;
  7440. if (size != 0)
  7441. {
  7442. retVal += "\n:addrs\t" + addrs;
  7443. if (valueType == NULL)
  7444. retVal += "\n:addrsEntrySize\t2";
  7445. if (continuationData.length() > 0)
  7446. retVal += "\n:continuation\t" + continuationData;
  7447. }
  7448. }
  7449. }
  7450. }
  7451. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_TreeItems)
  7452. {
  7453. DbgType* valueType = NULL;
  7454. if (!debugVis->mValueType.empty())
  7455. {
  7456. valueType = dbgModule->FindType(debugVisualizers->DoStringReplace(debugVis->mValueType, dbgVisWildcardCaptures), dwValueType);
  7457. if (valueType != NULL)
  7458. valueType = valueType->ResolveTypeDef();
  7459. }
  7460. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7461. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mHeadPointer, dbgVisWildcardCaptures), &formatInfo);
  7462. if (sizeValue)
  7463. sizeValue.mType = sizeValue.mType->RemoveModifiers();
  7464. if ((sizeValue) && (headPointer) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7465. {
  7466. DbgTypedValue curNode = headPointer;
  7467. Array<addr_target> parentList;
  7468. String continuationData;
  7469. int getItemCount = (int)BF_MIN(sizeValue.GetInt64(), 32LL);
  7470. String addrs = GetTreeItems(dbgCompileUnit, debugVis, parentList, valueType, curNode, getItemCount, &continuationData);
  7471. addr_target firstAddr = 0;
  7472. addr_target secondAddr = 0;
  7473. bool hasSecondAddr = valueType == NULL;
  7474. if (addrs.length() > 0)
  7475. {
  7476. const char* addrsPtr = addrs.c_str();
  7477. firstAddr = DecodeTargetDataPtr(addrsPtr);
  7478. if (hasSecondAddr)
  7479. secondAddr = DecodeTargetDataPtr(addrsPtr);
  7480. }
  7481. String evalStr;
  7482. if (valueType != NULL)
  7483. {
  7484. evalStr = "*(" + valueType->ToStringRaw();
  7485. if (!valueType->IsPointer())
  7486. evalStr += "*";
  7487. evalStr += ")0x{1}";
  7488. }
  7489. else
  7490. {
  7491. evalStr += "*(_T_{1}*)0x{2}";
  7492. }
  7493. int size = (int)sizeValue.GetInt64();
  7494. if (addrs.length() == 0)
  7495. {
  7496. evalStr = ""; // Failed
  7497. }
  7498. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7499. if (isReadOnly)
  7500. evalStr += ", ne";
  7501. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, size, 10000) +
  7502. "\t[{0}]\t" + evalStr + "\t" + EncodeDataPtr(firstAddr, false);
  7503. if (hasSecondAddr)
  7504. retVal += "\t" + EncodeDataPtr(secondAddr, false);
  7505. if (addrs.length() > 0)
  7506. {
  7507. retVal += "\n:addrs\t" + addrs;
  7508. if (continuationData.length() > 0)
  7509. retVal += "\n:continuation\t" + continuationData;
  7510. }
  7511. }
  7512. }
  7513. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Dictionary)
  7514. {
  7515. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7516. DbgTypedValue entriesPtrValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mEntries, dbgVisWildcardCaptures), &formatInfo);
  7517. if (sizeValue)
  7518. sizeValue.mType = sizeValue.mType->RemoveModifiers();
  7519. if ((sizeValue) && (entriesPtrValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7520. {
  7521. String continuationData;
  7522. DbgType* valueType = entriesPtrValue.mType;
  7523. int getItemCount = (int)std::min(sizeValue.GetInt64(), 2LL);
  7524. DbgType* useTypedValType = useTypedValue.mType;
  7525. addr_target useTypedValPtr = useTypedValue.mPtr;
  7526. addr_target useTypedValAddr = useTypedValue.mSrcAddress;
  7527. String addrs = GetDictionaryItems(dbgCompileUnit, debugVis, useTypedValue, 0, -1, getItemCount, &continuationData);
  7528. addr_target firstAddr = 0;
  7529. if (addrs.length() > 0)
  7530. {
  7531. const char* addrsPtr = addrs.c_str();
  7532. firstAddr = DecodeTargetDataPtr(addrsPtr);
  7533. }
  7534. String evalStr = "((" + valueType->ToStringRaw() + ")0x{1}), na";
  7535. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7536. if (isReadOnly)
  7537. evalStr += ", ne";
  7538. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64(), 10000) +
  7539. "\t[{0}]\t" + evalStr + "\t" + EncodeDataPtr(firstAddr, false);
  7540. if (addrs.length() > 0)
  7541. {
  7542. retVal += "\n:addrs\t" + addrs;
  7543. if (continuationData.length() > 0)
  7544. retVal += "\n:continuation\t" + continuationData;
  7545. }
  7546. }
  7547. }
  7548. if (formatInfo.mExpandItemDepth == 0)
  7549. {
  7550. //retVal += "\n[Raw View]\tthis, this=" + ptrDataStr + ", nv";
  7551. retVal += "\n[Raw View]\t" + ptrDataStr + ", nv";
  7552. }
  7553. }
  7554. bool WinDebugger::IsPaused()
  7555. {
  7556. return (mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint) || (mRunState == RunState_Exception) || (mRunState == RunState_DebugEval_Done);
  7557. }
  7558. DbgTypedValue WinDebugger::GetRegister(const StringImpl& regName, DbgLanguage language, CPURegisters* registers, Array<RegForm>* regForms)
  7559. {
  7560. int regNum = -1;
  7561. String lwrRegName(regName);
  7562. _strlwr((char*)lwrRegName.c_str());
  7563. // int regs
  7564. #ifdef BF_DBG_32
  7565. DbgTypeCode regType = DbgType_i32;
  7566. if (lwrRegName == "eax")
  7567. regNum = X86Reg_EAX;
  7568. else if (lwrRegName == "ecx")
  7569. regNum = X86Reg_ECX;
  7570. else if (lwrRegName == "edx")
  7571. regNum = X86Reg_EDX;
  7572. else if (lwrRegName == "ebx")
  7573. regNum = X86Reg_EBX;
  7574. else if (lwrRegName == "esp")
  7575. regNum = X86Reg_ESP;
  7576. else if (lwrRegName == "ebp")
  7577. regNum = X86Reg_EBP;
  7578. else if (lwrRegName == "esi")
  7579. regNum = X86Reg_ESI;
  7580. else if (lwrRegName == "edi")
  7581. regNum = X86Reg_EDI;
  7582. else if (lwrRegName == "eip")
  7583. regNum = X86Reg_EIP;
  7584. else if (lwrRegName == "efl")
  7585. regNum = X86Reg_EFL;
  7586. #else
  7587. DbgTypeCode regType = DbgType_i64;
  7588. if (lwrRegName == "rax")
  7589. regNum = X64Reg_RAX;
  7590. else if (lwrRegName == "rcx")
  7591. regNum = X64Reg_RCX;
  7592. else if (lwrRegName == "rdx")
  7593. regNum = X64Reg_RDX;
  7594. else if (lwrRegName == "rbx")
  7595. regNum = X64Reg_RBX;
  7596. else if (lwrRegName == "rsp")
  7597. regNum = X64Reg_RSP;
  7598. else if (lwrRegName == "rbp")
  7599. regNum = X64Reg_RBP;
  7600. else if (lwrRegName == "rsi")
  7601. regNum = X64Reg_RSI;
  7602. else if (lwrRegName == "rdi")
  7603. regNum = X64Reg_RDI;
  7604. else if (lwrRegName == "rip")
  7605. regNum = X64Reg_RIP;
  7606. else if (lwrRegName == "r8")
  7607. regNum = X64Reg_R8;
  7608. else if (lwrRegName == "r9")
  7609. regNum = X64Reg_R9;
  7610. else if (lwrRegName == "r10")
  7611. regNum = X64Reg_R10;
  7612. else if (lwrRegName == "r11")
  7613. regNum = X64Reg_R11;
  7614. else if (lwrRegName == "r12")
  7615. regNum = X64Reg_R12;
  7616. else if (lwrRegName == "r13")
  7617. regNum = X64Reg_R13;
  7618. else if (lwrRegName == "r14")
  7619. regNum = X64Reg_R14;
  7620. else if (lwrRegName == "r15")
  7621. regNum = X64Reg_R15;
  7622. else
  7623. {
  7624. regType = DbgType_i32;
  7625. if (lwrRegName == "eax")
  7626. regNum = X64Reg_RAX;
  7627. else if (lwrRegName == "ecx")
  7628. regNum = X64Reg_RCX;
  7629. else if (lwrRegName == "edx")
  7630. regNum = X64Reg_RDX;
  7631. else if (lwrRegName == "ebx")
  7632. regNum = X64Reg_RBX;
  7633. else if (lwrRegName == "efl")
  7634. regNum = X64Reg_EFL;
  7635. else if (lwrRegName == "esi")
  7636. regNum = X64Reg_RSI;
  7637. else if (lwrRegName == "edi")
  7638. regNum = X64Reg_RDI;
  7639. else if (lwrRegName == "r8d")
  7640. regNum = X64Reg_R8;
  7641. else if (lwrRegName == "r9d")
  7642. regNum = X64Reg_R9;
  7643. else if (lwrRegName == "r10d")
  7644. regNum = X64Reg_R10;
  7645. else if (lwrRegName == "r11d")
  7646. regNum = X64Reg_R11;
  7647. else if (lwrRegName == "r12d")
  7648. regNum = X64Reg_R12;
  7649. else if (lwrRegName == "r13d")
  7650. regNum = X64Reg_R13;
  7651. else if (lwrRegName == "r14d")
  7652. regNum = X64Reg_R14;
  7653. else if (lwrRegName == "r15d")
  7654. regNum = X64Reg_R15;
  7655. else
  7656. {
  7657. regType = DbgType_i16;
  7658. if (lwrRegName == "ax")
  7659. regNum = X64Reg_RAX;
  7660. else if (lwrRegName == "cx")
  7661. regNum = X64Reg_RCX;
  7662. else if (lwrRegName == "dx")
  7663. regNum = X64Reg_RDX;
  7664. else if (lwrRegName == "bx")
  7665. regNum = X64Reg_RBX;
  7666. else if (lwrRegName == "si")
  7667. regNum = X64Reg_RSI;
  7668. else if (lwrRegName == "di")
  7669. regNum = X64Reg_RDI;
  7670. else if (lwrRegName == "r8w")
  7671. regNum = X64Reg_R8;
  7672. else if (lwrRegName == "r9w")
  7673. regNum = X64Reg_R9;
  7674. else if (lwrRegName == "r10w")
  7675. regNum = X64Reg_R10;
  7676. else if (lwrRegName == "r11w")
  7677. regNum = X64Reg_R11;
  7678. else if (lwrRegName == "r12w")
  7679. regNum = X64Reg_R12;
  7680. else if (lwrRegName == "r13w")
  7681. regNum = X64Reg_R13;
  7682. else if (lwrRegName == "r14w")
  7683. regNum = X64Reg_R14;
  7684. else if (lwrRegName == "r15w")
  7685. regNum = X64Reg_R15;
  7686. else
  7687. {
  7688. regType = DbgType_i8;
  7689. if (lwrRegName == "al")
  7690. regNum = X64Reg_RAX;
  7691. else if (lwrRegName == "cl")
  7692. regNum = X64Reg_RCX;
  7693. else if (lwrRegName == "dl")
  7694. regNum = X64Reg_RDX;
  7695. else if (lwrRegName == "bl")
  7696. regNum = X64Reg_RBX;
  7697. else if (lwrRegName == "sil")
  7698. regNum = X64Reg_RSI;
  7699. else if (lwrRegName == "dil")
  7700. regNum = X64Reg_RDI;
  7701. else if (lwrRegName == "r8b")
  7702. regNum = X64Reg_R8;
  7703. else if (lwrRegName == "r9b")
  7704. regNum = X64Reg_R9;
  7705. else if (lwrRegName == "r10b")
  7706. regNum = X64Reg_R10;
  7707. else if (lwrRegName == "r11b")
  7708. regNum = X64Reg_R11;
  7709. else if (lwrRegName == "r12b")
  7710. regNum = X64Reg_R12;
  7711. else if (lwrRegName == "r13b")
  7712. regNum = X64Reg_R13;
  7713. else if (lwrRegName == "r14b")
  7714. regNum = X64Reg_R14;
  7715. else if (lwrRegName == "r15b")
  7716. regNum = X64Reg_R15;
  7717. }
  7718. }
  7719. }
  7720. #endif
  7721. auto dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  7722. if (regNum != -1)
  7723. {
  7724. DbgTypedValue typedVal;
  7725. typedVal.mType = dbgModule->GetPrimitiveType(regType, language);
  7726. typedVal.mInt64 = registers->mIntRegsArray[regNum];
  7727. typedVal.mRegNum = regNum;
  7728. return typedVal;
  7729. }
  7730. // st regs
  7731. if ((lwrRegName.length() == 3) && (lwrRegName[0] == 's') && (lwrRegName[1] == 't') && (lwrRegName[2] >= '0') && (lwrRegName[2] <= '7'))
  7732. {
  7733. regNum = CPUReg_FPSTREG_FIRST + (lwrRegName[2] - '0');
  7734. }
  7735. if (regNum != -1)
  7736. {
  7737. DbgTypedValue typedVal;
  7738. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Double, language);
  7739. typedVal.mDouble = ConvertFloat80ToDouble(registers->mFpMmRegsArray[regNum - CPUReg_FPSTREG_FIRST].fp.fp80);
  7740. typedVal.mRegNum = regNum;
  7741. return typedVal;
  7742. }
  7743. // mm regs
  7744. if ((lwrRegName.length() == 3) && (lwrRegName[0] == 'm') && (lwrRegName[1] == 'm') && (lwrRegName[2] >= '0') && (lwrRegName[2] <= '7'))
  7745. {
  7746. regNum = CPUReg_MMREG_FIRST + (lwrRegName[2] - '0');
  7747. }
  7748. if (regNum != -1)
  7749. {
  7750. DbgTypedValue typedVal;
  7751. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_i64, language);
  7752. typedVal.mInt64 = registers->mFpMmRegsArray[regNum - CPUReg_MMREG_FIRST].mm;
  7753. typedVal.mRegNum = regNum;
  7754. return typedVal;
  7755. }
  7756. // xmm regs
  7757. #ifdef BF_DBG_32
  7758. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '7') &&
  7759. (lwrRegName[4] == '_') && (lwrRegName[5] >= '0') && (lwrRegName[5] <= '3'))
  7760. {
  7761. regNum = CPUReg_XMMREG_FIRST + ((lwrRegName[3] - '0') * 4) + (lwrRegName[5] - '0');
  7762. }
  7763. #else
  7764. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '9') &&
  7765. (lwrRegName[4] == '_') && (lwrRegName[5] >= '0') && (lwrRegName[5] <= '3'))
  7766. {
  7767. regNum = CPUReg_XMMREG_FIRST + ((lwrRegName[3] - '0') * 4) + (lwrRegName[5] - '0');
  7768. }
  7769. if ((lwrRegName.length() == 7) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] == '1') && (lwrRegName[4] >= '0') && (lwrRegName[4] <= '9') &&
  7770. (lwrRegName[5] == '_') && (lwrRegName[6] >= '0') && (lwrRegName[6] <= '3'))
  7771. {
  7772. regNum = CPUReg_XMMREG_FIRST + ((10 + (lwrRegName[4] - '0')) * 4) + (lwrRegName[6] - '0');
  7773. }
  7774. #endif
  7775. if (regNum != -1)
  7776. {
  7777. int xmmMajor = (regNum - CPUReg_XMMREG_FIRST) >> 2;
  7778. int xmmMinor = (regNum - CPUReg_XMMREG_FIRST) & 3;
  7779. DwMmDisplayType mmDisplayType = GetDisplayInfo(StrFormat("$XMM%d", xmmMajor))->mMmDisplayType;
  7780. RegForm regForm = RegForm_Unknown;
  7781. if (regForms != NULL)
  7782. {
  7783. int regFormIdx = CPUReg_M128_XMMREG_FIRST + xmmMajor;
  7784. if (regFormIdx < (int)regForms->size())
  7785. regForm = (*regForms)[regFormIdx];
  7786. }
  7787. if (mmDisplayType == DwMmDisplayType_Default)
  7788. {
  7789. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2))
  7790. mmDisplayType = DwMmDisplayType_Double;
  7791. else if (regForm == RegForm_Int4)
  7792. mmDisplayType = DwMmDisplayType_Int32;
  7793. }
  7794. //TODO: Add int types
  7795. if (mmDisplayType == DwMmDisplayType_Double)
  7796. {
  7797. DbgTypedValue typedVal;
  7798. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Double, language);
  7799. typedVal.mDouble = registers->mXmmDRegsArray[xmmMajor].d[xmmMinor];
  7800. typedVal.mRegNum = regNum;
  7801. return typedVal;
  7802. }
  7803. else if ((mmDisplayType == DwMmDisplayType_UInt8) || (mmDisplayType == DwMmDisplayType_Int16) || (mmDisplayType == DwMmDisplayType_Int32))
  7804. {
  7805. DbgTypedValue typedVal;
  7806. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_i32, language);
  7807. typedVal.mInt32 = registers->mXmmI32RegsARray[xmmMajor].i[xmmMinor];
  7808. typedVal.mRegNum = regNum;
  7809. return typedVal;
  7810. }
  7811. else if (mmDisplayType == DwMmDisplayType_Int64)
  7812. {
  7813. DbgTypedValue typedVal;
  7814. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_i64, language);
  7815. typedVal.mInt64 = registers->mXmmI64RegsARray[xmmMajor].i[xmmMinor];
  7816. typedVal.mRegNum = regNum;
  7817. return typedVal;
  7818. }
  7819. DbgTypedValue typedVal;
  7820. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Single, language);
  7821. typedVal.mSingle = registers->mXmmRegsArray[xmmMajor].f[xmmMinor];
  7822. typedVal.mRegNum = regNum;
  7823. return typedVal;
  7824. }
  7825. #ifdef BF_DBG_32
  7826. if ((lwrRegName.length() == 4) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '7'))
  7827. {
  7828. regNum = CPUReg_M128_XMMREG_FIRST + (lwrRegName[3] - '0');
  7829. }
  7830. #else
  7831. if ((lwrRegName.length() == 4) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '9'))
  7832. {
  7833. regNum = CPUReg_M128_XMMREG_FIRST + (lwrRegName[3] - '0');
  7834. }
  7835. if ((lwrRegName.length() == 5) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] == '1') && (lwrRegName[4] >= '0') && (lwrRegName[4] <= '5'))
  7836. {
  7837. regNum = CPUReg_M128_XMMREG_FIRST + 10 + (lwrRegName[4] - '0');
  7838. }
  7839. #endif
  7840. if (regNum != -1)
  7841. {
  7842. DbgTypedValue typedVal;
  7843. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_RegGroup, language);
  7844. 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)
  7845. typedVal.mRegNum = regNum;
  7846. return typedVal;
  7847. }
  7848. // flags
  7849. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'f') && (lwrRegName[1] == 'l') && (lwrRegName[2] == 'a') && (lwrRegName[3] == 'g') && (lwrRegName[5] == 'f'))
  7850. {
  7851. switch(lwrRegName[4])
  7852. {
  7853. case 'c': regNum = CPUReg_FLAG_CF_CARRY; break;
  7854. case 'p': regNum = CPUReg_FLAG_PF_PARITY; break;
  7855. case 'a': regNum = CPUReg_FLAG_AF_ADJUST; break;
  7856. case 'z': regNum = CPUReg_FLAG_ZF_ZERO; break;
  7857. case 's': regNum = CPUReg_FLAG_SF_SIGN; break;
  7858. case 'i': regNum = CPUReg_FLAG_IF_INTERRUPT; break;
  7859. case 'd': regNum = CPUReg_FLAG_DF_DIRECTION; break;
  7860. case 'o': regNum = CPUReg_FLAG_OF_OVERFLOW; break;
  7861. default: break;
  7862. }
  7863. }
  7864. if (regNum != -1)
  7865. {
  7866. int flagBit = CPURegisters::GetFlagBitForRegister(regNum);
  7867. BF_ASSERT(flagBit >= 0);
  7868. DbgTypedValue typedVal;
  7869. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Bool, language);
  7870. typedVal.mBool = (registers->mIntRegs.efl & ((uint64)1 << flagBit)) != 0;
  7871. typedVal.mRegNum = regNum;
  7872. return typedVal;
  7873. }
  7874. // categories
  7875. if (lwrRegName == "allregs")
  7876. regNum = CPUReg_CAT_ALLREGS;
  7877. else if (lwrRegName == "iregs")
  7878. regNum = CPUReg_CAT_IREGS;
  7879. else if (lwrRegName == "fpregs")
  7880. regNum = CPUReg_CAT_FPREGS;
  7881. else if (lwrRegName == "mmregs")
  7882. regNum = CPUReg_CAT_MMREGS;
  7883. else if (lwrRegName == "xmmregs")
  7884. regNum = CPUReg_CAT_XMMREGS;
  7885. else if (lwrRegName == "flags")
  7886. regNum = CPUReg_CAT_FLAGS;
  7887. if (regNum != -1)
  7888. {
  7889. DbgTypedValue typedVal;
  7890. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_RegGroup, language);
  7891. 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)
  7892. typedVal.mRegNum = regNum;
  7893. return typedVal;
  7894. }
  7895. return DbgTypedValue();
  7896. }
  7897. DbgModule* WinDebugger::GetCallStackDbgModule(int callStackIdx)
  7898. {
  7899. if ((mRunState == RunState_NotStarted) || (!IsPaused()))
  7900. return mEmptyDebugTarget->GetMainDbgModule();
  7901. if (callStackIdx == -1)
  7902. return mDebugTarget->GetMainDbgModule();
  7903. FixCallStackIdx(callStackIdx);
  7904. if (callStackIdx >= mCallStack.size())
  7905. return mDebugTarget->GetMainDbgModule();
  7906. UpdateCallStackMethod(callStackIdx);
  7907. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  7908. if (subProgram != NULL)
  7909. return subProgram->mCompileUnit->mDbgModule;
  7910. auto dbgModule = mDebugTarget->FindDbgModuleForAddress(mCallStack[callStackIdx]->mRegisters.GetPC());
  7911. if (dbgModule != NULL)
  7912. return dbgModule;
  7913. return mDebugTarget->GetMainDbgModule();
  7914. }
  7915. DbgSubprogram* WinDebugger::GetCallStackSubprogram(int callStackIdx)
  7916. {
  7917. if ((IsInRunState()) || (mRunState == RunState_NotStarted) || (callStackIdx == -1))
  7918. return NULL;
  7919. if (callStackIdx >= (int)mCallStack.size())
  7920. UpdateCallStack();
  7921. if (mCallStack.IsEmpty())
  7922. return NULL;
  7923. if (callStackIdx >= (int)mCallStack.size())
  7924. callStackIdx = 0;
  7925. UpdateCallStackMethod(callStackIdx);
  7926. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  7927. return subProgram;
  7928. }
  7929. DbgCompileUnit* WinDebugger::GetCallStackCompileUnit(int callStackIdx)
  7930. {
  7931. if ((IsInRunState()) || (mRunState == RunState_NotStarted) || (callStackIdx == -1))
  7932. return NULL;
  7933. if (callStackIdx >= (int)mCallStack.size())
  7934. UpdateCallStack();
  7935. if (mCallStack.IsEmpty())
  7936. return NULL;
  7937. if (callStackIdx >= (int)mCallStack.size())
  7938. callStackIdx = 0;
  7939. UpdateCallStackMethod(callStackIdx);
  7940. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  7941. if (subProgram == NULL)
  7942. return NULL;
  7943. return subProgram->mCompileUnit;
  7944. }
  7945. String WinDebugger::EvaluateContinue(DbgPendingExpr* pendingExpr, BfPassInstance& bfPassInstance)
  7946. {
  7947. DbgModule* dbgModule = NULL;
  7948. DbgCompileUnit* dbgCompileUnit = NULL;
  7949. if (pendingExpr->mThreadId == -1)
  7950. {
  7951. if ((pendingExpr->mFormatInfo.mLanguage == DbgLanguage_Beef) && (mDebugTarget != NULL) && (mDebugTarget->mTargetBinary != NULL))
  7952. dbgModule = mDebugTarget->mTargetBinary;
  7953. else
  7954. dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  7955. }
  7956. else
  7957. {
  7958. dbgModule = GetCallStackDbgModule(pendingExpr->mCallStackIdx);
  7959. if ((dbgModule != NULL) &&(!dbgModule->mDebugTarget->mIsEmpty))
  7960. dbgCompileUnit = GetCallStackCompileUnit(pendingExpr->mCallStackIdx);
  7961. }
  7962. if (dbgModule == NULL)
  7963. dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  7964. if (!pendingExpr->mException.empty())
  7965. {
  7966. RestoreAllRegisters();
  7967. return "!" + pendingExpr->mException;
  7968. }
  7969. DwAutoComplete autoComplete;
  7970. if (bfPassInstance.HasFailed())
  7971. {
  7972. // Don't allow pending calls if we've already failed in the calling Evaluate()
  7973. pendingExpr->mExpressionFlags = (DwEvalExpressionFlags)(pendingExpr->mExpressionFlags & ~DwEvalExpressionFlag_AllowCalls);
  7974. }
  7975. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, pendingExpr->mCallStackIdx, pendingExpr->mCursorPos);
  7976. dbgExprEvaluator.mLanguage = pendingExpr->mFormatInfo.mLanguage;
  7977. dbgExprEvaluator.mReferenceId = &pendingExpr->mReferenceId;
  7978. dbgExprEvaluator.mExpressionFlags = pendingExpr->mExpressionFlags;
  7979. dbgExprEvaluator.mExplicitThis = pendingExpr->mFormatInfo.mExplicitThis;
  7980. dbgExprEvaluator.mSubjectExpr = pendingExpr->mFormatInfo.mSubjectExpr;
  7981. dbgExprEvaluator.mNamespaceSearchStr = pendingExpr->mFormatInfo.mNamespaceSearch;
  7982. dbgExprEvaluator.mExpectingTypeName = pendingExpr->mFormatInfo.mExpectedType;
  7983. dbgExprEvaluator.mCallResults = &pendingExpr->mCallResults;
  7984. if ((pendingExpr->mExpressionFlags & DwEvalExpressionFlag_ValidateOnly) != 0)
  7985. {
  7986. dbgExprEvaluator.mValidateOnly = true;
  7987. }
  7988. if (pendingExpr->mCursorPos != -1)
  7989. {
  7990. dbgExprEvaluator.mAutoComplete = &autoComplete;
  7991. }
  7992. dbgExprEvaluator.mDbgCompileUnit = dbgCompileUnit;
  7993. DbgTypedValue exprResult;
  7994. if (pendingExpr->mExplitType != NULL)
  7995. {
  7996. exprResult.mHasNoValue = true;
  7997. exprResult.mType = pendingExpr->mExplitType;
  7998. }
  7999. else if (pendingExpr->mExprNode != NULL)
  8000. {
  8001. exprResult = dbgExprEvaluator.Resolve(pendingExpr->mExprNode);
  8002. }
  8003. if (dbgExprEvaluator.mCreatedPendingCall)
  8004. {
  8005. BF_ASSERT(mRunState == RunState_DebugEval);
  8006. //ContinueDebugEvent();
  8007. return "!pending";
  8008. }
  8009. if (dbgExprEvaluator.mCountResultOverride != -1)
  8010. pendingExpr->mFormatInfo.mOverrideCount = dbgExprEvaluator.mCountResultOverride;
  8011. String val;
  8012. if (bfPassInstance.HasFailed())
  8013. {
  8014. BfLogDbgExpr("Evaluate Failed: %s\n", bfPassInstance.mErrors[0]->mError.c_str());
  8015. val = StrFormat("!%d\t%d\t%s", bfPassInstance.mErrors[0]->GetSrcStart(), bfPassInstance.mErrors[0]->GetSrcLength(), bfPassInstance.mErrors[0]->mError.c_str());
  8016. }
  8017. else if (dbgExprEvaluator.mBlockedSideEffects)
  8018. {
  8019. BfLogDbgExpr("Evaluate blocked side effects\n");
  8020. val = "!sideeffects";
  8021. }
  8022. else if (!exprResult)
  8023. {
  8024. if (exprResult.mType != NULL)
  8025. {
  8026. BfLogDbgExpr("Evaluate success\n");
  8027. String typeName = exprResult.mType->ToString();
  8028. DbgType* rawType = exprResult.mType;
  8029. if (rawType->IsBfObjectPtr())
  8030. rawType = rawType->mTypeParam;
  8031. String typeNameRaw = rawType->ToStringRaw();
  8032. val = typeName + "\n" + typeName;
  8033. val += "\n" + GetMemberList(exprResult.mType, typeNameRaw, false, true, false, false, exprResult.mIsReadOnly);
  8034. if (exprResult.mType->mTypeCode == DbgType_Namespace)
  8035. {
  8036. val += "\n:type\tnamespace";
  8037. }
  8038. else
  8039. {
  8040. auto type = exprResult.mType;
  8041. if (type->IsPointer())
  8042. type = type->mTypeParam;
  8043. if (type->IsBfObject())
  8044. val += "\n:type\tclass";
  8045. else
  8046. val += "\n:type\tvaluetype";
  8047. }
  8048. if (!pendingExpr->mReferenceId.empty())
  8049. val += "\n:referenceId\t" + pendingExpr->mReferenceId;
  8050. }
  8051. else
  8052. val = "!";
  8053. }
  8054. else if ((pendingExpr->mExpressionFlags & (DwEvalExpressionFlag_MemoryAddress)) != 0)
  8055. {
  8056. DbgType* resultType = exprResult.mType->RemoveModifiers();
  8057. if ((resultType->IsInteger()) || (resultType->IsPointerOrRef()))
  8058. {
  8059. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", 0);
  8060. }
  8061. else
  8062. {
  8063. if (exprResult.mSrcAddress != 0)
  8064. val = StrFormat("!Type '%s' is invalid. A pointer or address value is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  8065. else
  8066. val = StrFormat("!Type '%s' is invalid. A pointer or address value is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  8067. }
  8068. }
  8069. else if ((pendingExpr->mExpressionFlags & (DwEvalExpressionFlag_MemoryWatch)) != 0)
  8070. {
  8071. DbgType* resultType = exprResult.mType->RemoveModifiers();
  8072. bool isMemoryWatch = (pendingExpr->mExpressionFlags & DwEvalExpressionFlag_MemoryWatch) != 0;
  8073. if (!resultType->IsPointerOrRef())
  8074. {
  8075. if (exprResult.mSrcAddress != 0)
  8076. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  8077. else
  8078. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  8079. }
  8080. else
  8081. {
  8082. auto innerType = resultType->mTypeParam;
  8083. int byteCount = innerType->GetByteCount();
  8084. if (pendingExpr->mFormatInfo.mArrayLength != -1)
  8085. byteCount *= pendingExpr->mFormatInfo.mArrayLength;
  8086. if (byteCount == 0)
  8087. {
  8088. 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());
  8089. }
  8090. #ifdef BF_DBG_32
  8091. else if ((isMemoryWatch) && (!IsMemoryBreakpointSizeValid(exprResult.mPtr, byteCount)))
  8092. {
  8093. if (innerType->mSize > 16)
  8094. 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);
  8095. else if (!IsMemoryBreakpointSizeValid(0, byteCount))
  8096. 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);
  8097. else
  8098. 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);
  8099. }
  8100. #else
  8101. else if ((isMemoryWatch) && (!IsMemoryBreakpointSizeValid(exprResult.mPtr, byteCount)))
  8102. {
  8103. if (innerType->mSize > 32)
  8104. 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);
  8105. else if (!IsMemoryBreakpointSizeValid(0, byteCount))
  8106. 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);
  8107. else
  8108. 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);
  8109. }
  8110. #endif
  8111. else
  8112. {
  8113. auto language = dbgExprEvaluator.GetLanguage();
  8114. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", byteCount) + "\n" + StrFormat("%d\t", language) + innerType->ToStringRaw(language);
  8115. }
  8116. }
  8117. }
  8118. else
  8119. {
  8120. if (pendingExpr->mFormatInfo.mNoEdit)
  8121. exprResult.mIsReadOnly = true;
  8122. if (!pendingExpr->mReferenceId.empty())
  8123. pendingExpr->mFormatInfo.mReferenceId = pendingExpr->mReferenceId;
  8124. val = DbgTypedValueToString(exprResult, pendingExpr->mExprNode->ToString(), pendingExpr->mFormatInfo, &dbgExprEvaluator, (pendingExpr->mExpressionFlags & DwEvalExpressionFlag_FullPrecision) != 0);
  8125. if ((!val.empty()) && (val[0] == '!'))
  8126. return val;
  8127. if (pendingExpr->mFormatInfo.mRawString)
  8128. return val;
  8129. if (exprResult.mIsLiteral)
  8130. val += "\n:literal";
  8131. if (bfPassInstance.HasMessages())
  8132. {
  8133. for (auto error : bfPassInstance.mErrors)
  8134. {
  8135. if (error->mIsWarning)
  8136. {
  8137. val += "\n:warn\t";
  8138. val += error->mError;
  8139. }
  8140. }
  8141. }
  8142. if (!pendingExpr->mFormatInfo.mReferenceId.empty())
  8143. val += "\n:referenceId\t" + pendingExpr->mFormatInfo.mReferenceId;
  8144. if ((exprResult.mSrcAddress != 0) && (HasMemoryBreakpoint(exprResult.mSrcAddress, exprResult.mType->GetByteCount())))
  8145. val += StrFormat("\n:break\t%@", exprResult.mSrcAddress);
  8146. auto checkType = exprResult.mType->RemoveModifiers();
  8147. if (checkType->IsBfObjectPtr())
  8148. val += "\n:type\tobject";
  8149. else if ((checkType->IsPointer()) || (checkType->mTypeCode == DbgType_Subroutine))
  8150. val += "\n:type\tpointer";
  8151. else if (checkType->IsInteger())
  8152. val += "\n:type\tint";
  8153. else if (checkType->IsFloat())
  8154. val += "\n:type\tfloat";
  8155. else if ((exprResult.mRegNum >= X64Reg_M128_XMM0) && (exprResult.mRegNum <= X64Reg_M128_XMM15))
  8156. val += "\n:type\tmm128";
  8157. else
  8158. val += "\n:type\tvaluetype";
  8159. if ((pendingExpr->mFormatInfo.mTypeKindFlags & DbgTypeKindFlag_Int) != 0)
  8160. val += "\n:type\tint";
  8161. if (dbgExprEvaluator.mHadSideEffects)
  8162. val += "\n:sideeffects";
  8163. auto underlyingType = exprResult.mType->RemoveModifiers();
  8164. bool canEdit = true;
  8165. if (pendingExpr->mFormatInfo.mLanguage == DbgLanguage_Beef)
  8166. {
  8167. if (exprResult.mType->IsConst())
  8168. canEdit = false;
  8169. }
  8170. if (pendingExpr->mFormatInfo.mNoEdit)
  8171. canEdit = false;
  8172. if (exprResult.mIsReadOnly)
  8173. canEdit = false;
  8174. if (val[0] == '!')
  8175. {
  8176. // Already has an error embedded, can't edit
  8177. }
  8178. else if ((exprResult.mSrcAddress != 0) && (underlyingType->mTypeCode >= DbgType_i8) && (underlyingType->mTypeCode <= DbgType_Ptr) &&
  8179. (underlyingType->mTypeCode != DbgType_Class) && (underlyingType->mTypeCode != DbgType_Struct))
  8180. {
  8181. if (canEdit)
  8182. val += "\n:canEdit";
  8183. if (exprResult.mType->mTypeCode == DbgType_Ptr)
  8184. {
  8185. val += "\n:editVal\t" + EncodeDataPtr(exprResult.mPtr, true);
  8186. }
  8187. }
  8188. else if ((underlyingType->IsStruct()) && (exprResult.mSrcAddress != 0) && (underlyingType->IsTypedPrimitive()))
  8189. {
  8190. auto primType = underlyingType->GetRootBaseType();
  8191. DbgTypedValue primVal = dbgExprEvaluator.ReadTypedValue(NULL, primType, exprResult.mSrcAddress, DbgAddrType_Target);
  8192. String primResult = DbgTypedValueToString(primVal, "", pendingExpr->mFormatInfo, NULL);
  8193. int crPos = (int)primResult.IndexOf('\n');
  8194. if (crPos != -1)
  8195. primResult.RemoveToEnd(crPos);
  8196. if (canEdit)
  8197. val += "\n:canEdit";
  8198. val += "\n:editVal\t" + primResult;
  8199. }
  8200. else if (exprResult.mRegNum >= 0)
  8201. {
  8202. bool isPseudoReg = ( ((exprResult.mRegNum >= X86Reg_M128_XMMREG_FIRST) && (exprResult.mRegNum <= X86Reg_M128_XMMREG_LAST))
  8203. || ((exprResult.mRegNum >= X86Reg_CAT_FIRST) && (exprResult.mRegNum <= X86Reg_CAT_LAST)) );
  8204. if (!isPseudoReg)
  8205. {
  8206. if (canEdit)
  8207. val += "\n:canEdit";
  8208. }
  8209. }
  8210. }
  8211. if (pendingExpr->mFormatInfo.mRawString)
  8212. return "";
  8213. if (pendingExpr->mCursorPos != -1)
  8214. val += GetAutocompleteOutput(autoComplete);
  8215. return val;
  8216. }
  8217. String WinDebugger::EvaluateContinue()
  8218. {
  8219. BP_ZONE("WinDebugger::EvaluateContinue");
  8220. AutoCrit autoCrit(mDebugManager->mCritSect);
  8221. if (mDebugPendingExpr == NULL)
  8222. return "!Evaluation canceled";
  8223. if (!IsPaused())
  8224. return "!Not paused";
  8225. if (mRunState == RunState_DebugEval_Done)
  8226. mRunState = RunState_Paused;
  8227. BfPassInstance bfPassInstance(mBfSystem);
  8228. String result = EvaluateContinue(mDebugPendingExpr, bfPassInstance);
  8229. if (result != "!pending")
  8230. {
  8231. BfLogDbg("EvaluateContinue finishing pending expr in thread %d\n", mDebugEvalThreadInfo.mThreadId);
  8232. CleanupDebugEval();
  8233. }
  8234. return result;
  8235. }
  8236. void WinDebugger::EvaluateContinueKeep()
  8237. {
  8238. if (mDebugPendingExpr != NULL)
  8239. mDebugPendingExpr->mIdleTicks = 0;
  8240. }
  8241. static void PdbTestFile(WinDebugger* debugger, const StringImpl& path)
  8242. {
  8243. if (!path.EndsWith(".PDB", StringImpl::CompareKind_OrdinalIgnoreCase))
  8244. return;
  8245. OutputDebugStrF("Testing %s\n", path.c_str());
  8246. COFF coffFile(debugger->mDebugTarget);
  8247. uint8 wantGuid[16] = { 0 };
  8248. if (!coffFile.TryLoadPDB(path, wantGuid, -1))
  8249. return;
  8250. if (!coffFile.mIs64Bit)
  8251. return;
  8252. coffFile.ParseTypeData();
  8253. coffFile.ParseSymbolData();
  8254. coffFile.ParseGlobalsData();
  8255. }
  8256. static void PdbTest(WinDebugger* debugger, const StringImpl& path)
  8257. {
  8258. for (auto& fileEntry : FileEnumerator(path, FileEnumerator::Flags_Files))
  8259. {
  8260. String filePath = fileEntry.GetFilePath();
  8261. PdbTestFile(debugger, filePath);
  8262. }
  8263. for (auto& fileEntry : FileEnumerator(path, FileEnumerator::Flags_Directories))
  8264. {
  8265. String childPath = fileEntry.GetFilePath();
  8266. String dirName;
  8267. dirName = GetFileName(childPath);
  8268. PdbTest(debugger, childPath);
  8269. }
  8270. }
  8271. String WinDebugger::Evaluate(const StringImpl& expr, DwFormatInfo formatInfo, int callStackIdx, int cursorPos, int language, DwEvalExpressionFlags expressionFlags)
  8272. {
  8273. BP_ZONE_F("WinDebugger::Evaluate %s", BP_DYN_STR(expr.c_str()));
  8274. AutoCrit autoCrit(mDebugManager->mCritSect);
  8275. if ((expressionFlags & DwEvalExpressionFlag_Symbol) != 0)
  8276. {
  8277. DwAutoComplete autoComplete;
  8278. String retVal;
  8279. retVal += GetAutocompleteOutput(autoComplete);
  8280. return retVal;
  8281. }
  8282. UpdateCallStackMethod(callStackIdx);
  8283. BfLogDbgExpr("Evaluate %s in thread %d\n", expr.c_str(), (mActiveThread != NULL) ? mActiveThread->mThreadId : 0);
  8284. if (language != -1)
  8285. formatInfo.mLanguage = (DbgLanguage)language;
  8286. auto activeThread = mActiveThread;
  8287. if ((!IsPaused()) && (mRunState != RunState_NotStarted) && (mRunState != RunState_DebugEval))
  8288. {
  8289. activeThread = NULL;
  8290. callStackIdx = -1;
  8291. }
  8292. if (mDebugPendingExpr != NULL)
  8293. {
  8294. // We already have a pending call
  8295. expressionFlags = (DwEvalExpressionFlags)(expressionFlags & ~DwEvalExpressionFlag_AllowCalls);
  8296. }
  8297. if ((expressionFlags & DwEvalExpressionFlag_RawStr) != 0)
  8298. {
  8299. formatInfo.mRawString = true;
  8300. }
  8301. auto dbgModule = GetCallStackDbgModule(callStackIdx);
  8302. auto dbgSubprogram = GetCallStackSubprogram(callStackIdx);
  8303. DbgCompileUnit* dbgCompileUnit = NULL;
  8304. if (dbgSubprogram != NULL)
  8305. dbgCompileUnit = dbgSubprogram->mCompileUnit;
  8306. auto terminatedExpr = expr + ";";
  8307. if ((expr.length() > 0) && (expr[0] == '!'))
  8308. {
  8309. if (expr.StartsWith("!step "))
  8310. {
  8311. expressionFlags = (DwEvalExpressionFlags)(expressionFlags | DwEvalExpressionFlag_StepIntoCalls);
  8312. for (int i = 0; i < 5; i++)
  8313. terminatedExpr[i] = ' ';
  8314. }
  8315. else
  8316. {
  8317. String cmd = expr;
  8318. int commaPos = (int)cmd.IndexOf(',');
  8319. if (commaPos != -1)
  8320. cmd.RemoveToEnd(commaPos);
  8321. if (cmd == "!info")
  8322. {
  8323. OutputMessage(StrFormat("Module: %s\n", dbgModule->mDisplayName.c_str()));
  8324. if (dbgSubprogram == NULL)
  8325. {
  8326. //
  8327. }
  8328. else if (dbgSubprogram->mLinkName != NULL)
  8329. {
  8330. OutputMessage(StrFormat("Link Name: %s\n", dbgSubprogram->mLinkName));
  8331. }
  8332. else
  8333. {
  8334. String outSymbol;
  8335. if (mDebugTarget->FindSymbolAt(dbgSubprogram->mBlock.mLowPC, &outSymbol))
  8336. {
  8337. OutputMessage(StrFormat("Link Name: %s\n", outSymbol.c_str()));
  8338. }
  8339. }
  8340. return "";
  8341. }
  8342. else if (cmd == "!dbg")
  8343. {
  8344. mDbgBreak = true;
  8345. return "";
  8346. }
  8347. else if (cmd == "!pdbtest")
  8348. {
  8349. PdbTest(this, "c:\\");
  8350. }
  8351. }
  8352. }
  8353. bool valIsAddr = false;
  8354. BfParser* parser = new BfParser(mBfSystem);
  8355. parser->mCompatMode = true;
  8356. BfPassInstance bfPassInstance(mBfSystem);
  8357. if ((terminatedExpr.length() > 2) && (terminatedExpr[0] == '@'))
  8358. {
  8359. if (terminatedExpr[1] == '!') // Return string as error
  8360. {
  8361. int errorEnd = (int)terminatedExpr.IndexOf("@!", 2);
  8362. if (errorEnd != -1)
  8363. return terminatedExpr.Substring(1, errorEnd - 1);
  8364. else
  8365. return terminatedExpr.Substring(1);
  8366. }
  8367. else if (terminatedExpr[1] == '>') // Return string as text
  8368. {
  8369. int errorEnd = (int)terminatedExpr.IndexOf("@>", 2);
  8370. if (errorEnd != -1)
  8371. return terminatedExpr.Substring(2, errorEnd - 1);
  8372. else
  8373. return terminatedExpr.Substring(2);
  8374. }
  8375. else // Look for "@:" or "@Beef:" style
  8376. {
  8377. int colonIdx = terminatedExpr.IndexOf(':');
  8378. if (colonIdx > 0)
  8379. {
  8380. bool isValid = true;
  8381. DbgLanguage language = DbgLanguage_Unknown;
  8382. String lang = terminatedExpr.Substring(1, colonIdx - 1);
  8383. lang = ToUpper(lang);
  8384. if ((lang == "") || (lang == "BEEF"))
  8385. {
  8386. language = DbgLanguage_Beef;
  8387. }
  8388. else if (lang == "C")
  8389. {
  8390. language = DbgLanguage_C;
  8391. }
  8392. if (language != DbgLanguage_Unknown)
  8393. {
  8394. for (int i = 0; i < colonIdx + 1; i++)
  8395. terminatedExpr[i] = ' ';
  8396. DbgLanguage curLanguage = DbgLanguage_Unknown;
  8397. if (dbgSubprogram != NULL)
  8398. curLanguage = dbgSubprogram->GetLanguage();
  8399. if (language != curLanguage)
  8400. {
  8401. dbgModule = mDebugTarget->mTargetBinary;
  8402. dbgSubprogram = NULL;
  8403. formatInfo.mLanguage = language;
  8404. callStackIdx = -1;
  8405. }
  8406. }
  8407. }
  8408. }
  8409. }
  8410. parser->SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  8411. parser->Parse(&bfPassInstance);
  8412. BfReducer bfReducer;
  8413. bfReducer.mAlloc = parser->mAlloc;
  8414. bfReducer.mSystem = mBfSystem;
  8415. bfReducer.mPassInstance = &bfPassInstance;
  8416. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser->mRootNode);
  8417. bfReducer.mVisitorPos.MoveNext();
  8418. bfReducer.mCompatMode = parser->mCompatMode;
  8419. bfReducer.mSource = parser;
  8420. auto exprNode = bfReducer.CreateExpression(parser->mRootNode->mChildArr.GetAs<BfAstNode*>(0));
  8421. parser->Close();
  8422. formatInfo.mCallStackIdx = callStackIdx;
  8423. if ((formatInfo.mLanguage == DbgLanguage_Unknown) && (dbgSubprogram != NULL))
  8424. formatInfo.mLanguage = dbgSubprogram->GetLanguage();
  8425. DbgPendingExpr* pendingExpr = new DbgPendingExpr();
  8426. if (activeThread != NULL)
  8427. pendingExpr->mThreadId = activeThread->mThreadId;
  8428. pendingExpr->mParser = parser;
  8429. pendingExpr->mCallStackIdx = callStackIdx;
  8430. pendingExpr->mCursorPos = cursorPos;
  8431. pendingExpr->mExpressionFlags = expressionFlags;
  8432. pendingExpr->mExprNode = exprNode;
  8433. DbgType* explicitType = NULL;
  8434. String formatFlags;
  8435. String assignExpr;
  8436. int assignExprOffset = -1;
  8437. if ((exprNode != NULL) && (exprNode->GetSrcEnd() < (int)expr.length()))
  8438. {
  8439. int formatOffset = exprNode->GetSrcEnd();
  8440. while (formatOffset < (int)expr.length())
  8441. {
  8442. char c = expr[formatOffset];
  8443. if (c == ' ')
  8444. formatOffset++;
  8445. else
  8446. break;
  8447. }
  8448. formatFlags = Trim(expr.Substring(formatOffset));
  8449. bool isComplexType = false;
  8450. for (char c : formatFlags)
  8451. if (c == '>')
  8452. isComplexType = true;
  8453. if (isComplexType)
  8454. {
  8455. explicitType = dbgModule->FindType(expr);
  8456. }
  8457. if ((explicitType == NULL) && (formatFlags.length() > 0))
  8458. {
  8459. String errorString = "Invalid expression";
  8460. if (!ParseFormatInfo(dbgModule, formatFlags, &formatInfo, &bfPassInstance, &assignExprOffset, &assignExpr, &errorString))
  8461. {
  8462. if (formatInfo.mRawString)
  8463. return "";
  8464. bfPassInstance.FailAt(errorString, parser->mSourceData, exprNode->GetSrcEnd(), (int) expr.length() - exprNode->GetSrcEnd());
  8465. formatFlags = "";
  8466. }
  8467. if (assignExprOffset != -1)
  8468. assignExprOffset += formatOffset;
  8469. }
  8470. }
  8471. if (assignExpr.length() > 0)
  8472. {
  8473. String newEvalStr = exprNode->ToString() + " = ";
  8474. int errorOffset = (int)newEvalStr.length();
  8475. newEvalStr += assignExpr;
  8476. String result = Evaluate(newEvalStr, formatInfo, callStackIdx, cursorPos, language, expressionFlags);
  8477. if (result[0] == '!')
  8478. {
  8479. int tabPos = (int)result.IndexOf('\t');
  8480. if (tabPos > 0)
  8481. {
  8482. int errorStart = atoi(result.Substring(1, tabPos - 1).c_str());
  8483. if (errorStart >= errorOffset)
  8484. {
  8485. result = StrFormat("!%d", errorStart - errorOffset + assignExprOffset) + result.Substring(tabPos);
  8486. }
  8487. }
  8488. }
  8489. return result;
  8490. }
  8491. pendingExpr->mExplitType = explicitType;
  8492. pendingExpr->mFormatInfo = formatInfo;
  8493. String result = EvaluateContinue(pendingExpr, bfPassInstance);
  8494. if (result == "!pending")
  8495. {
  8496. BF_ASSERT(mDebugPendingExpr == NULL);
  8497. if (mDebugPendingExpr != NULL)
  8498. {
  8499. return "!retry"; // We already have a pending
  8500. }
  8501. mDebugPendingExpr = pendingExpr;
  8502. mDebugEvalThreadInfo = *mActiveThread;
  8503. mActiveThread->mIsAtBreakpointAddress = 0;
  8504. mActiveThread->mStoppedAtAddress = 0;
  8505. mActiveThread->mBreakpointAddressContinuing = 0;
  8506. }
  8507. else
  8508. delete pendingExpr;
  8509. return result;
  8510. }
  8511. String WinDebugger::Evaluate(const StringImpl& expr, int callStackIdx, int cursorPos, int language, DwEvalExpressionFlags expressionFlags)
  8512. {
  8513. DwFormatInfo formatInfo;
  8514. return Evaluate(expr, formatInfo, callStackIdx, cursorPos, language, expressionFlags);
  8515. }
  8516. static void ConvertDoubleToFloat80(double d, byte fp80[10])
  8517. {
  8518. uint64 di = *reinterpret_cast<uint64*>(&d);
  8519. uint64 m = di & (((uint64)1 << 52) - 1);
  8520. uint64 e = (di >> 52) & 0x7ff;
  8521. memset(fp80, 0, 10);
  8522. // sign bit is directly transferred
  8523. if (di & ((uint64)1 << 63))
  8524. fp80[9] |= 0x80;
  8525. if (!e && !m)
  8526. return; // zero
  8527. fp80[7] |= 0x80; // leading integer bit in mantissa (always 1 in normalized numbers)
  8528. if (e == 0x7ff)
  8529. {
  8530. fp80[9] |= 0x7f;
  8531. fp80[8] = 0xff;
  8532. if (m == 0)
  8533. return; // inf
  8534. fp80[7] |= 0x3f; // any nonzero value will be a NaN (SNaN or QNaN)
  8535. if (m & ((uint64)1 << 51))
  8536. fp80[7] |= 0x40; // QNaN
  8537. return;
  8538. }
  8539. int useExponent = (int)e - 1023;
  8540. if (!e)
  8541. {
  8542. // denormal; can renormalize though since fp80 supports lower exponents
  8543. BF_ASSERT(m != 0); // we should have trapped zero above
  8544. while (!(m & ((uint64)1 << 51)))
  8545. {
  8546. m <<= 1;
  8547. --useExponent;
  8548. }
  8549. // finally we have our leading 1 bit; strip that off and we have a normalized number again
  8550. m <<= 1;
  8551. --useExponent;
  8552. m &= (((uint64)1 << 52) - 1);
  8553. }
  8554. useExponent += 16383;
  8555. BF_ASSERT((useExponent > 0) && (useExponent < 0x7fff));
  8556. *reinterpret_cast<uint16*>(&fp80[8]) |= (uint16)useExponent;
  8557. *reinterpret_cast<uint64*>(&fp80[0]) |= (m << 11);
  8558. }
  8559. bool WinDebugger::AssignToReg(int callStackIdx, DbgTypedValue regVal, DbgTypedValue value, String& outError)
  8560. {
  8561. BF_ASSERT(regVal.mRegNum >= 0);
  8562. if (mCallStack.size() == 0)
  8563. {
  8564. outError = "No call stack";
  8565. return false;
  8566. }
  8567. if (callStackIdx >= (int)mCallStack.size())
  8568. {
  8569. outError = "Invalid call stack index";
  8570. return false;
  8571. }
  8572. auto registers = &mCallStack[callStackIdx]->mRegisters;
  8573. void* regPtr = NULL;
  8574. #ifdef BF_DBG_32
  8575. if ((regVal.mRegNum >= X86Reg_INTREG_FIRST) && (regVal.mRegNum <= X86Reg_INTREG_LAST))
  8576. {
  8577. BF_ASSERT(regVal.mType->mSize == sizeof(int32));
  8578. registers->mIntRegsArray[regVal.mRegNum - X86Reg_INTREG_FIRST] = (uint64)value.mUInt32; // don't sign-extend
  8579. }
  8580. else if ((regVal.mRegNum >= X86Reg_FPSTREG_FIRST) && (regVal.mRegNum <= X86Reg_FPSTREG_LAST))
  8581. {
  8582. BF_ASSERT(regVal.mType->mSize == sizeof(float) || regVal.mType->mSize == sizeof(double));
  8583. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X86Reg_FPSTREG_FIRST];
  8584. double d;
  8585. if (regVal.mType->mSize == sizeof(float))
  8586. d = (double)value.mSingle;
  8587. else
  8588. d = value.mDouble;
  8589. ConvertDoubleToFloat80(d, reg->fp.fp80);
  8590. }
  8591. else if ((regVal.mRegNum >= X86Reg_MMREG_FIRST) && (regVal.mRegNum <= X86Reg_MMREG_LAST))
  8592. {
  8593. BF_ASSERT(regVal.mType->mSize == sizeof(int32) || regVal.mType->mSize == sizeof(int64));
  8594. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X86Reg_MMREG_FIRST];
  8595. if (regVal.mType->mSize == sizeof(int32))
  8596. reg->mm = (uint64)value.mUInt32; // don't sign-extend
  8597. else if (regVal.mType->mSize == sizeof(int64))
  8598. reg->mm = value.mInt64;
  8599. // 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
  8600. reg->fp.fp80[8] = reg->fp.fp80[9] = 0xFF;
  8601. }
  8602. else if ((regVal.mRegNum >= X86Reg_XMMREG_FIRST) && (regVal.mRegNum <= X86Reg_XMMREG_LAST))
  8603. {
  8604. int xmmMajor = (regVal.mRegNum - X86Reg_XMMREG_FIRST) >> 2;
  8605. int xmmMinor = (regVal.mRegNum - X86Reg_XMMREG_FIRST) & 3;
  8606. registers->mXmmRegsArray[xmmMajor].f[xmmMinor] = value.mSingle;
  8607. }
  8608. else if ((regVal.mRegNum >= X86Reg_M128_XMMREG_FIRST) && (regVal.mRegNum <= X86Reg_M128_XMMREG_LAST))
  8609. {
  8610. outError = "Cannot write directly to 128-bit XMM register, please use inner float components";
  8611. return false;
  8612. }
  8613. else if ((regVal.mRegNum >= X86Reg_FLAG_FIRST) && (regVal.mRegNum <= X86Reg_FLAG_LAST))
  8614. {
  8615. int flagBit = CPURegisters::GetFlagBitForRegister(regVal.mRegNum);
  8616. if (flagBit >= 0)
  8617. {
  8618. if (value.mBool)
  8619. registers->mIntRegs.efl |= ((uint64)1 << flagBit);
  8620. else
  8621. registers->mIntRegs.efl &= ~((uint64)1 << flagBit);
  8622. }
  8623. else
  8624. {
  8625. outError = "Unrecognized flag";
  8626. return false;
  8627. }
  8628. }
  8629. else if ((regVal.mRegNum >= X86Reg_CAT_FIRST) && (regVal.mRegNum <= X86Reg_CAT_LAST))
  8630. {
  8631. outError = "Cannot write directly to register categories, please use inner float components";
  8632. return false;
  8633. }
  8634. #else
  8635. if ((regVal.mRegNum >= X64Reg_INTREG_FIRST) && (regVal.mRegNum <= X64Reg_INTREG_LAST))
  8636. {
  8637. //BF_ASSERT(regVal.mType->mSize == sizeof(addr_target));
  8638. registers->mIntRegsArray[regVal.mRegNum - X64Reg_INTREG_FIRST] = value.GetInt64(); // don't sign-extend
  8639. regPtr = &registers->mIntRegsArray[regVal.mRegNum - X64Reg_INTREG_FIRST];
  8640. }
  8641. else if ((regVal.mRegNum >= X64Reg_FPSTREG_FIRST) && (regVal.mRegNum <= X64Reg_FPSTREG_LAST))
  8642. {
  8643. BF_ASSERT(regVal.mType->mSize == sizeof(float) || regVal.mType->mSize == sizeof(double));
  8644. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X64Reg_FPSTREG_FIRST];
  8645. double d;
  8646. if (regVal.mType->mSize == sizeof(float))
  8647. d = (double)value.mSingle;
  8648. else
  8649. d = value.mDouble;
  8650. ConvertDoubleToFloat80(d, reg->fp.fp80);
  8651. regPtr = reg;
  8652. }
  8653. else if ((regVal.mRegNum >= X64Reg_MMREG_FIRST) && (regVal.mRegNum <= X64Reg_MMREG_LAST))
  8654. {
  8655. BF_ASSERT(regVal.mType->mSize == sizeof(int32) || regVal.mType->mSize == sizeof(int64));
  8656. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X64Reg_MMREG_FIRST];
  8657. if (regVal.mType->mSize == sizeof(int32))
  8658. reg->mm = (uint64)value.mUInt32; // don't sign-extend
  8659. else if (regVal.mType->mSize == sizeof(int64))
  8660. reg->mm = value.mInt64;
  8661. // 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
  8662. reg->fp.fp80[8] = reg->fp.fp80[9] = 0xFF;
  8663. regPtr = reg;
  8664. }
  8665. else if ((regVal.mRegNum >= X64Reg_XMMREG_FIRST) && (regVal.mRegNum <= X64Reg_XMMREG_LAST))
  8666. {
  8667. int xmmMajor = (regVal.mRegNum - X64Reg_XMMREG_FIRST) >> 2;
  8668. int xmmMinor = (regVal.mRegNum - X64Reg_XMMREG_FIRST) & 3;
  8669. if (value.mType->GetByteCount() == 4)
  8670. registers->mXmmRegsArray[xmmMajor].f[xmmMinor] = value.mSingle;
  8671. else if (value.mType->GetByteCount() == 8)
  8672. registers->mXmmDRegsArray[xmmMajor].d[xmmMinor] = value.mDouble;
  8673. else
  8674. BF_FATAL("Invalid XMM set value type");
  8675. regPtr = &registers->mXmmRegsArray[xmmMajor];
  8676. }
  8677. else if ((regVal.mRegNum >= X64Reg_M128_XMMREG_FIRST) && (regVal.mRegNum <= X64Reg_M128_XMMREG_LAST))
  8678. {
  8679. outError = "Cannot write directly to 128-bit XMM register, please use inner float components";
  8680. return false;
  8681. }
  8682. else if ((regVal.mRegNum >= X64Reg_FLAG_FIRST) && (regVal.mRegNum <= X64Reg_FLAG_LAST))
  8683. {
  8684. int flagBit = CPURegisters::GetFlagBitForRegister(regVal.mRegNum);
  8685. if (flagBit >= 0)
  8686. {
  8687. if (value.mBool)
  8688. registers->mIntRegs.efl |= ((uint64)1 << flagBit);
  8689. else
  8690. registers->mIntRegs.efl &= ~((uint64)1 << flagBit);
  8691. regPtr = &registers->mIntRegs.efl;
  8692. }
  8693. else
  8694. {
  8695. outError = "Unrecognized flag";
  8696. return false;
  8697. }
  8698. }
  8699. else if ((regVal.mRegNum >= X64Reg_CAT_FIRST) && (regVal.mRegNum <= X64Reg_CAT_LAST))
  8700. {
  8701. outError = "Cannot write directly to register categories, please use inner float components";
  8702. return false;
  8703. }
  8704. else
  8705. BF_FATAL("Not implemented");
  8706. #endif
  8707. if (callStackIdx == 0)
  8708. {
  8709. SetRegisters(&mCallStack[0]->mRegisters);
  8710. return true;
  8711. }
  8712. else
  8713. {
  8714. bool wasSaved = false;
  8715. for (int calleeStackIdx = callStackIdx - 1; calleeStackIdx >= 0; calleeStackIdx--)
  8716. {
  8717. auto calleeRegisters = &mCallStack[calleeStackIdx]->mRegisters;
  8718. if (!mDebugTarget->PropogateRegisterUpCallStack(registers, calleeRegisters, regPtr, wasSaved))
  8719. {
  8720. outError = "Failed to set register";
  8721. return false;
  8722. }
  8723. if (wasSaved)
  8724. return true;
  8725. }
  8726. // This register wasn't saved, so commit it to the callstack top
  8727. return AssignToReg(0, regVal, value, outError);
  8728. }
  8729. }
  8730. String WinDebugger::GetAutocompleteOutput(DwAutoComplete& autoComplete)
  8731. {
  8732. String val = "\n:autocomplete\n";
  8733. if (autoComplete.mInsertStartIdx != -1)
  8734. {
  8735. val += StrFormat("insertRange\t%d %d\n", autoComplete.mInsertStartIdx, autoComplete.mInsertEndIdx);
  8736. }
  8737. Array<AutoCompleteEntry*> entries;
  8738. for (auto& entry : autoComplete.mEntriesSet)
  8739. {
  8740. entries.Add(&entry);
  8741. }
  8742. std::sort(entries.begin(), entries.end(), [](AutoCompleteEntry* lhs, AutoCompleteEntry* rhs)
  8743. {
  8744. return stricmp(lhs->mDisplay, rhs->mDisplay) < 0;
  8745. });
  8746. for (auto entry : entries)
  8747. {
  8748. val += String(entry->mEntryType);
  8749. val += "\t";
  8750. val += String(entry->mDisplay);
  8751. val += "\n";
  8752. }
  8753. /*if (autoComplete.mEntries.size() != 0)
  8754. {
  8755. for (auto& entry : autoComplete.mEntries)
  8756. {
  8757. val += String(entry.mEntryType) + "\t" + String(entry.mDisplay) + "\n";
  8758. }
  8759. }*/
  8760. return val;
  8761. }
  8762. String WinDebugger::EvaluateToAddress(const StringImpl& expr, int callStackIdx, int cursorPos)
  8763. {
  8764. AutoCrit autoCrit(mDebugManager->mCritSect);
  8765. if (IsInRunState())
  8766. return "!Target not paused";
  8767. auto dbgModule = GetCallStackDbgModule(callStackIdx);
  8768. auto dbgCompileUnit = GetCallStackCompileUnit(callStackIdx);
  8769. BfParser parser(mBfSystem);
  8770. parser.mCompatMode = true;
  8771. BfPassInstance bfPassInstance(mBfSystem);
  8772. auto terminatedExpr = expr + ";";
  8773. parser.SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  8774. parser.Parse(&bfPassInstance);
  8775. BfReducer bfReducer;
  8776. bfReducer.mAlloc = parser.mAlloc;
  8777. bfReducer.mSystem = mBfSystem;
  8778. bfReducer.mPassInstance = &bfPassInstance;
  8779. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser.mRootNode);
  8780. bfReducer.mVisitorPos.MoveNext();
  8781. bfReducer.mSource = &parser;
  8782. auto exprNode = bfReducer.CreateExpression(parser.mRootNode->GetFirst());
  8783. parser.Close();
  8784. DwAutoComplete autoComplete;
  8785. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, callStackIdx, cursorPos);
  8786. if (cursorPos != -1)
  8787. dbgExprEvaluator.mAutoComplete = &autoComplete;
  8788. dbgExprEvaluator.mDbgCompileUnit = dbgCompileUnit;
  8789. DwFormatInfo formatInfo;
  8790. formatInfo.mCallStackIdx = callStackIdx;
  8791. DbgTypedValue exprResult;
  8792. if (exprNode != NULL)
  8793. exprResult = dbgExprEvaluator.Resolve(exprNode);
  8794. DbgType* resultType = exprResult.mType->RemoveModifiers();
  8795. String val;
  8796. if (bfPassInstance.HasFailed())
  8797. {
  8798. val = StrFormat("!%d\t%d\t%s", bfPassInstance.mErrors[0]->mSrcStart, bfPassInstance.mErrors[0]->GetSrcLength(), bfPassInstance.mErrors[0]->mError.c_str());
  8799. }
  8800. else if (exprResult.mType == NULL)
  8801. {
  8802. val = "!Invalid expression";
  8803. }
  8804. else if (!resultType->IsPointerOrRef())
  8805. {
  8806. if (exprResult.mSrcAddress != 0)
  8807. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  8808. else
  8809. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  8810. }
  8811. else
  8812. {
  8813. auto innerType = resultType->mTypeParam;
  8814. int byteCount = innerType->GetByteCount();
  8815. if (byteCount == 0)
  8816. {
  8817. 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());
  8818. }
  8819. #ifdef BF_DBG_32
  8820. else if ((byteCount != 1) && (byteCount != 2) && (byteCount != 4))
  8821. {
  8822. 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);
  8823. }
  8824. #else
  8825. else if ((byteCount != 1) && (byteCount != 2) && (byteCount != 4) && (byteCount != 8))
  8826. {
  8827. 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);
  8828. }
  8829. #endif
  8830. else
  8831. {
  8832. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", byteCount);
  8833. }
  8834. }
  8835. if (cursorPos != -1)
  8836. val += GetAutocompleteOutput(autoComplete);
  8837. return val;
  8838. }
  8839. // This is currently only used for autocomplete during conditional breakpoint expression entry.
  8840. // If we want to use it for more than that then remove DwEvalExpressionFlags_ValidateOnly
  8841. String WinDebugger::EvaluateAtAddress(const StringImpl& expr, intptr atAddr, int cursorPos)
  8842. {
  8843. AutoCrit autoCrit(mDebugManager->mCritSect);
  8844. if (IsInRunState())
  8845. return "!Target not paused";
  8846. if (!IsPaused())
  8847. return "!Target not running";
  8848. WdStackFrame stackFrame;
  8849. memset(&stackFrame.mRegisters, 0, sizeof(stackFrame.mRegisters));
  8850. stackFrame.mHasGottenSubProgram = true;
  8851. *stackFrame.mRegisters.GetPCRegisterRef() = (intptr_target)atAddr;
  8852. stackFrame.mSubProgram = mDebugTarget->FindSubProgram((addr_target)atAddr);
  8853. if (stackFrame.mSubProgram == NULL)
  8854. return "!Invalid address";
  8855. mCallStack.push_back(&stackFrame);
  8856. int callStackIdx = (int)mCallStack.size() - 1;
  8857. String val = Evaluate(expr, callStackIdx, cursorPos, -1, DwEvalExpressionFlag_ValidateOnly);
  8858. mCallStack.pop_back();
  8859. return val;
  8860. }
  8861. String WinDebugger::GetAutoExpressions(int callStackIdx, uint64 memoryRangeStart, uint64 memoryRangeLen)
  8862. {
  8863. BP_ZONE("WinDebugger::GetAutoExpressions");
  8864. AutoCrit autoCrit(mDebugManager->mCritSect);
  8865. if (IsInRunState())
  8866. return "!Not paused";
  8867. if (!IsPaused())
  8868. return "!Not running";
  8869. if (!FixCallStackIdx(callStackIdx))
  8870. return "";
  8871. CPUStackFrame* stackFrame = (callStackIdx >= 0) ? mCallStack[callStackIdx] : mCallStack.front();
  8872. String result;
  8873. DbgAutoValueMapType dwarfAutos;
  8874. mDebugTarget->GetAutoValueNames(dwarfAutos, stackFrame, memoryRangeStart, memoryRangeLen);
  8875. for (auto const &a : dwarfAutos)
  8876. {
  8877. std::pair<uint64, uint64> varRange = a.mValue;
  8878. if (varRange.first != 0)
  8879. result += StrFormat("&%s\t%llu\t%llu\n", a.mKey.c_str(), varRange.second, varRange.first);
  8880. else
  8881. result += StrFormat("?%s\t%llu\n", a.mKey.c_str(), varRange.second);
  8882. }
  8883. #ifdef BF_DBG_64
  8884. // add int regs
  8885. const char* regStrs[] = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "rip", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", 0 };
  8886. #else
  8887. // add int regs
  8888. const char* regStrs[] = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "eip", 0 };
  8889. #endif
  8890. for (const char** p = regStrs; *p; ++p)
  8891. result += StrFormat("$%s\t%d\n", *p, sizeof(addr_target));
  8892. if (callStackIdx < (int)mCallStack.size() - 2)
  8893. {
  8894. WdStackFrame* prevStackFrame = mCallStack[callStackIdx + 1];
  8895. // Inlined methods have no stack frame
  8896. int stackSize = prevStackFrame->mRegisters.GetSP() - stackFrame->mRegisters.GetSP();
  8897. result += StrFormat("&$StackFrame\t%llu\t%llu\n", stackSize, stackFrame->mRegisters.GetSP());
  8898. }
  8899. return result;
  8900. }
  8901. String WinDebugger::GetAutoLocals(int stackFrameIdx, bool showRegs)
  8902. {
  8903. BP_ZONE("WinDebugger::GetAutoExpressions");
  8904. AutoCrit autoCrit(mDebugManager->mCritSect);
  8905. if (IsInRunState())
  8906. return "";
  8907. if (!IsPaused())
  8908. return "";
  8909. if (mCallStack.size() == 0)
  8910. UpdateCallStack();
  8911. String result;
  8912. Array<String> localList;
  8913. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  8914. UpdateCallStackMethod(actualStackFrameIdx);
  8915. if (actualStackFrameIdx >= mCallStack.size())
  8916. return "";
  8917. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  8918. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  8919. if (dwSubprogram == NULL)
  8920. return "";
  8921. auto langage = dwSubprogram->GetLanguage();
  8922. DbgLineData* dwLineData = FindLineDataInSubprogram(wdStackFrame->GetSourcePC(), dwSubprogram);
  8923. if (dwLineData == NULL)
  8924. return "";
  8925. dwSubprogram->PopulateSubprogram();
  8926. mDebugTarget->GetAutoLocalsInBlock(localList, dwSubprogram, &dwSubprogram->mBlock, wdStackFrame, dwLineData);
  8927. String lastLocal;
  8928. for (auto local : localList)
  8929. {
  8930. if (langage == DbgLanguage_C)
  8931. {
  8932. if ((local == "this") && (strncmp(dwSubprogram->mName, "<lambda_", 8) == 0))
  8933. {
  8934. // Use explicit "$this" so we can see the actual capture
  8935. result += "$this\n";
  8936. continue;
  8937. }
  8938. }
  8939. bool wasAlias = false;
  8940. for (int i = 0; i < (int)local.length() - 1; i++)
  8941. {
  8942. if ((local[i] == '$') && (local[i + 1] == 'a'))
  8943. {
  8944. // Alias
  8945. wasAlias = true;
  8946. String localName = local.Substring(0, i) + "\n";
  8947. if (localName != lastLocal)
  8948. {
  8949. result += localName;
  8950. lastLocal = localName;
  8951. }
  8952. break;
  8953. }
  8954. }
  8955. if (!wasAlias)
  8956. result += local + "\n";
  8957. }
  8958. if (showRegs)
  8959. {
  8960. result += "$FLAGS\n";
  8961. UpdateRegisterUsage(stackFrameIdx);
  8962. for (int regIdx = 0; regIdx < (int)wdStackFrame->mRegForms.size(); regIdx++)
  8963. {
  8964. if (wdStackFrame->mRegForms[regIdx] != RegForm_Invalid)
  8965. result += "$" + String(CPURegisters::GetRegisterName(regIdx)) + "\n";
  8966. }
  8967. }
  8968. return result;
  8969. }
  8970. String WinDebugger::CompactChildExpression(const StringImpl& expr, const StringImpl& parentExpr, int callStackIdx)
  8971. {
  8972. DbgCompileUnit* compileUnit = GetCallStackCompileUnit(callStackIdx);
  8973. DbgModule* dbgModule = GetCallStackDbgModule(callStackIdx);
  8974. if (dbgModule == NULL)
  8975. return "!failed";
  8976. DbgLanguage language = DbgLanguage_Unknown;
  8977. if (compileUnit != NULL)
  8978. language = compileUnit->mLanguage;
  8979. BfPassInstance bfPassInstance(mBfSystem);
  8980. BfParser parser(mBfSystem);
  8981. parser.mCompatMode = language != DbgLanguage_Beef;
  8982. auto terminatedExpr = expr + ";";
  8983. parser.SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  8984. parser.Parse(&bfPassInstance);
  8985. BfParser parentParser(mBfSystem);
  8986. auto terminatedParentExpr = parentExpr + ";";
  8987. parentParser.mCompatMode = language != DbgLanguage_Beef;
  8988. parentParser.SetSource(terminatedParentExpr.c_str(), terminatedParentExpr.length());
  8989. parentParser.Parse(&bfPassInstance);
  8990. BfReducer bfReducer;
  8991. bfReducer.mCompatMode = true;
  8992. bfReducer.mAlloc = parser.mAlloc;
  8993. bfReducer.mSystem = mBfSystem;
  8994. bfReducer.mPassInstance = &bfPassInstance;
  8995. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser.mRootNode);
  8996. bfReducer.mVisitorPos.MoveNext();
  8997. bfReducer.mSource = &parser;
  8998. auto exprNode = bfReducer.CreateExpression(parser.mRootNode->GetFirst());
  8999. bfReducer.mAlloc = parentParser.mAlloc;
  9000. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parentParser.mRootNode);
  9001. bfReducer.mVisitorPos.MoveNext();
  9002. auto parentExprNode = bfReducer.CreateExpression(parentParser.mRootNode->GetFirst());
  9003. parser.Close();
  9004. if ((exprNode == NULL) || (parentExprNode == NULL))
  9005. return "!failed";
  9006. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, callStackIdx, -1);
  9007. DwFormatInfo formatInfo;
  9008. formatInfo.mCallStackIdx = callStackIdx;
  9009. String formatFlags;
  9010. String assignExpr;
  9011. if ((exprNode != NULL) && (exprNode->GetSrcEnd() < (int) expr.length()))
  9012. {
  9013. formatFlags = Trim(expr.Substring(exprNode->GetSrcEnd()));
  9014. if (formatFlags.length() > 0)
  9015. {
  9016. String errorString = "Invalid expression";
  9017. if (!ParseFormatInfo(dbgModule, formatFlags, &formatInfo, &bfPassInstance, NULL, &assignExpr, &errorString))
  9018. {
  9019. bfPassInstance.FailAt(errorString, parser.mSourceData, exprNode->GetSrcEnd(), (int) expr.length() - exprNode->GetSrcEnd());
  9020. formatFlags = "";
  9021. }
  9022. }
  9023. }
  9024. dbgExprEvaluator.mExplicitThis = formatInfo.mExplicitThis;
  9025. dbgExprEvaluator.mExplicitThisExpr = parentExprNode;
  9026. DbgTypedValue exprResult = dbgExprEvaluator.Resolve(exprNode);
  9027. BfAstNode* headNode = dbgExprEvaluator.FinalizeExplicitThisReferences(exprNode);
  9028. BfPrinter printer(parser.mRootNode, NULL, NULL);
  9029. printer.mIgnoreTrivia = true;
  9030. printer.mReformatting = true;
  9031. printer.VisitChild(headNode);
  9032. auto result = printer.mOutString;
  9033. if (formatInfo.mNoVisualizers)
  9034. result += ", nv";
  9035. if (formatInfo.mNoMembers)
  9036. result += ", nm";
  9037. if (formatInfo.mNoEdit)
  9038. result += ", ne";
  9039. if (formatInfo.mIgnoreDerivedClassInfo)
  9040. result += ", nd";
  9041. if (formatInfo.mDisplayType == DwDisplayType_Ascii)
  9042. result += ", s";
  9043. if (formatInfo.mDisplayType == DwDisplayType_Utf8)
  9044. result += ", s8";
  9045. if (formatInfo.mDisplayType == DwDisplayType_Utf16)
  9046. result += ", s16";
  9047. if (formatInfo.mDisplayType == DwDisplayType_Utf32)
  9048. result += ", s32";
  9049. return result;
  9050. }
  9051. String WinDebugger::GetProcessInfo()
  9052. {
  9053. AutoCrit autoCrit(mDebugManager->mCritSect);
  9054. if ((mActiveThread == NULL) && (!mIsRunning))
  9055. return "";
  9056. SYSTEM_INFO sysinfo = { 0 };
  9057. GetSystemInfo(&sysinfo);
  9058. FILETIME creationTime = { 0 };
  9059. FILETIME exitTime = { 0 };
  9060. FILETIME kernelTime = { 0 };
  9061. FILETIME userTime = { 0 };
  9062. ::GetProcessTimes(mProcessInfo.hProcess, &creationTime, &exitTime, &kernelTime, &userTime);
  9063. String retStr;
  9064. PROCESS_MEMORY_COUNTERS memInfo = { 0 };
  9065. ::GetProcessMemoryInfo(mProcessInfo.hProcess, &memInfo, sizeof(PROCESS_MEMORY_COUNTERS));
  9066. FILETIME currentTime = { 0 };
  9067. ::GetSystemTimeAsFileTime(&currentTime);
  9068. retStr += StrFormat("VirtualMemory\t%d\n", memInfo.PagefileUsage);
  9069. retStr += StrFormat("WorkingMemory\t%d\n", memInfo.WorkingSetSize);
  9070. retStr += StrFormat("RunningTime\t%lld\n", *(int64*)&currentTime - *(int64*)&creationTime);
  9071. retStr += StrFormat("KernelTime\t%lld\n", *(int64*)&kernelTime / sysinfo.dwNumberOfProcessors);
  9072. retStr += StrFormat("UserTime\t%lld\n", *(int64*)&userTime / sysinfo.dwNumberOfProcessors);
  9073. return retStr;
  9074. }
  9075. String WinDebugger::GetThreadInfo()
  9076. {
  9077. AutoCrit autoCrit(mDebugManager->mCritSect);
  9078. String retStr;
  9079. if ((mActiveThread == NULL) && (!mIsRunning))
  9080. {
  9081. retStr = "";
  9082. }
  9083. else
  9084. {
  9085. if (mActiveThread != NULL)
  9086. retStr = StrFormat("%d", mActiveThread->mThreadId);
  9087. for (auto threadInfo : mThreadList)
  9088. {
  9089. SetAndRestoreValue<WdThreadInfo*> prevThread(mActiveThread, threadInfo);
  9090. retStr += "\n";
  9091. for (int pass = 0; pass < 2; pass++)
  9092. {
  9093. CPURegisters registers;
  9094. PopulateRegisters(&registers);
  9095. String locString = EncodeDataPtr((addr_target)registers.GetPC(), true);
  9096. TryGetThreadName(threadInfo);
  9097. bool hadThreadName = true;
  9098. String threadName = threadInfo->mName;
  9099. if (threadName.IsEmpty())
  9100. {
  9101. hadThreadName = false;
  9102. if (threadInfo->mThreadId == mProcessInfo.dwThreadId)
  9103. threadName = "Main Thread";
  9104. else
  9105. threadName = "Worker Thread";
  9106. }
  9107. bool isInvalid = false;
  9108. addr_target appendAddr = 0;
  9109. for (int stackIdx = 0; true; stackIdx++)
  9110. {
  9111. auto subProgram = mDebugTarget->FindSubProgram(registers.GetPC(), DbgOnDemandKind_LocalOnly);
  9112. if (subProgram != NULL)
  9113. {
  9114. if (subProgram->mLineInfo != NULL)
  9115. {
  9116. DbgModule* module = subProgram->mCompileUnit->mDbgModule;
  9117. DbgModule* linkedModule = module->GetLinkedModule();
  9118. if (linkedModule->mDisplayName.length() > 0)
  9119. {
  9120. locString = linkedModule->mDisplayName + "!" + subProgram->ToString();
  9121. if (!hadThreadName)
  9122. threadName = module->mDisplayName + " thread";
  9123. }
  9124. else
  9125. {
  9126. locString = subProgram->ToString();
  9127. }
  9128. appendAddr = 0;
  9129. break;
  9130. }
  9131. }
  9132. DbgModule* module = mDebugTarget->FindDbgModuleForAddress(registers.GetPC());
  9133. if (module == NULL)
  9134. {
  9135. isInvalid = true;
  9136. break;
  9137. }
  9138. DbgModule* linkedModule = module->GetLinkedModule();
  9139. appendAddr = (addr_target)registers.GetPC();
  9140. locString = linkedModule->mDisplayName + "!" + EncodeDataPtr((addr_target)registers.GetPC(), true);
  9141. if (!hadThreadName)
  9142. threadName = linkedModule->mDisplayName + " thread";
  9143. if ((mActiveThread == mExplicitStopThread) && (mActiveBreakpoint != NULL))
  9144. {
  9145. if ((subProgram == NULL) ||
  9146. (mActiveBreakpoint->mAddr < subProgram->mBlock.mLowPC) ||
  9147. (mActiveBreakpoint->mAddr >= subProgram->mBlock.mHighPC))
  9148. break;
  9149. }
  9150. if (pass == 1) // Just take the first item
  9151. break;
  9152. if (stackIdx == 128)
  9153. break; // Too many!
  9154. addr_target returnAddr;
  9155. if (!mDebugTarget->RollBackStackFrame(&registers, &returnAddr, true))
  9156. {
  9157. isInvalid = true;
  9158. break;
  9159. }
  9160. }
  9161. if ((isInvalid) && (pass == 0))
  9162. continue;
  9163. if (appendAddr != 0)
  9164. {
  9165. String symbolName;
  9166. addr_target offset;
  9167. DbgModule* dwarf;
  9168. if (mDebugTarget->FindSymbolAt(appendAddr, &symbolName, &offset, &dwarf))
  9169. {
  9170. DbgModule* linkedModule = dwarf->GetLinkedModule();
  9171. String demangledName = BfDemangler::Demangle(symbolName, DbgLanguage_Unknown);
  9172. if (!linkedModule->mDisplayName.empty())
  9173. {
  9174. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  9175. }
  9176. locString = demangledName + StrFormat("+0x%X", offset);
  9177. }
  9178. }
  9179. retStr += StrFormat("%d\t%s\t%s", threadInfo->mThreadId, threadName.c_str(), locString.c_str());
  9180. String attrs;
  9181. if (threadInfo->mFrozen)
  9182. {
  9183. attrs += "Fr";
  9184. }
  9185. if (!attrs.IsEmpty())
  9186. {
  9187. retStr += "\t";
  9188. retStr += attrs;
  9189. }
  9190. break;
  9191. }
  9192. }
  9193. }
  9194. return retStr;
  9195. }
  9196. void WinDebugger::SetActiveThread(int threadId)
  9197. {
  9198. AutoCrit autoCrit(mDebugManager->mCritSect);
  9199. if (mThreadMap.TryGetValue(threadId, &mActiveThread))
  9200. {
  9201. BfLogDbg("SetActiveThread %d\n", threadId);
  9202. ClearCallStack();
  9203. }
  9204. else
  9205. {
  9206. BfLogDbg("SetActiveThread %d FAILED\n", threadId);
  9207. }
  9208. }
  9209. int WinDebugger::GetActiveThread()
  9210. {
  9211. AutoCrit autoCrit(mDebugManager->mCritSect);
  9212. if (mActiveThread == NULL)
  9213. return -1;
  9214. return mActiveThread->mThreadId;
  9215. }
  9216. void WinDebugger::FreezeThread(int threadId)
  9217. {
  9218. AutoCrit autoCrit(mDebugManager->mCritSect);
  9219. BF_ASSERT(!IsInRunState());
  9220. auto thread = mThreadMap[threadId];
  9221. if (!thread->mFrozen)
  9222. {
  9223. thread->mFrozen = true;
  9224. ::SuspendThread(thread->mHThread);
  9225. BfLogDbg("SuspendThread %d from FreezeThread\n", thread->mThreadId);
  9226. }
  9227. }
  9228. void WinDebugger::ThawThread(int threadId)
  9229. {
  9230. AutoCrit autoCrit(mDebugManager->mCritSect);
  9231. BF_ASSERT(!IsInRunState());
  9232. auto thread = mThreadMap[threadId];
  9233. if (thread->mFrozen)
  9234. {
  9235. thread->mFrozen = false;
  9236. ::ResumeThread(thread->mHThread);
  9237. BfLogDbg("ResumeThread %d from ThawThread\n", thread->mThreadId);
  9238. }
  9239. }
  9240. bool WinDebugger::IsActiveThreadWaiting()
  9241. {
  9242. AutoCrit autoCrit(mDebugManager->mCritSect);
  9243. return mActiveThread == mDebuggerWaitingThread;
  9244. }
  9245. void WinDebugger::ClearCallStack()
  9246. {
  9247. AutoCrit autoCrit(mDebugManager->mCritSect);
  9248. BfLogDbg("ClearCallstack\n");
  9249. BF_ASSERT(mRunState != RunState_DebugEval);
  9250. for (auto wdStackFrame : mCallStack)
  9251. delete wdStackFrame;
  9252. mCallStack.Clear();
  9253. mIsPartialCallStack = true;
  9254. }
  9255. void WinDebugger::UpdateCallStack(bool slowEarlyOut)
  9256. {
  9257. AutoCrit autoCrit(mDebugManager->mCritSect);
  9258. if (!mIsPartialCallStack)
  9259. return;
  9260. BF_ASSERT(!IsInRunState());
  9261. uint32 tickStart = BFTickCount();
  9262. CPURegisters registers;
  9263. if (mCallStack.size() > 0)
  9264. {
  9265. WdStackFrame* wdStackFrame = mCallStack.back();
  9266. if (wdStackFrame->mIsEnd)
  9267. {
  9268. return;
  9269. }
  9270. memcpy(&registers, &wdStackFrame->mRegisters, sizeof(registers));
  9271. bool regsRolledBack = RollBackStackFrame(&registers, mCallStack.size() == 1);
  9272. // If we can't roll them back then mIsEnd should have been set for the previous frame
  9273. BF_ASSERT(regsRolledBack);
  9274. }
  9275. else
  9276. {
  9277. BF_ASSERT(mIsPartialCallStack);
  9278. mCallStack.Reserve(1024);
  9279. PopulateRegisters(&registers);
  9280. BfLogDbg("UpdateCallStack starting. Thread=%d PC=0x%p\n", mActiveThread->mThreadId, registers.GetPC());
  9281. }
  9282. bool isPartial = false;
  9283. // Incrementally fill callstack structure to avoid stepping slowdown during deep nesting
  9284. for (int fillIdx = 0; fillIdx < (slowEarlyOut ? 10000 : 100000); fillIdx++)
  9285. {
  9286. WdStackFrame* wdStackFrame = new WdStackFrame();
  9287. memcpy(&wdStackFrame->mRegisters, &registers, sizeof(registers));
  9288. wdStackFrame->mIsStart = mCallStack.size() == 0;
  9289. wdStackFrame->mIsEnd = false;
  9290. bool rollbackSuccess = false;
  9291. for (int tryCount = 0; tryCount < 16; tryCount++)
  9292. {
  9293. if (!RollBackStackFrame(&registers, wdStackFrame->mIsStart))
  9294. {
  9295. break;
  9296. }
  9297. if (registers.GetPC() > 0xFFFF)
  9298. {
  9299. rollbackSuccess = true;
  9300. break;
  9301. }
  9302. if (mCallStack.size() > 0)
  9303. break; // Only retry for the first frame
  9304. }
  9305. if (!rollbackSuccess)
  9306. wdStackFrame->mIsEnd = true;
  9307. if (registers.GetSP() <= wdStackFrame->mRegisters.GetSP())
  9308. {
  9309. // SP went the wrong direction, stop rolling back
  9310. wdStackFrame->mIsEnd = true;
  9311. }
  9312. mCallStack.push_back(wdStackFrame);
  9313. if (IsMiniDumpDebugger())
  9314. {
  9315. // Make sure to queue up any debug stuff we need
  9316. UpdateCallStackMethod((int)mCallStack.size() - 1);
  9317. }
  9318. if (wdStackFrame->mIsEnd)
  9319. break;
  9320. // Time-limit callstack generation. Most useful for debug mode.
  9321. if ((slowEarlyOut) && ((fillIdx % 100) == 0))
  9322. {
  9323. uint32 tickEnd = BFTickCount();
  9324. if (tickEnd - tickStart >= 10)
  9325. {
  9326. isPartial = true;
  9327. break;
  9328. }
  9329. }
  9330. }
  9331. if (!isPartial)
  9332. mIsPartialCallStack = false;
  9333. }
  9334. int WinDebugger::GetCallStackCount()
  9335. {
  9336. AutoCrit autoCrit(mDebugManager->mCritSect);
  9337. return (int)mCallStack.size();
  9338. }
  9339. int WinDebugger::GetRequestedStackFrameIdx()
  9340. {
  9341. AutoCrit autoCrit(mDebugManager->mCritSect);
  9342. if ((mActiveThread == mExplicitStopThread) && (mRequestedStackFrameIdx >= -1))
  9343. {
  9344. if (mActiveBreakpoint != NULL)
  9345. mRequestedStackFrameIdx = GetBreakStackFrameIdx();
  9346. if (mRequestedStackFrameIdx == -1)
  9347. mRequestedStackFrameIdx = 0;
  9348. return mRequestedStackFrameIdx;
  9349. }
  9350. int newCallStackIdx = 0;
  9351. while (true)
  9352. {
  9353. if (newCallStackIdx >= (int)mCallStack.size() - 1)
  9354. UpdateCallStack();
  9355. if (newCallStackIdx >= (int)mCallStack.size() - 1)
  9356. break;
  9357. intptr addr;
  9358. String file;
  9359. int hotIdx;
  9360. int defLineStart;
  9361. int defLineEnd;
  9362. int line;
  9363. int column;
  9364. int language;
  9365. int stackSize;
  9366. int8 flags;
  9367. GetStackFrameInfo(newCallStackIdx, &addr, &file, &hotIdx, &defLineStart, &defLineEnd, &line, &column, &language, &stackSize, &flags);
  9368. if (!file.empty())
  9369. return newCallStackIdx;
  9370. newCallStackIdx++;
  9371. }
  9372. return 0;
  9373. }
  9374. int WinDebugger::GetBreakStackFrameIdx()
  9375. {
  9376. AutoCrit autoCrit(mDebugManager->mCritSect);
  9377. if ((mActiveBreakpoint == NULL) || (mRunState != RunState_Breakpoint))
  9378. return -1;
  9379. if ((mBreakStackFrameIdx != -1) || (mActiveThread != mExplicitStopThread))
  9380. return mBreakStackFrameIdx;
  9381. mBreakStackFrameIdx = 0;
  9382. BF_ASSERT(mActiveBreakpoint != NULL);
  9383. if (mCallStack.IsEmpty())
  9384. UpdateCallStack();
  9385. if (!mCallStack.IsEmpty())
  9386. {
  9387. UpdateCallStackMethod(0);
  9388. for (int stackIdx = 0; stackIdx < (int)mCallStack.size(); stackIdx++)
  9389. {
  9390. auto callStackEntry = mCallStack[stackIdx];
  9391. if (callStackEntry->mSubProgram == NULL)
  9392. break;
  9393. if ((mActiveBreakpoint->mAddr < callStackEntry->mSubProgram->mBlock.mLowPC) ||
  9394. (mActiveBreakpoint->mAddr >= callStackEntry->mSubProgram->mBlock.mHighPC))
  9395. break;
  9396. DbgSubprogram* specificSubprogram = callStackEntry->mSubProgram;
  9397. auto dwLineData = callStackEntry->mSubProgram->FindClosestLine(mActiveBreakpoint->mAddr, &specificSubprogram);
  9398. if (dwLineData == NULL)
  9399. break;
  9400. if (mActiveBreakpoint->mLineData == dwLineData)
  9401. {
  9402. mBreakStackFrameIdx = stackIdx;
  9403. break;
  9404. }
  9405. }
  9406. }
  9407. return mBreakStackFrameIdx;
  9408. }
  9409. static const char* SafeString(const char* str)
  9410. {
  9411. if (str == NULL)
  9412. return "???";
  9413. return str;
  9414. }
  9415. void WinDebugger::UpdateRegisterUsage(int stackFrameIdx)
  9416. {
  9417. WdStackFrame* wdStackFrame = mCallStack[stackFrameIdx];
  9418. if (wdStackFrame->mRegForms.size() != 0)
  9419. return;
  9420. auto dwSubprogram = wdStackFrame->mSubProgram;
  9421. if (dwSubprogram == NULL)
  9422. return;
  9423. addr_target addr = dwSubprogram->mBlock.mLowPC;
  9424. const uint8* baseOp = nullptr;
  9425. while (addr < dwSubprogram->mBlock.mHighPC)
  9426. {
  9427. CPUInst inst;
  9428. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  9429. break;
  9430. bool overrideForm = inst.mAddress <= (addr_target)wdStackFrame->mRegisters.GetPC();
  9431. inst.MarkRegsUsed(wdStackFrame->mRegForms, overrideForm);
  9432. addr += inst.GetLength();
  9433. }
  9434. }
  9435. // It's safe to pass an invalid idx in here
  9436. void WinDebugger::UpdateCallStackMethod(int stackFrameIdx)
  9437. {
  9438. if (mCallStack.empty())
  9439. return;
  9440. int startIdx = std::min(stackFrameIdx, (int)mCallStack.size() - 1);
  9441. while (startIdx >= 0)
  9442. {
  9443. WdStackFrame* wdStackFrame = mCallStack[startIdx];
  9444. if (wdStackFrame->mHasGottenSubProgram)
  9445. break;
  9446. startIdx--;
  9447. }
  9448. startIdx++;
  9449. for (int checkFrameIdx = startIdx; checkFrameIdx <= stackFrameIdx; checkFrameIdx++)
  9450. {
  9451. //BF_ASSERT(checkFrameIdx < mCallStack.size());
  9452. if (checkFrameIdx >= mCallStack.size())
  9453. break;
  9454. WdStackFrame* wdStackFrame = mCallStack[checkFrameIdx];
  9455. wdStackFrame->mHasGottenSubProgram = true;
  9456. addr_target pcAddress = (addr_target)wdStackFrame->GetSourcePC();
  9457. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress, DbgOnDemandKind_LocalOnly);
  9458. wdStackFrame->mHasGottenSubProgram = true;
  9459. wdStackFrame->mSubProgram = dwSubprogram;
  9460. if ((dwSubprogram == NULL) && (IsMiniDumpDebugger()))
  9461. {
  9462. // FindSymbolAt will queue up debug info if necessary...
  9463. String symbolName;
  9464. addr_target offset;
  9465. DbgModule* dbgModule;
  9466. mDebugTarget->FindSymbolAt(pcAddress, &symbolName, &offset, &dbgModule);
  9467. }
  9468. // Insert inlines
  9469. int insertIdx = checkFrameIdx + 1;
  9470. while ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL))
  9471. {
  9472. WdStackFrame* inlineStackFrame = new WdStackFrame();
  9473. *inlineStackFrame = *wdStackFrame;
  9474. inlineStackFrame->mInInlineMethod = true;
  9475. wdStackFrame->mInInlineCall = true;
  9476. inlineStackFrame->mSubProgram = dwSubprogram->mInlineeInfo->mInlineParent;
  9477. mCallStack.Insert(insertIdx, inlineStackFrame);
  9478. dwSubprogram = dwSubprogram->mInlineeInfo->mInlineParent;
  9479. insertIdx++;
  9480. checkFrameIdx++;
  9481. }
  9482. }
  9483. }
  9484. void WinDebugger::GetCodeAddrInfo(intptr addr, String* outFile, int* outHotIdx, int* outDefLineStart, int* outDefLineEnd, int* outLine, int* outColumn)
  9485. {
  9486. AutoCrit autoCrit(mDebugManager->mCritSect);
  9487. DbgSubprogram* subProgram = NULL;
  9488. DbgLineData* callingLineData = FindLineDataAtAddress((addr_target)addr, &subProgram);
  9489. if (subProgram != NULL)
  9490. {
  9491. *outHotIdx = subProgram->mCompileUnit->mDbgModule->mHotIdx;
  9492. *outFile = subProgram->GetLineSrcFile(*callingLineData)->GetLocalPath();
  9493. *outLine = callingLineData->mLine;
  9494. *outColumn = callingLineData->mColumn;
  9495. FixupLineDataForSubprogram(subProgram);
  9496. DbgLineData* dwStartLineData = NULL;
  9497. DbgLineData* dwEndLineData = NULL;
  9498. if (subProgram->mLineInfo != NULL)
  9499. {
  9500. if (subProgram->mLineInfo->mLines.size() > 0)
  9501. {
  9502. dwStartLineData = &subProgram->mLineInfo->mLines[0];
  9503. dwEndLineData = &subProgram->mLineInfo->mLines.back();
  9504. }
  9505. }
  9506. else
  9507. {
  9508. if (subProgram->mInlineeInfo != NULL)
  9509. {
  9510. dwStartLineData = &subProgram->mInlineeInfo->mFirstLineData;
  9511. dwEndLineData = &subProgram->mInlineeInfo->mLastLineData;
  9512. }
  9513. }
  9514. if (dwEndLineData != NULL)
  9515. {
  9516. *outDefLineStart = dwStartLineData->mLine;
  9517. *outDefLineEnd = dwEndLineData->mLine;
  9518. }
  9519. }
  9520. }
  9521. void WinDebugger::GetStackAllocInfo(intptr addr, int* outThreadId, int* outStackIdx)
  9522. {
  9523. AutoCrit autoCrit(mDebugManager->mCritSect);
  9524. *outThreadId = 0;
  9525. if (outStackIdx != NULL)
  9526. *outStackIdx = -1;
  9527. if (!IsPaused())
  9528. return;
  9529. for (auto thread : mThreadList)
  9530. {
  9531. NT_TIB64 tib = { 0 };
  9532. if (!ReadMemory((intptr)thread->mThreadLocalBase, sizeof(tib), &tib))
  9533. continue;
  9534. MEMORY_BASIC_INFORMATION stackInfo = { 0 };
  9535. if (VirtualQueryEx(mProcessInfo.hProcess, (void*)(tib.StackBase - 1), &stackInfo, sizeof(MEMORY_BASIC_INFORMATION)) == 0)
  9536. continue;
  9537. if ((addr >= (intptr)stackInfo.AllocationBase) && (addr < (intptr)tib.StackBase))
  9538. {
  9539. *outThreadId = thread->mThreadId;
  9540. if (outStackIdx == NULL)
  9541. return;
  9542. if (mActiveThread == thread)
  9543. {
  9544. UpdateCallStack(false);
  9545. for (int callStackIdx = 0; callStackIdx < (int)mCallStack.size(); callStackIdx++)
  9546. {
  9547. UpdateCallStackMethod(callStackIdx);
  9548. auto stackFrame = mCallStack[callStackIdx];
  9549. if (addr >= (intptr)stackFrame->mRegisters.GetSP())
  9550. {
  9551. *outStackIdx = callStackIdx;
  9552. }
  9553. }
  9554. }
  9555. return;
  9556. }
  9557. }
  9558. }
  9559. String WinDebugger::GetStackFrameInfo(int stackFrameIdx, intptr* addr, String* outFile, int* outHotIdx, int* outDefLineStart, int* outDefLineEnd,
  9560. int* outLine, int* outColumn, int* outLanguage, int* outStackSize, int8* outFlags)
  9561. {
  9562. enum FrameFlags
  9563. {
  9564. FrameFlags_Optimized = 1,
  9565. FrameFlags_HasPendingDebugInfo = 2,
  9566. FrameFlags_CanGetOldSource = 4,
  9567. FrameFlags_WasHotReplaced = 8,
  9568. FrameFlags_HadError = 0x10
  9569. };
  9570. AutoCrit autoCrit(mDebugManager->mCritSect);
  9571. if (mCallStack.size() == 0)
  9572. UpdateCallStack();
  9573. *addr = 0;
  9574. *outFile = "";
  9575. *outHotIdx = 0;
  9576. *outDefLineStart = -1;
  9577. *outDefLineEnd = -1;
  9578. *outLine = -1;
  9579. *outColumn = 0;
  9580. *outLanguage = 0;
  9581. *outStackSize = 0;
  9582. *outFlags = 0;
  9583. UpdateCallStackMethod(stackFrameIdx);
  9584. if (stackFrameIdx >= mCallStack.size())
  9585. {
  9586. return "";
  9587. }
  9588. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9589. UpdateCallStackMethod(actualStackFrameIdx);
  9590. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9591. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  9592. if (stackFrameIdx == -1)
  9593. pcAddress = mShowPCOverride;
  9594. *addr = pcAddress;
  9595. if (actualStackFrameIdx < (int)mCallStack.size() - 2)
  9596. {
  9597. WdStackFrame* prevStackFrame = mCallStack[actualStackFrameIdx + 1];
  9598. // Inlined methods have no stack frame
  9599. *outStackSize = prevStackFrame->mRegisters.GetSP() - wdStackFrame->mRegisters.GetSP();
  9600. }
  9601. const auto& _CheckHashSrcFile = [&](String& outStr, DbgModule* dbgModule, DbgSrcFile* srcFile)
  9602. {
  9603. if (srcFile->mHashKind != DbgHashKind_None)
  9604. {
  9605. outStr += "#";
  9606. srcFile->GetHash(outStr);
  9607. }
  9608. };
  9609. auto _SetFlags = [&](DbgSubprogram* dwSubprogram)
  9610. {
  9611. DbgModule* dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  9612. if (dwSubprogram->mIsOptimized)
  9613. *outFlags |= FrameFlags_Optimized;
  9614. if (dbgModule->HasPendingDebugInfo())
  9615. *outFlags |= FrameFlags_HasPendingDebugInfo;
  9616. if (dbgModule->CanGetOldSource())
  9617. *outFlags |= FrameFlags_CanGetOldSource;
  9618. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) || (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid))
  9619. *outFlags |= FrameFlags_WasHotReplaced;
  9620. };
  9621. if (wdStackFrame->mInInlineMethod)
  9622. {
  9623. WdStackFrame* nextStackFrame = mCallStack[actualStackFrameIdx - 1];
  9624. auto subProgram = nextStackFrame->mSubProgram;
  9625. _SetFlags(subProgram);
  9626. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  9627. DbgSubprogram* parentSubprogram = subProgram->mInlineeInfo->mInlineParent; // Require it be in the inline parent
  9628. auto foundLine = parentSubprogram->FindClosestLine(subProgram->mBlock.mLowPC, &parentSubprogram);
  9629. if (foundLine != NULL)
  9630. {
  9631. auto srcFile = parentSubprogram->GetLineSrcFile(*foundLine);
  9632. *outFile = srcFile->GetLocalPath();
  9633. _CheckHashSrcFile(*outFile, subProgram->mCompileUnit->mDbgModule, srcFile);
  9634. *outLine = foundLine->mLine;
  9635. }
  9636. *outLanguage = subProgram->GetLanguage();
  9637. *outHotIdx = subProgram->mCompileUnit->mDbgModule->mHotIdx;
  9638. *outColumn = -1;
  9639. DbgSubprogram* callingSubProgram = NULL;
  9640. DbgLineData* callingLineData = FindLineDataAtAddress(nextStackFrame->mSubProgram->mBlock.mLowPC - 1, &callingSubProgram);
  9641. if ((callingLineData != NULL) && (callingSubProgram == wdStackFrame->mSubProgram))
  9642. {
  9643. auto callingSrcFile = callingSubProgram->GetLineSrcFile(*callingLineData);
  9644. *outLanguage = callingSubProgram->mCompileUnit->mLanguage;
  9645. auto srcFile = callingSrcFile;
  9646. *outFile = srcFile->GetLocalPath();
  9647. _CheckHashSrcFile(*outFile, subProgram->mCompileUnit->mDbgModule, srcFile);
  9648. if (*outLine == callingLineData->mLine)
  9649. *outColumn = callingLineData->mColumn;
  9650. }
  9651. String name = wdStackFrame->mSubProgram->ToString();
  9652. DbgModule* dbgModule = wdStackFrame->mSubProgram->mCompileUnit->mDbgModule;
  9653. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  9654. if (!linkedModule->mDisplayName.empty())
  9655. name = linkedModule->mDisplayName + "!" + name;
  9656. return name;
  9657. }
  9658. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  9659. if (dwSubprogram != NULL)
  9660. {
  9661. String demangledName;
  9662. if ((dwSubprogram->mName != NULL) && (strncmp(dwSubprogram->mName, ":Sep@", 5) == 0))
  9663. {
  9664. char* p;
  9665. auto addr = strtoll(dwSubprogram->mName + 5, &p, 16);
  9666. if (addr != 0)
  9667. {
  9668. auto parentSubprogram = mDebugTarget->FindSubProgram(addr);
  9669. if (parentSubprogram != NULL)
  9670. demangledName = parentSubprogram->ToString();
  9671. }
  9672. }
  9673. if (demangledName.IsEmpty())
  9674. {
  9675. dwSubprogram->ToString(demangledName, true);
  9676. }
  9677. DbgSrcFile* dwSrcFile = NULL;
  9678. DbgLineData* dwLineData = NULL;
  9679. FixupLineDataForSubprogram(dwSubprogram);
  9680. addr_target findAddress = wdStackFrame->GetSourcePC();
  9681. DbgSubprogram* specificSubprogram = dwSubprogram;
  9682. dwLineData = dwSubprogram->FindClosestLine(findAddress, &specificSubprogram);
  9683. if (dwLineData != NULL)
  9684. dwSrcFile = dwSubprogram->GetLineSrcFile(*dwLineData);
  9685. DbgLineData* dwStartLineData = NULL;
  9686. DbgLineData* dwEndLineData = NULL;
  9687. if (dwSubprogram->mLineInfo != NULL)
  9688. {
  9689. if (dwSubprogram->mLineInfo->mLines.size() > 0)
  9690. {
  9691. dwStartLineData = &dwSubprogram->mLineInfo->mLines[0];
  9692. dwEndLineData = &dwSubprogram->mLineInfo->mLines.back();
  9693. }
  9694. }
  9695. else
  9696. {
  9697. if (dwSubprogram->mInlineeInfo != NULL)
  9698. {
  9699. dwStartLineData = &dwSubprogram->mInlineeInfo->mFirstLineData;
  9700. dwEndLineData = &dwSubprogram->mInlineeInfo->mLastLineData;
  9701. }
  9702. }
  9703. DbgModule* dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  9704. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  9705. if (!linkedModule->mDisplayName.empty())
  9706. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  9707. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) || (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid))
  9708. demangledName = "#" + demangledName;
  9709. _SetFlags(dwSubprogram);
  9710. if ((dwLineData != NULL) && (dwSrcFile != NULL))
  9711. {
  9712. *outFile = dwSrcFile->GetLocalPath();
  9713. _CheckHashSrcFile(*outFile, dbgModule, dwSrcFile);
  9714. *outHotIdx = dbgModule->mHotIdx;
  9715. *outLine = dwLineData->mLine;
  9716. *outColumn = dwLineData->mColumn;
  9717. *outLanguage = (int)dwSubprogram->mCompileUnit->mLanguage;
  9718. if (dwEndLineData != NULL)
  9719. {
  9720. *outDefLineStart = dwStartLineData->mLine;
  9721. *outDefLineEnd = dwEndLineData->mLine;
  9722. }
  9723. return demangledName;
  9724. }
  9725. else
  9726. {
  9727. return demangledName + StrFormat("+0x%X", pcAddress - dwSubprogram->mBlock.mLowPC);
  9728. }
  9729. }
  9730. else
  9731. {
  9732. String symbolName;
  9733. addr_target offset;
  9734. DbgModule* dbgModule;
  9735. if (mDebugTarget->FindSymbolAt(pcAddress, &symbolName, &offset, &dbgModule))
  9736. {
  9737. if (dbgModule->HasPendingDebugInfo())
  9738. {
  9739. *outFlags |= FrameFlags_HasPendingDebugInfo;
  9740. if (mPendingDebugInfoLoad.ContainsKey(dbgModule))
  9741. {
  9742. String outName = EncodeDataPtr(pcAddress, true);
  9743. if ((dbgModule != NULL) && (!dbgModule->mDisplayName.empty()))
  9744. outName = dbgModule->mDisplayName + "!<Loading...>" + outName;
  9745. return outName;
  9746. }
  9747. }
  9748. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  9749. String demangledName = BfDemangler::Demangle(symbolName, DbgLanguage_Unknown);
  9750. if (!linkedModule->mDisplayName.empty())
  9751. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  9752. return demangledName + StrFormat("+0x%X", offset);
  9753. }
  9754. }
  9755. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress(pcAddress);
  9756. DbgModule* linkedModule = NULL;
  9757. if (dbgModule != NULL)
  9758. {
  9759. linkedModule = dbgModule->GetLinkedModule();
  9760. if (dbgModule->HasPendingDebugInfo())
  9761. *outFlags |= FrameFlags_HasPendingDebugInfo;
  9762. }
  9763. String outName = EncodeDataPtr(pcAddress, true);
  9764. if ((linkedModule != NULL) && (!linkedModule->mDisplayName.empty()))
  9765. outName = linkedModule->mDisplayName + "!" + outName;
  9766. return outName;
  9767. }
  9768. String WinDebugger::Callstack_GetStackFrameOldFileInfo(int stackFrameIdx)
  9769. {
  9770. AutoCrit autoCrit(mDebugManager->mCritSect);
  9771. if (!FixCallStackIdx(stackFrameIdx))
  9772. return "";
  9773. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9774. UpdateCallStackMethod(actualStackFrameIdx);
  9775. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9776. DbgModule* dbgModule = NULL;
  9777. DbgSrcFile* dbgSrcFile = NULL;
  9778. if (wdStackFrame->mInInlineMethod)
  9779. {
  9780. WdStackFrame* nextStackFrame = mCallStack[actualStackFrameIdx - 1];
  9781. auto subProgram = nextStackFrame->mSubProgram;
  9782. dbgModule = subProgram->mCompileUnit->mDbgModule;
  9783. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  9784. DbgSubprogram* parentSubprogram = subProgram->mInlineeInfo->mInlineParent; // Require it be in the inline parent
  9785. auto foundLine = parentSubprogram->FindClosestLine(subProgram->mBlock.mLowPC, &parentSubprogram);
  9786. if (foundLine != NULL)
  9787. dbgSrcFile = parentSubprogram->GetLineSrcFile(*foundLine);
  9788. DbgSubprogram* callingSubProgram = NULL;
  9789. DbgLineData* callingLineData = FindLineDataAtAddress(nextStackFrame->mSubProgram->mBlock.mLowPC - 1, &callingSubProgram);
  9790. if ((callingLineData != NULL) && (callingSubProgram == wdStackFrame->mSubProgram))
  9791. dbgSrcFile = callingSubProgram->GetLineSrcFile(*callingLineData);
  9792. }
  9793. else
  9794. {
  9795. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  9796. if (dwSubprogram != NULL)
  9797. {
  9798. FixupLineDataForSubprogram(dwSubprogram);
  9799. addr_target findAddress = wdStackFrame->GetSourcePC();
  9800. DbgSubprogram* dbgSubprogram = NULL;
  9801. DbgLineData* dwLineData = dwSubprogram->FindClosestLine(findAddress, &dbgSubprogram, &dbgSrcFile);
  9802. dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  9803. }
  9804. }
  9805. if (dbgSrcFile != NULL)
  9806. {
  9807. // Note: we must use mFilePath here, make sure we don't use GetLocalPath()
  9808. return dbgModule->GetOldSourceCommand(dbgSrcFile->mFilePath);
  9809. }
  9810. return "";
  9811. }
  9812. int WinDebugger::GetJmpState(int stackFrameIdx)
  9813. {
  9814. AutoCrit autoCrit(mDebugManager->mCritSect);
  9815. if (!FixCallStackIdx(stackFrameIdx))
  9816. return -1;
  9817. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9818. UpdateCallStackMethod(actualStackFrameIdx);
  9819. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9820. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  9821. CPUInst inst;
  9822. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  9823. return -1;
  9824. return inst.GetJmpState(wdStackFrame->mRegisters.mIntRegs.efl);
  9825. }
  9826. intptr WinDebugger::GetStackFrameCalleeAddr(int stackFrameIdx)
  9827. {
  9828. AutoCrit autoCrit(mDebugManager->mCritSect);
  9829. if (!FixCallStackIdx(stackFrameIdx))
  9830. return -1;
  9831. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9832. UpdateCallStackMethod(actualStackFrameIdx);
  9833. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9834. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  9835. if (stackFrameIdx == -1)
  9836. pcAddress = mShowPCOverride;
  9837. if (wdStackFrame->mInInlineMethod)
  9838. {
  9839. WdStackFrame* inlineStackFrame = mCallStack[actualStackFrameIdx - 1];
  9840. return inlineStackFrame->mSubProgram->mBlock.mLowPC - 1;
  9841. }
  9842. return pcAddress - 1;
  9843. }
  9844. String WinDebugger::GetStackMethodOwner(int stackFrameIdx, int& language)
  9845. {
  9846. AutoCrit autoCrit(mDebugManager->mCritSect);
  9847. if (!FixCallStackIdx(stackFrameIdx))
  9848. return "";
  9849. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9850. if (actualStackFrameIdx >= (int)mCallStack.size())
  9851. actualStackFrameIdx = 0;
  9852. UpdateCallStackMethod(actualStackFrameIdx);
  9853. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9854. if (wdStackFrame->mSubProgram == NULL)
  9855. return "";
  9856. auto parentType = wdStackFrame->mSubProgram->GetParent();
  9857. if (parentType == NULL)
  9858. return "";
  9859. parentType = parentType->GetPrimaryType();
  9860. language = (int)parentType->GetLanguage();
  9861. return parentType->ToString();
  9862. }
  9863. String WinDebugger::FindCodeAddresses(const StringImpl& fileName, int line, int column, bool allowAutoResolve)
  9864. {
  9865. String result;
  9866. if (mDebugTarget == NULL)
  9867. return "";
  9868. DbgSrcFile* srcFile = mDebugTarget->GetSrcFile(fileName);
  9869. if (srcFile == NULL)
  9870. return result;
  9871. bool foundInSequence = false;
  9872. WdBreakpoint* prevBreakpoint = NULL;
  9873. int bestLineOffset = 0x7FFFFFFF;
  9874. for (auto dbgSubprogram : srcFile->mLineDataRefs)
  9875. {
  9876. for (auto& lineData : dbgSubprogram->mLineInfo->mLines)
  9877. {
  9878. auto lineSrcFile = dbgSubprogram->GetLineSrcFile(lineData);
  9879. if (lineSrcFile != srcFile)
  9880. continue;
  9881. int lineOffset = lineData.mLine - line;
  9882. if ((lineOffset >= 0) && (lineOffset <= 12) && (lineOffset <= bestLineOffset))
  9883. {
  9884. if (lineOffset < bestLineOffset)
  9885. {
  9886. bestLineOffset = lineOffset;
  9887. result = "";
  9888. }
  9889. if (!foundInSequence)
  9890. {
  9891. auto addr = dbgSubprogram->GetLineAddr(lineData);
  9892. result += EncodeDataPtr(addr, false) + "\t" + dbgSubprogram->ToString() + "\n";
  9893. }
  9894. }
  9895. // New sequence?
  9896. if (!lineData.IsStackFrameSetup())
  9897. foundInSequence = false;
  9898. }
  9899. }
  9900. return result;
  9901. }
  9902. String WinDebugger::GetAddressSourceLocation(intptr address)
  9903. {
  9904. DbgSubprogram* subProgram = NULL;
  9905. DbgLineData* lineData = FindLineDataAtAddress(address, &subProgram);
  9906. if (lineData != NULL)
  9907. return StrFormat("%s:%d:%d", subProgram->GetLineSrcFile(*lineData)->GetLocalPath().c_str(), lineData->mLine + 1, lineData->mColumn + 1);
  9908. String outSymbol;
  9909. addr_target offset = 0;
  9910. DbgModule* dbgModule;
  9911. if (mDebugTarget->FindSymbolAt(address, &outSymbol, &offset, &dbgModule))
  9912. {
  9913. if (offset < 0x10000)
  9914. {
  9915. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9916. if (offset > 0)
  9917. outSymbol += StrFormat("+%x", offset);
  9918. return outSymbol;
  9919. }
  9920. }
  9921. return StrFormat("0x%@", address);
  9922. }
  9923. String WinDebugger::GetAddressSymbolName(intptr address, bool demangle)
  9924. {
  9925. String outSymbol;
  9926. addr_target offset = 0;
  9927. DbgModule* dbgModule;
  9928. if (mDebugTarget->FindSymbolAt(address, &outSymbol, &offset, &dbgModule))
  9929. {
  9930. if (offset < 0x10000)
  9931. {
  9932. if (demangle)
  9933. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9934. if (offset > 0)
  9935. outSymbol += StrFormat("+%x", offset);
  9936. return outSymbol;
  9937. }
  9938. }
  9939. return StrFormat("0x%@", address);
  9940. }
  9941. String WinDebugger::DisassembleAtRaw(intptr inAddress)
  9942. {
  9943. addr_target address = (addr_target)inAddress;
  9944. const int addrBorder = 1024;
  9945. for (int offset = 0; offset < 8; offset++)
  9946. {
  9947. String result;
  9948. bool addOffset = true;
  9949. bool hadAddr = false;
  9950. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress(address);
  9951. DbgModuleMemoryCache* memCache = NULL;
  9952. defer
  9953. (
  9954. if (dbgModule == NULL)
  9955. delete memCache;
  9956. );
  9957. if ((dbgModule != NULL) && (dbgModule->mOrigImageData == NULL))
  9958. dbgModule = NULL;
  9959. result += "R\n"; // Raw
  9960. addr_target addrStart = address;
  9961. if (dbgModule != NULL)
  9962. {
  9963. dbgModule->ParseSymbolData();
  9964. memCache = dbgModule->mOrigImageData;
  9965. addrStart = BF_MAX((addr_target)dbgModule->mImageBase, address - addrBorder - offset);
  9966. }
  9967. else
  9968. {
  9969. memCache = new DbgModuleMemoryCache(addrStart & (4096 - 1), 4096 * 2);
  9970. }
  9971. //addr_target imageBase = dbgModule->mImageBase;
  9972. //int imageSize = dbgModule->mImageSize;
  9973. addr_target dataAddr = addrStart;
  9974. addr_target addrEnd = addrStart + addrBorder * 2 + 16;
  9975. while (dataAddr < addrEnd)
  9976. {
  9977. if (dataAddr == address)
  9978. hadAddr = true;
  9979. if (dataAddr > address)
  9980. {
  9981. if (!hadAddr)
  9982. {
  9983. if (offset == 7)
  9984. {
  9985. dataAddr = address;
  9986. }
  9987. break;
  9988. }
  9989. }
  9990. String outSymbol;
  9991. addr_target symOffset = 0;
  9992. DbgModule* symDWARF;
  9993. if (mDebugTarget->FindSymbolAt(dataAddr, &outSymbol, &symOffset, &symDWARF))
  9994. {
  9995. if (symOffset == 0)
  9996. {
  9997. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9998. if ((symDWARF != NULL) && (!symDWARF->mDisplayName.empty()))
  9999. outSymbol = symDWARF->GetLinkedModule()->mDisplayName + "!" + outSymbol;
  10000. result += "T " + outSymbol + ":\n";
  10001. }
  10002. }
  10003. CPUInst inst;
  10004. if (!mCPU->Decode(dataAddr, memCache, &inst))
  10005. {
  10006. if ((offset == 7) && (!hadAddr))
  10007. {
  10008. uint8 instData[1];
  10009. memCache->Read(dataAddr, instData, 1);
  10010. int instLen = 1;
  10011. #ifdef BF_DBG_32
  10012. result += StrFormat("D %08X: ", dataAddr);
  10013. #else
  10014. result += StrFormat("D %@: ", dataAddr);
  10015. #endif
  10016. for (int i = 0; i < instLen; i++)
  10017. result += StrFormat("%02X ", instData[i]);
  10018. for (int i = instLen; i < 8; i++)
  10019. result += " ";
  10020. result += "\n";
  10021. dataAddr++;
  10022. continue;
  10023. }
  10024. break;
  10025. }
  10026. int instLen = inst.GetLength();
  10027. #ifdef BF_DBG_32
  10028. result += StrFormat("D %08X: ", dataAddr);
  10029. #else
  10030. result += StrFormat("D %@: ", dataAddr);
  10031. #endif
  10032. uint8 instData[32];
  10033. int showInstLen = BF_MIN(32, instLen);
  10034. memCache->Read(dataAddr, instData, showInstLen);
  10035. for (int i = 0; i < showInstLen; i++)
  10036. result += StrFormat("%02X ", instData[i]);
  10037. for (int i = instLen; i < 8; i++)
  10038. result += " ";
  10039. result += mCPU->InstructionToString(&inst, dataAddr);
  10040. if ((inst.IsCall()) || (inst.IsBranch()))
  10041. {
  10042. addr_target targetAddr = inst.GetTarget();
  10043. if (targetAddr != 0)
  10044. {
  10045. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &symOffset))
  10046. {
  10047. if (symOffset < 0x10000)
  10048. {
  10049. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  10050. result += " ; " + outSymbol;
  10051. if (symOffset > 0)
  10052. result += StrFormat("+%x", symOffset);
  10053. //result += ">";
  10054. }
  10055. }
  10056. }
  10057. }
  10058. result += "\n";
  10059. dataAddr += instLen;
  10060. }
  10061. if (!hadAddr)
  10062. continue;
  10063. return result;
  10064. }
  10065. return "";
  10066. }
  10067. String WinDebugger::DisassembleAt(intptr inAddress)
  10068. {
  10069. BP_ZONE("WinDebugger::DisassembleAt");
  10070. AutoCrit autoCrit(mDebugManager->mCritSect);
  10071. addr_target address = (addr_target)inAddress;
  10072. if (mDebugTarget == NULL)
  10073. return "";
  10074. String result;
  10075. auto dwSubProgram = mDebugTarget->FindSubProgram(address);
  10076. if (dwSubProgram == NULL)
  10077. return DisassembleAtRaw(address);
  10078. dwSubProgram = dwSubProgram->GetRootInlineParent();
  10079. DbgModule* dwarf = dwSubProgram->mCompileUnit->mDbgModule;
  10080. int frameBaseRegister = mDebugTarget->GetFrameBaseRegister(dwSubProgram);
  10081. addr_target addrStart = dwSubProgram->mBlock.mLowPC;
  10082. addr_target addrEnd = dwSubProgram->mBlock.mHighPC;
  10083. auto dwCompileUnit = dwSubProgram->mCompileUnit;
  10084. {
  10085. FixupLineData(dwCompileUnit);
  10086. }
  10087. DbgSrcFile* dwSrcFile = NULL;
  10088. FixupLineDataForSubprogram(dwSubProgram);
  10089. DbgLineData* dwLineData = NULL;
  10090. if (dwSubProgram->mLineInfo != NULL)
  10091. dwLineData = &dwSubProgram->mLineInfo->mLines[0];
  10092. int nextLineDataIdx = 1;
  10093. if (dwSubProgram->mIsOptimized)
  10094. result += "O\n";
  10095. DbgSrcFile* srcFile = NULL;
  10096. int firstLine = 0;
  10097. int curLine = 0;
  10098. if (dwLineData != NULL)
  10099. {
  10100. srcFile = dwSubProgram->GetLineSrcFile(*dwLineData);
  10101. result += "S " + srcFile->GetLocalPath() + "\n";
  10102. if (srcFile->mHashKind != DbgHashKind_None)
  10103. {
  10104. result += "H ";
  10105. srcFile->GetHash(result);
  10106. result += "\n";
  10107. }
  10108. curLine = BF_MAX(0, dwLineData->mLine - 5);
  10109. //for (; curLine <= dwLineData->mLine; curLine++)
  10110. result += StrFormat("L %d %d\n", curLine, dwLineData->mLine - curLine + 1);
  10111. curLine = dwLineData->mLine + 1;
  10112. firstLine = dwLineData->mLine;
  10113. }
  10114. Array<DbgSubprogram*> inlineStack;
  10115. Array<DbgBlock*> blockList;
  10116. blockList.push_back(&dwSubProgram->mBlock);
  10117. addr_target dataAddr = addrStart;
  10118. int decodeFailureCount = 0;
  10119. auto& _PopInlineStack = [&]()
  10120. {
  10121. int depth = inlineStack.size();
  10122. auto curStackEntry = inlineStack.back();
  10123. if (depth > 1)
  10124. result += StrFormat("T <<<%d Inline End ", depth);
  10125. else
  10126. result += "T <<< Inline End ";
  10127. result += curStackEntry->ToString();
  10128. result += "\n";
  10129. inlineStack.pop_back();
  10130. };
  10131. std::function<void(DbgSubprogram* subprogram, int depth)> _UpdateInlineStackHelper = [&](DbgSubprogram* subprogram, int depth)
  10132. {
  10133. int stackIdx = depth - 1;
  10134. if (stackIdx < inlineStack.size())
  10135. {
  10136. auto curStackEntry = inlineStack[stackIdx];
  10137. if (curStackEntry != subprogram)
  10138. _PopInlineStack();
  10139. }
  10140. if (depth > 1)
  10141. {
  10142. _UpdateInlineStackHelper(subprogram->mInlineeInfo->mInlineParent, depth - 1);
  10143. }
  10144. if (stackIdx >= inlineStack.size())
  10145. {
  10146. if (depth > 1)
  10147. result += StrFormat("T >>>%d Inline ", depth);
  10148. else
  10149. result += "T >>> Inline ";
  10150. result += subprogram->ToString();
  10151. result += "\n";
  10152. inlineStack.push_back(subprogram);
  10153. }
  10154. };
  10155. auto _UpdateInlineStack = [&](DbgSubprogram* subprogram)
  10156. {
  10157. if (subprogram == NULL)
  10158. {
  10159. while (!inlineStack.IsEmpty())
  10160. _PopInlineStack();
  10161. return;
  10162. }
  10163. int inlineDepth = subprogram->GetInlineDepth();
  10164. while (inlineDepth < inlineStack.size())
  10165. _PopInlineStack();
  10166. if (inlineDepth > 0)
  10167. _UpdateInlineStackHelper(subprogram, inlineDepth);
  10168. };
  10169. while (dataAddr < addrEnd)
  10170. {
  10171. // Pop off old scopes
  10172. while (blockList.size() > 0)
  10173. {
  10174. auto lastBlock = blockList.back();
  10175. if (dataAddr < lastBlock->mHighPC)
  10176. break;
  10177. blockList.pop_back();
  10178. }
  10179. // Check entry into new child scopes
  10180. auto lastBlock = blockList.back();
  10181. for (auto checkBlock : lastBlock->mSubBlocks)
  10182. {
  10183. if ((dataAddr >= checkBlock->mLowPC) && (dataAddr < checkBlock->mHighPC))
  10184. {
  10185. blockList.push_back(checkBlock);
  10186. break;
  10187. }
  10188. }
  10189. bool allowSourceJump = false;
  10190. if ((dwLineData != NULL) && (dwLineData->mContribSize != 0) && (dataAddr >= dwSubProgram->GetLineAddr(*dwLineData) + dwLineData->mContribSize))
  10191. {
  10192. DbgSubprogram* inlinedSubprogram = NULL;
  10193. auto inlinedLine = dwSubProgram->FindClosestLine(dataAddr, &inlinedSubprogram);
  10194. _UpdateInlineStack(dwSubProgram);
  10195. }
  10196. // Update line data
  10197. while ((dwLineData != NULL) && (dwSubProgram->GetLineAddr(*dwLineData) <= dataAddr))
  10198. {
  10199. _UpdateInlineStack(dwSubProgram->GetLineInlinee(*dwLineData));
  10200. const int lineLimit = 5; // 15
  10201. if (allowSourceJump)
  10202. curLine = dwLineData->mLine;
  10203. auto lineSrcFile = dwSubProgram->GetLineSrcFile(*dwLineData);
  10204. if (lineSrcFile != srcFile)
  10205. {
  10206. srcFile = lineSrcFile;
  10207. result += "S ";
  10208. result += srcFile->GetLocalPath();
  10209. result += "\n";
  10210. // Just show the one line from the new file
  10211. curLine = dwLineData->mLine;
  10212. }
  10213. if (dwLineData->mLine < curLine - 1)
  10214. {
  10215. // Jumping backwards - possibly into inlined method, or possibly in current method.
  10216. // Show previous 6 lines, for context
  10217. curLine = BF_MAX(0, dwLineData->mLine - lineLimit);
  10218. }
  10219. if ((curLine <= firstLine) && (dwLineData->mLine >= firstLine))
  10220. {
  10221. // Jumping from inlined method (declared above) back into main method
  10222. curLine = dwLineData->mLine;
  10223. }
  10224. if (curLine < dwLineData->mLine - lineLimit)
  10225. {
  10226. // Don't show huge span of source - only show the last 6 lines at maximum
  10227. curLine = dwLineData->mLine - lineLimit;
  10228. }
  10229. //for ( ; curLine <= dwLineData->mLine; curLine++)
  10230. result += StrFormat("L %d %d\n", curLine, dwLineData->mLine - curLine + 1);
  10231. curLine = dwLineData->mLine + 1;
  10232. DbgLineData* nextLineData = NULL;
  10233. while (nextLineDataIdx < dwSubProgram->mLineInfo->mLines.mSize)
  10234. {
  10235. nextLineData = &dwSubProgram->mLineInfo->mLines[nextLineDataIdx];
  10236. //TODO:
  10237. /*{
  10238. result += StrFormat("T LineIdx: %d (%@ to %@)", nextLineDataIdx, dwSubProgram->GetLineAddr(*nextLineData), dwSubProgram->GetLineAddr(*nextLineData) + nextLineData->mContribSize);
  10239. auto inlinee = dwSubProgram->GetLineInlinee(*nextLineData);
  10240. if (inlinee != NULL)
  10241. {
  10242. result += StrFormat(" Inlinee: %s Depth: %d", inlinee->mName, inlinee->GetInlineDepth());
  10243. }
  10244. result += "\n";
  10245. }*/
  10246. auto nextLineAddr = dwSubProgram->GetLineAddr(*nextLineData);
  10247. if (nextLineAddr > dataAddr)
  10248. {
  10249. if (nextLineDataIdx + 1 < dwSubProgram->mLineInfo->mLines.mSize)
  10250. {
  10251. auto peekLineData = &dwSubProgram->mLineInfo->mLines[nextLineDataIdx + 1];
  10252. if (peekLineData->mRelAddress == nextLineData->mRelAddress)
  10253. {
  10254. // Use the later entry
  10255. ++nextLineDataIdx;
  10256. continue;
  10257. }
  10258. }
  10259. break;
  10260. }
  10261. // If we go back to an older entry beacuse of a gap then we need to catch back up...
  10262. ++nextLineDataIdx;
  10263. nextLineData = NULL; // Keep searching...
  10264. }
  10265. dwLineData = nextLineData;
  10266. nextLineDataIdx++;
  10267. }
  10268. // Have we gone off the end of the inline function?
  10269. // We may not have an explicit non-inlined line data at the transition point...
  10270. while (!inlineStack.IsEmpty())
  10271. {
  10272. auto subProgram = inlineStack.back();
  10273. if (dataAddr < subProgram->mBlock.mHighPC)
  10274. break;
  10275. _PopInlineStack();
  10276. }
  10277. bool hadDecodeFailure = false;
  10278. CPUInst inst;
  10279. if (!mCPU->Decode(dataAddr, dwarf->mOrigImageData, &inst))
  10280. hadDecodeFailure = true;
  10281. if ((decodeFailureCount == 8) || ((decodeFailureCount > 0) && (!hadDecodeFailure)))
  10282. {
  10283. for (int i = decodeFailureCount; i < 4 + sizeof(addr_target); i++)
  10284. result += " ";
  10285. result += " ???\n";
  10286. decodeFailureCount = 0;
  10287. }
  10288. if (decodeFailureCount == 0)
  10289. {
  10290. #ifdef BF_DBG_32
  10291. result += StrFormat("D %08X: ", dataAddr);
  10292. #else
  10293. result += StrFormat("D %@: ", dataAddr);
  10294. #endif
  10295. }
  10296. if (hadDecodeFailure)
  10297. {
  10298. uint8 byte = 0;
  10299. dwarf->mOrigImageData->Read(dataAddr, &byte, 1);
  10300. result += StrFormat("%02X ", byte);
  10301. dataAddr++;
  10302. decodeFailureCount++;
  10303. continue;
  10304. }
  10305. int instLen = inst.GetLength();
  10306. uint8 instData[32];
  10307. int showInstLen = BF_MIN(32, instLen);
  10308. dwarf->mOrigImageData->Read(dataAddr, instData, showInstLen);
  10309. for (int i = 0; i < showInstLen; i++)
  10310. result += StrFormat("%02X ", instData[i]);
  10311. for (int i = instLen; i < 4 + sizeof(addr_target); i++)
  10312. result += " ";
  10313. result += " ";
  10314. result += mCPU->InstructionToString(&inst, dataAddr);
  10315. int reg;
  10316. int offset;
  10317. if (inst.GetIndexRegisterAndOffset(&reg, &offset))
  10318. {
  10319. for (int blockIdx = (int)blockList.size() - 1; blockIdx >= 0; blockIdx--)
  10320. {
  10321. auto dwBlock = blockList[blockIdx];
  10322. for (auto variable : dwBlock->mVariables)
  10323. {
  10324. int varRegister;
  10325. int varOffset;
  10326. if (mDebugTarget->GetVariableIndexRegisterAndOffset(variable, &varRegister, &varOffset))
  10327. {
  10328. if (varRegister == -1)
  10329. varRegister = frameBaseRegister;
  10330. if ((reg == varRegister) && (offset == varOffset))
  10331. {
  10332. result += " ; ";
  10333. result += variable->mName;
  10334. break;
  10335. }
  10336. }
  10337. }
  10338. }
  10339. }
  10340. else if ((inst.IsCall()) || (inst.IsBranch()) || (inst.IsLoadAddress()))
  10341. {
  10342. addr_target targetAddr = inst.GetTarget();
  10343. if (targetAddr != 0)
  10344. {
  10345. if ((targetAddr >= addrStart) && (targetAddr < addrEnd))
  10346. {
  10347. result += StrFormat("\nJ %s", EncodeDataPtr(targetAddr, false).c_str());
  10348. }
  10349. else
  10350. {
  10351. String outSymbol;
  10352. addr_target offset = 0;
  10353. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &offset))
  10354. {
  10355. if (offset < 0x10000)
  10356. {
  10357. outSymbol = BfDemangler::Demangle(outSymbol, dwSubProgram->GetLanguage());
  10358. result += " ; " + outSymbol;
  10359. if (offset > 0)
  10360. result += StrFormat("+%x", offset);
  10361. }
  10362. }
  10363. }
  10364. }
  10365. }
  10366. result += "\n";
  10367. dataAddr += instLen;
  10368. }
  10369. // Why did we want to "show lines at end"??
  10370. // Show lines at end
  10371. /*if (curLine > 0)
  10372. {
  10373. for (int i = 0; i < 6; i++, curLine++)
  10374. result += StrFormat("L %d\n", curLine);
  10375. }*/
  10376. return result;
  10377. }
  10378. String WinDebugger::FindLineCallAddresses(intptr inAddress)
  10379. {
  10380. String callAddresses;
  10381. addr_target address = (addr_target)inAddress;
  10382. DbgSubprogram* dwSubprogram = NULL;
  10383. DbgLineData* startLineData = FindLineDataAtAddress(address, &dwSubprogram, NULL);
  10384. if (dwSubprogram == NULL)
  10385. return "";
  10386. CPURegisters registers;
  10387. PopulateRegisters(&registers);
  10388. auto inlinerSubprogram = dwSubprogram->GetRootInlineParent();
  10389. FixupLineDataForSubprogram(inlinerSubprogram);
  10390. if (inlinerSubprogram->mLineInfo->mLines.mSize == 0)
  10391. return "";
  10392. auto lineData = &inlinerSubprogram->mLineInfo->mLines[0];
  10393. addr_target addr = dwSubprogram->mBlock.mLowPC;
  10394. addr_target endAddr = dwSubprogram->mBlock.mHighPC;
  10395. DbgSubprogram* checkSubprogram = dwSubprogram;
  10396. DbgLineData* checkLineData = lineData;
  10397. addr_target checkLineAddr = 0;
  10398. int lineIdx = 0;
  10399. while (checkLineData != NULL)
  10400. {
  10401. //auto nextLineData = dwSubprogram->mCompileUnit->mLineDataMap.GetNext(checkLineData);
  10402. ++lineIdx;
  10403. DbgLineData* nextLineData = NULL;
  10404. addr_target nextLineAddr;
  10405. if (lineIdx < inlinerSubprogram->mLineInfo->mLines.size())
  10406. {
  10407. nextLineData = &inlinerSubprogram->mLineInfo->mLines[lineIdx];
  10408. nextLineAddr = dwSubprogram->GetLineAddr(*nextLineData);
  10409. }
  10410. else
  10411. nextLineAddr = inlinerSubprogram->mBlock.mHighPC;
  10412. // This stuff doesn't make sense...
  10413. DbgSubprogram* nextSubProgram;
  10414. if (nextLineData != NULL)
  10415. {
  10416. if (nextLineAddr > dwSubprogram->mBlock.mHighPC)
  10417. break;
  10418. endAddr = nextLineAddr;
  10419. nextSubProgram = mDebugTarget->FindSubProgram(endAddr);
  10420. if (nextSubProgram != NULL)
  10421. {
  10422. auto dbgModule = nextSubProgram->mCompileUnit->mDbgModule;
  10423. dbgModule->ParseSymbolData();
  10424. }
  10425. }
  10426. else
  10427. {
  10428. nextSubProgram = dwSubprogram;
  10429. endAddr = dwSubprogram->mBlock.mHighPC;
  10430. }
  10431. auto _HandleSection = [&]()
  10432. {
  10433. while (addr < endAddr)
  10434. {
  10435. CPUInst inst;
  10436. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  10437. break;
  10438. *registers.GetPCRegisterRef() = addr;
  10439. if (inst.IsCall())
  10440. {
  10441. bool addSymbol = true;
  10442. if (addr < (addr_target)inAddress)
  10443. callAddresses += "-";
  10444. callAddresses += EncodeDataPtr(addr, false);
  10445. addr_target targetAddr = inst.GetTarget(this, &registers);
  10446. if (targetAddr != 0)
  10447. {
  10448. String outSymbol;
  10449. auto subprogram = mDebugTarget->FindSubProgram(targetAddr);
  10450. if (subprogram != NULL)
  10451. {
  10452. CreateFilterName(outSymbol, subprogram);
  10453. addSymbol = true;
  10454. }
  10455. else
  10456. {
  10457. addr_target offset = 0;
  10458. String fullSymbolName;
  10459. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &offset))
  10460. {
  10461. if (offset < 0x200)
  10462. {
  10463. //outSymbol = BfDemangler::Demangle(outSymbol, dwSubprogram->GetLanguage());
  10464. if (outSymbol == "___chkstk_ms")
  10465. addSymbol = false;
  10466. else
  10467. {
  10468. String demangledName = BfDemangler::Demangle(outSymbol, DbgLanguage_C);
  10469. outSymbol.clear();
  10470. CreateFilterName(outSymbol, demangledName.c_str(), DbgLanguage_C);
  10471. }
  10472. }
  10473. else
  10474. outSymbol.clear();
  10475. }
  10476. }
  10477. if (addSymbol)
  10478. {
  10479. if (outSymbol.empty())
  10480. callAddresses += "\tFunc@" + EncodeDataPtr(targetAddr, false);
  10481. else
  10482. callAddresses += "\t" + outSymbol;
  10483. String attrs;
  10484. bool isFiltered = false;
  10485. if (subprogram != NULL)
  10486. {
  10487. subprogram->PopulateSubprogram();
  10488. isFiltered = subprogram->mIsStepFilteredDefault;
  10489. if (isFiltered)
  10490. attrs += "d"; // 'd' for default filtered
  10491. }
  10492. StepFilter* stepFilterPtr = NULL;
  10493. if (mDebugManager->mStepFilters.TryGetValue(outSymbol, &stepFilterPtr))
  10494. isFiltered = stepFilterPtr->IsFiltered(isFiltered);
  10495. if (isFiltered)
  10496. attrs += "f"; // 'f' for filter
  10497. if (!attrs.IsEmpty())
  10498. callAddresses += "\t" + attrs;
  10499. }
  10500. }
  10501. if (addSymbol)
  10502. callAddresses += "\n";
  10503. }
  10504. inst.PartialSimulate(this, &registers);
  10505. addr += inst.GetLength();
  10506. }
  10507. };
  10508. // For inlining - only add calls that are found either directly in our main block (not an inlined block)
  10509. // But add inlined methods when their parent is our current block
  10510. if ((checkSubprogram == dwSubprogram) && (checkLineData->mLine == startLineData->mLine))
  10511. {
  10512. _HandleSection();
  10513. }
  10514. else if ((checkSubprogram->mInlineeInfo != NULL) && (checkSubprogram->mInlineeInfo->mInlineParent == dwSubprogram))
  10515. {
  10516. if (checkLineAddr == checkSubprogram->mBlock.mLowPC)
  10517. {
  10518. addr_target inlineStartAddr = checkSubprogram->mBlock.mLowPC;
  10519. // Find the calling line
  10520. DbgSubprogram* callingSubprogram = dwSubprogram;
  10521. auto checkLineData = dwSubprogram->FindClosestLine(inlineStartAddr, &callingSubprogram);
  10522. if ((checkLineData != NULL) && (checkLineData->mCtxIdx == startLineData->mCtxIdx) && (checkLineData->mLine == startLineData->mLine))
  10523. {
  10524. if (inlineStartAddr <= (addr_target)inAddress)
  10525. callAddresses += "-";
  10526. callAddresses += EncodeDataPtr(inlineStartAddr, false);
  10527. String outSymbol;
  10528. CreateFilterName(outSymbol, checkSubprogram);
  10529. callAddresses += "\t" + outSymbol;
  10530. bool isFiltered = dwSubprogram->mIsStepFilteredDefault;
  10531. StepFilter* stepFilterPtr;
  10532. if (mDebugManager->mStepFilters.TryGetValue(outSymbol, &stepFilterPtr))
  10533. isFiltered = stepFilterPtr->IsFiltered(isFiltered);
  10534. if (isFiltered)
  10535. callAddresses += "\tf"; // 'f' for filter
  10536. callAddresses += "\n";
  10537. }
  10538. // if (checkSubprogram->mBlock.mHighPC < endAddr)
  10539. // {
  10540. // addr = checkSubprogram->mBlock.mHighPC;
  10541. // _HandleSection();
  10542. // }
  10543. }
  10544. // If we have unattributed data after the end of an inlined method, add that
  10545. if ((endAddr > checkSubprogram->mBlock.mHighPC) && (nextSubProgram == dwSubprogram))
  10546. {
  10547. addr = checkSubprogram->mBlock.mHighPC;
  10548. _HandleSection();
  10549. }
  10550. }
  10551. checkLineData = nextLineData;
  10552. checkSubprogram = nextSubProgram;
  10553. checkLineAddr = nextLineAddr;
  10554. addr = endAddr;
  10555. }
  10556. return callAddresses;
  10557. }
  10558. String WinDebugger::GetCurrentException()
  10559. {
  10560. AutoCrit autoCrit(mDebugManager->mCritSect);
  10561. String result = StrFormat("%s\n%08X",
  10562. EncodeDataPtr((addr_target)(intptr)mCurException.ExceptionAddress, true).c_str(),
  10563. mCurException.ExceptionCode);
  10564. String exStr;
  10565. switch (mCurException.ExceptionCode)
  10566. {
  10567. case EXCEPTION_ACCESS_VIOLATION:
  10568. {
  10569. String accessType;
  10570. if (mCurException.ExceptionInformation[0] == 0)
  10571. accessType = "reading from";
  10572. else if (mCurException.ExceptionInformation[0] == 8)
  10573. accessType = "executing";
  10574. else
  10575. accessType = "writing to";
  10576. exStr = StrFormat("EXCEPTION_ACCESS_VIOLATION %s %s", accessType.c_str(), EncodeDataPtr((addr_target)mCurException.ExceptionInformation[1], true).c_str());
  10577. }
  10578. break;
  10579. case EXCEPTION_DATATYPE_MISALIGNMENT:
  10580. exStr = "EXCEPTION_DATATYPE_MISALIGNMENT";
  10581. case EXCEPTION_SINGLE_STEP:
  10582. exStr = "EXCEPTION_SINGLE_STEP";
  10583. break;
  10584. case EXCEPTION_BREAKPOINT:
  10585. exStr = "EXCEPTION_BREAKPOINT";
  10586. break;
  10587. case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
  10588. exStr = "EXCEPTION_ARRAY_BOUNDS_EXCEEDED";
  10589. break;
  10590. case EXCEPTION_FLT_DENORMAL_OPERAND:
  10591. exStr = "EXCEPTION_FLT_DENORMAL_OPERAND";
  10592. break;
  10593. case EXCEPTION_FLT_DIVIDE_BY_ZERO:
  10594. exStr = "EXCEPTION_FLT_DIVIDE_BY_ZERO";
  10595. break;
  10596. case EXCEPTION_FLT_INEXACT_RESULT:
  10597. exStr = "EXCEPTION_FLT_INEXACT_RESULT";
  10598. break;
  10599. case EXCEPTION_FLT_INVALID_OPERATION:
  10600. exStr = "EXCEPTION_FLT_INVALID_OPERATIO";
  10601. break;
  10602. case EXCEPTION_FLT_OVERFLOW:
  10603. exStr = "EXCEPTION_FLT_OVERFLOW";
  10604. break;
  10605. case EXCEPTION_FLT_STACK_CHECK:
  10606. exStr = "EXCEPTION_FLT_STACK_CHECK";
  10607. break;
  10608. case EXCEPTION_FLT_UNDERFLOW:
  10609. exStr = "EXCEPTION_FLT_UNDERFLOW";
  10610. break;
  10611. case EXCEPTION_INT_DIVIDE_BY_ZERO:
  10612. exStr = "EXCEPTION_INT_DIVIDE_BY_ZERO";
  10613. break;
  10614. case EXCEPTION_INT_OVERFLOW:
  10615. exStr = "EXCEPTION_INT_OVERFLOW";
  10616. break;
  10617. case EXCEPTION_PRIV_INSTRUCTION:
  10618. exStr = "EXCEPTION_PRIV_INSTRUCTION";
  10619. break;
  10620. case EXCEPTION_IN_PAGE_ERROR:
  10621. exStr = "EXCEPTION_IN_PAGE_ERROR";
  10622. break;
  10623. case EXCEPTION_ILLEGAL_INSTRUCTION:
  10624. exStr = "EXCEPTION_ILLEGAL_INSTRUCTION";
  10625. break;
  10626. case EXCEPTION_NONCONTINUABLE_EXCEPTION:
  10627. exStr = "EXCEPTION_NONCONTINUABLE_EXCEPTION";
  10628. break;
  10629. case EXCEPTION_STACK_OVERFLOW:
  10630. exStr = "EXCEPTION_STACK_OVERFLOW";
  10631. break;
  10632. case EXCEPTION_INVALID_DISPOSITION:
  10633. exStr = "EXCEPTION_INVALID_DISPOSITION";
  10634. break;
  10635. case EXCEPTION_GUARD_PAGE:
  10636. exStr = "EXCEPTION_GUARD_PAGE";
  10637. break;
  10638. case EXCEPTION_INVALID_HANDLE:
  10639. exStr = "EXCEPTION_INVALID_HANDLE";
  10640. break;
  10641. case CONTROL_C_EXIT:
  10642. exStr = "CONTROL_C_EXIT";
  10643. break;
  10644. default:
  10645. exStr += StrFormat("EXCEPTION %08X", mCurException.ExceptionCode);
  10646. }
  10647. if (mActiveThread != NULL)
  10648. exStr += StrFormat(" in thread %d", mActiveThread->mThreadId);
  10649. if (!exStr.empty())
  10650. result += "\n" + exStr;
  10651. // After we retrieve the exception then we can go back to just being normal 'paused'
  10652. // This allows us to evaluate stuff, Set Next Statement, etc.
  10653. mRunState = RunState_Paused;
  10654. return result.c_str();
  10655. }
  10656. void WinDebugger::SetAliasPath(const StringImpl& origPath, const StringImpl& localPath)
  10657. {
  10658. AutoCrit autoCrit(mDebugManager->mCritSect);
  10659. String fixedOrigPath = FixPathAndCase(origPath);
  10660. String fixedLocalPath = FixPathAndCase(localPath);
  10661. auto origFile = mDebugTarget->AddSrcFile(origPath);
  10662. origFile->mLocalPath = FixPath(localPath);
  10663. mDebugTarget->mLocalToOrigSrcMap[fixedLocalPath] = fixedOrigPath;
  10664. // We invalidate the step filters, because previously-failing 'CheckSourceFileExist' checks may now succeed
  10665. mDebugManager->mStepFilterVersion++;
  10666. }
  10667. String WinDebugger::GetModulesInfo()
  10668. {
  10669. AutoCrit autoCrit(mDebugManager->mCritSect);
  10670. String str;
  10671. for (auto module : mDebugTarget->mDbgModules)
  10672. {
  10673. COFF* coff = (COFF*)module;
  10674. if (module->mHotIdx > 0)
  10675. continue;
  10676. str += module->mDisplayName;
  10677. str += "\t";
  10678. if (module->mLoadState == DbgModuleLoadState_Loaded)
  10679. {
  10680. str += module->mFilePath;
  10681. }
  10682. else if (module->mLoadState == DbgModuleLoadState_NotLoaded)
  10683. {
  10684. str += module->mFilePath;
  10685. str += " (Loading...)";
  10686. }
  10687. else if (module->mLoadState == DbgModuleLoadState_Failed)
  10688. {
  10689. str += "!";
  10690. str += module->mFilePath;
  10691. }
  10692. if (module->mMappedImageFile != NULL)
  10693. {
  10694. str += " (";
  10695. str += module->mMappedImageFile->mFileName;
  10696. str += ")";
  10697. }
  10698. str += "\t";
  10699. str += coff->mPDBPath;
  10700. str += "\t";
  10701. str += module->mVersion;
  10702. str += StrFormat("\t%@-%@\t%dk\t", module->mImageBase, module->mImageBase + module->mImageSize, module->mImageSize / 1024);
  10703. time_t timestamp = coff->mTimeStamp;
  10704. if (timestamp == 0)
  10705. timestamp = GetFileTimeWrite(coff->mFilePath);
  10706. if (timestamp != 0)
  10707. {
  10708. char timeString[256];
  10709. auto time_info = localtime(&timestamp);
  10710. strftime(timeString, sizeof(timeString), "%D %T", time_info);
  10711. str += timeString;
  10712. }
  10713. str += "\n";
  10714. }
  10715. return str;
  10716. }
  10717. void WinDebugger::CancelSymSrv()
  10718. {
  10719. AutoCrit autoCrit(mDebugManager->mCritSect);
  10720. if (mActiveSymSrvRequest != NULL)
  10721. mActiveSymSrvRequest->Cancel();
  10722. }
  10723. bool WinDebugger::HasPendingDebugLoads()
  10724. {
  10725. AutoCrit autoCrit(mDebugManager->mCritSect);
  10726. return (!mPendingImageLoad.IsEmpty()) || (!mPendingDebugInfoLoad.IsEmpty());
  10727. }
  10728. int WinDebugger::LoadImageForModule(const StringImpl &modulePath, const StringImpl& imagePath)
  10729. {
  10730. AutoCrit autoCrit(mDebugManager->mCritSect);
  10731. for (auto dbgModule : mDebugTarget->mDbgModules)
  10732. {
  10733. if (modulePath.Equals(dbgModule->mFilePath, StringImpl::CompareKind_OrdinalIgnoreCase))
  10734. {
  10735. auto coff = (COFF*)dbgModule;
  10736. if (!coff->LoadModuleImage(imagePath))
  10737. {
  10738. mDebugManager->mOutMessages.push_back("error Failed to load image " + imagePath);
  10739. }
  10740. ModuleChanged(dbgModule);
  10741. return 0;
  10742. }
  10743. }
  10744. return 0;
  10745. }
  10746. int WinDebugger::LoadDebugInfoForModule(DbgModule* dbgModule)
  10747. {
  10748. if (!dbgModule->HasPendingDebugInfo())
  10749. return 0;
  10750. if (dbgModule->RequestDebugInfo())
  10751. {
  10752. ClearCallStack(); // Make this re-resolve with debug info
  10753. return 1;
  10754. }
  10755. DbgPendingDebugInfoLoad* dbgPendingDebugInfoLoad = NULL;
  10756. if (mPendingDebugInfoLoad.TryAdd(dbgModule, NULL, &dbgPendingDebugInfoLoad))
  10757. {
  10758. dbgPendingDebugInfoLoad->mModule = dbgModule;
  10759. dbgPendingDebugInfoLoad->mAllowRemote = true;
  10760. return 2;
  10761. }
  10762. dbgPendingDebugInfoLoad->mAllowRemote = true;
  10763. return 0;
  10764. }
  10765. int WinDebugger::LoadDebugInfoForModule(const StringImpl& moduleName)
  10766. {
  10767. AutoCrit autoCrit(mDebugManager->mCritSect);
  10768. for (auto dbgModule : mDebugTarget->mDbgModules)
  10769. {
  10770. String checkModuleName = GetFileName(dbgModule->mFilePath);
  10771. if (moduleName.Equals(checkModuleName, StringImpl::CompareKind_OrdinalIgnoreCase))
  10772. {
  10773. return LoadDebugInfoForModule(dbgModule);
  10774. }
  10775. }
  10776. return 0;
  10777. }
  10778. int WinDebugger::LoadDebugInfoForModule(const StringImpl& modulePath, const StringImpl& debugFileName)
  10779. {
  10780. AutoCrit autoCrit(mDebugManager->mCritSect);
  10781. for (auto dbgModule : mDebugTarget->mDbgModules)
  10782. {
  10783. if (modulePath.Equals(dbgModule->mFilePath, StringImpl::CompareKind_OrdinalIgnoreCase))
  10784. {
  10785. auto coff = (COFF*)dbgModule;
  10786. String err;
  10787. if (!coff->mPDBLoaded)
  10788. {
  10789. dbgModule->mFailMsgPtr = &err;
  10790. if (coff->TryLoadPDB(debugFileName, coff->mWantPDBGuid, coff->mWantAge))
  10791. {
  10792. ModuleChanged(dbgModule);
  10793. }
  10794. dbgModule->mFailMsgPtr = NULL;
  10795. }
  10796. else
  10797. {
  10798. err = StrFormat("Module '%s' already has debug information loaded", GetFileName(modulePath).c_str());
  10799. }
  10800. if (!err.IsEmpty())
  10801. {
  10802. mDebugManager->mOutMessages.push_back("error " + err);
  10803. }
  10804. return 0;
  10805. }
  10806. }
  10807. return 0;
  10808. }
  10809. void WinDebugger::FixupLineData(DbgCompileUnit* compileUnit)
  10810. {
  10811. if (!compileUnit || !compileUnit->mNeedsLineDataFixup)
  10812. return;
  10813. compileUnit->mNeedsLineDataFixup = false;
  10814. }
  10815. static int CompareLineData(const void* lineDataP1, const void* lineDataP2)
  10816. {
  10817. int cmpResult = (int)(((DbgLineData*)lineDataP1)->mRelAddress - ((DbgLineData*)lineDataP2)->mRelAddress);
  10818. if (cmpResult != 0)
  10819. return cmpResult;
  10820. // A larger contrib size means it's the 'outer' inlinee
  10821. cmpResult = -(((DbgLineData*)lineDataP1)->mContribSize - ((DbgLineData*)lineDataP2)->mContribSize);
  10822. if (cmpResult != 0)
  10823. return cmpResult;
  10824. return -(((DbgLineData*)lineDataP1)->mCtxIdx - ((DbgLineData*)lineDataP2)->mCtxIdx);
  10825. }
  10826. void WinDebugger::FixupLineDataForSubprogram(DbgSubprogram* subProgram)
  10827. {
  10828. if ((subProgram == NULL) || (!subProgram->mNeedLineDataFixup))
  10829. return;
  10830. BP_ZONE("FixupLineDataForSubprogram");
  10831. subProgram->mNeedLineDataFixup = false;
  10832. if (subProgram->mInlineeInfo != NULL)
  10833. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  10834. if ((subProgram->mLineInfo == NULL) || (subProgram->mLineInfo->mLines.mSize == 0))
  10835. return;
  10836. //TODO: I think this was covering up a bug in DWARF line encoding? Figure this out
  10837. // if (subProgram->mLineInfo->mLines.mSize >= 2)
  10838. // {
  10839. // DbgLineData* line0 = &subProgram->mLineInfo->mLines[0];
  10840. // DbgLineData* line1 = &subProgram->mLineInfo->mLines[1];
  10841. //
  10842. //
  10843. // if ((line0->mRelAddress == line1->mRelAddress) && (!line0->IsStackFrameSetup()) && (line1->IsStackFrameSetup()))
  10844. // {
  10845. // CPUInst inst;
  10846. // if (mCPU->Decode(line0->mAddress, subProgram->mCompileUnit->mDbgModule->mOrigImageData, &inst))
  10847. // line1->mAddress += inst.GetLength();
  10848. // }
  10849. // }
  10850. qsort(subProgram->mLineInfo->mLines.mVals, subProgram->mLineInfo->mLines.mSize, sizeof(DbgLineData), CompareLineData);
  10851. // If we have multiple lines with the same line/column/context, merge them
  10852. if (!subProgram->mLineInfo->mLines.IsEmpty())
  10853. {
  10854. auto prevLine = &subProgram->mLineInfo->mLines[0];
  10855. for (int i = 1; i < subProgram->mLineInfo->mLines.mSize; i++)
  10856. {
  10857. auto nextLine = &subProgram->mLineInfo->mLines[i];
  10858. if ((nextLine->mLine == prevLine->mLine) && (nextLine->mColumn == prevLine->mColumn) && (nextLine->mCtxIdx == prevLine->mCtxIdx) &&
  10859. (nextLine->mRelAddress == prevLine->mRelAddress + prevLine->mContribSize))
  10860. {
  10861. prevLine->mContribSize += nextLine->mContribSize;
  10862. // This messed up inline cases because mContribSize actually INCLUDES inlined lines so it caused the address to skip too far
  10863. //nextLine->mRelAddress += nextLine->mContribSize;
  10864. //nextLine->mContribSize = 0;
  10865. }
  10866. else
  10867. {
  10868. prevLine = nextLine;
  10869. }
  10870. }
  10871. }
  10872. }
  10873. void WinDebugger::ReserveHotTargetMemory(int size)
  10874. {
  10875. HotTargetMemory hotTargetMemory;
  10876. hotTargetMemory.mOffset = 0;
  10877. hotTargetMemory.mSize = 0;
  10878. hotTargetMemory.mPtr = NULL;
  10879. if (size > 0)
  10880. {
  10881. // In 64-bit mode we have a reserved region on program load that we commit here because the offsets
  10882. // must be within 32-bits of the original EXE image, but in 32-bit mode we don't reserve anything
  10883. // until here
  10884. #ifdef BF_DBG_32
  10885. //hotTargetMemory.mSize = std::max(1024 * 1024, size);
  10886. BF_ASSERT((size & (mPageSize - 1)) == 0);
  10887. hotTargetMemory.mSize = size;
  10888. hotTargetMemory.mPtr = (addr_target)(intptr)VirtualAllocEx(mProcessInfo.hProcess, NULL, hotTargetMemory.mSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
  10889. mDebugTarget->mHotHeap->AddTrackedRegion(hotTargetMemory.mPtr, hotTargetMemory.mSize);
  10890. #else
  10891. hotTargetMemory.mSize = size;
  10892. hotTargetMemory.mPtr = mDebugTarget->mHotHeap->Alloc(size);
  10893. BF_ASSERT(hotTargetMemory.mPtr != 0);
  10894. auto ptr = ::VirtualAllocEx(mProcessInfo.hProcess, (void*)(intptr)hotTargetMemory.mPtr, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  10895. BF_ASSERT(ptr == (void*)(intptr)hotTargetMemory.mPtr);
  10896. #endif
  10897. }
  10898. BfLogDbg("ReserveHotTargetMemory %p %d", hotTargetMemory.mPtr, hotTargetMemory.mSize);
  10899. int err = GetLastError();
  10900. mHotTargetMemory.push_back(hotTargetMemory);
  10901. }
  10902. addr_target WinDebugger::AllocHotTargetMemory(int size, bool canExecute, bool canWrite, int* outAllocSize)
  10903. {
  10904. int prot = PAGE_READWRITE;
  10905. if (canExecute && canWrite)
  10906. prot = PAGE_EXECUTE_READWRITE;
  10907. else if (canExecute)
  10908. prot = PAGE_EXECUTE_READ;
  10909. auto hotTargetMemory = (HotTargetMemory*)&mHotTargetMemory.back();
  10910. if (hotTargetMemory->mPtr == 0)
  10911. {
  10912. Fail("Failed to allocate memory for hot loading");
  10913. return 0;
  10914. }
  10915. size = (size + (mPageSize - 1)) & ~(mPageSize - 1);
  10916. *outAllocSize = size;
  10917. BF_ASSERT(hotTargetMemory->mOffset + size <= hotTargetMemory->mSize);
  10918. addr_target result = hotTargetMemory->mPtr + hotTargetMemory->mOffset;
  10919. ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)result, size, prot, NULL);
  10920. BfLogDbg("AllocHotTargetMemory: %p %d %d %d\n", result, size, canExecute, canWrite);
  10921. hotTargetMemory->mOffset += size;
  10922. return result;
  10923. }
  10924. void WinDebugger::ReleaseHotTargetMemory(addr_target addr, int size)
  10925. {
  10926. #ifdef BF_DBG_32
  10927. ::VirtualFreeEx(mProcessInfo.hProcess, (void*)(intptr)addr, 0, MEM_RELEASE);
  10928. #else
  10929. mDebugTarget->mHotHeap->Release(addr, size);
  10930. ::VirtualFreeEx(mProcessInfo.hProcess, (void*)(intptr)addr, size, MEM_DECOMMIT);
  10931. #endif
  10932. }
  10933. void WinDebugger::CleanupHotHeap()
  10934. {
  10935. mDebugTarget->mLastHotHeapCleanIdx = mDebugTarget->mHotHeap->mBlockAllocIdx;
  10936. // Our criteria for determining whether a hot loaded file is still being used:
  10937. // 1) If we are currently executing a method from that object file.
  10938. // 2) If the symbol map has a symbol with that address.
  10939. // 3) If the static variable map contains a reference - including a conservative scan of the data
  10940. // This handles vdata references
  10941. // This is a conservative check which won't purge hot reloads that contain deleted
  10942. // methods (for example), but it will purge hot reloads where all the changed
  10943. // data has been overwritten.
  10944. // For delegate bindings, the original module declaring the bind creates a "preserve"
  10945. // global such as "bf_hs_preserve@_ZN5TestO4TestEv", whose preserved symbol ensures it
  10946. // doesn't get unloaded. The current version of that method resides in "_ZN5TestO4TestEv",
  10947. // ensuring that the method pointed to by the global variable is valid
  10948. mDebugTarget->mHotHeap->ClearReferencedFlags();
  10949. addr_target lowAddr = mDebugTarget->mHotHeap->mHotAreaStart;
  10950. addr_target highAddr = lowAddr + mDebugTarget->mHotHeap->mHotAreaSize;
  10951. // Do conservative scan through all thread stacks. Stack traces aren't 100% reliable, so we
  10952. // need to do a full conservative scan of any addresses stored in the stack
  10953. // to ensure we don't miss any return addresses
  10954. for (int threadIdx = 0; threadIdx < (int)mThreadList.size(); threadIdx++)
  10955. {
  10956. WdThreadInfo* threadInfo = mThreadList[threadIdx];
  10957. BF_CONTEXT lcContext;
  10958. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  10959. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  10960. addr_target checkStackAddr = BF_CONTEXT_SP(lcContext);
  10961. checkStackAddr &= ~(sizeof(addr_target) - 1);
  10962. // Conservative check on registers
  10963. for (int regNum = 0; regNum < sizeof(BF_CONTEXT)/sizeof(addr_target); regNum++)
  10964. {
  10965. addr_target checkAddr = ((addr_target*)&lcContext)[regNum];
  10966. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  10967. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  10968. }
  10969. // Conservative check on all stack data
  10970. while (checkStackAddr < threadInfo->mStartSP)
  10971. {
  10972. addr_target checkAddrArr[1024];
  10973. int numAddrsChecking = BF_MIN(1024, (int)((threadInfo->mStartSP - checkStackAddr) / sizeof(addr_target)));
  10974. ReadMemory(checkStackAddr, numAddrsChecking * sizeof(addr_target), checkAddrArr);
  10975. checkStackAddr += numAddrsChecking * sizeof(addr_target);
  10976. for (int addrIdx = 0; addrIdx < numAddrsChecking; addrIdx++)
  10977. {
  10978. addr_target checkAddr = checkAddrArr[addrIdx];
  10979. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  10980. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  10981. }
  10982. }
  10983. }
  10984. auto mainModule = mDebugTarget->mTargetBinary;
  10985. for (auto entry : mainModule->mSymbolNameMap)
  10986. {
  10987. auto dwSymbol = entry->mValue;
  10988. addr_target checkAddr = dwSymbol->mAddress;
  10989. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  10990. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  10991. }
  10992. mDebugTarget->CleanupHotHeap();
  10993. BfLogDbg("Hot load memory used: %dk\n", (int)mDebugTarget->mHotHeap->GetUsedSize() / 1024);
  10994. }
  10995. int WinDebugger::EnableWriting(intptr address, int size)
  10996. {
  10997. DWORD oldProt;
  10998. bool success = ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)address, size, PAGE_READWRITE, &oldProt);
  10999. if (!success)
  11000. {
  11001. int err = GetLastError();
  11002. }
  11003. return (int)oldProt;
  11004. }
  11005. int WinDebugger::SetProtection(intptr address, int size, int prot)
  11006. {
  11007. DWORD oldProt;
  11008. ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)address, size, prot, &oldProt);
  11009. return (int)oldProt;
  11010. }
  11011. void WinDebugger::EnableMemCache()
  11012. {
  11013. mMemCacheAddr = 1;
  11014. }
  11015. void WinDebugger::DisableMemCache()
  11016. {
  11017. mMemCacheAddr = 0;
  11018. }
  11019. bool WinDebugger::ReadMemory(intptr address, uint64 length, void* dest, bool local)
  11020. {
  11021. if (local)
  11022. {
  11023. __try
  11024. {
  11025. memcpy(dest, (void*)address, length);
  11026. return true;
  11027. }
  11028. __except(EXCEPTION_EXECUTE_HANDLER)
  11029. {
  11030. return false;
  11031. }
  11032. }
  11033. if (mMemCacheAddr != 0)
  11034. {
  11035. addr_target targetAddr = (addr_target)address;
  11036. if ((targetAddr >= mMemCacheAddr) && (targetAddr + length <= mMemCacheAddr + WD_MEMCACHE_SIZE) && (mMemCacheAddr > 1))
  11037. {
  11038. memcpy(dest, mMemCacheData + (targetAddr - mMemCacheAddr), length);
  11039. return true;
  11040. }
  11041. // We need a new block
  11042. SIZE_T dwReadBytes;
  11043. if (::ReadProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, mMemCacheData, (SIZE_T)WD_MEMCACHE_SIZE, &dwReadBytes) != 0)
  11044. {
  11045. mMemCacheAddr = targetAddr;
  11046. memcpy(dest, mMemCacheData, length);
  11047. return true;
  11048. }
  11049. // Failed, turn off caching
  11050. mMemCacheAddr = 0;
  11051. }
  11052. SIZE_T dwReadBytes;
  11053. if (::ReadProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, dest, (SIZE_T)length, &dwReadBytes) != 0)
  11054. return true;
  11055. int lastErr = ::GetLastError();
  11056. memset(dest, 0, length);
  11057. return false;
  11058. }
  11059. bool WinDebugger::WriteMemory(intptr address, void* src, uint64 length)
  11060. {
  11061. SIZE_T dwBytesWritten = 0;
  11062. int result = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, src, (SIZE_T)length, &dwBytesWritten);
  11063. return result != 0;
  11064. }
  11065. addr_target WinDebugger::GetTLSOffset(int tlsIndex)
  11066. {
  11067. typedef LONG NTSTATUS;
  11068. typedef DWORD KPRIORITY;
  11069. typedef WORD UWORD;
  11070. enum THREADINFOCLASS
  11071. {
  11072. ThreadBasicInformation,
  11073. };
  11074. struct CLIENT_ID
  11075. {
  11076. HANDLE UniqueProcess;
  11077. HANDLE UniqueThread;
  11078. };
  11079. struct
  11080. {
  11081. NTSTATUS mExitStatus;
  11082. void* mTebBaseAddress;
  11083. CLIENT_ID mClientId;
  11084. KAFFINITY mAffinityMask;
  11085. KPRIORITY mPriority;
  11086. KPRIORITY mBasePriority;
  11087. } threadInfo = { 0 };
  11088. ULONG len = 0;
  11089. bool loadedManually = false;
  11090. static HMODULE module = NULL;
  11091. static NTSTATUS(__stdcall *NtQueryInformationThread)(HANDLE ThreadHandle, THREADINFOCLASS ThreadInformationClass, PVOID ThreadInformation, ULONG ThreadInformationLength, PULONG ReturnLength);
  11092. if (module == NULL)
  11093. {
  11094. module = GetModuleHandleA("ntdll.dll");
  11095. NtQueryInformationThread = reinterpret_cast<decltype(NtQueryInformationThread)>(GetProcAddress(module, "NtQueryInformationThread"));
  11096. }
  11097. if (NtQueryInformationThread == NULL)
  11098. return 0;
  11099. NTSTATUS status = NtQueryInformationThread(mActiveThread->mHThread, (THREADINFOCLASS)0, &threadInfo, sizeof(threadInfo), nullptr);
  11100. if (status < 0)
  11101. return 0;
  11102. #ifdef BF_DBG_32
  11103. addr_target tibAddr = ReadMemory<addr_target>((intptr)threadInfo.mTebBaseAddress + 0x0);
  11104. addr_target tlsTable = ReadMemory<addr_target>((intptr)tibAddr + 0x2C);
  11105. #else
  11106. addr_target tlsTable = ReadMemory<addr_target>((intptr)threadInfo.mTebBaseAddress + 0x58);
  11107. #endif
  11108. return ReadMemory<addr_target>(tlsTable + tlsIndex * sizeof(addr_target));
  11109. }
  11110. bool WinDebugger::WriteInstructions(intptr address, void* src, uint64 length)
  11111. {
  11112. SIZE_T dwBytesWritten = 0;
  11113. bool result = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, src, (SIZE_T)length, &dwBytesWritten) != 0;
  11114. result |= ::FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, (SIZE_T)length) != 0;
  11115. BF_ASSERT(result);
  11116. BfLogDbg("WriteInstructions: %p %d\n", address, length);
  11117. return result;
  11118. }
  11119. DbgMemoryFlags WinDebugger::GetMemoryFlags(intptr address)
  11120. {
  11121. MEMORY_BASIC_INFORMATION memBasicInfo;
  11122. if (::VirtualQueryEx(mProcessInfo.hProcess, (void*)address, &memBasicInfo, sizeof(MEMORY_BASIC_INFORMATION)) == 0)
  11123. {
  11124. //BfLogDbg("VirtualQueryEx failed with %d\n", GetLastError());
  11125. return DbgMemoryFlags_None;
  11126. }
  11127. DbgMemoryFlags flags = DbgMemoryFlags_None;
  11128. if (memBasicInfo.AllocationProtect & PAGE_READWRITE)
  11129. {
  11130. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11131. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11132. }
  11133. if (memBasicInfo.AllocationProtect & PAGE_READONLY)
  11134. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11135. if (memBasicInfo.AllocationProtect & PAGE_WRITECOPY)
  11136. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11137. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE)
  11138. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11139. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_READ)
  11140. {
  11141. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11142. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11143. }
  11144. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_READWRITE)
  11145. {
  11146. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11147. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11148. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11149. }
  11150. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_WRITECOPY)
  11151. {
  11152. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11153. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11154. }
  11155. return flags;
  11156. }
  11157. #ifdef BF_DBG_32
  11158. Debugger* Beefy::CreateDebugger32(DebugManager* debugManager, DbgMiniDump* miniDump)
  11159. #else
  11160. Debugger* Beefy::CreateDebugger64(DebugManager* debugManager, DbgMiniDump* miniDump)
  11161. #endif
  11162. {
  11163. if (miniDump != NULL)
  11164. {
  11165. auto debugger = new MiniDumpDebugger(debugManager, miniDump);
  11166. return debugger;
  11167. }
  11168. return new WinDebugger(debugManager);
  11169. }
  11170. #ifdef BF_DBG_32
  11171. void WdAllocTest()
  11172. {
  11173. Array<BeefyDbg32::WdStackFrame*> stackFrameList;
  11174. for (int i = 0; true; i++)
  11175. {
  11176. WdStackFrame* stackFrame = new WdStackFrame();
  11177. stackFrameList.push_back(stackFrame);
  11178. }
  11179. }
  11180. #endif
  11181. #endif //!defined BF32 || !defined BF_DBG_64