WinDebugger.cpp 369 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679
  1. #pragma warning(disable:4996)
  2. // TODO: Remove for 64-bit
  3. #pragma warning(disable:4244)
  4. #pragma warning(disable:4267)
  5. #define NTDDI_VERSION 0x06020000
  6. #include "WinDebugger.h"
  7. #include "CPU.h"
  8. #include "DbgModule.h"
  9. #include "DebugVisualizers.h"
  10. #include "MiniDumpDebugger.h"
  11. #include "X86.h"
  12. #include "BeefySysLib/Common.h"
  13. #include "BeefySysLib/util/PerfTimer.h"
  14. #include "BeefySysLib/util/BeefPerf.h"
  15. #include "BeefySysLib/util/CritSect.h"
  16. #include "BeefySysLib/util/UTF8.h"
  17. #include "BeefySysLib/FileStream.h"
  18. #include "BeefySysLib/FileHandleStream.h"
  19. #include <inttypes.h>
  20. #include <windows.h>
  21. #include "DbgExprEvaluator.h"
  22. #include "Compiler/BfSystem.h"
  23. #include "Compiler/BfParser.h"
  24. #include "Compiler/BfReducer.h"
  25. #include "Compiler/BfDemangler.h"
  26. #include "Compiler/BfPrinter.h"
  27. #include <Shlobj.h>
  28. #include "NetManager.h"
  29. #include "DebugManager.h"
  30. #include "X86Target.h"
  31. #include "HotHeap.h"
  32. #include "HotScanner.h"
  33. #include "Profiler.h"
  34. #include <float.h>
  35. #include <psapi.h>
  36. #if !defined BF32 || !defined BF_DBG_64
  37. #define STATUS_WX86_CONTINUE 0x4000001DL
  38. #define STATUS_WX86_SINGLE_STEP 0x4000001EL
  39. #define STATUS_WX86_BREAKPOINT 0x4000001FL
  40. #define STATUS_WX86_EXCEPTION_CONTINUE 0x40000020L
  41. #pragma pack(push, 1)
  42. struct HotJumpOp
  43. {
  44. uint8 mOpCode;
  45. int32 mRelTarget;
  46. };
  47. #pragma pack(pop)
  48. #include "BeefySysLib/util/AllocDebug.h"
  49. #include <limits>
  50. USING_NS_BF_DBG;
  51. static void FilterThreadName(String& name)
  52. {
  53. for (int i = 0; i < (int)name.length(); i++)
  54. {
  55. uint8 c = name[i];
  56. if (c == 0)
  57. {
  58. name.RemoveToEnd(i);
  59. return;
  60. }
  61. if (c < 32)
  62. {
  63. name.Remove(i);
  64. i--;
  65. continue;
  66. }
  67. }
  68. }
  69. //////////////////////////////////////////////////////////////////////////
  70. WdBreakpointCondition::~WdBreakpointCondition()
  71. {
  72. delete mDbgEvaluationContext;
  73. }
  74. //////////////////////////////////////////////////////////////////////////
  75. DbgEvaluationContext::DbgEvaluationContext(WinDebugger* winDebugger, DbgModule* dbgModule, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  76. {
  77. Init(winDebugger, dbgModule, expr, formatInfo, contextValue);
  78. }
  79. DbgEvaluationContext::DbgEvaluationContext(WinDebugger* winDebugger, DbgCompileUnit* dbgCompileUnit, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  80. {
  81. DbgModule* dbgModule = NULL;
  82. if (dbgCompileUnit != NULL)
  83. dbgModule = dbgCompileUnit->mDbgModule;
  84. Init(winDebugger, dbgModule, expr, formatInfo, contextValue);
  85. }
  86. void DbgEvaluationContext::Init(WinDebugger* winDebugger, DbgModule* dbgModule, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  87. {
  88. if (expr.empty())
  89. {
  90. mParser = NULL;
  91. mReducer = NULL;
  92. mPassInstance = NULL;
  93. mDbgExprEvaluator = NULL;
  94. mExprNode = NULL;
  95. return;
  96. }
  97. mParser = new BfParser(winDebugger->mBfSystem);
  98. mParser->mCompatMode = true;
  99. mPassInstance = new BfPassInstance(winDebugger->mBfSystem);
  100. auto terminatedExpr = expr + ";";
  101. mParser->SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  102. mParser->Parse(mPassInstance);
  103. mReducer = new BfReducer();
  104. mReducer->mAlloc = mParser->mAlloc;
  105. mReducer->mSystem = winDebugger->mBfSystem;
  106. mReducer->mPassInstance = mPassInstance;
  107. mReducer->mVisitorPos = BfReducer::BfVisitorPos(mParser->mRootNode);
  108. mReducer->mVisitorPos.MoveNext();
  109. mReducer->mCompatMode = mParser->mCompatMode;
  110. mReducer->mSource = mParser;
  111. mExprNode = mReducer->CreateExpression(mParser->mRootNode->GetFirst());
  112. mParser->Close();
  113. mDbgExprEvaluator = new DbgExprEvaluator(winDebugger, dbgModule, mPassInstance, -1, -1);
  114. if ((formatInfo != NULL) && (mExprNode != NULL) && (mExprNode->GetSrcEnd() < (int) expr.length()))
  115. {
  116. String formatFlags = expr.Substring(mExprNode->GetSrcEnd());
  117. String errorString = "Invalid expression";
  118. if (!winDebugger->ParseFormatInfo(dbgModule, formatFlags, formatInfo, mPassInstance, NULL, NULL, &errorString, contextValue))
  119. {
  120. mPassInstance->FailAt(errorString, mParser->mSourceData, mExprNode->GetSrcEnd(), (int)expr.length() - mExprNode->GetSrcEnd());
  121. formatFlags = "";
  122. }
  123. }
  124. if (formatInfo != NULL)
  125. {
  126. mDbgExprEvaluator->mExplicitThis = formatInfo->mExplicitThis;
  127. mDbgExprEvaluator->mCallStackIdx = formatInfo->mCallStackIdx;
  128. mDbgExprEvaluator->mLanguage = formatInfo->mLanguage;
  129. }
  130. }
  131. bool DbgEvaluationContext::HasExpression()
  132. {
  133. return mExprNode != NULL;
  134. }
  135. DbgEvaluationContext::~DbgEvaluationContext()
  136. {
  137. delete mParser;
  138. delete mReducer;
  139. delete mDbgExprEvaluator;
  140. delete mPassInstance;
  141. }
  142. DbgTypedValue DbgEvaluationContext::EvaluateInContext(DbgTypedValue contextTypedValue)
  143. {
  144. if (mExprNode == NULL)
  145. return DbgTypedValue();
  146. mPassInstance->ClearErrors();
  147. if (contextTypedValue)
  148. {
  149. mDbgExprEvaluator->mExplicitThis = contextTypedValue;
  150. if ((mDbgExprEvaluator->mExplicitThis.mType->IsPointer()) && (mDbgExprEvaluator->mExplicitThis.mType->mTypeParam->WantsRefThis()))
  151. {
  152. mDbgExprEvaluator->mExplicitThis.mType = mDbgExprEvaluator->mExplicitThis.mType->mTypeParam;
  153. mDbgExprEvaluator->mExplicitThis.mSrcAddress = mDbgExprEvaluator->mExplicitThis.mPtr;
  154. mDbgExprEvaluator->mExplicitThis.mPtr = 0;
  155. }
  156. if ((mDbgExprEvaluator->mExplicitThis.mType->IsCompositeType()) && (!mDbgExprEvaluator->mExplicitThis.mType->WantsRefThis()))
  157. {
  158. if (mDbgExprEvaluator->mExplicitThis.mSrcAddress != 0)
  159. {
  160. mDbgExprEvaluator->mExplicitThis.mType = mDbgExprEvaluator->mDbgModule->GetPointerType(mDbgExprEvaluator->mExplicitThis.mType);
  161. mDbgExprEvaluator->mExplicitThis.mPtr = mDbgExprEvaluator->mExplicitThis.mSrcAddress;
  162. mDbgExprEvaluator->mExplicitThis.mSrcAddress = 0;
  163. }
  164. }
  165. }
  166. if (contextTypedValue.mType != NULL)
  167. mDbgExprEvaluator->mDbgCompileUnit = contextTypedValue.mType->mCompileUnit;
  168. DbgTypedValue exprResult;
  169. auto result = mDbgExprEvaluator->Resolve(mExprNode);
  170. return result;
  171. }
  172. bool DbgEvaluationContext::HadError()
  173. {
  174. return mPassInstance->mFailedIdx != 0;
  175. }
  176. String DbgEvaluationContext::GetErrorStr()
  177. {
  178. String errorStr = mPassInstance->mErrors[0]->mError;
  179. if (mExprNode != NULL)
  180. {
  181. errorStr += ": ";
  182. errorStr += mExprNode->ToString();
  183. }
  184. return errorStr;
  185. }
  186. //////////////////////////////////////////////////////////////////////////
  187. typedef HRESULT(WINAPI* SetThreadDescription_t)(HANDLE hThread, PCWSTR lpThreadDescription);
  188. typedef HRESULT(WINAPI* GetThreadDescription_t)(HANDLE hThread, PWSTR* lpThreadDescription);
  189. static SetThreadDescription_t gSetThreadDescription = NULL;
  190. static GetThreadDescription_t gGetThreadDescription = NULL;
  191. static HMODULE gKernelDll = NULL;
  192. static void ImportKernel()
  193. {
  194. if (gKernelDll != NULL)
  195. return;
  196. WCHAR path[MAX_PATH];
  197. GetSystemDirectory(path, MAX_PATH);
  198. wcscat(path, L"\\kernel32.dll");
  199. gKernelDll = GetModuleHandle(path);
  200. if (gKernelDll == NULL)
  201. {
  202. return;
  203. }
  204. gSetThreadDescription = (SetThreadDescription_t)GetProcAddress(gKernelDll, "SetThreadDescription");
  205. gGetThreadDescription = (GetThreadDescription_t)GetProcAddress(gKernelDll, "GetThreadDescription");
  206. }
  207. void WinDebugger::TryGetThreadName(WdThreadInfo* threadInfo)
  208. {
  209. if (threadInfo->mHThread == NULL)
  210. return;
  211. ImportKernel();
  212. PWSTR wStr = NULL;
  213. if (gGetThreadDescription != NULL)
  214. {
  215. gGetThreadDescription(threadInfo->mHThread, &wStr);
  216. if (wStr == NULL)
  217. return;
  218. threadInfo->mName = UTF8Encode(wStr);
  219. FilterThreadName(threadInfo->mName);
  220. LocalFree(wStr);
  221. }
  222. }
  223. static void CreateFilterName(String& name, DbgType* type)
  224. {
  225. CreateFilterName(name, type->mParent);
  226. switch (type->mTypeCode)
  227. {
  228. case DbgType_Namespace:
  229. case DbgType_Struct:
  230. case DbgType_Class:
  231. name += type->mName;
  232. break;
  233. }
  234. }
  235. static void CreateFilterName(String& name, const char* srcStr, DbgLanguage language)
  236. {
  237. int chevronDepth = 0;
  238. const char* cPtr = srcStr;
  239. for (; true; cPtr++)
  240. {
  241. char c = *cPtr;
  242. if (c == 0)
  243. break;
  244. if (c == '>')
  245. chevronDepth--;
  246. bool inGeneric = chevronDepth > 0;
  247. if (c == '<')
  248. chevronDepth++;
  249. if (inGeneric) // Bundle all generic instances together
  250. continue;
  251. if (c == '[') // Bundle all arrays together
  252. name.clear();
  253. if (c == '(')
  254. return; // Start of params
  255. if ((c == ':') && (cPtr[1] == ':') && (language == DbgLanguage_Beef))
  256. {
  257. name.Append('.');
  258. cPtr++;
  259. }
  260. else
  261. name.Append(c);
  262. }
  263. }
  264. static void CreateFilterName(String& name, DbgSubprogram* subprogram)
  265. {
  266. auto language = subprogram->GetLanguage();
  267. if (subprogram->mName == NULL)
  268. {
  269. if (subprogram->mLinkName[0] == '<')
  270. {
  271. name += subprogram->mLinkName;
  272. return;
  273. }
  274. name = BfDemangler::Demangle(subprogram->mLinkName, language);
  275. // Strip off the params since we need to generate those ourselves
  276. int parenPos = (int)name.IndexOf('(');
  277. if (parenPos != -1)
  278. name.RemoveToEnd(parenPos);
  279. return;
  280. }
  281. else if (subprogram->mHasQualifiedName)
  282. {
  283. const char* cPtr = subprogram->mName;
  284. if (strncmp(cPtr, "_bf::", 5) == 0)
  285. {
  286. CreateFilterName(name, cPtr + 5, DbgLanguage_Beef);
  287. name.Replace(".__BfStaticCtor", ".this$static");
  288. name.Replace(".__BfCtorClear", ".this$clear");
  289. name.Replace(".__BfCtor", ".this");
  290. }
  291. else
  292. CreateFilterName(name, subprogram->mName, language);
  293. return;
  294. }
  295. else
  296. {
  297. if (subprogram->mParentType != NULL)
  298. {
  299. String parentName = subprogram->mParentType->ToString();
  300. CreateFilterName(name, parentName.c_str(), language);
  301. if (!name.empty())
  302. {
  303. if (language == DbgLanguage_Beef)
  304. name += ".";
  305. else
  306. name += "::";
  307. }
  308. }
  309. if ((language == DbgLanguage_Beef) && (subprogram->mParentType != NULL) && (subprogram->mParentType->mTypeName != NULL) &&
  310. (strcmp(subprogram->mName, subprogram->mParentType->mTypeName) == 0))
  311. name += "this";
  312. else if ((language == DbgLanguage_Beef) && (subprogram->mName[0] == '~'))
  313. name += "~this";
  314. else if (strncmp(subprogram->mName, "_bf::", 5) == 0)
  315. {
  316. CreateFilterName(name, subprogram->mName + 5, DbgLanguage_Beef);
  317. }
  318. else
  319. {
  320. CreateFilterName(name, subprogram->mName, language);
  321. }
  322. }
  323. if (name.empty())
  324. name += "`anon";
  325. if ((name[name.length() - 1] == '!') || (name[0] == '<'))
  326. {
  327. if (language == DbgLanguage_Beef)
  328. {
  329. // It's a mixin - assert that there's no params
  330. //BF_ASSERT(subprogram->mParams.Size() == 0);
  331. }
  332. return;
  333. }
  334. }
  335. //////////////////////////////////////////////////////////////////////////
  336. DbgPendingExpr::DbgPendingExpr()
  337. {
  338. mThreadId = -1;
  339. mCallStackIdx = -1;
  340. mParser = NULL;
  341. mCursorPos = -1;
  342. mExprNode = NULL;
  343. mIdleTicks = 0;
  344. mExplitType = NULL;
  345. mExpressionFlags = DwEvalExpressionFlag_None;
  346. }
  347. DbgPendingExpr::~DbgPendingExpr()
  348. {
  349. delete mParser;
  350. }
  351. // conversion logic based on table at http://en.wikipedia.org/wiki/Extended_precision
  352. //CDH TODO put this somewhere more general
  353. static double ConvertFloat80ToDouble(const byte fp80[10])
  354. {
  355. uint16 e = *((uint16*)&fp80[8]);
  356. uint64 m = *((uint64*)&fp80[0]);
  357. uint64 bit63 = (uint64)1 << 63;
  358. uint64 bit62 = (uint64)1 << 62;
  359. bool isNegative = (e & 0x8000) != 0;
  360. double s = isNegative ? -1.0 : 1.0;
  361. e &= 0x7fff;
  362. if (!e)
  363. {
  364. // the high bit and mantissa content will determine whether it's an actual zero, or a denormal or
  365. // pseudo-denormal number with an effective exponent of -16382. But since that exponent is so far
  366. // below anything we can handle in double-precision (even accounting for denormal bit shifts), we're
  367. // effectively still dealing with zero.
  368. return s * 0.0;
  369. }
  370. else if (e == 0x7fff)
  371. {
  372. if (m & bit63)
  373. {
  374. if (m & bit62)
  375. {
  376. return std::numeric_limits<double>::quiet_NaN();
  377. }
  378. else
  379. {
  380. if (m == bit63)
  381. return s * std::numeric_limits<double>::infinity();
  382. else
  383. return std::numeric_limits<double>::signaling_NaN();
  384. }
  385. }
  386. else
  387. {
  388. return std::numeric_limits<double>::quiet_NaN();
  389. }
  390. }
  391. else
  392. {
  393. if (!(m & bit63))
  394. return std::numeric_limits<double>::quiet_NaN(); // unnormal (we don't handle these since 80387 and later treat them as invalid operands anyway)
  395. // else is a normalized value
  396. }
  397. int useExponent = (int)e - 16383;
  398. if (useExponent < -1022)
  399. return s * 0.0; // we could technically support e from -1023 to -1074 as denormals, but don't bother with that for now.
  400. else if (useExponent > 1023)
  401. return s * HUGE_VAL;
  402. useExponent += 1023;
  403. BF_ASSERT((useExponent > 0) && (useExponent < 0x7ff)); // assume we've filtered for valid exponent range
  404. BF_ASSERT(m & bit63); // assume we've filtered out values that aren't normalized by now
  405. uint64 result = 0;
  406. if (isNegative)
  407. result |= bit63;
  408. result |= (uint64)useExponent << 52;
  409. result |= (m & ~bit63) >> 11;
  410. return *reinterpret_cast<double*>(&result);
  411. }
  412. addr_target NS_BF_DBG::DecodeTargetDataPtr(const char*& strRef)
  413. {
  414. addr_target val = (addr_target)stouln(strRef, sizeof(intptr_target) * 2);
  415. strRef += sizeof(intptr_target) * 2;
  416. return val;
  417. }
  418. WinDebugger::WinDebugger(DebugManager* debugManager) : mDbgSymSrv(this)
  419. {
  420. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  421. mActiveHotIdx = -1;
  422. mGotStartupEvent = false;
  423. mIsContinuingFromException = false;
  424. mDestroying = false;
  425. mDebugManager = debugManager;
  426. mNeedsRehupBreakpoints = false;
  427. mStepInAssembly = false;
  428. mStepSP = 0;
  429. mStepIsRecursing = false;
  430. mStepStopOnNextInstruction = false;
  431. mDebugTarget = NULL;
  432. mShuttingDown = false;
  433. mBfSystem = new BfSystem();
  434. mAtBreakThread = NULL;
  435. mActiveThread = NULL;
  436. mActiveBreakpoint = NULL;
  437. mSteppingThread = NULL;
  438. mExplicitStopThread = NULL;
  439. mStepSwitchedThreads = false;
  440. mIsDebuggerWaiting = false;
  441. mWantsDebugContinue = false;
  442. mContinueFromBreakpointFailed = false;
  443. mIsStepIntoSpecific = false;
  444. mDbgBreak = false;
  445. mDebuggerWaitingThread = NULL;
  446. mStepType = StepType_None;
  447. mOrigStepType = StepType_None;
  448. mLastValidStepIntoPC = 0;
  449. mActiveSymSrvRequest = NULL;
  450. mStoredReturnValueAddr = 0;
  451. #ifdef BF_DBG_32
  452. mCPU = gX86Target->mX86CPU;
  453. #else
  454. mCPU = gX86Target->mX64CPU;
  455. #endif
  456. mRunState = RunState_NotStarted;
  457. mIsRunning = false;
  458. mSavedAtBreakpointAddress = 0;
  459. mSavedBreakpointAddressContinuing = 0;
  460. mRequestedStackFrameIdx = 0;
  461. mShowPCOverride = 0;
  462. mCurNoInfoStepTries = 0;
  463. mDbgAttachFlags = BfDbgAttachFlag_None;
  464. mDbgProcessHandle = 0;
  465. mDbgThreadHandle = 0;
  466. mDbgProcessId = 0;
  467. mIsPartialCallStack = true;
  468. for (int i = 0; i < 4; i++)
  469. {
  470. mFreeMemoryBreakIndices.push_back(i);
  471. }
  472. SYSTEM_INFO systemInfo;
  473. GetSystemInfo(&systemInfo);
  474. mPageSize = systemInfo.dwPageSize;
  475. mEmptyDebugTarget = new DebugTarget(this);
  476. mEmptyDebugTarget->CreateEmptyTarget();
  477. mEmptyDebugTarget->mIsEmpty = true;
  478. mDebugTarget = mEmptyDebugTarget;
  479. mDebugPendingExpr = NULL;
  480. mDebugEvalThreadInfo = WdThreadInfo();
  481. mMemCacheAddr = 0;
  482. mDebuggerThreadId = 0;
  483. }
  484. WinDebugger::~WinDebugger()
  485. {
  486. mDestroying = true;
  487. delete gDbgPerfManager;
  488. gDbgPerfManager = NULL;
  489. if ((mDebugTarget != NULL) && (mDebugTarget != mEmptyDebugTarget))
  490. Detach();
  491. for (auto breakpoint : mBreakpoints)
  492. {
  493. auto checkBreakpoint = breakpoint->mLinkedSibling;
  494. while (checkBreakpoint != NULL)
  495. {
  496. auto nextBreakpoint = checkBreakpoint->mLinkedSibling;
  497. delete checkBreakpoint;
  498. checkBreakpoint = nextBreakpoint;
  499. }
  500. delete breakpoint;
  501. }
  502. delete mEmptyDebugTarget;
  503. delete mBfSystem;
  504. for (auto kv : mPendingProfilerMap)
  505. delete kv.mValue;
  506. for (auto profiler : mNewProfilerList)
  507. delete profiler;
  508. delete mDebugPendingExpr;
  509. }
  510. void WinDebugger::Fail(const StringImpl& error)
  511. {
  512. if (mIsRunning)
  513. mDebugManager->mOutMessages.push_back(StrFormat("error %s", error.c_str()));
  514. }
  515. // Leave active thread unpaused
  516. void WinDebugger::ThreadRestorePause(WdThreadInfo* onlyPauseThread, WdThreadInfo* dontPauseThread)
  517. {
  518. BfLogDbg("ThreadRestorePause %d %d\n", (onlyPauseThread != NULL) ? onlyPauseThread->mThreadId : 0, (dontPauseThread != NULL) ? dontPauseThread->mThreadId : 0);
  519. for (auto threadInfo : mThreadList)
  520. {
  521. if (((threadInfo != dontPauseThread) && (!threadInfo->mIsBreakRestorePaused)) &&
  522. ((onlyPauseThread == NULL) || (threadInfo == onlyPauseThread)))
  523. {
  524. BF_ASSERT(!threadInfo->mIsBreakRestorePaused);
  525. BfLogDbg("SuspendThread %d\n", threadInfo->mThreadId);
  526. ::SuspendThread(threadInfo->mHThread);
  527. threadInfo->mIsBreakRestorePaused = true;
  528. }
  529. }
  530. }
  531. void WinDebugger::ThreadRestoreUnpause()
  532. {
  533. BfLogDbg("ThreadRestoreUnpause\n");
  534. for (auto threadInfo : mThreadList)
  535. {
  536. if (threadInfo->mIsBreakRestorePaused)
  537. {
  538. BfLogDbg("ResumeThread %d\n", threadInfo->mThreadId);
  539. ::ResumeThread(threadInfo->mHThread);
  540. threadInfo->mIsBreakRestorePaused = false;
  541. }
  542. }
  543. }
  544. void WinDebugger::UpdateThreadDebugRegisters(WdThreadInfo* threadInfo)
  545. {
  546. auto threadId = threadInfo->mHThread;
  547. BF_CONTEXT lcContext;
  548. lcContext.ContextFlags = BF_CONTEXT_DEBUG_REGISTERS;
  549. BF_GetThreadContext(threadId, &lcContext);
  550. for (int memoryBreakIdx = 0; memoryBreakIdx < 4; memoryBreakIdx++)
  551. {
  552. WdMemoryBreakpointBind memoryBreakpointBind = mMemoryBreakpoints[memoryBreakIdx];
  553. WdBreakpoint* wdBreakpoint = memoryBreakpointBind.mBreakpoint;
  554. if (wdBreakpoint == NULL)
  555. {
  556. *(&lcContext.Dr0 + memoryBreakIdx) = 0;
  557. lcContext.Dr7 &= ~((1 << (memoryBreakIdx * 2)) | (1 << (16 + memoryBreakIdx * 4)) | (3 << (18 + memoryBreakIdx * 4)));
  558. }
  559. else
  560. {
  561. int sizeCode = 0;
  562. if (memoryBreakpointBind.mByteCount == 2)
  563. sizeCode = 1;
  564. else if (memoryBreakpointBind.mByteCount == 4)
  565. sizeCode = 3;
  566. else if (memoryBreakpointBind.mByteCount == 8)
  567. sizeCode = 2;
  568. addr_target calcAddr = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress + memoryBreakpointBind.mOfs;
  569. BF_ASSERT(calcAddr == memoryBreakpointBind.mAddress);
  570. *(&lcContext.Dr0 + memoryBreakIdx) = calcAddr;
  571. lcContext.Dr7 |= (1 << (memoryBreakIdx * 2)) | (1 << (16 + memoryBreakIdx * 4)) | (sizeCode << (18 + memoryBreakIdx * 4));
  572. }
  573. }
  574. bool worked = BF_SetThreadContext(threadId, &lcContext) != 0;
  575. BF_ASSERT(worked || (mRunState == RunState_Terminating) || (mRunState == RunState_Terminated));
  576. }
  577. void WinDebugger::UpdateThreadDebugRegisters()
  578. {
  579. for (auto threadInfo : mThreadList)
  580. {
  581. ::SuspendThread(threadInfo->mHThread);
  582. UpdateThreadDebugRegisters(threadInfo);
  583. ::ResumeThread(threadInfo->mHThread);
  584. }
  585. }
  586. void WinDebugger::PhysSetBreakpoint(addr_target address)
  587. {
  588. BfLogDbg("PhysSetBreakpoint %p\n", address);
  589. uint8 newData = 0xCC;
  590. // This ensure that we have the orig image data cached
  591. DbgMemoryFlags flags = mDebugTarget->ReadOrigImageData(address, NULL, 1);
  592. if ((flags & DbgMemoryFlags_Execute) == 0)
  593. {
  594. BfLogDbg("Breakpoint ignored - execute flag NOT set in breakpoint address\n", address);
  595. BfLogDbg("Memory Flags = %d\n", gDebugger->GetMemoryFlags(address));
  596. return;
  597. }
  598. // Replace it with Breakpoint
  599. SIZE_T dwReadBytes;
  600. BOOL worked = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, &newData, 1, &dwReadBytes);
  601. if (!worked)
  602. {
  603. int err = GetLastError();
  604. BfLogDbg("SetBreakpoint FAILED %p\n", address);
  605. }
  606. FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, 1);
  607. {
  608. uint8 mem = ReadMemory<uint8>(address);
  609. BfLogDbg("Breakpoint byte %X\n", mem);
  610. }
  611. }
  612. void WinDebugger::SetBreakpoint(addr_target address, bool fromRehup)
  613. {
  614. int* countPtr = NULL;
  615. if (mPhysBreakpointAddrMap.TryAdd(address, NULL, &countPtr))
  616. {
  617. BfLogDbg("SetBreakpoint %p\n", address);
  618. *countPtr = 1;
  619. }
  620. else
  621. {
  622. if (fromRehup)
  623. {
  624. BfLogDbg("SetBreakpoint %p Count: %d. Rehup (ignored).\n", address, *countPtr);
  625. return;
  626. }
  627. (*countPtr)++;
  628. BfLogDbg("SetBreakpoint %p Count: %d\n", address, *countPtr);
  629. return;
  630. }
  631. PhysSetBreakpoint(address);
  632. }
  633. void WinDebugger::SetTempBreakpoint(addr_target address)
  634. {
  635. BfLogDbg("SetTempBreakpoint %p\n", address);
  636. mTempBreakpoint.push_back(address);
  637. SetBreakpoint(address);
  638. }
  639. void WinDebugger::PhysRemoveBreakpoint(addr_target address)
  640. {
  641. BfLogDbg("PhysRemoveBreakpoint %p\n", address);
  642. uint8 origData;
  643. DbgMemoryFlags flags = mDebugTarget->ReadOrigImageData(address, &origData, 1);
  644. if ((flags & DbgMemoryFlags_Execute) == 0)
  645. {
  646. //BF_ASSERT("Failed" == 0);
  647. return;
  648. }
  649. SIZE_T dwReadBytes;
  650. if (!WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, &origData, 1, &dwReadBytes))
  651. {
  652. int err = GetLastError();
  653. BfLogDbg("RemoveBreakpoint FAILED %p\n", address);
  654. }
  655. FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, 1);
  656. }
  657. void WinDebugger::RemoveBreakpoint(addr_target address)
  658. {
  659. int* countPtr = NULL;
  660. mPhysBreakpointAddrMap.TryGetValue(address, &countPtr);
  661. // This can happen when we shutdown and we're continuing from a breakpoint
  662. //BF_ASSERT(*countPtr != NULL);
  663. if (countPtr == NULL)
  664. {
  665. BfLogDbg("RemoveBreakpoint %p FAILED\n", address);
  666. return;
  667. }
  668. BfLogDbg("RemoveBreakpoint %p count: %d\n", address, *countPtr);
  669. if (*countPtr > 1)
  670. {
  671. (*countPtr)--;
  672. return;
  673. }
  674. mPhysBreakpointAddrMap.Remove(address);
  675. PhysRemoveBreakpoint(address);
  676. }
  677. void WinDebugger::SingleStepX86()
  678. {
  679. // In what cases did this catch bugs?
  680. // This caused other failures (caught in tests)
  681. // if (mActiveThread->mIsAtBreakpointAddress != 0)
  682. // {
  683. // ContinueFromBreakpoint();
  684. // return;
  685. // }
  686. BfLogDbg("Setup SingleStepX86 ActiveThread: %d\n", (mActiveThread != NULL) ? mActiveThread->mThreadId : -1);
  687. BF_CONTEXT lcContext;
  688. lcContext.ContextFlags = BF_CONTEXT_ALL;
  689. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  690. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  691. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  692. }
  693. bool WinDebugger::IsInRunState()
  694. {
  695. return (mRunState == RunState_Running) || (mRunState == RunState_Running_ToTempBreakpoint);
  696. }
  697. bool WinDebugger::ContinueFromBreakpoint()
  698. {
  699. if (mDebuggerWaitingThread->mFrozen)
  700. {
  701. BfLogDbg("ContinueFromBreakpoint bailout on frozen thread\n");
  702. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  703. mDebuggerWaitingThread->mIsAtBreakpointAddress = 0;
  704. return true;
  705. }
  706. mActiveThread = mDebuggerWaitingThread;
  707. mActiveBreakpoint = NULL;
  708. BfLogDbg("ContinueFromBreakpoint. ActiveThread: %d\n", (mActiveThread != NULL) ? mActiveThread->mThreadId : -1);
  709. BfLogDbg("ResumeThread %d\n", mActiveThread->mThreadId);
  710. BOOL success = ::ResumeThread(mActiveThread->mHThread);
  711. if (success)
  712. {
  713. // It's possible the active thread is suspended - possibly by the GC, so we would deadlock if we
  714. // attempted to pause the other threads
  715. BfLogDbg("SuspendThread %d\n", mActiveThread->mThreadId);
  716. BfLogDbg("Thread already paused!\n");
  717. ::SuspendThread(mActiveThread->mHThread);
  718. return false;
  719. }
  720. ThreadRestorePause(NULL, mActiveThread);
  721. PhysRemoveBreakpoint(mActiveThread->mIsAtBreakpointAddress);
  722. BF_CONTEXT lcContext;
  723. lcContext.ContextFlags = BF_CONTEXT_ALL;
  724. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  725. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  726. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  727. mActiveThread->mStoppedAtAddress = 0;
  728. mActiveThread->mBreakpointAddressContinuing = mActiveThread->mIsAtBreakpointAddress;
  729. mActiveThread->mIsAtBreakpointAddress = 0;
  730. BfLogDbg("ContinueFromBreakpoint set mIsAtBreakpointAddress = 0\n");
  731. return true;
  732. }
  733. void WinDebugger::ValidateBreakpoints()
  734. {
  735. HashSet<addr_target> usedBreakpoints;
  736. std::function<void(WdBreakpoint*)> _AddBreakpoint = [&](WdBreakpoint* breakpoint)
  737. {
  738. if (breakpoint->mAddr != 0)
  739. {
  740. usedBreakpoints.Add(breakpoint->mAddr);
  741. WdBreakpoint* foundBreakpoint = NULL;
  742. auto itr = mBreakpointAddrMap.Find(breakpoint->mAddr);
  743. bool found = false;
  744. while (itr != mBreakpointAddrMap.end())
  745. {
  746. WdBreakpoint* foundBreakpoint = itr->mValue;
  747. found |= foundBreakpoint == breakpoint;
  748. itr.NextWithSameKey(breakpoint->mAddr);
  749. }
  750. BF_ASSERT(found);
  751. }
  752. auto checkSibling = (WdBreakpoint*)breakpoint->mLinkedSibling;
  753. while (checkSibling != NULL)
  754. {
  755. _AddBreakpoint(checkSibling);
  756. checkSibling = (WdBreakpoint*)checkSibling->mLinkedSibling;
  757. }
  758. };
  759. for (auto breakpoint : mBreakpoints)
  760. _AddBreakpoint(breakpoint);
  761. for (auto& entry : mBreakpointAddrMap)
  762. {
  763. BF_ASSERT(usedBreakpoints.Contains(entry.mKey));
  764. }
  765. }
  766. Breakpoint* WinDebugger::FindBreakpointAt(intptr address)
  767. {
  768. #ifdef _DEBUG
  769. //ValidateBreakpoints();
  770. #endif
  771. WdBreakpoint* breakpoint = NULL;
  772. mBreakpointAddrMap.TryGetValue(address, &breakpoint);
  773. return breakpoint;
  774. }
  775. Breakpoint* WinDebugger::GetActiveBreakpoint()
  776. {
  777. if ((mActiveBreakpoint != NULL) && (mActiveBreakpoint->mHead != NULL))
  778. return mActiveBreakpoint->mHead;
  779. return mActiveBreakpoint;
  780. }
  781. void WinDebugger::DebugThreadProc()
  782. {
  783. BpSetThreadName("DebugThread");
  784. BfpThread_SetName(NULL, "DebugThread", NULL);
  785. mDebuggerThreadId = GetCurrentThreadId();
  786. if (!IsMiniDumpDebugger())
  787. {
  788. if (!DoOpenFile(mLaunchPath, mArgs, mWorkingDir, mEnvBlock))
  789. {
  790. if (mDbgProcessId != 0)
  791. OutputRawMessage("error Unable to attach to process");
  792. else
  793. OutputRawMessage(StrFormat("error Failed to launch: %s", mLaunchPath.c_str()));
  794. mShuttingDown = true;
  795. mRunState = RunState_Terminated;
  796. }
  797. }
  798. while (!mShuttingDown)
  799. {
  800. DoUpdate();
  801. }
  802. mIsRunning = false;
  803. for (int i = 0; i < (int) mBreakpoints.size(); i++)
  804. {
  805. WdBreakpoint* wdBreakpoint = mBreakpoints[i];
  806. if (wdBreakpoint->mAddr != 0)
  807. mBreakpointAddrMap.Remove(wdBreakpoint->mAddr, wdBreakpoint);
  808. wdBreakpoint->mAddr = 0;
  809. wdBreakpoint->mLineData = DbgLineDataEx();
  810. wdBreakpoint->mSrcFile = NULL;
  811. if (wdBreakpoint->mLinkedSibling != NULL)
  812. {
  813. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  814. wdBreakpoint->mLinkedSibling = NULL;
  815. }
  816. }
  817. if (!IsMiniDumpDebugger())
  818. {
  819. while (true)
  820. {
  821. if (!mIsDebuggerWaiting)
  822. {
  823. if (!WaitForDebugEvent(&mDebugEvent, 0))
  824. break;
  825. }
  826. if (mDebuggerWaitingThread != NULL)
  827. {
  828. BF_ASSERT_REL((mDebuggerWaitingThread->mIsAtBreakpointAddress == 0) || (mShuttingDown));
  829. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_CONTINUE);
  830. BfLogDbg("::ContinueDebugEvent startup ThreadId:%d\n", mDebuggerWaitingThread->mThreadId);
  831. }
  832. mIsDebuggerWaiting = false;
  833. mDebuggerWaitingThread = NULL;
  834. }
  835. }
  836. mDebuggerThreadId = 0;
  837. }
  838. static void DebugThreadProcThunk(void* winDebugger)
  839. {
  840. ((WinDebugger*) winDebugger)->DebugThreadProc();
  841. }
  842. int WinDebugger::GetAddrSize()
  843. {
  844. return sizeof(addr_target);
  845. }
  846. bool WinDebugger::CanOpen(const StringImpl& fileName, DebuggerResult* outResult)
  847. {
  848. FILE* fp = fopen(fileName.c_str(), "rb");
  849. if (fp == NULL)
  850. {
  851. *outResult = DebuggerResult_CannotOpen;
  852. return false;
  853. }
  854. FileStream fs;
  855. fs.mFP = fp;
  856. *outResult = DebuggerResult_Ok;
  857. bool canRead = DbgModule::CanRead(&fs, outResult);
  858. fclose(fp);
  859. return canRead;
  860. }
  861. void WinDebugger::OpenFile(const StringImpl& launchPath, const StringImpl& targetPath, const StringImpl& args, const StringImpl& workingDir, const Array<uint8>& envBlock)
  862. {
  863. BF_ASSERT(!mIsRunning);
  864. mLaunchPath = launchPath;
  865. mTargetPath = targetPath;
  866. mArgs = args;
  867. mWorkingDir = workingDir;
  868. mEnvBlock = envBlock;
  869. mDebugTarget = new DebugTarget(this);
  870. }
  871. bool WinDebugger::Attach(int processId, BfDbgAttachFlags attachFlags)
  872. {
  873. BF_ASSERT(!mIsRunning);
  874. mDbgAttachFlags = attachFlags;
  875. mDbgProcessHandle = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)processId);
  876. if (mDbgProcessHandle == 0)
  877. return false;
  878. BOOL is32Bit = false;
  879. if (!IsWow64Process(mDbgProcessHandle, &is32Bit))
  880. {
  881. mDbgProcessHandle = 0;
  882. ::CloseHandle(mDbgProcessHandle);
  883. return false;
  884. }
  885. bool want32Bit = sizeof(intptr_target) == 4;
  886. if (want32Bit != (is32Bit != 0))
  887. {
  888. mDbgProcessHandle = 0;
  889. ::CloseHandle(mDbgProcessHandle);
  890. return false;
  891. }
  892. HMODULE mainModule = 0;
  893. DWORD memNeeded = 0;
  894. ::EnumProcessModules(mDbgProcessHandle, &mainModule, sizeof(HMODULE), &memNeeded);
  895. WCHAR fileName[MAX_PATH] = {0};
  896. GetModuleFileNameExW(mDbgProcessHandle, mainModule, fileName, MAX_PATH);
  897. mLaunchPath = UTF8Encode(fileName);
  898. mTargetPath = mLaunchPath;
  899. mDbgProcessId = processId;
  900. mDbgProcessHandle = 0;
  901. ::CloseHandle(mDbgProcessHandle);
  902. mDebugTarget = new DebugTarget(this);
  903. return true;
  904. }
  905. void WinDebugger::Run()
  906. {
  907. mIsRunning = true;
  908. DWORD localThreadId;
  909. HANDLE hThread = ::CreateThread(NULL, 64 * 1024, (LPTHREAD_START_ROUTINE) &DebugThreadProcThunk, (void*)this, 0, &localThreadId);
  910. CloseHandle(hThread);
  911. }
  912. void WinDebugger::HotLoad(const Array<String>& objectFiles, int hotIdx)
  913. {
  914. AutoCrit autoCrit(mDebugManager->mCritSect);
  915. BfLogDbg("WinDebugger::HotLoad Start %d\n", hotIdx);
  916. SetAndRestoreValue<int> prevHotIdx(mActiveHotIdx, hotIdx);
  917. BF_ASSERT(mHotThreadStates.empty());
  918. mHotThreadStates.Resize(mThreadList.size());
  919. for (int threadIdx = 0; threadIdx < (int)mThreadList.size(); threadIdx++)
  920. {
  921. WdThreadInfo* threadInfo = mThreadList[threadIdx];
  922. SetAndRestoreValue<WdThreadInfo*> prevActiveThread(mActiveThread, threadInfo);
  923. BfLogDbg("SuspendThread %d\n", threadInfo->mThreadId);
  924. ::SuspendThread(threadInfo->mHThread);
  925. mHotThreadStates[threadIdx].mThreadId = threadInfo->mThreadId;
  926. PopulateRegisters(&mHotThreadStates[threadIdx].mRegisters);
  927. }
  928. for (auto address : mTempBreakpoint)
  929. RemoveBreakpoint(address);
  930. mTempBreakpoint.Clear();
  931. mStepBreakpointAddrs.Clear();
  932. for (auto breakpoint : mBreakpoints)
  933. {
  934. DetachBreakpoint(breakpoint);
  935. }
  936. int startingModuleIdx = (int)mDebugTarget->mDbgModules.size();
  937. bool failed = false;
  938. for (auto fileName : objectFiles)
  939. {
  940. BfLogDbg("WinDebugger::HotLoad: %s\n", fileName.c_str());
  941. DbgModule* newBinary = mDebugTarget->HotLoad(fileName, hotIdx);
  942. if ((newBinary != NULL) && (newBinary->mFailed))
  943. failed = true;
  944. }
  945. for (int moduleIdx = startingModuleIdx; moduleIdx < (int)mDebugTarget->mDbgModules.size(); moduleIdx++)
  946. {
  947. auto dbgModule = mDebugTarget->mDbgModules[moduleIdx];
  948. BF_ASSERT(dbgModule->IsObjectFile());
  949. BF_ASSERT(dbgModule->mHotIdx == hotIdx);
  950. dbgModule->FinishHotSwap();
  951. }
  952. for (auto dwarf : mDebugTarget->mDbgModules)
  953. dwarf->RevertWritingEnable();
  954. int blockAllocSinceClean = mDebugTarget->mHotHeap->mBlockAllocIdx - mDebugTarget->mLastHotHeapCleanIdx;
  955. // Clean up the hot heap every 64MB
  956. int blocksBetweenCleans = (64 * 1024 * 1024) / HotHeap::BLOCK_SIZE;
  957. #ifdef _DEBUG
  958. //TODO: This is just for testing
  959. blocksBetweenCleans = 1;
  960. #endif
  961. //TODO: Put this back after we fix the cleanup
  962. if (blockAllocSinceClean >= blocksBetweenCleans)
  963. CleanupHotHeap();
  964. mDebugTarget->RehupSrcFiles();
  965. for (int breakIdx = 0; breakIdx < (int)mBreakpoints.size(); breakIdx++)
  966. {
  967. auto breakpoint = mBreakpoints[breakIdx];
  968. CheckBreakpoint(breakpoint);
  969. }
  970. for (int hotThreadIdx = 0; hotThreadIdx < (int)mHotThreadStates.size(); hotThreadIdx++)
  971. {
  972. auto& hotThreadState = mHotThreadStates[hotThreadIdx];
  973. WdThreadInfo* threadInfo = NULL;
  974. if (!mThreadMap.TryGetValue((uint32)hotThreadState.mThreadId, &threadInfo))
  975. continue;
  976. BfLogDbg("ResumeThread %d\n", threadInfo->mThreadId);
  977. ::ResumeThread(threadInfo->mHThread);
  978. }
  979. mHotThreadStates.Clear();
  980. if (IsPaused())
  981. {
  982. ClearCallStack();
  983. UpdateCallStack();
  984. }
  985. }
  986. void WinDebugger::InitiateHotResolve(DbgHotResolveFlags flags)
  987. {
  988. AutoCrit autoCrit(mDebugManager->mCritSect);
  989. delete mHotResolveData;
  990. mHotResolveData = NULL;
  991. mHotResolveData = new DbgHotResolveData();
  992. DbgHotScanner* hotScanner = new DbgHotScanner(this);
  993. hotScanner->Scan(flags);
  994. delete hotScanner;
  995. }
  996. bool WinDebugger::DoOpenFile(const StringImpl& fileName, const StringImpl& args, const StringImpl& workingDir, const Array<uint8>& envBlock)
  997. {
  998. BP_ZONE("WinDebugger::DoOpenFile");
  999. AutoCrit autoCrit(mDebugManager->mCritSect);
  1000. //gDbgPerfManager->StartRecording();
  1001. STARTUPINFOW si;
  1002. ZeroMemory(&si, sizeof(si));
  1003. si.cb = sizeof(si);
  1004. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  1005. if (mDbgProcessId != 0)
  1006. {
  1007. BOOL success = ::DebugActiveProcess(mDbgProcessId);
  1008. if (!success)
  1009. return false;
  1010. mProcessInfo.dwProcessId = mDbgProcessId;
  1011. }
  1012. else
  1013. {
  1014. BP_ZONE("DoOpenFile_CreateProcessW");
  1015. UTF16String envW;
  1016. DWORD flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS | CREATE_DEFAULT_ERROR_MODE;
  1017. void* envPtr = NULL;
  1018. if (!envBlock.IsEmpty())
  1019. {
  1020. //UTF16?
  1021. if (envBlock[1] == 0)
  1022. {
  1023. envPtr = (void*)&envBlock[0];
  1024. flags |= CREATE_UNICODE_ENVIRONMENT;
  1025. }
  1026. else
  1027. {
  1028. String str8((char*)&envBlock[0], (int)envBlock.size());
  1029. envW = UTF8Decode(str8);
  1030. envPtr = (void*)envW.c_str();
  1031. flags |= CREATE_UNICODE_ENVIRONMENT;
  1032. }
  1033. }
  1034. String cmdLine = "\"";
  1035. cmdLine += fileName;
  1036. cmdLine += "\"";
  1037. if (!args.IsEmpty())
  1038. {
  1039. cmdLine += " ";
  1040. cmdLine += args;
  1041. }
  1042. BOOL worked = CreateProcessW(NULL, (WCHAR*)UTF8Decode(cmdLine).c_str(), NULL, NULL, FALSE,
  1043. flags, envPtr, (WCHAR*)UTF8Decode(workingDir).c_str(), &si, &mProcessInfo);
  1044. if (!worked)
  1045. {
  1046. auto lastError = ::GetLastError();
  1047. if (lastError == ERROR_DIRECTORY)
  1048. {
  1049. mDebugManager->mOutMessages.push_back(StrFormat("error Unable to locate specified working directory '%s'", SlashString(workingDir, false, false).c_str()));
  1050. }
  1051. return false;
  1052. }
  1053. WdThreadInfo* threadInfo = new WdThreadInfo();
  1054. threadInfo->mProcessId = mProcessInfo.dwProcessId;
  1055. threadInfo->mThreadId = mProcessInfo.dwThreadId;
  1056. threadInfo->mHThread = mProcessInfo.hThread;
  1057. threadInfo->mThreadLocalBase = NULL;
  1058. threadInfo->mStartAddress = NULL;
  1059. mThreadMap[mProcessInfo.dwThreadId] = threadInfo;
  1060. mThreadList.push_back(threadInfo);
  1061. }
  1062. mRunState = RunState_Running;
  1063. while (true)
  1064. {
  1065. BP_ZONE("DoOpenFile_WaitForImageBase");
  1066. autoCrit.mCritSect->Unlock();
  1067. DoUpdate();
  1068. autoCrit.mCritSect->Lock();
  1069. ContinueDebugEvent();
  1070. if ((mDebugTarget->mLaunchBinary != NULL) && (mDebugTarget->mLaunchBinary->mOrigImageData != NULL))
  1071. break;
  1072. }
  1073. RehupBreakpoints(true);
  1074. //gDbgPerfManager->StopRecording();
  1075. //gDbgPerfManager->DbgPrint();
  1076. return true;
  1077. }
  1078. void WinDebugger::StopDebugging()
  1079. {
  1080. AutoCrit autoCrit(mDebugManager->mCritSect);
  1081. BfLogDbg("WinDebugger::Terminate\n");
  1082. if (mActiveSymSrvRequest != NULL)
  1083. mActiveSymSrvRequest->Cancel();
  1084. if ((mRunState == RunState_NotStarted) || (mRunState == RunState_Terminated) || (mRunState == RunState_Terminating))
  1085. return;
  1086. if ((mDbgProcessId != 0) && ((mDbgAttachFlags & BfDbgAttachFlag_ShutdownOnExit) == 0))
  1087. {
  1088. for (auto address : mTempBreakpoint)
  1089. RemoveBreakpoint(address);
  1090. for (auto breakpoint : mBreakpoints)
  1091. DetachBreakpoint(breakpoint);
  1092. BfLogDbg("StopDebugging\n");
  1093. ::DebugActiveProcessStop(mDbgProcessId);
  1094. mRunState = RunState_Terminated;
  1095. BfLogDbg("mRunState = RunState_Terminated\n");
  1096. }
  1097. else
  1098. {
  1099. TerminateProcess(mProcessInfo.hProcess, 0);
  1100. mRunState = RunState_Terminating;
  1101. BfLogDbg("mRunState = RunState_Terminating\n");
  1102. }
  1103. }
  1104. void WinDebugger::Terminate()
  1105. {
  1106. AutoCrit autoCrit(mDebugManager->mCritSect);
  1107. BfLogDbg("WinDebugger::Terminate\n");
  1108. if (mActiveSymSrvRequest != NULL)
  1109. mActiveSymSrvRequest->Cancel();
  1110. if ((mRunState == RunState_NotStarted) || (mRunState == RunState_Terminated) || (mRunState == RunState_Terminating))
  1111. return;
  1112. TerminateProcess(mProcessInfo.hProcess, 0);
  1113. mRunState = RunState_Terminating;
  1114. BfLogDbg("mRunState = RunState_Terminating\n");
  1115. }
  1116. static int gDebugUpdateCnt = 0;
  1117. void WinDebugger::Detach()
  1118. {
  1119. BfLogDbg("Debugger Detach\n");
  1120. mDebugManager->mNetManager->CancelAll();
  1121. while ((mIsRunning) || (mDebuggerThreadId != 0))
  1122. {
  1123. mShuttingDown = true;
  1124. Sleep(1);
  1125. }
  1126. for (auto profiler : mProfilerSet)
  1127. profiler->Stop();
  1128. BfLogDbg("Debugger Detach - thread finished\n");
  1129. mPendingProfilerMap.Clear();
  1130. for (auto profiler : mNewProfilerList)
  1131. delete profiler;
  1132. mNewProfilerList.Clear();
  1133. mPendingImageLoad.Clear();
  1134. mPendingDebugInfoLoad.Clear();
  1135. RemoveTempBreakpoints();
  1136. mContinueEvent.Reset();
  1137. if (mDebugTarget != mEmptyDebugTarget)
  1138. delete mDebugTarget;
  1139. mDebugTarget = mEmptyDebugTarget;
  1140. mShuttingDown = false;
  1141. mStepSP = 0;
  1142. ClearCallStack();
  1143. mRunState = RunState_NotStarted;
  1144. mStepType = StepType_None;
  1145. mHadImageFindError = false;
  1146. mIsPartialCallStack = true;
  1147. delete mDebugPendingExpr;
  1148. mDebugPendingExpr = NULL;
  1149. for (auto threadPair : mThreadMap)
  1150. {
  1151. auto threadInfo = threadPair.mValue;
  1152. delete threadInfo;
  1153. }
  1154. mThreadMap.Clear();
  1155. mThreadList.Clear();
  1156. mHotTargetMemory.Clear();
  1157. // We don't need to close the hThread when we have attached to a process
  1158. if (mDbgProcessId == 0)
  1159. {
  1160. CloseHandle(mProcessInfo.hThread);
  1161. CloseHandle(mProcessInfo.hProcess);
  1162. }
  1163. for (auto breakpoint : mBreakpoints)
  1164. {
  1165. if (!mDestroying)
  1166. {
  1167. BF_FATAL("Breakpoints should be deleted already");
  1168. }
  1169. if (breakpoint->mMemoryBreakpointInfo != NULL)
  1170. {
  1171. DetachBreakpoint(breakpoint);
  1172. }
  1173. }
  1174. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  1175. mStepBreakpointAddrs.Clear();
  1176. mIsRunning = false;
  1177. mDbgAttachFlags = BfDbgAttachFlag_None;
  1178. mDbgProcessId = 0;
  1179. mDbgProcessHandle = 0;
  1180. ClearCallStack();
  1181. mWantsDebugContinue = false;
  1182. mAtBreakThread = NULL;
  1183. mActiveThread = NULL;
  1184. mActiveBreakpoint = NULL;
  1185. mSteppingThread = NULL;
  1186. mExplicitStopThread = NULL;
  1187. mIsContinuingFromException = false;
  1188. mGotStartupEvent = false;
  1189. mIsDebuggerWaiting = false;
  1190. mPhysBreakpointAddrMap.Clear();
  1191. mBreakpointAddrMap.Clear();
  1192. gDebugUpdateCnt = 0;
  1193. }
  1194. Profiler* WinDebugger::StartProfiling()
  1195. {
  1196. return new DbgProfiler(this);
  1197. }
  1198. Profiler* WinDebugger::PopProfiler()
  1199. {
  1200. AutoCrit autoCrit(mDebugManager->mCritSect);
  1201. if (mNewProfilerList.IsEmpty())
  1202. return NULL;
  1203. auto profiler = (DbgProfiler*)mNewProfilerList[0];
  1204. mNewProfilerList.erase(mNewProfilerList.begin());
  1205. return profiler;
  1206. }
  1207. void WinDebugger::AddProfiler(DbgProfiler * profiler)
  1208. {
  1209. AutoCrit autoCrit(mDebugManager->mCritSect);
  1210. mProfilerSet.Add(profiler);
  1211. }
  1212. void WinDebugger::RemoveProfiler(DbgProfiler * profiler)
  1213. {
  1214. AutoCrit autoCrit(mDebugManager->mCritSect);
  1215. mProfilerSet.Remove(profiler);
  1216. }
  1217. void WinDebugger::ReportMemory(MemReporter* memReporter)
  1218. {
  1219. mEmptyDebugTarget->ReportMemory(memReporter);
  1220. if (mDebugTarget != mEmptyDebugTarget)
  1221. mDebugTarget->ReportMemory(memReporter);
  1222. }
  1223. void WinDebugger::ModuleChanged(DbgModule* dbgModule)
  1224. {
  1225. mDebugManager->mOutMessages.push_back(String("dbgInfoLoaded ") + dbgModule->mFilePath);
  1226. }
  1227. bool WinDebugger::DoUpdate()
  1228. {
  1229. if ((mDbgProcessId != 0) && ((mDbgAttachFlags & BfDbgAttachFlag_ShutdownOnExit) == 0))
  1230. ::DebugSetProcessKillOnExit(FALSE);
  1231. else
  1232. ::DebugSetProcessKillOnExit(TRUE);
  1233. //
  1234. {
  1235. AutoCrit autoCrit(mDebugManager->mCritSect);
  1236. auto _ModuleChanged = [&](DbgModule* dbgModule)
  1237. {
  1238. ModuleChanged(dbgModule);
  1239. ClearCallStack(); // We may have actual dbgSubprograms and stuff now...
  1240. };
  1241. for (auto dbgModule : mPendingImageLoad)
  1242. {
  1243. dbgModule->PreCacheImage();
  1244. }
  1245. for (auto kv : mPendingDebugInfoLoad)
  1246. {
  1247. kv.mKey->PreCacheDebugInfo();
  1248. }
  1249. while (!mPendingImageLoad.IsEmpty())
  1250. {
  1251. auto dbgModule = mPendingImageLoad.back();
  1252. mPendingImageLoad.pop_back();
  1253. dbgModule->RequestImage();
  1254. _ModuleChanged(dbgModule);
  1255. }
  1256. if (!mPendingDebugInfoLoad.IsEmpty())
  1257. {
  1258. Array<DbgPendingDebugInfoLoad> pendingList;
  1259. for (auto kv : mPendingDebugInfoLoad)
  1260. pendingList.Add(kv.mValue);
  1261. mPendingDebugInfoLoad.Clear();
  1262. for (auto& entry : pendingList)
  1263. {
  1264. auto dbgModule = entry.mModule;
  1265. entry.mModule->RequestDebugInfo(entry.mAllowRemote);
  1266. // We do a "_ModuleChanged" even if the load failed, so we rehup the callstack and stop
  1267. // saying "<Loading...>"
  1268. _ModuleChanged(entry.mModule);
  1269. }
  1270. }
  1271. }
  1272. if (IsMiniDumpDebugger())
  1273. {
  1274. //
  1275. {
  1276. AutoCrit autoCrit(mDebugManager->mCritSect);
  1277. if (mRunState == RunState_Terminating)
  1278. {
  1279. mRunState = RunState_Terminated;
  1280. return false;
  1281. }
  1282. }
  1283. Sleep(20);
  1284. return false;
  1285. }
  1286. if (mIsDebuggerWaiting)
  1287. {
  1288. if ((IsInRunState()) || (mRunState == RunState_Terminating) || (mRunState == RunState_DebugEval))
  1289. ContinueDebugEvent();
  1290. if (mContinueEvent.WaitFor(8))
  1291. {
  1292. BF_ASSERT(!mWantsDebugContinue); // mWantsDebugContinue should already been reset
  1293. BfLogDbg("::ContinueDebugEvent 1 ThreadId:%d\n", mDebuggerWaitingThread->mThreadId);
  1294. BF_ASSERT_REL(mDebuggerWaitingThread->mIsAtBreakpointAddress == 0);
  1295. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, mIsContinuingFromException ? DBG_EXCEPTION_NOT_HANDLED : DBG_CONTINUE);
  1296. mIsContinuingFromException = false;
  1297. mIsDebuggerWaiting = false;
  1298. mDebuggerWaitingThread = NULL;
  1299. }
  1300. else
  1301. return false;
  1302. }
  1303. if (!WaitForDebugEvent(&mDebugEvent, 8))
  1304. return false;
  1305. gDebugUpdateCnt++;
  1306. static const char* eventNames[] = { "DBG_EVENT ?",
  1307. "EXCEPTION_DEBUG_EVENT",
  1308. "CREATE_THREAD_DEBUG_EVENT",
  1309. "CREATE_PROCESS_DEBUG_EVENT",
  1310. "EXIT_THREAD_DEBUG_EVENT",
  1311. "EXIT_PROCESS_DEBUG_EVENT",
  1312. "LOAD_DLL_DEBUG_EVENT",
  1313. "UNLOAD_DLL_DEBUG_EVENT",
  1314. "OUTPUT_DEBUG_STRING_EVENT",
  1315. "RIP_EVENT"};
  1316. BfLogDbg("WaitForDebugEvent %s ThreadId:%d\n", eventNames[mDebugEvent.dwDebugEventCode], mDebugEvent.dwThreadId);
  1317. BP_ZONE(eventNames[mDebugEvent.dwDebugEventCode]);
  1318. AutoCrit autoCrit(mDebugManager->mCritSect);
  1319. mActiveBreakpoint = NULL;
  1320. mIsDebuggerWaiting = true;
  1321. mWantsDebugContinue = true;
  1322. mRequestedStackFrameIdx = 0;
  1323. mBreakStackFrameIdx = 0;
  1324. mShowPCOverride = 0;
  1325. WdThreadInfo* threadInfo = NULL;
  1326. mThreadMap.TryGetValue(mDebugEvent.dwThreadId, &threadInfo);
  1327. mDebuggerWaitingThread = threadInfo;
  1328. mExplicitStopThread = mDebuggerWaitingThread;
  1329. switch (mDebugEvent.dwDebugEventCode)
  1330. {
  1331. case CREATE_PROCESS_DEBUG_EVENT:
  1332. {
  1333. if (threadInfo == NULL)
  1334. {
  1335. BF_ASSERT(mThreadMap.size() == 0);
  1336. WdThreadInfo* newThreadInfo = new WdThreadInfo();
  1337. newThreadInfo->mProcessId = mDebugEvent.dwProcessId;
  1338. newThreadInfo->mThreadId = mDebugEvent.dwThreadId;
  1339. newThreadInfo->mHThread = mDebugEvent.u.CreateProcessInfo.hThread;
  1340. newThreadInfo->mThreadLocalBase = mDebugEvent.u.CreateProcessInfo.lpThreadLocalBase;
  1341. newThreadInfo->mStartAddress = (void*)mDebugEvent.u.CreateProcessInfo.lpStartAddress;
  1342. BF_CONTEXT lcContext;
  1343. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1344. BF_GetThreadContext(newThreadInfo->mHThread, &lcContext);
  1345. newThreadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1346. mThreadMap[mDebugEvent.dwThreadId] = newThreadInfo;
  1347. mDebuggerWaitingThread = newThreadInfo;
  1348. mThreadList.push_back(mDebuggerWaitingThread);
  1349. UpdateThreadDebugRegisters();
  1350. OutputMessage(StrFormat("Creating thread from CREATE_PROCESS_DEBUG_EVENT %d\n", mDebugEvent.dwThreadId));
  1351. threadInfo = mDebuggerWaitingThread;
  1352. mProcessInfo.dwThreadId = threadInfo->mThreadId;
  1353. mProcessInfo.hThread = threadInfo->mHThread;
  1354. mProcessInfo.hProcess = mDebugEvent.u.CreateProcessInfo.hProcess;
  1355. }
  1356. else
  1357. {
  1358. threadInfo->mThreadLocalBase = mDebugEvent.u.CreateProcessInfo.lpThreadLocalBase;
  1359. threadInfo->mStartAddress = (void*)mDebugEvent.u.CreateProcessInfo.lpStartAddress;
  1360. }
  1361. BF_CONTEXT lcContext;
  1362. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1363. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1364. threadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1365. DbgModule* launchBinary = mDebugTarget->Init(mLaunchPath, mTargetPath, (addr_target)(intptr)mDebugEvent.u.CreateProcessInfo.lpBaseOfImage);
  1366. addr_target gotImageBase = (addr_target)(intptr)mDebugEvent.u.CreateProcessInfo.lpBaseOfImage;
  1367. if (launchBinary->mImageBase != gotImageBase)
  1368. {
  1369. BF_FATAL("Image base didn't match");
  1370. }
  1371. launchBinary->mImageBase = gotImageBase;
  1372. launchBinary->mImageSize = (int)launchBinary->GetImageSize();
  1373. launchBinary->mOrigImageData = new DbgModuleMemoryCache(launchBinary->mImageBase, launchBinary->mImageSize);
  1374. if (launchBinary == mDebugTarget->mTargetBinary)
  1375. mDebugTarget->SetupTargetBinary();
  1376. if (mDebugEvent.u.CreateProcessInfo.hFile != NULL)
  1377. CloseHandle(mDebugEvent.u.CreateProcessInfo.hFile);
  1378. mDbgProcessHandle = mDebugEvent.u.CreateProcessInfo.hProcess;
  1379. mDbgThreadHandle = mDebugEvent.u.CreateProcessInfo.hThread;
  1380. mGotStartupEvent = true;
  1381. mDebugManager->mOutMessages.push_back("modulesChanged");
  1382. }
  1383. break;
  1384. case EXIT_PROCESS_DEBUG_EVENT:
  1385. {
  1386. BfLogDbg("EXIT_PROCESS_DEBUG_EVENT\n");
  1387. DWORD exitCode = mDebugEvent.u.ExitProcess.dwExitCode;
  1388. String exitMessage;
  1389. switch (exitCode)
  1390. {
  1391. case STATUS_DLL_NOT_FOUND:
  1392. exitMessage = "STATUS_DLL_NOT_FOUND";
  1393. break;
  1394. case STATUS_DLL_INIT_FAILED:
  1395. exitMessage = "STATUS_DLL_INIT_FAILED";
  1396. break;
  1397. case STATUS_ENTRYPOINT_NOT_FOUND:
  1398. exitMessage = "STATUS_ENTRYPOINT_NOT_FOUND";
  1399. break;
  1400. }
  1401. String exitCodeStr;
  1402. if ((exitCode >= 0x10000000) && (exitCode <= 0xF7000000))
  1403. exitCodeStr = StrFormat("0x%X", exitCode);
  1404. else
  1405. exitCodeStr = StrFormat("%d", exitCode);
  1406. if (!exitMessage.IsEmpty())
  1407. OutputMessage(StrFormat("Process terminated. ExitCode: %s (%s).\n", exitCodeStr.c_str(), exitMessage.c_str()));
  1408. else
  1409. OutputMessage(StrFormat("Process terminated. ExitCode: %s.\n", exitCodeStr.c_str()));
  1410. mRunState = RunState_Terminated;
  1411. mDebugManager->mOutMessages.push_back("modulesChanged");
  1412. }
  1413. break;
  1414. case LOAD_DLL_DEBUG_EVENT:
  1415. {
  1416. WCHAR moduleNameStr[MAX_PATH] = { 0 };
  1417. GetFinalPathNameByHandleW(mDebugEvent.u.LoadDll.hFile, moduleNameStr, MAX_PATH, FILE_NAME_NORMALIZED);
  1418. std::wstring wow64Dir;
  1419. std::wstring systemDir;
  1420. PWSTR wow64DirPtr = NULL;
  1421. SHGetKnownFolderPath(FOLDERID_SystemX86, KF_FLAG_NO_ALIAS, NULL, &wow64DirPtr);
  1422. if (wow64DirPtr != NULL)
  1423. {
  1424. wow64Dir = wow64DirPtr;
  1425. CoTaskMemFree(wow64DirPtr);
  1426. }
  1427. PWSTR systemDirPtr = NULL;
  1428. SHGetKnownFolderPath(FOLDERID_System, KF_FLAG_NO_ALIAS, NULL, &systemDirPtr);
  1429. if (systemDirPtr != NULL)
  1430. {
  1431. systemDir = systemDirPtr;
  1432. CoTaskMemFree(systemDirPtr);
  1433. }
  1434. if ((mDebugEvent.u.LoadDll.lpImageName != 0) && (mDebugEvent.u.LoadDll.fUnicode))
  1435. {
  1436. addr_target strAddr = ReadMemory<addr_target>((addr_target)(intptr)mDebugEvent.u.LoadDll.lpImageName);
  1437. for (int i = 0; i < MAX_PATH - 1; i++)
  1438. {
  1439. WCHAR c = ReadMemory<WCHAR>(strAddr + i*2);
  1440. moduleNameStr[i] = (WCHAR)c;
  1441. if (c == 0)
  1442. break;
  1443. }
  1444. }
  1445. String origModuleName = UTF8Encode(moduleNameStr);
  1446. String moduleName = origModuleName;
  1447. String loadMsg;
  1448. HANDLE altFileHandle = INVALID_HANDLE_VALUE;
  1449. if (moduleName != origModuleName)
  1450. {
  1451. loadMsg = StrFormat("Loading DLL: %s(%s) @ %s", origModuleName.c_str(), moduleName.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.LoadDll.lpBaseOfDll, true).c_str());
  1452. altFileHandle = ::CreateFileW(UTF8Decode(moduleName).c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  1453. }
  1454. else
  1455. {
  1456. loadMsg = StrFormat("Loading DLL: %s @ %s", moduleName.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.LoadDll.lpBaseOfDll, true).c_str());
  1457. }
  1458. BfLogDbg("LOAD_DLL_DEBUG_EVENT %s\n", moduleName.c_str());
  1459. bool skipLoad = false;
  1460. #ifdef BF_DBG_32
  1461. if (((uintptr)mDebugEvent.u.LoadDll.lpBaseOfDll & 0xFFFFFFFF00000000LL) != 0)
  1462. {
  1463. skipLoad = true;
  1464. loadMsg += " - Skipped";
  1465. }
  1466. #endif
  1467. if (!skipLoad)
  1468. {
  1469. FileHandleStream stream;
  1470. stream.mFileHandle = mDebugEvent.u.LoadDll.hFile;
  1471. if (altFileHandle != INVALID_HANDLE_VALUE)
  1472. stream.mFileHandle = altFileHandle;
  1473. if (mDebugTarget->SetupDyn(moduleName, &stream, (intptr)mDebugEvent.u.LoadDll.lpBaseOfDll) == NULL)
  1474. loadMsg += " - Failed to load";
  1475. stream.mFileHandle = 0;
  1476. }
  1477. OutputMessage(loadMsg + "\n");
  1478. if (altFileHandle != INVALID_HANDLE_VALUE)
  1479. ::CloseHandle(altFileHandle);
  1480. ::CloseHandle(mDebugEvent.u.LoadDll.hFile);
  1481. // Try to bind any breakpoints tied to this DLL
  1482. RehupBreakpoints(true);
  1483. mDebugManager->mOutMessages.push_back("modulesChanged");
  1484. }
  1485. break;
  1486. case UNLOAD_DLL_DEBUG_EVENT:
  1487. {
  1488. bool needsBreakpointRehup = false;
  1489. String name = "???";
  1490. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress((addr_target)(intptr)mDebugEvent.u.UnloadDll.lpBaseOfDll);
  1491. if (dbgModule != NULL)
  1492. {
  1493. name = dbgModule->mFilePath;
  1494. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  1495. {
  1496. auto breakpoint = mBreakpoints[i];
  1497. auto checkBreakpoint = breakpoint;
  1498. bool hasAddr = false;
  1499. while (checkBreakpoint != NULL)
  1500. {
  1501. if ((checkBreakpoint->mAddr >= dbgModule->mImageBase) && (checkBreakpoint->mAddr < dbgModule->mImageBase + dbgModule->mImageSize))
  1502. hasAddr = true;
  1503. checkBreakpoint = (WdBreakpoint*)checkBreakpoint->mLinkedSibling;
  1504. }
  1505. if (hasAddr)
  1506. {
  1507. DetachBreakpoint(breakpoint);
  1508. needsBreakpointRehup = true;
  1509. }
  1510. }
  1511. mDebugTarget->UnloadDyn(dbgModule->mImageBase);
  1512. if (needsBreakpointRehup)
  1513. RehupBreakpoints(true);
  1514. mPendingDebugInfoLoad.Remove(dbgModule);
  1515. mPendingDebugInfoRequests.Remove(dbgModule);
  1516. mDebugManager->mOutMessages.push_back("modulesChanged");
  1517. }
  1518. if (!name.empty())
  1519. OutputMessage(StrFormat("Unloading DLL: %s @ %0s\n", name.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.UnloadDll.lpBaseOfDll, true).c_str()));
  1520. BfLogDbg("UNLOAD_DLL_DEBUG_EVENT %s\n", name.c_str());
  1521. }
  1522. break;
  1523. case OUTPUT_DEBUG_STRING_EVENT:
  1524. {
  1525. const int maxChars = 1024 * 1024;
  1526. int len = BF_MIN(maxChars, (int)mDebugEvent.u.DebugString.nDebugStringLength); // 1MB max
  1527. char* message = new char[len + 1];
  1528. message[0] = 0;
  1529. message[len] = 0;
  1530. ReadMemory((addr_target)(intptr)mDebugEvent.u.DebugString.lpDebugStringData, len, message);
  1531. if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId == mDebugEvalThreadInfo.mThreadId))
  1532. mDebugManager->mOutMessages.push_back(String("dbgEvalMsg ") + message);
  1533. else
  1534. mDebugManager->mOutMessages.push_back(String("msg ") + message);
  1535. BfLogDbg("OUTPUT_DEBUG_STRING_EVENT (BreakAddr:%@): %s\n", threadInfo->mIsAtBreakpointAddress, message);
  1536. BF_ASSERT_REL(threadInfo->mIsAtBreakpointAddress == 0);
  1537. delete [] message;
  1538. }
  1539. break;
  1540. case CREATE_THREAD_DEBUG_EVENT:
  1541. {
  1542. WdThreadInfo* threadInfo = new WdThreadInfo();
  1543. threadInfo->mProcessId = mDebugEvent.dwProcessId;
  1544. threadInfo->mThreadId = mDebugEvent.dwThreadId;
  1545. threadInfo->mHThread = mDebugEvent.u.CreateThread.hThread;
  1546. threadInfo->mThreadLocalBase = mDebugEvent.u.CreateThread.lpThreadLocalBase;
  1547. threadInfo->mStartAddress = (void*)mDebugEvent.u.CreateThread.lpStartAddress;
  1548. BF_CONTEXT lcContext;
  1549. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1550. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1551. threadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1552. mThreadMap[mDebugEvent.dwThreadId] = threadInfo;
  1553. mDebuggerWaitingThread = threadInfo;
  1554. mThreadList.push_back(mDebuggerWaitingThread);
  1555. UpdateThreadDebugRegisters();
  1556. OutputMessage(StrFormat("Creating thread %d\n", mDebugEvent.dwThreadId));
  1557. }
  1558. break;
  1559. case EXIT_THREAD_DEBUG_EVENT:
  1560. {
  1561. OutputMessage(StrFormat("Exiting thread %d\n", mDebugEvent.dwThreadId));
  1562. if (mSteppingThread == threadInfo)
  1563. {
  1564. // We were attempting stepping on this thread, but not anymore!
  1565. ClearStep();
  1566. }
  1567. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_CONTINUE);
  1568. mIsDebuggerWaiting = false;
  1569. mWantsDebugContinue = false;
  1570. if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId == mDebugEvalThreadInfo.mThreadId))
  1571. {
  1572. // Thread terminated while evaluating! Is there a more graceful way of handling this?
  1573. CleanupDebugEval(false);
  1574. mRunState = RunState_Running;
  1575. }
  1576. mThreadList.Remove(mDebuggerWaitingThread);
  1577. delete mDebuggerWaitingThread;
  1578. mDebuggerWaitingThread = NULL;
  1579. mThreadMap.Remove(mDebugEvent.dwThreadId);
  1580. return true;
  1581. }
  1582. break;
  1583. case RIP_EVENT:
  1584. OutputMessage("RIP Event\n");
  1585. break;
  1586. case EXCEPTION_DEBUG_EVENT:
  1587. {
  1588. auto exceptionRecord = &mDebugEvent.u.Exception.ExceptionRecord;
  1589. switch (exceptionRecord->ExceptionCode)
  1590. {
  1591. case STATUS_WX86_BREAKPOINT:
  1592. case EXCEPTION_BREAKPOINT:
  1593. {
  1594. if (mRunState == RunState_Terminating)
  1595. {
  1596. BfLogDbg("Ignoring event because of RunState_Terminating\n");
  1597. break;
  1598. }
  1599. mAtBreakThread = threadInfo;
  1600. mActiveThread = mAtBreakThread;
  1601. bool isHighAddr = false;
  1602. #ifdef BF_DBG_32
  1603. if (((uintptr)exceptionRecord->ExceptionAddress & 0xFFFFFFFF00000000) != 0)
  1604. {
  1605. if (mActiveThread == mThreadList.front())
  1606. {
  1607. // Skip the initial Wow64 ntdll.dll!LdrpDoDebuggerBreak
  1608. mRunState = RunState_Running;
  1609. break;
  1610. }
  1611. isHighAddr = true;
  1612. }
  1613. #endif
  1614. addr_target pcAddress = (addr_target)(intptr)exceptionRecord->ExceptionAddress;
  1615. if (isHighAddr)
  1616. pcAddress = (addr_target)-1;
  1617. //mStoppedAtAddress = pcAddress;
  1618. bool isStepOut = false;
  1619. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto))
  1620. {
  1621. isStepOut = mStepBreakpointAddrs.Contains(pcAddress);
  1622. }
  1623. BF_CONTEXT lcContext;
  1624. lcContext.ContextFlags = BF_CONTEXT_ALL;
  1625. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1626. BfLogDbg("EXCEPTION_BREAKPOINT Thread:%d %p SP:%p\n", mActiveThread->mThreadId, pcAddress, BF_CONTEXT_SP(lcContext));
  1627. uint8 origImageData = 0xCC;
  1628. mDebugTarget->ReadOrigImageData(pcAddress, &origImageData, 1);
  1629. bool wasDebugBreakpoint = origImageData != 0xCC;
  1630. DbgSubprogram* dwSubprogram = NULL;
  1631. DbgLineData* dwLineData = NULL;
  1632. if (!isStepOut)
  1633. {
  1634. dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  1635. if (dwSubprogram == NULL)
  1636. dwSubprogram = mDebugTarget->FindSubProgram(pcAddress, DbgOnDemandKind_LocalOnly);
  1637. }
  1638. bool isLineStart = (dwLineData != NULL) && (dwSubprogram->GetLineAddr(*dwLineData) == pcAddress);
  1639. bool isNonDebuggerBreak = false;
  1640. if (wasDebugBreakpoint)
  1641. {
  1642. // Go ahead and set EIP back one instruction
  1643. BF_CONTEXT_IP(lcContext)--;
  1644. BF_SetThreadContext(threadInfo->mHThread, &lcContext);
  1645. if ((dwSubprogram != NULL) && (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid) &&
  1646. (pcAddress == dwSubprogram->mBlock.mLowPC))
  1647. {
  1648. BfLogDbg("Hit HotReplaceKind_Invalid breakpoint\n");
  1649. mRunState = RunState_Paused;
  1650. mDebugManager->mOutMessages.push_back("error This lambda was replaced by a new version that has incompatible captures. A program restart is required.");
  1651. PhysRemoveBreakpoint(pcAddress);
  1652. break;
  1653. }
  1654. }
  1655. else
  1656. {
  1657. // This was an actual "break" instruction
  1658. BfLogDbg("Non-debugger break\n");
  1659. isNonDebuggerBreak = true;
  1660. auto prevState = mRunState;
  1661. // Make it an "auto" stop, so for example when we have an assert/retry we won't stop inside assembly
  1662. mRequestedStackFrameIdx = -2;
  1663. mRunState = RunState_Paused;
  1664. CheckNonDebuggerBreak();
  1665. if (IsInRunState())
  1666. {
  1667. BF_ASSERT((prevState == RunState_Running) || (prevState == RunState_DebugEval));
  1668. mRunState = prevState;
  1669. break; // Continue as if nothing happened
  1670. }
  1671. if (prevState == RunState_DebugEval)
  1672. mRequestedStackFrameIdx = -1; // Don't show a rolled back stack idx if a debug eval fails
  1673. ClearStep();
  1674. }
  1675. if (threadInfo->mIsBreakRestorePaused)
  1676. {
  1677. // The thread is supposed to be paused, but the IP has been reset
  1678. // so just break here so we'll hit that breakpoint again once we're
  1679. // actually unpaused properly
  1680. BfLogDbg("Ignoring EXCEPTION_BREAKPOINT\n", threadInfo->mThreadId);
  1681. break;
  1682. }
  1683. if ((mRunState == RunState_DebugEval) || (mRunState == RunState_HotStep))
  1684. {
  1685. // If we hit a breakpoint while doing a debug eval, we just remove the breakpoint
  1686. // and expect to reinstate it during a rehup after the evaluation has completed
  1687. WdBreakpoint* breakpoint = (WdBreakpoint*)FindBreakpointAt((uintptr_t) exceptionRecord->ExceptionAddress);
  1688. if (breakpoint != NULL)
  1689. {
  1690. mNeedsRehupBreakpoints = true;
  1691. RemoveBreakpoint(breakpoint->mLineData.GetAddress());
  1692. }
  1693. break;
  1694. }
  1695. bool isDeeper = false;
  1696. int stepBreakAddrIdx = (int)mStepBreakpointAddrs.IndexOf(pcAddress);
  1697. WdBreakpoint* breakpoint = NULL;
  1698. bool ignoreBreakpoint = false;
  1699. if ((mStepType != StepType_None) && (mSteppingThread == mAtBreakThread))
  1700. {
  1701. if (mStepType == StepType_ToTempBreakpoint)
  1702. {
  1703. RemoveTempBreakpoints();
  1704. mRunState = RunState_Paused;
  1705. break;
  1706. }
  1707. if (mContinueFromBreakpointFailed)
  1708. {
  1709. BfLogDbg("Continuing from ContinueFromBreakpointFailed\n");
  1710. SetupStep(mStepType);
  1711. mRunState = RunState_Running;
  1712. break;
  1713. }
  1714. if (!isStepOut)
  1715. breakpoint = (WdBreakpoint*)FindBreakpointAt(pcAddress);
  1716. // Ignore breakpoint if it's on the line we're stepping off of
  1717. if ((breakpoint != NULL) && (breakpoint->mAddr == mStepPC) &&
  1718. (mStepSP == BF_CONTEXT_SP(lcContext)))
  1719. {
  1720. ignoreBreakpoint = true;
  1721. }
  1722. else if ((breakpoint != NULL) && (stepBreakAddrIdx == -1) && (!CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress)))
  1723. {
  1724. ignoreBreakpoint = true;
  1725. }
  1726. if ((stepBreakAddrIdx == -1) && (breakpoint == NULL) && (!isNonDebuggerBreak))
  1727. {
  1728. // If a breakpoint is removed in a prior thread
  1729. BfLogDbg("Ignoring step break (old breakpoint)\n");
  1730. if ((mSteppingThread == mAtBreakThread) && (mStepSwitchedThreads))
  1731. {
  1732. SetupStep(mStepType);
  1733. }
  1734. break;
  1735. }
  1736. if ((stepBreakAddrIdx != -1) && (breakpoint == NULL) && (mSteppingThread != mActiveThread))
  1737. {
  1738. BfLogDbg("Ignoring break (wrong thread)\n");
  1739. ThreadRestorePause(mSteppingThread, mActiveThread);
  1740. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1741. break;
  1742. }
  1743. isDeeper = mStepSP > BF_CONTEXT_SP(lcContext);
  1744. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto))
  1745. {
  1746. isDeeper = mStepSP >= BF_CONTEXT_SP(lcContext);
  1747. BfLogDbg("StepOut Iteration SP:%p StartSP:%p IsDeeper:%d\n", BF_CONTEXT_SP(lcContext), mStepSP, isDeeper);
  1748. }
  1749. if (((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto)) && (breakpoint == NULL) && (isDeeper))
  1750. {
  1751. // We're encountered recursion
  1752. // Make sure we don't already have one of these stored
  1753. BF_ASSERT(mStoredReturnValueAddr == 0);
  1754. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1755. break; // Don't fall through, we don't want to set mIsAtBreakpointAddress
  1756. }
  1757. if (isStepOut)
  1758. {
  1759. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1760. if (mStepType == StepType_StepOut_ThenInto)
  1761. {
  1762. dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  1763. if ((dwLineData != NULL) && (pcAddress == dwSubprogram->GetLineAddr(*dwLineData)))
  1764. {
  1765. // Our step out from a filtered function put us at the start of a new line. Stop here
  1766. // <do nothing>
  1767. }
  1768. else
  1769. {
  1770. // .. otherwise keep going until we get to the start of a new line
  1771. SetupStep(StepType_StepInto);
  1772. mRunState = RunState_Running;
  1773. break;
  1774. }
  1775. }
  1776. if (!mStepInAssembly)
  1777. {
  1778. // Keep stepping out until we find a frame that we have source for
  1779. DbgSubprogram* dwSubprogram = NULL;
  1780. DbgLineData* dwLineData = FindLineDataAtAddress(BF_CONTEXT_IP(lcContext), &dwSubprogram);
  1781. if (dwLineData == NULL)
  1782. {
  1783. SetupStep(StepType_StepOut);
  1784. break;
  1785. }
  1786. if ((dwLineData->mColumn == -1) && (!dwSubprogram->HasValidLines()))
  1787. {
  1788. // This is a method we don't actually want to be in, it has no valid lines!
  1789. SetupStep(StepType_StepOut);
  1790. break;
  1791. }
  1792. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  1793. {
  1794. // We've stepped out, but right into the start of an inlined method, so step out of this inlined method now...
  1795. SetupStep(StepType_StepOut);
  1796. break;
  1797. }
  1798. }
  1799. ClearStep();
  1800. mRunState = RunState_Paused;
  1801. threadInfo->mStoppedAtAddress = pcAddress;
  1802. break;
  1803. }
  1804. mRunState = RunState_Paused;
  1805. if (breakpoint != NULL)
  1806. {
  1807. // While stepping we hit a legit breakpoint
  1808. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  1809. // Ignore breakpoint on return statement if we're return-stepping
  1810. mRunState = RunState_Breakpoint;
  1811. }
  1812. if ((mStepType == StepType_StepInto) && (dwSubprogram != NULL))
  1813. {
  1814. // Don't filter out the current subprogram (would break cases where we explicitly stepped into or hit breakpoint in a filtered subprogram)
  1815. bool isInStartSubprogram = (mStepStartPC >= dwSubprogram->mBlock.mLowPC) && (mStepStartPC < dwSubprogram->mBlock.mHighPC);
  1816. if ((!isInStartSubprogram) && (IsStepFiltered(dwSubprogram, dwLineData)))
  1817. {
  1818. BfLogDbg("Hit step filter\n");
  1819. mRunState = RunState_Running;
  1820. SetupStep(StepType_StepOut_ThenInto);
  1821. break;
  1822. }
  1823. }
  1824. if ((mStepType == StepType_StepOver) && (stepBreakAddrIdx == 0) && (mStepBreakpointAddrs[0] != 0) && (mStepBreakpointAddrs.size() > 1))
  1825. {
  1826. // Break was on the 'call' instruction, not the instruction after it -- means recursion
  1827. BfLogDbg("StepOver detected recursing\n");
  1828. mStepIsRecursing = true;
  1829. if (mTempBreakpoint.Remove(mStepBreakpointAddrs[0]))
  1830. {
  1831. RemoveBreakpoint(mStepBreakpointAddrs[0]);
  1832. }
  1833. mStepBreakpointAddrs[0] = 0;
  1834. mRunState = RunState_Running;
  1835. break;
  1836. }
  1837. if ((mStepType == StepType_StepOver) && (stepBreakAddrIdx > 0) && (mStepBreakpointAddrs[0] != 0) && (isDeeper))
  1838. {
  1839. // This is the first time we've hit the target breakpoint.
  1840. if (HasSteppedIntoCall())
  1841. {
  1842. mStepIsRecursing = true;
  1843. RemoveBreakpoint(mStepBreakpointAddrs[0]);
  1844. mStepBreakpointAddrs[0] = 0;
  1845. //mStepBreakpointAddrs.erase(mStepBreakpointAddrs.begin());
  1846. }
  1847. }
  1848. if ((mStepType == StepType_StepOver) && (mStepIsRecursing) && (stepBreakAddrIdx != -1) && (isDeeper))
  1849. {
  1850. // Decrement so the equality test on "step out" marks us as not being deeper when we
  1851. // hit the expected SP
  1852. BfLogDbg("Converting StepOver to StepOut\n");
  1853. mStepSP--;
  1854. mStepType = StepType_StepOut_ThenInto;
  1855. //SetupStep(StepType_StepOut);
  1856. mRunState = RunState_Running;
  1857. break;
  1858. }
  1859. if ((mStepType == StepType_StepOver) && (!ignoreBreakpoint) && (breakpoint == NULL) && (!mStepInAssembly))
  1860. {
  1861. // Test for stepping over inline method
  1862. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  1863. // mTempBreakpoints will have 2 entries if we are on a 'call' line. If we have an inlined call immediately following a call, then we
  1864. // assume we're hitting a return break
  1865. /*if ((dwSubprogram != NULL) && (dwSubprogram->mInlineParent != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC) && (mTempBreakpoint.size() < 2))
  1866. {
  1867. BfLogDbg("Attempting StepOver of inlined method\n");
  1868. SetupStep(StepType_StepOut);
  1869. mRunState = RunState_Running;
  1870. break;
  1871. } */
  1872. //TODO: The previous logic with the "(mTempBreakpoint.size() < 2)" was causing Try!(Method()); stepovers to enter into Try!. What did we mean by
  1873. // "assume we're hitting a return break"?
  1874. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  1875. {
  1876. RemoveTempBreakpoints();
  1877. BfLogDbg("Attempting StepOver of inlined method\n");
  1878. SetupStep(StepType_StepOut);
  1879. mRunState = RunState_Running;
  1880. break;
  1881. }
  1882. }
  1883. if (mStepType == StepType_StepOut_Inline)
  1884. {
  1885. if (mOrigStepType == StepType_StepOver)
  1886. {
  1887. // For the step over, if we are still inside the source line after an inline then step over again...
  1888. DbgSubprogram* origSubprogram = NULL;
  1889. auto origLineData = FindLineDataAtAddress(mStepStartPC, &origSubprogram);
  1890. DbgSubprogram* curSubprogram = NULL;
  1891. auto curLineData = FindLineDataAtAddress(pcAddress, &curSubprogram);
  1892. if ((origLineData != NULL) &&
  1893. ((origLineData == curLineData) ||
  1894. ((origSubprogram == curSubprogram) && (origLineData->mLine == curLineData->mLine))))
  1895. {
  1896. mRunState = RunState_Running;
  1897. SetupStep(StepType_StepOver);
  1898. break;
  1899. }
  1900. }
  1901. ClearStep();
  1902. break;
  1903. }
  1904. if ((mStepType != StepType_None) && (ignoreBreakpoint) && (!mStepInAssembly) && (stepBreakAddrIdx == -1))
  1905. {
  1906. // Ignore breakpoint by just continuing...
  1907. mRunState = RunState_Running;
  1908. break;
  1909. }
  1910. RemoveTempBreakpoints();
  1911. if ((mStepType != StepType_None) && (!mStepInAssembly) && (!isLineStart) && (stepBreakAddrIdx != -1))
  1912. {
  1913. SetupStep(mStepType);
  1914. mRunState = RunState_Running;
  1915. }
  1916. else
  1917. {
  1918. //if (mStepType != StepType_Return)
  1919. if (stepBreakAddrIdx != -1)
  1920. {
  1921. // Even if we've detected we're at a breakpoint, we mark ourselves as just stepping if we also
  1922. // have a step breakpoint here
  1923. StepLineTryPause(pcAddress, true);
  1924. }
  1925. if (mRunState == RunState_Paused)
  1926. ClearStep();
  1927. }
  1928. if (ignoreBreakpoint)
  1929. {
  1930. SetupStep(mStepType);
  1931. mRunState = RunState_Running;
  1932. }
  1933. if ((mRunState == RunState_Paused) && (breakpoint != NULL))
  1934. {
  1935. // Just do the 'check' here so we can do the logging/condition stuff
  1936. CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress);
  1937. }
  1938. }
  1939. else
  1940. {
  1941. breakpoint = (WdBreakpoint*)FindBreakpointAt((uintptr_t)exceptionRecord->ExceptionAddress);
  1942. if ((breakpoint != NULL) && (!CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress)))
  1943. {
  1944. ClearCallStack();
  1945. BfLogDbg("Skipping conditional breakpoint. Setting mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  1946. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  1947. mRunState = RunState_Running;
  1948. break;
  1949. }
  1950. if (breakpoint != NULL)
  1951. {
  1952. BfLogDbg("Breakpoint hit. mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  1953. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  1954. mRunState = RunState_Breakpoint;
  1955. }
  1956. else if ((stepBreakAddrIdx != -1) || (isNonDebuggerBreak))
  1957. {
  1958. if (mRunState != RunState_DebugEval)
  1959. {
  1960. // Was in mStepBreakpointAddrs list
  1961. if ((isNonDebuggerBreak) || (mStepType == StepType_None) || (mSteppingThread == mAtBreakThread))
  1962. {
  1963. BfLogDbg("Hit mStepBreakpointAddrs breakpoint\n");
  1964. mRunState = RunState_Paused;
  1965. }
  1966. else
  1967. {
  1968. BfLogDbg("Ignored mStepBreakpointAddrs breakpoint (wrong thread)\n");
  1969. mRunState = RunState_Running;
  1970. }
  1971. }
  1972. }
  1973. else
  1974. {
  1975. BfLogDbg("Ignoring break (old or ignored breakpoint)\n");
  1976. mRunState = RunState_Running;
  1977. }
  1978. }
  1979. if ((breakpoint != NULL) && (!ignoreBreakpoint))
  1980. {
  1981. mActiveBreakpoint = breakpoint;
  1982. mBreakStackFrameIdx = -1;
  1983. }
  1984. if ((mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint))
  1985. threadInfo->mStoppedAtAddress = pcAddress;
  1986. }
  1987. break;
  1988. case STATUS_WX86_SINGLE_STEP:
  1989. case EXCEPTION_SINGLE_STEP:
  1990. {
  1991. if (mRunState == RunState_Terminating)
  1992. {
  1993. BfLogDbg("Ignoring event because of RunState_Terminating\n");
  1994. break;
  1995. }
  1996. if ((mStepSwitchedThreads) && (mActiveThread == mSteppingThread) && (mActiveThread->mIsAtBreakpointAddress != NULL))
  1997. {
  1998. ContinueFromBreakpoint();
  1999. break;
  2000. }
  2001. if (mRunState == RunState_HotStep)
  2002. {
  2003. BF_ASSERT(mActiveThread == mDebuggerWaitingThread);
  2004. mRunState = RunState_Paused;
  2005. break;
  2006. }
  2007. mActiveThread = mDebuggerWaitingThread;
  2008. BF_CONTEXT lcContext;
  2009. lcContext.ContextFlags = BF_CONTEXT_ALL;
  2010. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  2011. addr_target pcAddress = BF_CONTEXT_IP(lcContext);
  2012. bool wasUnfilteredStep = mStepType == StepType_StepInto_Unfiltered;
  2013. if (mStepType == StepType_StepInto_UnfilteredSingle)
  2014. {
  2015. wasUnfilteredStep = true;
  2016. mStepType = StepType_StepInto;
  2017. mStepStartPC = pcAddress;
  2018. }
  2019. BfLogDbg("EXCEPTION_SINGLE_STEP Thread:%d PC:%p\n", mActiveThread->mThreadId, exceptionRecord->ExceptionAddress);
  2020. if (lcContext.Dr6 & 0x0F) // Memory breakpoint hit
  2021. {
  2022. WdBreakpoint* foundBreakpoint = NULL;
  2023. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  2024. {
  2025. if ((lcContext.Dr6 & ((intptr_target)1 << memoryWatchSlot)) != 0)
  2026. {
  2027. foundBreakpoint = mMemoryBreakpoints[memoryWatchSlot].mBreakpoint;
  2028. break;
  2029. }
  2030. }
  2031. BF_ASSERT(foundBreakpoint != NULL);
  2032. DbgSubprogram* subprogram = mDebugTarget->FindSubProgram(pcAddress);
  2033. if (CheckConditionalBreakpoint(foundBreakpoint, subprogram, pcAddress))
  2034. {
  2035. if (foundBreakpoint != NULL)
  2036. {
  2037. mDebugManager->mOutMessages.push_back(StrFormat("memoryBreak %s", EncodeDataPtr(foundBreakpoint->mMemoryBreakpointInfo->mMemoryAddress, false).c_str()));
  2038. mRunState = RunState_Paused;
  2039. }
  2040. mActiveBreakpoint = foundBreakpoint;
  2041. mBreakStackFrameIdx = -1;
  2042. RemoveTempBreakpoints();
  2043. BfLogDbg("Memory breakpoint hit: %p\n", foundBreakpoint);
  2044. }
  2045. else
  2046. ClearCallStack();
  2047. break;
  2048. }
  2049. if ((mRunState == RunState_DebugEval) && (mDebugEvalThreadInfo.mThreadId == mDebuggerWaitingThread->mThreadId))
  2050. {
  2051. if ((addr_target)(intptr)exceptionRecord->ExceptionAddress == mDebugEvalSetRegisters.GetPC())
  2052. {
  2053. // This indicates we are returning from kernel mode and our registers are clobbered
  2054. SetRegisters(&mDebugEvalSetRegisters);
  2055. }
  2056. break;
  2057. }
  2058. bool hadBreakpointContinue = true;
  2059. if (threadInfo->mBreakpointAddressContinuing != 0)
  2060. {
  2061. bool wantsBreakpoint = WantsBreakpointAt(threadInfo->mBreakpointAddressContinuing);
  2062. BfLogDbg("Continuing breakpoint at %p WantsReset:%d\n", threadInfo->mBreakpointAddressContinuing, wantsBreakpoint);
  2063. if (wantsBreakpoint)
  2064. {
  2065. PhysSetBreakpoint(threadInfo->mBreakpointAddressContinuing);
  2066. }
  2067. threadInfo->mBreakpointAddressContinuing = NULL;
  2068. hadBreakpointContinue = true;
  2069. ThreadRestoreUnpause();
  2070. }
  2071. if ((mSteppingThread != NULL) && (mSteppingThread != mActiveThread))
  2072. {
  2073. // This SINGLE_STEP happened in the wrong thread - we need the stepping thread to do the stepping!
  2074. // Try again.
  2075. mActiveThread = mSteppingThread;
  2076. SingleStepX86();
  2077. break;
  2078. }
  2079. bool isDeeper = mStepSP > BF_CONTEXT_SP(lcContext);
  2080. if ((mStepSwitchedThreads) && (mStepType == StepType_StepOver) && (isDeeper))
  2081. {
  2082. if (HasSteppedIntoCall())
  2083. {
  2084. // Since we switched threads, we needed to do a hardware step which has placed us inside a
  2085. // call, so we need to step out of that now...
  2086. SetupStep(StepType_StepOut_NoFrame);
  2087. break;
  2088. }
  2089. }
  2090. // If we don't have a mStepBreakpointAddrs set, that means we're stepping through individual instructions --
  2091. // so process the new location here
  2092. if (((mStepType == StepType_StepInto) || (mStepType == StepType_StepInto_Unfiltered) || (mStepType == StepType_StepOver)) && (mStepBreakpointAddrs.size() == 0))
  2093. {
  2094. DbgSubprogram* dwSubprogram = NULL;
  2095. DbgLineData* dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  2096. if ((dwSubprogram != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC) && (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced))
  2097. {
  2098. BfLogDbg("Stepping through hot thunk\n");
  2099. mRunState = RunState_Running;
  2100. SingleStepX86();
  2101. break;
  2102. }
  2103. if ((mStepType == StepType_StepOver) && (!mStepInAssembly))
  2104. {
  2105. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  2106. {
  2107. BfLogDbg("Attempting StepOver of inlined method - SingleStep\n");
  2108. SetupStep(StepType_StepOut);
  2109. mRunState = RunState_Running;
  2110. break;
  2111. }
  2112. }
  2113. // Column of -1 means "Illegal", keep stepping!
  2114. if ((mStepInAssembly) ||
  2115. ((dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dwLineData->mColumn >= 0) &&
  2116. ((dwSubprogram->GetLineAddr(*dwLineData) == pcAddress) || (mStepStopOnNextInstruction))))
  2117. {
  2118. // Hit a line while stepping, we're done!
  2119. mRunState = RunState_Paused;
  2120. StepLineTryPause(pcAddress, false);
  2121. if (mRunState == RunState_Paused)
  2122. {
  2123. if ((mStepType == StepType_StepInto) && (!wasUnfilteredStep) && (!mStepInAssembly) && (dwSubprogram != NULL))
  2124. {
  2125. // Don't filter out the current subprogram (would break cases where we explicitly stepped into or hit breakpoint in a filtered subprogram)
  2126. bool isInStartSubprogram = (mStepStartPC >= dwSubprogram->mBlock.mLowPC) && (mStepStartPC < dwSubprogram->mBlock.mHighPC);
  2127. if ((!isInStartSubprogram) && (IsStepFiltered(dwSubprogram, dwLineData)))
  2128. {
  2129. BfLogDbg("Hit step filter (2)\n");
  2130. mRunState = RunState_Running;
  2131. SetupStep(StepType_StepOut_ThenInto);
  2132. break;
  2133. }
  2134. }
  2135. ClearStep();
  2136. mCurNoInfoStepTries = 0; // Reset
  2137. }
  2138. else
  2139. SetupStep(mStepType);
  2140. }
  2141. else if (dwSubprogram != NULL)
  2142. {
  2143. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && ((mStepType == StepType_StepInto) || (mStepType == StepType_StepInto_Unfiltered)))
  2144. {
  2145. SingleStepX86();
  2146. }
  2147. else
  2148. {
  2149. // Inside a line's instruction, keep going
  2150. SetupStep(mStepType);
  2151. mCurNoInfoStepTries = 0; // Reset
  2152. }
  2153. }
  2154. else if (mStepType == StepType_StepInto_Unfiltered)
  2155. {
  2156. CPUInst inst;
  2157. if (mDebugTarget->DecodeInstruction(pcAddress, &inst))
  2158. {
  2159. if (inst.IsBranch())
  2160. {
  2161. auto target = inst.GetTarget();
  2162. if (target != 0)
  2163. {
  2164. DbgSubprogram* destSubprogram = mDebugTarget->FindSubProgram(target);
  2165. if ((destSubprogram != NULL) && (target == destSubprogram->mBlock.mLowPC))
  2166. {
  2167. // We're jumping to an actual subprogram, so continue stepping here
  2168. mStepType = StepType_StepInto_UnfilteredSingle;
  2169. SingleStepX86();
  2170. break;
  2171. }
  2172. }
  2173. }
  2174. }
  2175. // We requested to step into this method so stop here even if we don't have source
  2176. mRunState = RunState_Paused;
  2177. }
  2178. else
  2179. {
  2180. // No debug info!
  2181. bool doStepOut = false;
  2182. if (mCurNoInfoStepTries < 16)
  2183. {
  2184. mCurNoInfoStepTries++;
  2185. BfLogDbg("NoInfoStepTries: %d\n", mCurNoInfoStepTries);
  2186. if (!SetupStep(mStepType))
  2187. doStepOut = true;
  2188. }
  2189. else
  2190. doStepOut = true;
  2191. if (doStepOut)
  2192. {
  2193. // Step out of current call.
  2194. mStepSP = 0;
  2195. SetupStep(StepType_StepOut_NoFrame);
  2196. // Aggressive stepout - don't monitor BP
  2197. mStepSP = 0;
  2198. }
  2199. }
  2200. }
  2201. else if (!hadBreakpointContinue)
  2202. {
  2203. BF_DBG_FATAL("EXCEPTION_SINGLE_STEP bad debugger state");
  2204. }
  2205. if (mRunState == RunState_Paused)
  2206. threadInfo->mStoppedAtAddress = pcAddress;
  2207. }
  2208. break;
  2209. default:
  2210. {
  2211. bool isSystemException =
  2212. (exceptionRecord->ExceptionCode >= STATUS_ACCESS_VIOLATION) &&
  2213. (exceptionRecord->ExceptionCode <= STATUS_ASSERTION_FAILURE);
  2214. bool isFirstChance = mDebugEvent.u.Exception.dwFirstChance != 0;
  2215. bool handled = false;
  2216. //TODO: Use a user-defined filter here to determine whether to stop or continue
  2217. if ((!isSystemException) && (isFirstChance))
  2218. {
  2219. if (exceptionRecord->ExceptionCode == 0x406D1388) // Visual C
  2220. {
  2221. if ((int32)exceptionRecord->ExceptionInformation[0] == 0x1000)
  2222. {
  2223. struct THREADNAME_INFO
  2224. {
  2225. DWORD dwType; // Must be 0x1000.
  2226. LPCSTR szName; // Pointer to name (in user addr space).
  2227. DWORD dwThreadID; // Thread ID (-1=caller thread).
  2228. DWORD dwFlags; // Reserved for future use, must be zero.
  2229. };
  2230. THREADNAME_INFO* threadNameInfo = (THREADNAME_INFO*)exceptionRecord->ExceptionInformation;
  2231. DwFormatInfo formatInfo;
  2232. formatInfo.mRawString = true;
  2233. String nameStr = ReadString(DbgType_SChar, (intptr)threadNameInfo->szName, false, 1024, formatInfo);
  2234. WdThreadInfo* namingThreadInfo = threadInfo;
  2235. if (threadNameInfo->dwThreadID != (DWORD)-1)
  2236. {
  2237. namingThreadInfo = NULL;
  2238. mThreadMap.TryGetValue(threadNameInfo->dwThreadID, &namingThreadInfo);
  2239. }
  2240. if (namingThreadInfo != NULL)
  2241. {
  2242. namingThreadInfo->mName = nameStr;
  2243. FilterThreadName(namingThreadInfo->mName);
  2244. }
  2245. }
  2246. else if (((int32)exceptionRecord->ExceptionInformation[0] == 0x1001) && ((int32)exceptionRecord->ExceptionInformation[1] == 0x1002))
  2247. {
  2248. struct FailMessage
  2249. {
  2250. addr_target mPtr0; // Unknown
  2251. addr_target mPtr1; // 0
  2252. addr_target mPtr2; // 0
  2253. addr_target mPtr3; // Unknown
  2254. addr_target mErrorStr;
  2255. };
  2256. FailMessage failMessage = ReadMemory<FailMessage>(exceptionRecord->ExceptionInformation[2]);
  2257. DwFormatInfo formatInfo;
  2258. String failStr = ReadString(DbgType_SChar16, failMessage.mErrorStr, false, 8192, formatInfo);
  2259. mDebugManager->mOutMessages.push_back(StrFormat("error Run-Time Check Failure %d - %s", exceptionRecord->ExceptionInformation[6], failStr.c_str()));
  2260. mRunState = RunState_Paused;
  2261. mRequestedStackFrameIdx = -2; // -2 = "auto"
  2262. handled = true;
  2263. }
  2264. }
  2265. if (!handled)
  2266. {
  2267. OutputMessage(StrFormat("Skipping first chance exception %08Xd at address %@ in thread %d\n", exceptionRecord->ExceptionCode, exceptionRecord->ExceptionAddress, threadInfo->mThreadId));
  2268. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_EXCEPTION_NOT_HANDLED);
  2269. mIsDebuggerWaiting = false;
  2270. }
  2271. }
  2272. else
  2273. {
  2274. BfLogDbg("EXCEPTION in thread %d at %p\n", threadInfo->mThreadId, exceptionRecord->ExceptionAddress);
  2275. OutputDebugStrF("EXCEPTION\n");
  2276. mActiveThread = threadInfo;
  2277. memcpy(&mCurException, exceptionRecord, sizeof(EXCEPTION_RECORD));
  2278. if (mRunState == RunState_DebugEval)
  2279. {
  2280. if ((intptr)mCurException.ExceptionAddress == 42)
  2281. {
  2282. BfLogDbg("RunState_DebugEval_Done\n");
  2283. OutputDebugStrF(" RunState_DebugEval_Done\n");
  2284. }
  2285. else
  2286. {
  2287. BfLogDbg("Exception at 0x%@ in thread %d, exception code 0x%08X",
  2288. mCurException.ExceptionAddress, mActiveThread->mThreadId, mCurException.ExceptionCode);
  2289. mDebugPendingExpr->mException = StrFormat("Exception at 0x%@ in thread %d, exception code 0x%08X",
  2290. mCurException.ExceptionAddress, mActiveThread->mThreadId, mCurException.ExceptionCode);
  2291. }
  2292. mRunState = RunState_DebugEval_Done;
  2293. mExplicitStopThread = mActiveThread;
  2294. mRequestedStackFrameIdx = mDebugPendingExpr->mCallStackIdx;
  2295. }
  2296. else
  2297. {
  2298. mRunState = RunState_Exception;
  2299. }
  2300. }
  2301. }
  2302. break;
  2303. }
  2304. }
  2305. break;
  2306. }
  2307. if ((mDebugEvalThreadInfo.mThreadId != 0) && (mRunState != RunState_DebugEval) && (mRunState != RunState_DebugEval_Done))
  2308. {
  2309. CleanupDebugEval();
  2310. }
  2311. // Stepping done?
  2312. if (mStepType == StepType_None)
  2313. {
  2314. mLastValidStepIntoPC = 0;
  2315. }
  2316. BF_ASSERT(mDebuggerWaitingThread != NULL);
  2317. return true;
  2318. }
  2319. void WinDebugger::Update()
  2320. {
  2321. AutoCrit autoCrit(mDebugManager->mCritSect);
  2322. // if (mRunState == RunState_DebugEval)
  2323. // ContinueDebugEvent();
  2324. if (mRunState == RunState_DebugEval_Done)
  2325. {
  2326. if (mDebugPendingExpr != NULL)
  2327. {
  2328. mDebugPendingExpr->mIdleTicks++;
  2329. if (mDebugPendingExpr->mIdleTicks >= 2)
  2330. {
  2331. BfLogDbg("Finishing pending expr in thread %d\n", mDebugEvalThreadInfo.mThreadId);
  2332. mRunState = RunState_Paused;
  2333. CleanupDebugEval();
  2334. }
  2335. }
  2336. }
  2337. else if (mDebugPendingExpr != NULL)
  2338. {
  2339. mDebugPendingExpr->mIdleTicks = 0;
  2340. }
  2341. }
  2342. void WinDebugger::ContinueDebugEvent()
  2343. {
  2344. AutoCrit autoCrit(mDebugManager->mCritSect);
  2345. BF_ASSERT(mRunState != RunState_DebugEval_Done);
  2346. if (!mWantsDebugContinue)
  2347. return;
  2348. if (!TryRunContinue())
  2349. return;
  2350. // if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId != mDebugEvalThreadInfo.mThreadId))
  2351. // {
  2352. // // Don't process the 'mIsAtBreakpointAddress' stuff
  2353. // mWantsDebugContinue = false;
  2354. // mContinueEvent.Set();
  2355. // return;
  2356. // }
  2357. if ((mDebuggerWaitingThread->mIsAtBreakpointAddress == 0) && (mDebuggerWaitingThread->mStoppedAtAddress != 0))
  2358. {
  2359. auto breakpoint = FindBreakpointAt(mDebuggerWaitingThread->mStoppedAtAddress);
  2360. if (breakpoint != NULL)
  2361. {
  2362. mDebuggerWaitingThread->mIsAtBreakpointAddress = mDebuggerWaitingThread->mStoppedAtAddress;
  2363. }
  2364. }
  2365. if (mDebuggerWaitingThread->mIsAtBreakpointAddress != 0)
  2366. {
  2367. if (!ContinueFromBreakpoint())
  2368. {
  2369. BfLogDbg("ContinueFromBreakpoint failed\n");
  2370. ClearCallStack();
  2371. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  2372. mDebuggerWaitingThread->mIsAtBreakpointAddress = 0;
  2373. mWantsDebugContinue = false;
  2374. mContinueFromBreakpointFailed = true;
  2375. mContinueEvent.Set();
  2376. return;
  2377. }
  2378. }
  2379. if ((mRunState == RunState_Breakpoint) || (mRunState == RunState_Paused))
  2380. {
  2381. ClearCallStack();
  2382. mRunState = RunState_Running;
  2383. }
  2384. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  2385. mWantsDebugContinue = false;
  2386. BF_ASSERT_REL(mDebuggerWaitingThread->mIsAtBreakpointAddress == 0);
  2387. mContinueEvent.Set();
  2388. }
  2389. static BOOL CALLBACK WdEnumWindowsProc(HWND hwnd, LPARAM lParam)
  2390. {
  2391. HWND owner = GetWindow(hwnd, GW_OWNER);
  2392. if (!IsWindowVisible(hwnd))
  2393. return TRUE;
  2394. DWORD processId = 0;
  2395. DWORD threadId = GetWindowThreadProcessId(hwnd, &processId);
  2396. if (processId != ((WinDebugger*)gDebugger)->mProcessInfo.dwProcessId)
  2397. return TRUE;
  2398. SetForegroundWindow(hwnd);
  2399. return TRUE;
  2400. }
  2401. void WinDebugger::ForegroundTarget()
  2402. {
  2403. EnumWindows(WdEnumWindowsProc, 0);
  2404. }
  2405. static int gFindLineDataAt = 0;
  2406. DbgLineData* WinDebugger::FindLineDataAtAddress(addr_target address, DbgSubprogram** outSubProgram, DbgSrcFile** outSrcFile, int* outLineIdx, DbgOnDemandKind onDemandKind)
  2407. {
  2408. gFindLineDataAt++;
  2409. BP_ZONE("WinDebugger::FindLineDataAtAddress");
  2410. auto dwSubprogram = mDebugTarget->FindSubProgram((addr_target)address, onDemandKind);
  2411. if (dwSubprogram == NULL)
  2412. return NULL;
  2413. FixupLineDataForSubprogram(dwSubprogram);
  2414. auto lineData = dwSubprogram->FindClosestLine(address, outSubProgram, outSrcFile, outLineIdx);
  2415. return lineData;
  2416. }
  2417. DbgLineData* WinDebugger::FindLineDataInSubprogram(addr_target address, DbgSubprogram* dwSubprogram)
  2418. {
  2419. auto dwCompileUnit = dwSubprogram->mCompileUnit;
  2420. FixupLineDataForSubprogram(dwSubprogram);
  2421. auto lineData = dwSubprogram->FindClosestLine(address);
  2422. return lineData;
  2423. }
  2424. bool WinDebugger::IsStepFiltered(DbgSubprogram* dbgSubprogram, DbgLineData* dbgLineData)
  2425. {
  2426. if (mIsStepIntoSpecific)
  2427. return false;
  2428. if (dbgSubprogram->mStepFilterVersion != mDebugManager->mStepFilterVersion)
  2429. {
  2430. String filterName;
  2431. CreateFilterName(filterName, dbgSubprogram);
  2432. dbgSubprogram->PopulateSubprogram();
  2433. bool doDefault = false;
  2434. StepFilter* stepFilterPtr;
  2435. if (mDebugManager->mStepFilters.TryGetValue(filterName, &stepFilterPtr))
  2436. {
  2437. switch (stepFilterPtr->mFilterKind)
  2438. {
  2439. case BfStepFilterKind_Default:
  2440. doDefault = true;
  2441. break;
  2442. case BfStepFilterKind_Filtered:
  2443. dbgSubprogram->mIsStepFiltered = true;
  2444. break;
  2445. case BfStepFilterKind_NotFiltered:
  2446. dbgSubprogram->mIsStepFiltered = false;
  2447. break;
  2448. }
  2449. }
  2450. else
  2451. {
  2452. doDefault = true;
  2453. }
  2454. if (doDefault)
  2455. {
  2456. dbgSubprogram->mIsStepFiltered = dbgSubprogram->mIsStepFilteredDefault;
  2457. }
  2458. dbgSubprogram->mStepFilterVersion = mDebugManager->mStepFilterVersion;
  2459. }
  2460. if (!dbgSubprogram->mIsStepFiltered)
  2461. {
  2462. if (dbgLineData != NULL)
  2463. {
  2464. auto dbgSrcFile = dbgSubprogram->GetLineSrcFile(*dbgLineData);
  2465. if (dbgSrcFile->mStepFilterVersion != mDebugManager->mStepFilterVersion)
  2466. {
  2467. dbgSrcFile->mFileExistKind = dbgSubprogram->mCompileUnit->mDbgModule->CheckSourceFileExist(dbgSrcFile->GetLocalPath());
  2468. dbgSrcFile->mStepFilterVersion = mDebugManager->mStepFilterVersion;
  2469. }
  2470. switch (dbgSrcFile->mFileExistKind)
  2471. {
  2472. case DbgFileExistKind_NotFound:
  2473. return true;
  2474. case DbgFileExistKind_HasOldSourceCommand:
  2475. if (mDebugManager->mStepOverExternalFiles)
  2476. return true;
  2477. }
  2478. }
  2479. }
  2480. return dbgSubprogram->mIsStepFiltered;
  2481. }
  2482. void WinDebugger::RemoveTempBreakpoints()
  2483. {
  2484. BfLogDbg("RemoveTempBreakpoints\n");
  2485. for (auto address : mTempBreakpoint)
  2486. {
  2487. RemoveBreakpoint(address);
  2488. // if (FindBreakpointAt(address) == NULL)
  2489. // {
  2490. // RemoveBreakpoint(address);
  2491. // }
  2492. // else
  2493. // {
  2494. // BfLogDbg("Ignoring remove on temp breakpoint %p\n", address);
  2495. // }
  2496. }
  2497. mTempBreakpoint.Clear();
  2498. mStepBreakpointAddrs.Clear();
  2499. }
  2500. void WinDebugger::RehupBreakpoints(bool doFlush)
  2501. {
  2502. BfLogDbg("RehupBreakpoints\n");
  2503. // First pass- detach breakpoints that need to be rebound
  2504. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  2505. {
  2506. auto breakpoint = mBreakpoints[i];
  2507. while (breakpoint != NULL)
  2508. {
  2509. if (((breakpoint->mSrcFile != NULL) && (breakpoint->mSrcFile->mDeferredRefs.size() > 0)) ||
  2510. (!breakpoint->mSymbolName.IsEmpty()))
  2511. {
  2512. // This breakpoint was already bound, but we loaded a debug module that also had this file so rebind it
  2513. DetachBreakpoint(breakpoint);
  2514. }
  2515. breakpoint = (WdBreakpoint*)breakpoint->mLinkedSibling;
  2516. }
  2517. }
  2518. // Second pass- actually set breakpoints
  2519. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  2520. {
  2521. auto breakpoint = mBreakpoints[i];
  2522. while (breakpoint != NULL)
  2523. {
  2524. CheckBreakpoint(breakpoint);
  2525. if (breakpoint->mAddr != 0)
  2526. SetBreakpoint(breakpoint->mAddr, true);
  2527. breakpoint = (WdBreakpoint*)breakpoint->mLinkedSibling;
  2528. }
  2529. }
  2530. mNeedsRehupBreakpoints = false;
  2531. }
  2532. bool WinDebugger::WantsBreakpointAt(addr_target address)
  2533. {
  2534. if (mTempBreakpoint.Contains(address))
  2535. return true;
  2536. for (auto breakpoint : mBreakpoints)
  2537. {
  2538. WdBreakpoint* checkBreakpoint = breakpoint;
  2539. while (checkBreakpoint != NULL)
  2540. {
  2541. if (address == checkBreakpoint->mAddr)
  2542. return true;
  2543. checkBreakpoint = (WdBreakpoint*)checkBreakpoint->mLinkedSibling;
  2544. }
  2545. }
  2546. return false;
  2547. }
  2548. void WinDebugger::CheckBreakpoint(WdBreakpoint* wdBreakpoint, DbgSrcFile* srcFile, int lineNum, int hotIdx)
  2549. {
  2550. BP_ZONE("WinDebugger::CheckBreakpoint:atLoc");
  2551. if (hotIdx == -1)
  2552. {
  2553. BF_ASSERT(wdBreakpoint->mPendingHotBindIdx == -1);
  2554. }
  2555. WdBreakpoint* headBreakpoint = wdBreakpoint;
  2556. headBreakpoint->mPendingHotBindIdx = -1;
  2557. bool foundInSequence = false;
  2558. DbgSubprogram* lastFoundSubprogram = NULL;
  2559. int highestHotIdx = -1;
  2560. bool foundLine = false;
  2561. int bestLineNum = -1;
  2562. int bestLineOffset = 0x7FFFFFFF;
  2563. auto _CheckLineInfo = [&](DbgSubprogram* dbgSubprogram, DbgLineInfo* dbgLineInfo)
  2564. {
  2565. // Scan first so we can determine if we want to do fix up line data or not.
  2566. bool hasNear = false;
  2567. int maxLineDist = 6;
  2568. for (int lineIdx = 0; lineIdx < dbgLineInfo->mLines.mSize; lineIdx++)
  2569. {
  2570. auto lineData = &dbgLineInfo->mLines[lineIdx];
  2571. auto& ctx = dbgLineInfo->mContexts[lineData->mCtxIdx];
  2572. if (ctx.mSrcFile != srcFile)
  2573. continue;
  2574. int lineOffset = lineData->mLine - lineNum;
  2575. if ((lineOffset >= 0) && (lineOffset <= maxLineDist))
  2576. hasNear = true;
  2577. }
  2578. if (!hasNear)
  2579. return;
  2580. FixupLineDataForSubprogram(dbgSubprogram);
  2581. for (int lineIdx = 0; lineIdx < dbgLineInfo->mLines.mSize; lineIdx++)
  2582. {
  2583. //TODO: Do fixup lineData... ?
  2584. auto lineData = &dbgLineInfo->mLines[lineIdx];
  2585. auto& ctx = dbgLineInfo->mContexts[lineData->mCtxIdx];
  2586. if (ctx.mSrcFile != srcFile)
  2587. continue;
  2588. // if (ctx.mInlinee != NULL)
  2589. // {
  2590. // if (lineIdx + 1 < dbgLineInfo->mLines.mSize)
  2591. // {
  2592. // auto nextLineData = &dbgLineInfo->mLines[lineIdx + 1];
  2593. // if (nextLineData->mRelAddress == lineData->mRelAddress)
  2594. // {
  2595. // // Use the later entry (same logic from DisassembleAt)
  2596. // continue;
  2597. // }
  2598. // }
  2599. // }
  2600. if ((lineData->mColumn == -1) && (wdBreakpoint->mInstrOffset == -1))
  2601. continue;
  2602. int lineOffset = lineData->mLine - lineNum;
  2603. if (lineOffset == 0)
  2604. {
  2605. foundLine = true;
  2606. auto address = dbgSubprogram->GetLineAddr(*lineData);
  2607. auto subProgram = mDebugTarget->FindSubProgram(address);
  2608. if (subProgram->mNeedLineDataFixup)
  2609. FixupLineDataForSubprogram(subProgram);
  2610. if (subProgram != NULL)
  2611. highestHotIdx = BF_MAX(highestHotIdx, subProgram->mCompileUnit->mDbgModule->mHotIdx);
  2612. if ((foundInSequence) && (subProgram != lastFoundSubprogram))
  2613. foundInSequence = false;
  2614. if ((subProgram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && (address < subProgram->mBlock.mLowPC + sizeof(HotJumpOp)))
  2615. {
  2616. // If this breakpoint ends up on the hot jmp instruction
  2617. continue;
  2618. }
  2619. if (!foundInSequence)
  2620. {
  2621. lastFoundSubprogram = subProgram;
  2622. if ((subProgram != NULL) && (subProgram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && (address == subProgram->mBlock.mLowPC))
  2623. {
  2624. // This instruction is actually the hot jump, we don't need a breakpoint here
  2625. foundInSequence = true;
  2626. continue;
  2627. }
  2628. if (wdBreakpoint->mSrcFile != NULL)
  2629. {
  2630. wdBreakpoint = new WdBreakpoint();
  2631. // Insert at head
  2632. wdBreakpoint->mLinkedSibling = headBreakpoint->mLinkedSibling;
  2633. headBreakpoint->mLinkedSibling = wdBreakpoint;
  2634. wdBreakpoint->mRequestedLineNum = headBreakpoint->mRequestedLineNum;
  2635. wdBreakpoint->mLineNum = headBreakpoint->mLineNum;
  2636. wdBreakpoint->mColumn = headBreakpoint->mColumn;
  2637. wdBreakpoint->mInstrOffset = headBreakpoint->mInstrOffset;
  2638. wdBreakpoint->mIsLinkedSibling = true;
  2639. wdBreakpoint->mHead = headBreakpoint;
  2640. }
  2641. if (wdBreakpoint->mInstrOffset > 0)
  2642. {
  2643. for (int instIdx = 0; instIdx < wdBreakpoint->mInstrOffset; instIdx++)
  2644. {
  2645. CPUInst inst;
  2646. if (!mDebugTarget->DecodeInstruction(address, &inst))
  2647. break;
  2648. address += inst.mSize;
  2649. }
  2650. }
  2651. wdBreakpoint->mSrcFile = ctx.mSrcFile;
  2652. wdBreakpoint->mLineData = DbgLineDataEx(lineData, subProgram);
  2653. wdBreakpoint->mBreakpointType = BreakpointType_User;
  2654. wdBreakpoint->mAddr = address;
  2655. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mStoppedAtAddress == address))
  2656. {
  2657. BfLogDbg("CheckBreakpoint setting mIsAtBreakpointAddress = %p\n", address);
  2658. mDebuggerWaitingThread->mIsAtBreakpointAddress = address;
  2659. }
  2660. BfLogDbg("Breakpoint %p found at %s in %s\n", wdBreakpoint, subProgram->mName, GetFileName(subProgram->mCompileUnit->mDbgModule->mFilePath).c_str());
  2661. mBreakpointAddrMap.ForceAdd(address, wdBreakpoint);
  2662. SetBreakpoint(address);
  2663. foundInSequence = true;
  2664. }
  2665. }
  2666. else
  2667. {
  2668. //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
  2669. // multiple places so we need to ensure this will break on them all
  2670. foundInSequence = false;
  2671. }
  2672. if ((lineOffset >= 0) && (lineOffset <= maxLineDist) && (lineOffset <= bestLineOffset))
  2673. {
  2674. if (lineOffset < bestLineOffset)
  2675. {
  2676. bestLineNum = lineData->mLine;
  2677. bestLineOffset = lineOffset;
  2678. }
  2679. }
  2680. }
  2681. };
  2682. for (int pass = 0; pass < 2; pass++)
  2683. {
  2684. if (lineNum == -1)
  2685. break;
  2686. bestLineNum = -1;
  2687. bestLineOffset = 0x7FFFFFFF;
  2688. if (hotIdx >= 0)
  2689. {
  2690. if (hotIdx >= srcFile->mHotReplacedDbgLineInfo.size())
  2691. return;
  2692. auto hotReplacedLineInfo = srcFile->mHotReplacedDbgLineInfo[hotIdx];
  2693. for (auto& hotReplacedEntry : hotReplacedLineInfo->mEntries)
  2694. {
  2695. _CheckLineInfo(hotReplacedEntry.mSubprogram, hotReplacedEntry.mLineInfo);
  2696. }
  2697. }
  2698. else
  2699. {
  2700. for (auto subprogram : srcFile->mLineDataRefs)
  2701. _CheckLineInfo(subprogram, subprogram->mLineInfo);
  2702. }
  2703. if (foundLine)
  2704. break;
  2705. // Don't allow the breakpoint to be inexactly bound -- only match on pass 0
  2706. if (hotIdx != -1)
  2707. break;
  2708. if (bestLineNum == -1)
  2709. break;
  2710. lineNum = bestLineNum;
  2711. wdBreakpoint->mLineNum = bestLineNum;
  2712. }
  2713. int highestCheckHotIdx = highestHotIdx - 1;
  2714. if (hotIdx != -1)
  2715. highestCheckHotIdx = hotIdx - 1;
  2716. for (int hotFileIdx = highestCheckHotIdx; hotFileIdx >= 0; hotFileIdx--)
  2717. {
  2718. auto& hotReplacedDbgLineData = wdBreakpoint->mSrcFile->mHotReplacedDbgLineInfo;
  2719. // Only try to bind to an old hot version if we haven't unloaded the hot module
  2720. if ((hotFileIdx < (int)hotReplacedDbgLineData.size()) && (hotReplacedDbgLineData[hotFileIdx]->mEntries.size() > 0))
  2721. {
  2722. headBreakpoint->mPendingHotBindIdx = hotFileIdx;
  2723. break;
  2724. }
  2725. }
  2726. }
  2727. void WinDebugger::HotBindBreakpoint(Breakpoint* breakpoint, int lineNum, int hotIdx)
  2728. {
  2729. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  2730. CheckBreakpoint(wdBreakpoint, wdBreakpoint->mSrcFile, lineNum, hotIdx);
  2731. }
  2732. void WinDebugger::CheckBreakpoint(WdBreakpoint* wdBreakpoint)
  2733. {
  2734. if (!mGotStartupEvent)
  2735. return;
  2736. if (wdBreakpoint->mThreadId == 0) // Not bound to threadId yet...
  2737. {
  2738. return;
  2739. }
  2740. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  2741. {
  2742. if (wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap != 0)
  2743. return;
  2744. if (mFreeMemoryBreakIndices.size() == 0)
  2745. return;
  2746. if ((IsInRunState()) || (mActiveThread == NULL))
  2747. return;
  2748. int wantBytes[4];
  2749. int wantBindCount = 0;
  2750. int bytesLeft = wdBreakpoint->mMemoryBreakpointInfo->mByteCount;
  2751. addr_target curAddr = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress;
  2752. while (bytesLeft > 0)
  2753. {
  2754. if (wantBindCount >= mFreeMemoryBreakIndices.size())
  2755. return;
  2756. int curByteCount = 1;
  2757. #ifdef BF_DBG_64
  2758. if ((bytesLeft >= 8) && ((curAddr & 7) == 0))
  2759. curByteCount = 8;
  2760. else
  2761. #endif
  2762. if ((bytesLeft >= 4) && ((curAddr & 3) == 0))
  2763. curByteCount = 4;
  2764. else if ((bytesLeft >= 2) && ((curAddr & 1) == 0))
  2765. curByteCount = 2;
  2766. wantBytes[wantBindCount++] = curByteCount;
  2767. bytesLeft -= curByteCount;
  2768. curAddr += curByteCount;
  2769. }
  2770. addr_target curOfs = 0;
  2771. for (int i = 0; i < wantBindCount; i++)
  2772. {
  2773. int memoryBreakIdx = mFreeMemoryBreakIndices.back();
  2774. mFreeMemoryBreakIndices.pop_back();
  2775. mMemoryBreakpoints[memoryBreakIdx].mBreakpoint = wdBreakpoint;
  2776. mMemoryBreakpoints[memoryBreakIdx].mAddress = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress + curOfs;
  2777. mMemoryBreakpoints[memoryBreakIdx].mByteCount = wantBytes[i];
  2778. mMemoryBreakpoints[memoryBreakIdx].mOfs = curOfs;
  2779. curOfs += wantBytes[i];
  2780. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap |= 1<<memoryBreakIdx;
  2781. }
  2782. UpdateThreadDebugRegisters();
  2783. }
  2784. if (wdBreakpoint->mAddr != 0)
  2785. return;
  2786. if (!wdBreakpoint->mSymbolName.IsEmpty())
  2787. {
  2788. auto headBreakpoint = wdBreakpoint->GetHeadBreakpoint();
  2789. String symbolName = wdBreakpoint->mSymbolName;
  2790. bool onlyBindFirst = false;
  2791. if (symbolName.StartsWith("-"))
  2792. {
  2793. symbolName.Remove(0);
  2794. onlyBindFirst = true;
  2795. }
  2796. for (auto dbgModule : mDebugTarget->mDbgModules)
  2797. {
  2798. dbgModule->ParseSymbolData();
  2799. addr_target targetAddr = -1;
  2800. auto entry = dbgModule->mSymbolNameMap.Find(symbolName.c_str());
  2801. if (entry != NULL)
  2802. {
  2803. DbgSymbol* dwSymbol = entry->mValue;
  2804. targetAddr = dwSymbol->mAddress;
  2805. }
  2806. if (targetAddr == -1)
  2807. {
  2808. if (symbolName == ".")
  2809. {
  2810. targetAddr = mDebugTarget->mLaunchBinary->mImageBase + mDebugTarget->mLaunchBinary->mEntryPoint;
  2811. onlyBindFirst = true;
  2812. }
  2813. }
  2814. if (targetAddr != -1)
  2815. {
  2816. if (wdBreakpoint->mAddr == 0)
  2817. {
  2818. wdBreakpoint->mAddr = targetAddr;
  2819. wdBreakpoint->mBreakpointType = BreakpointType_User;
  2820. mBreakpointAddrMap.ForceAdd(wdBreakpoint->mAddr, wdBreakpoint);
  2821. SetBreakpoint(wdBreakpoint->mAddr);
  2822. }
  2823. else
  2824. {
  2825. wdBreakpoint = new WdBreakpoint();
  2826. // Insert at head
  2827. wdBreakpoint->mLinkedSibling = headBreakpoint->mLinkedSibling;
  2828. headBreakpoint->mLinkedSibling = wdBreakpoint;
  2829. wdBreakpoint->mSymbolName = headBreakpoint->mSymbolName;
  2830. wdBreakpoint->mIsLinkedSibling = true;
  2831. wdBreakpoint->mHead = headBreakpoint;
  2832. }
  2833. if (onlyBindFirst)
  2834. break;
  2835. }
  2836. }
  2837. return;
  2838. }
  2839. BP_ZONE("WinDebugger::CheckBreakpoint");
  2840. // Rehup if we load a DLL that also uses this file we bound to (thus the mDeferredRefs check)
  2841. if (wdBreakpoint->mSrcFile == NULL)
  2842. {
  2843. DbgSrcFile* srcFile = mDebugTarget->GetSrcFile(wdBreakpoint->mFilePath);
  2844. if (srcFile == NULL)
  2845. return;
  2846. for (auto& deferredSrcFileRef : srcFile->mDeferredRefs)
  2847. {
  2848. deferredSrcFileRef.mDbgModule->ParseCompileUnit(deferredSrcFileRef.mCompileUnitId);
  2849. }
  2850. srcFile->mDeferredRefs.Clear();
  2851. CheckBreakpoint(wdBreakpoint, srcFile, wdBreakpoint->mRequestedLineNum, -1);
  2852. }
  2853. }
  2854. bool WinDebugger::IsMemoryBreakpointSizeValid(addr_target addr, int size)
  2855. {
  2856. int wantBindCount = 0;
  2857. int bytesLeft = size;
  2858. addr_target curAddr = addr;
  2859. for (int i = 0; i < 4; i++)
  2860. {
  2861. int curByteCount = 1;
  2862. #ifdef BF_DBG_64
  2863. if ((bytesLeft >= 8) && ((curAddr & 7) == 0))
  2864. curByteCount = 8;
  2865. else
  2866. #endif
  2867. if ((bytesLeft >= 4) && ((curAddr & 3) == 0))
  2868. curByteCount = 4;
  2869. else if ((bytesLeft >= 2) && ((curAddr & 1) == 0))
  2870. curByteCount = 2;
  2871. bytesLeft -= curByteCount;
  2872. curAddr += curByteCount;
  2873. if (bytesLeft == 0)
  2874. return true;
  2875. }
  2876. return false;
  2877. }
  2878. bool WinDebugger::HasMemoryBreakpoint(addr_target addr, int size)
  2879. {
  2880. for (int i = 0; i < 4; i++)
  2881. {
  2882. if ((mMemoryBreakpoints[i].mAddress == addr) &&
  2883. (mMemoryBreakpoints[i].mOfs == 0) &&
  2884. (mMemoryBreakpoints[i].mBreakpoint->mMemoryBreakpointInfo->mByteCount == size))
  2885. return true;
  2886. }
  2887. return false;
  2888. }
  2889. Breakpoint* WinDebugger::CreateBreakpoint(const StringImpl& fileName, int lineNum, int wantColumn, int instrOffset)
  2890. {
  2891. AutoCrit autoCrit(mDebugManager->mCritSect);
  2892. BfLogDbg("CreateBreakpoint %s %d %d\n", fileName.c_str(), lineNum, wantColumn);
  2893. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  2894. wdBreakpoint->mFilePath = FixPathAndCase(fileName);
  2895. wdBreakpoint->mRequestedLineNum = lineNum;
  2896. wdBreakpoint->mLineNum = lineNum;
  2897. wdBreakpoint->mColumn = wantColumn;
  2898. wdBreakpoint->mInstrOffset = instrOffset;
  2899. mBreakpoints.push_back(wdBreakpoint);
  2900. BfLogDbg("CreateBreakpoint Created %p\n", wdBreakpoint);
  2901. return wdBreakpoint;
  2902. }
  2903. void WinDebugger::CheckBreakpoint(Breakpoint* checkBreakpoint)
  2904. {
  2905. AutoCrit autoCrit(mDebugManager->mCritSect);
  2906. CheckBreakpoint((WdBreakpoint*)checkBreakpoint);
  2907. }
  2908. Breakpoint* WinDebugger::CreateMemoryBreakpoint(intptr addr, int byteCount)
  2909. {
  2910. AutoCrit autoCrit(mDebugManager->mCritSect);
  2911. BfLogDbg("CreateMemoryBreakpoint %p %d\n", addr, byteCount);
  2912. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  2913. WdMemoryBreakpointInfo* memoryBreakInfo = new WdMemoryBreakpointInfo();
  2914. memoryBreakInfo->mMemoryAddress = addr;
  2915. memoryBreakInfo->mByteCount = byteCount;
  2916. wdBreakpoint->mMemoryBreakpointInfo = memoryBreakInfo;
  2917. mBreakpoints.push_back(wdBreakpoint);
  2918. CheckBreakpoint(wdBreakpoint);
  2919. return wdBreakpoint;
  2920. }
  2921. Breakpoint* WinDebugger::CreateSymbolBreakpoint(const StringImpl& symbolName)
  2922. {
  2923. AutoCrit autoCrit(mDebugManager->mCritSect);
  2924. BfLogDbg("CreateSymbolBreakpoint %s\n", symbolName.c_str());
  2925. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  2926. wdBreakpoint->mSymbolName = symbolName;
  2927. mBreakpoints.push_back(wdBreakpoint);
  2928. CheckBreakpoint(wdBreakpoint);
  2929. return wdBreakpoint;
  2930. }
  2931. Breakpoint* WinDebugger::CreateAddressBreakpoint(intptr inAddress)
  2932. {
  2933. AutoCrit autoCrit(mDebugManager->mCritSect);
  2934. BfLogDbg("CreateAddressBreakpoint %p\n", inAddress);
  2935. addr_target address = (addr_target)inAddress;
  2936. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  2937. wdBreakpoint->mAddr = address;
  2938. mBreakpointAddrMap.ForceAdd(wdBreakpoint->mAddr, wdBreakpoint);
  2939. SetBreakpoint(address);
  2940. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mStoppedAtAddress == address))
  2941. {
  2942. BfLogDbg("CreateAddressBreakpoint setting mIsAtBreakpointAddress = %p\n", address);
  2943. mDebuggerWaitingThread->mIsAtBreakpointAddress = address;
  2944. }
  2945. mBreakpoints.push_back(wdBreakpoint);
  2946. return wdBreakpoint;
  2947. }
  2948. void WinDebugger::DeleteBreakpoint(Breakpoint* breakpoint)
  2949. {
  2950. AutoCrit autoCrit(mDebugManager->mCritSect);
  2951. if (breakpoint == mActiveBreakpoint)
  2952. mActiveBreakpoint = NULL;
  2953. BfLogDbg("WinDebugger::DeleteBreakpoint %p Count:%d\n", breakpoint, mBreakpoints.size());
  2954. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  2955. if (wdBreakpoint->mCondition != NULL)
  2956. {
  2957. if (!wdBreakpoint->mIsLinkedSibling)
  2958. delete wdBreakpoint->mCondition;
  2959. }
  2960. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  2961. {
  2962. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  2963. {
  2964. if (mMemoryBreakpoints[memoryWatchSlot].mBreakpoint == wdBreakpoint)
  2965. {
  2966. mFreeMemoryBreakIndices.push_back(memoryWatchSlot);
  2967. mMemoryBreakpoints[memoryWatchSlot] = WdMemoryBreakpointBind();
  2968. UpdateThreadDebugRegisters();
  2969. }
  2970. }
  2971. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap = 0;
  2972. }
  2973. if (wdBreakpoint->mAddr != 0)
  2974. {
  2975. mBreakpointAddrMap.Remove(wdBreakpoint->mAddr, wdBreakpoint);
  2976. RemoveBreakpoint(wdBreakpoint->mAddr);
  2977. for (auto thread : mThreadList)
  2978. {
  2979. if (thread->mIsAtBreakpointAddress == wdBreakpoint->mAddr)
  2980. thread->mIsAtBreakpointAddress = NULL;
  2981. if (thread->mBreakpointAddressContinuing == wdBreakpoint->mAddr)
  2982. thread->mBreakpointAddressContinuing = NULL;
  2983. }
  2984. }
  2985. if (!wdBreakpoint->mIsLinkedSibling)
  2986. {
  2987. mBreakpoints.Remove(wdBreakpoint);
  2988. }
  2989. if (wdBreakpoint->mLinkedSibling != NULL)
  2990. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  2991. delete wdBreakpoint;
  2992. }
  2993. void WinDebugger::DetachBreakpoint(Breakpoint* breakpoint)
  2994. {
  2995. AutoCrit autoCrit(mDebugManager->mCritSect);
  2996. BfLogDbg("WinDebugger::DetachBreakpoint %p\n", breakpoint);
  2997. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  2998. if (wdBreakpoint->mAddr != 0)
  2999. {
  3000. mBreakpointAddrMap.Remove(wdBreakpoint->mAddr, wdBreakpoint);
  3001. RemoveBreakpoint(wdBreakpoint->mAddr);
  3002. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mIsAtBreakpointAddress == wdBreakpoint->mAddr))
  3003. mDebuggerWaitingThread->mIsAtBreakpointAddress = NULL;
  3004. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mBreakpointAddressContinuing == wdBreakpoint->mAddr))
  3005. mDebuggerWaitingThread->mBreakpointAddressContinuing = NULL;
  3006. wdBreakpoint->mLineData = DbgLineDataEx();
  3007. wdBreakpoint->mAddr = 0;
  3008. }
  3009. if (wdBreakpoint->mCondition != NULL)
  3010. {
  3011. delete wdBreakpoint->mCondition->mDbgEvaluationContext;
  3012. wdBreakpoint->mCondition->mDbgEvaluationContext = NULL;
  3013. }
  3014. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  3015. {
  3016. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  3017. {
  3018. if (mMemoryBreakpoints[memoryWatchSlot].mBreakpoint == wdBreakpoint)
  3019. {
  3020. mFreeMemoryBreakIndices.push_back(memoryWatchSlot);
  3021. mMemoryBreakpoints[memoryWatchSlot] = WdMemoryBreakpointBind();
  3022. UpdateThreadDebugRegisters();
  3023. }
  3024. }
  3025. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap = 0;
  3026. }
  3027. if (wdBreakpoint->mLinkedSibling != NULL)
  3028. {
  3029. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  3030. wdBreakpoint->mLinkedSibling = NULL;
  3031. }
  3032. wdBreakpoint->mSrcFile = NULL;
  3033. wdBreakpoint->mPendingHotBindIdx = -1;
  3034. }
  3035. void WinDebugger::MoveBreakpoint(Breakpoint* breakpoint, int lineNum, int wantColumn, bool rebindNow)
  3036. {
  3037. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3038. AutoCrit autoCrit(mDebugManager->mCritSect);
  3039. DetachBreakpoint(wdBreakpoint);
  3040. //TODO: This doesn't actually rebind correctly while the app is running
  3041. if ((lineNum != -1) && (wantColumn != -1))
  3042. {
  3043. wdBreakpoint->mRequestedLineNum = lineNum;
  3044. wdBreakpoint->mLineNum = lineNum;
  3045. wdBreakpoint->mColumn = wantColumn;
  3046. }
  3047. if (rebindNow)
  3048. CheckBreakpoint(wdBreakpoint);
  3049. }
  3050. void WinDebugger::MoveMemoryBreakpoint(Breakpoint* breakpoint, intptr addr, int byteCount)
  3051. {
  3052. AutoCrit autoCrit(mDebugManager->mCritSect);
  3053. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3054. DetachBreakpoint(wdBreakpoint);
  3055. wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress = addr;
  3056. wdBreakpoint->mMemoryBreakpointInfo->mByteCount = byteCount;
  3057. CheckBreakpoint(wdBreakpoint);
  3058. }
  3059. void WinDebugger::DisableBreakpoint(Breakpoint* breakpoint)
  3060. {
  3061. AutoCrit autoCrit(mDebugManager->mCritSect);
  3062. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3063. DetachBreakpoint(wdBreakpoint);
  3064. delete wdBreakpoint->mMemoryBreakpointInfo;
  3065. wdBreakpoint->mMemoryBreakpointInfo = NULL;
  3066. }
  3067. void WinDebugger::SetBreakpointCondition(Breakpoint* breakpoint, const StringImpl& conditionExpr)
  3068. {
  3069. AutoCrit autoCrit(mDebugManager->mCritSect);
  3070. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3071. BF_ASSERT(!wdBreakpoint->mIsLinkedSibling);
  3072. if (conditionExpr.empty())
  3073. {
  3074. delete wdBreakpoint->mCondition;
  3075. WdBreakpoint* curBreakpoint = wdBreakpoint;
  3076. wdBreakpoint->mCondition = NULL;
  3077. }
  3078. else
  3079. {
  3080. delete wdBreakpoint->mCondition;
  3081. auto condition = new WdBreakpointCondition();
  3082. condition->mExpr = conditionExpr;
  3083. wdBreakpoint->mCondition = condition;
  3084. }
  3085. }
  3086. void WinDebugger::SetBreakpointLogging(Breakpoint* breakpoint, const StringImpl& logging, bool breakAfterLogging)
  3087. {
  3088. AutoCrit autoCrit(mDebugManager->mCritSect);
  3089. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3090. BF_ASSERT(!wdBreakpoint->mIsLinkedSibling);
  3091. wdBreakpoint->mLogging = logging;
  3092. wdBreakpoint->mBreakAfterLogging = breakAfterLogging;
  3093. }
  3094. bool WinDebugger::CheckConditionalBreakpoint(WdBreakpoint* breakpoint, DbgSubprogram* dbgSubprogram, addr_target pcAddress)
  3095. {
  3096. // What was this assertion for?
  3097. //BF_ASSERT(mCallStack.size() == 0);
  3098. auto headBreakpoint = breakpoint->GetHeadBreakpoint();
  3099. if (headBreakpoint->mThreadId != -1)
  3100. {
  3101. if ((mActiveThread != NULL) && (mActiveThread->mThreadId != headBreakpoint->mThreadId))
  3102. return false;
  3103. }
  3104. auto _SplitExpr = [&](const StringImpl& expr, StringImpl& outExpr, StringImpl& outSubject)
  3105. {
  3106. int crPos = expr.IndexOf('\n');
  3107. if (crPos != -1)
  3108. {
  3109. outExpr += expr.Substring(0, crPos);
  3110. outSubject += expr.Substring(crPos + 1);
  3111. }
  3112. else
  3113. {
  3114. outExpr += expr;
  3115. }
  3116. };
  3117. if (headBreakpoint->mCondition != NULL)
  3118. {
  3119. ClearCallStack();
  3120. auto conditional = headBreakpoint->mCondition;
  3121. if (conditional->mDbgEvaluationContext == NULL)
  3122. {
  3123. CPURegisters registers;
  3124. PopulateRegisters(&registers);
  3125. auto pcAddress = registers.GetPC();
  3126. DbgSubprogram* subprogram = mDebugTarget->FindSubProgram(pcAddress);
  3127. if (subprogram == NULL)
  3128. {
  3129. return false;
  3130. }
  3131. StringT<256> expr;
  3132. StringT<256> subjectExpr;
  3133. if (breakpoint->mMemoryBreakpointInfo != NULL)
  3134. {
  3135. subjectExpr += "*";
  3136. }
  3137. _SplitExpr(conditional->mExpr, expr, subjectExpr);
  3138. DbgLanguage language = DbgLanguage_Unknown;
  3139. if (expr.StartsWith("@Beef:"))
  3140. {
  3141. expr.Remove(0, 6);
  3142. language = DbgLanguage_Beef;
  3143. }
  3144. else if (expr.StartsWith("@C:"))
  3145. {
  3146. expr.Remove(0, 3);
  3147. language = DbgLanguage_C;
  3148. }
  3149. conditional->mDbgEvaluationContext = new DbgEvaluationContext(this, subprogram->mCompileUnit->mDbgModule, expr);
  3150. if (language != DbgLanguage_Unknown)
  3151. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mLanguage = language;
  3152. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mSubjectExpr = subjectExpr;
  3153. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mDbgCompileUnit = subprogram->mCompileUnit;
  3154. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mCallStackIdx = 0;
  3155. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mExpressionFlags = (DwEvalExpressionFlags)(DwEvalExpressionFlag_AllowSideEffects);
  3156. }
  3157. WdStackFrame* wdStackFrame = new WdStackFrame();
  3158. PopulateRegisters(&wdStackFrame->mRegisters);
  3159. mCallStack.Add(wdStackFrame);
  3160. DbgTypedValue result = conditional->mDbgEvaluationContext->EvaluateInContext(DbgTypedValue());
  3161. ClearCallStack();
  3162. if (conditional->mDbgEvaluationContext->mPassInstance->HasFailed())
  3163. {
  3164. String errorStr = "FAILED";
  3165. for (auto error : conditional->mDbgEvaluationContext->mPassInstance->mErrors)
  3166. {
  3167. if (!error->mIsWarning)
  3168. errorStr = error->mError;
  3169. }
  3170. String condError = StrFormat("error Conditional breakpoint expression '%s' failed: %s", conditional->mExpr.c_str(), errorStr.c_str());
  3171. mDebugManager->mOutMessages.push_back(condError);
  3172. return true;
  3173. }
  3174. else if (conditional->mDbgEvaluationContext->mDbgExprEvaluator->mBlockedSideEffects)
  3175. {
  3176. mDebugManager->mOutMessages.push_back(StrFormat("error Conditional breakpoint expression '%s' contained function calls, which is not allowed", conditional->mExpr.c_str()));
  3177. return true;
  3178. }
  3179. else if ((!result) || (!result.mType->IsBoolean()))
  3180. {
  3181. mDebugManager->mOutMessages.push_back(StrFormat("error Conditional breakpoint expression '%s' must result in a boolean value", conditional->mExpr.c_str()));
  3182. return true;
  3183. }
  3184. else if (!result.mBool)
  3185. return false;
  3186. }
  3187. headBreakpoint->mHitCount++;
  3188. switch (headBreakpoint->mHitCountBreakKind)
  3189. {
  3190. case DbgHitCountBreakKind_Equals:
  3191. if (headBreakpoint->mHitCount != headBreakpoint->mTargetHitCount)
  3192. return false;
  3193. break;
  3194. case DbgHitCountBreakKind_GreaterEquals:
  3195. if (headBreakpoint->mHitCount < headBreakpoint->mTargetHitCount)
  3196. return false;
  3197. break;
  3198. case DbgHitCountBreakKind_Multiple:
  3199. if ((headBreakpoint->mHitCount % headBreakpoint->mTargetHitCount) != 0)
  3200. return false;
  3201. break;
  3202. }
  3203. mActiveBreakpoint = breakpoint;
  3204. mBreakStackFrameIdx = -1;
  3205. if (!headBreakpoint->mLogging.IsEmpty())
  3206. {
  3207. ClearCallStack();
  3208. DwFormatInfo formatInfo;
  3209. formatInfo.mCallStackIdx = 0;
  3210. DbgCompileUnit* dbgCompileUnit = NULL;
  3211. if (dbgSubprogram == NULL)
  3212. dbgSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3213. if (dbgSubprogram != NULL)
  3214. {
  3215. dbgCompileUnit = dbgSubprogram->mCompileUnit;
  3216. formatInfo.mLanguage = dbgSubprogram->GetLanguage();
  3217. }
  3218. auto prevRunState = mRunState;
  3219. mRunState = RunState_Paused; // We need to be paused to avoid certain errors in the eval
  3220. String displayString;
  3221. String expr;
  3222. _SplitExpr(headBreakpoint->mLogging, expr, formatInfo.mSubjectExpr);
  3223. if (expr.StartsWith("@Beef:"))
  3224. {
  3225. expr.Remove(0, 6);
  3226. formatInfo.mLanguage = DbgLanguage_Beef;
  3227. }
  3228. else if (expr.StartsWith("@C:"))
  3229. {
  3230. expr.Remove(0, 3);
  3231. formatInfo.mLanguage = DbgLanguage_C;
  3232. }
  3233. ProcessEvalString(dbgCompileUnit, DbgTypedValue(), expr, displayString, formatInfo, NULL, false);
  3234. mRunState = prevRunState;
  3235. displayString.Insert(0, "log ");
  3236. displayString.Append("\n");
  3237. mDebugManager->mOutMessages.push_back(displayString);
  3238. if (!headBreakpoint->mBreakAfterLogging)
  3239. return false;
  3240. }
  3241. return true;
  3242. }
  3243. void WinDebugger::CleanupDebugEval(bool restoreRegisters)
  3244. {
  3245. BfLogDbg("CleanupDebugEval ThreadId=%d\n", mDebugEvalThreadInfo.mThreadId);
  3246. WdThreadInfo* evalThreadInfo = NULL;
  3247. if (mThreadMap.TryGetValue(mDebugEvalThreadInfo.mThreadId, &evalThreadInfo))
  3248. {
  3249. if ((restoreRegisters) && (!mDbgBreak))
  3250. {
  3251. SetAndRestoreValue<WdThreadInfo*> activeThread(mActiveThread, evalThreadInfo);
  3252. RestoreAllRegisters();
  3253. // if (mRunState == RunState_Running_ToTempBreakpoint)
  3254. // mRunState = RunState_Paused;
  3255. }
  3256. evalThreadInfo->mStartSP = mDebugEvalThreadInfo.mStartSP;
  3257. evalThreadInfo->mStoppedAtAddress = mDebugEvalThreadInfo.mStoppedAtAddress;
  3258. evalThreadInfo->mIsAtBreakpointAddress = mDebugEvalThreadInfo.mIsAtBreakpointAddress;
  3259. evalThreadInfo->mBreakpointAddressContinuing = mDebugEvalThreadInfo.mBreakpointAddressContinuing;
  3260. }
  3261. delete mDebugPendingExpr;
  3262. mDebugPendingExpr = NULL;
  3263. mDebugEvalThreadInfo = WdThreadInfo();
  3264. OutputRawMessage("rehupLoc");
  3265. }
  3266. bool WinDebugger::FixCallStackIdx(int& callStackIdx)
  3267. {
  3268. callStackIdx = BF_MAX(callStackIdx, 0);
  3269. if (mCallStack.IsEmpty())
  3270. UpdateCallStack();
  3271. int stackSize = (int)mCallStack.size();
  3272. while (callStackIdx >= mCallStack.size())
  3273. {
  3274. UpdateCallStack();
  3275. if (stackSize == (int)mCallStack.size())
  3276. break; // Didn't change
  3277. stackSize = (int)mCallStack.size();
  3278. }
  3279. if (callStackIdx >= stackSize)
  3280. {
  3281. callStackIdx = 0;
  3282. return false;
  3283. }
  3284. return true;
  3285. }
  3286. bool WinDebugger::HasLineInfoAt(addr_target address)
  3287. {
  3288. BP_ZONE("WinDebugger::HasLineInfoAt");
  3289. DbgSubprogram* dbgSubprogram = NULL;
  3290. auto dwLineData = FindLineDataAtAddress(address, &dbgSubprogram);
  3291. return (dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dbgSubprogram->GetLineAddr(*dwLineData) == address);
  3292. }
  3293. void WinDebugger::StepLineTryPause(addr_target address, bool requireExactMatch)
  3294. {
  3295. if (mStepInAssembly)
  3296. return;
  3297. if (mStepLineData.mLineData != NULL)
  3298. {
  3299. DbgSubprogram* dbgSubprogram = NULL;
  3300. DbgSrcFile* dbgSrcFile = NULL;
  3301. auto dwLineData = FindLineDataAtAddress(address, &dbgSubprogram, &dbgSrcFile);
  3302. if ((dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && ((!requireExactMatch) || (dbgSubprogram->GetLineAddr(*dwLineData) == address)))
  3303. {
  3304. // "Invalid" line
  3305. if (dwLineData->mColumn == -1)
  3306. {
  3307. SetupStep(mStepType);
  3308. mRunState = RunState_Running;
  3309. return;
  3310. }
  3311. // If we're on the same line but a different column or a <= address then keep it keep looking
  3312. if ((dbgSrcFile == mStepLineData.GetSrcFile()) &&
  3313. ((!requireExactMatch) || (dwLineData != mStepLineData.mLineData) || (address <= mStepStartPC)) &&
  3314. (dwLineData->mLine == mStepLineData.mLineData->mLine))
  3315. {
  3316. SetupStep(mStepType);
  3317. mRunState = RunState_Running;
  3318. return;
  3319. }
  3320. }
  3321. }
  3322. mRunState = RunState_Paused;
  3323. }
  3324. void WinDebugger::BreakAll()
  3325. {
  3326. AutoCrit autoCrit(mDebugManager->mCritSect);
  3327. ::DebugBreakProcess(mProcessInfo.hProcess);
  3328. }
  3329. void WinDebugger::StepInto(bool inAssembly)
  3330. {
  3331. AutoCrit autoCrit(mDebugManager->mCritSect);
  3332. if (!TryRunContinue())
  3333. return;
  3334. BfLogDbg("StepInto\n");
  3335. mCurNoInfoStepTries = 0; // Reset
  3336. mStepInAssembly = inAssembly;
  3337. SetupStep(StepType_StepInto);
  3338. ContinueDebugEvent();
  3339. }
  3340. void WinDebugger::StepIntoSpecific(intptr inAddr)
  3341. {
  3342. addr_target addr = (addr_target)inAddr;
  3343. AutoCrit autoCrit(mDebugManager->mCritSect);
  3344. if (!TryRunContinue())
  3345. return;
  3346. BfLogDbg("StepIntoSpecific %p\n", addr);
  3347. mCurNoInfoStepTries = 0; // Reset
  3348. mStepInAssembly = false;
  3349. SetupStep(StepType_StepInto);
  3350. mIsStepIntoSpecific = true;
  3351. mStepType = StepType_StepInto_Unfiltered;
  3352. if (mStepStartPC != addr)
  3353. {
  3354. RemoveTempBreakpoints();
  3355. SetTempBreakpoint(addr);
  3356. mStepBreakpointAddrs.push_back(addr);
  3357. }
  3358. ContinueDebugEvent();
  3359. }
  3360. void WinDebugger::PushValue(CPURegisters* registers, int64 val)
  3361. {
  3362. addr_target* regSP = registers->GetSPRegisterRef();
  3363. *regSP -= sizeof(addr_target);
  3364. WriteMemory<addr_target>(*regSP, (addr_target)val);
  3365. }
  3366. void WinDebugger::PushValue(CPURegisters* registers, const DbgTypedValue& typedValue)
  3367. {
  3368. addr_target* regSP = registers->GetSPRegisterRef();
  3369. int byteCount = typedValue.mType->GetByteCount();
  3370. if ((byteCount == 8) || (sizeof(addr_target) == 8))
  3371. {
  3372. *regSP -= sizeof(int64);
  3373. addr_target val = typedValue.mInt64;
  3374. if (typedValue.mType->IsCompositeType())
  3375. val = typedValue.mSrcAddress;
  3376. WriteMemory<int64>(*regSP, val);
  3377. }
  3378. else
  3379. {
  3380. *regSP -= sizeof(int32);
  3381. addr_target val = typedValue.mInt32;
  3382. if (typedValue.mType->IsCompositeType())
  3383. val = typedValue.mSrcAddress;
  3384. WriteMemory<int32>(*regSP, val);
  3385. }
  3386. }
  3387. void WinDebugger::SetThisRegister(CPURegisters* registers, addr_target val)
  3388. {
  3389. #if BF_DBG_32
  3390. registers->mIntRegs.ecx = val;
  3391. #else
  3392. registers->mIntRegs.rcx = val;
  3393. #endif
  3394. }
  3395. void WinDebugger::AddParamValue(int paramIdx, bool hadThis, CPURegisters* registers, const DbgTypedValue& typedValue)
  3396. {
  3397. #if BF_DBG_32
  3398. PushValue(registers, typedValue);
  3399. #else
  3400. int regIdx = paramIdx + (hadThis ? 1 : 0);
  3401. if (typedValue.mType->IsFloat())
  3402. {
  3403. PushValue(registers, typedValue);
  3404. if (regIdx < 4)
  3405. {
  3406. if (typedValue.mType->mTypeCode == DbgType_Single)
  3407. {
  3408. registers->mXmmRegsArray[regIdx].f[0] = typedValue.mSingle;
  3409. }
  3410. else
  3411. {
  3412. registers->mXmmDRegsArray[regIdx].d[0] = typedValue.mDouble;
  3413. }
  3414. }
  3415. }
  3416. else
  3417. {
  3418. PushValue(registers, typedValue);
  3419. if (regIdx < 4)
  3420. {
  3421. int64 val;
  3422. if (typedValue.mType->IsCompositeType())
  3423. val = typedValue.mSrcAddress;
  3424. else
  3425. val = typedValue.mPtr;
  3426. if (regIdx == 0)
  3427. registers->mIntRegs.rcx = val;
  3428. else if (regIdx == 1)
  3429. registers->mIntRegs.rdx = val;
  3430. else if (regIdx == 2)
  3431. registers->mIntRegs.r8 = val;
  3432. else if (regIdx == 3)
  3433. registers->mIntRegs.r9 = val;
  3434. }
  3435. }
  3436. #endif
  3437. }
  3438. bool WinDebugger::CheckNeedsSRetArgument(DbgType* retType)
  3439. {
  3440. if (!retType->IsCompositeType())
  3441. return false;
  3442. //TODO: Change when we change the calling convention
  3443. if (retType->GetLanguage() == DbgLanguage_Beef)
  3444. return true;
  3445. int retSize = retType->GetByteCount();
  3446. //TODO: Check for 'POD' type?
  3447. if ((retSize == 1) || (retSize == 2) || (retSize == 4) || (retSize == sizeof(addr_target)))
  3448. return false;
  3449. return true;
  3450. }
  3451. DbgTypedValue WinDebugger::ReadReturnValue(CPURegisters* registers, DbgType* type)
  3452. {
  3453. DbgTypedValue retValue;
  3454. if (type->IsFloat())
  3455. {
  3456. retValue.mType = type;
  3457. #if BF_DBG_32
  3458. retValue.mDouble = ConvertFloat80ToDouble(registers->mFpMmRegsArray[0].fp.fp80);
  3459. if (type->mSize == 4)
  3460. retValue.mSingle = (float)retValue.mDouble;
  3461. #else
  3462. if (retValue.mType->mTypeCode == DbgType_Single)
  3463. retValue.mSingle = registers->mXmmRegsArray[0].f[0];
  3464. else
  3465. retValue.mDouble = registers->mXmmDRegsArray[0].d[0];
  3466. #endif
  3467. }
  3468. else if (type->IsCompositeType())
  3469. {
  3470. retValue.mType = type;
  3471. if (CheckNeedsSRetArgument(type))
  3472. {
  3473. #ifdef BF_DBG_32
  3474. retValue.mSrcAddress = mSavedContext.Esp - BF_ALIGN(type->GetByteCount(), 16);
  3475. #else
  3476. retValue.mSrcAddress = mSavedContext.Rsp - BF_ALIGN(type->GetByteCount(), 16);
  3477. #endif
  3478. }
  3479. else
  3480. {
  3481. #ifdef BF_DBG_32
  3482. retValue.mInt32 = mSavedContext.Eax;
  3483. #else
  3484. retValue.mInt64 = mSavedContext.Rax;
  3485. #endif
  3486. }
  3487. }
  3488. else
  3489. {
  3490. #ifdef BF_DBG_32
  3491. retValue.mType = type;
  3492. retValue.mInt32 = registers->mIntRegs.eax;
  3493. if (type->mSize == 8)
  3494. (&retValue.mInt32)[1] = registers->mIntRegs.edx;
  3495. #else
  3496. retValue.mType = type;
  3497. retValue.mInt64 = registers->mIntRegs.rax;
  3498. #endif
  3499. return retValue;
  3500. }
  3501. return retValue;
  3502. }
  3503. bool WinDebugger::SetRegisters(CPURegisters* registers)
  3504. {
  3505. BF_CONTEXT lcContext;
  3506. lcContext.ContextFlags = BF_CONTEXT_CONTROL | BF_CONTEXT_INTEGER | BF_CONTEXT_FLOATING_POINT | BF_CONTEXT_EXTENDED_REGISTERS | BF_CONTEXT_SEGMENTS;
  3507. lcContext.ContextFlags |= BF_CONTEXT_EXCEPTION_REQUEST;
  3508. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  3509. #ifdef BF_DBG_32
  3510. lcContext.Eax = registers->mIntRegs.eax;
  3511. lcContext.Ecx = registers->mIntRegs.ecx;
  3512. lcContext.Edx = registers->mIntRegs.edx;
  3513. lcContext.Ebx = registers->mIntRegs.ebx;
  3514. lcContext.Esp = registers->mIntRegs.esp;
  3515. lcContext.Ebp = registers->mIntRegs.ebp;
  3516. lcContext.Esi = registers->mIntRegs.esi;
  3517. lcContext.Edi = registers->mIntRegs.edi;
  3518. lcContext.Eip = registers->mIntRegs.eip;
  3519. lcContext.EFlags = registers->mIntRegs.efl;
  3520. BF_ASSERT(sizeof(lcContext.FloatSave.RegisterArea) == sizeof(registers->mFpMmRegsArray));
  3521. memcpy(lcContext.FloatSave.RegisterArea, registers->mFpMmRegsArray, sizeof(lcContext.FloatSave.RegisterArea));
  3522. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 32*sizeof(float));
  3523. memcpy(&lcContext.ExtendedRegisters[160], registers->mXmmRegsArray, sizeof(registers->mXmmRegsArray));
  3524. #else
  3525. lcContext.Rax = registers->mIntRegs.rax;
  3526. lcContext.Rcx = registers->mIntRegs.rcx;
  3527. lcContext.Rdx = registers->mIntRegs.rdx;
  3528. lcContext.Rbx = registers->mIntRegs.rbx;
  3529. lcContext.Rsp = registers->mIntRegs.rsp;
  3530. lcContext.Rbp = registers->mIntRegs.rbp;
  3531. lcContext.Rsi = registers->mIntRegs.rsi;
  3532. lcContext.Rdi = registers->mIntRegs.rdi;
  3533. lcContext.Rip = registers->mIntRegs.rip;
  3534. lcContext.EFlags = (DWORD)registers->mIntRegs.efl;
  3535. lcContext.R8 = registers->mIntRegs.r8;
  3536. lcContext.R9 = registers->mIntRegs.r9;
  3537. lcContext.R10 = registers->mIntRegs.r10;
  3538. lcContext.R11 = registers->mIntRegs.r11;
  3539. lcContext.R12 = registers->mIntRegs.r12;
  3540. lcContext.R13 = registers->mIntRegs.r13;
  3541. lcContext.R14 = registers->mIntRegs.r14;
  3542. lcContext.R15 = registers->mIntRegs.r15;
  3543. for (int i = 0; i < 8; i++)
  3544. {
  3545. memcpy(&lcContext.FltSave.FloatRegisters[i], &registers->mFpMmRegsArray[i], 10);
  3546. }
  3547. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 64 * sizeof(float));
  3548. memcpy(BF_CONTEXT_XMMDATA(lcContext), registers->mXmmRegsArray, sizeof(registers->mXmmRegsArray));
  3549. #endif
  3550. //lcContext.ContextFlags |= BF_CONTEXT_EXCEPTION_REQUEST;
  3551. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  3552. return (lcContext.ContextFlags & (BF_CONTEXT_EXCEPTION_ACTIVE | BF_CONTEXT_SERVICE_ACTIVE)) == 0;
  3553. }
  3554. void WinDebugger::SaveAllRegisters()
  3555. {
  3556. BfLogDbg("SaveAllRegisters setting mSavedAtBreakpointAddress = %p\n", mActiveThread->mIsAtBreakpointAddress);
  3557. mSavedAtBreakpointAddress = mActiveThread->mIsAtBreakpointAddress;
  3558. mSavedBreakpointAddressContinuing = mActiveThread->mBreakpointAddressContinuing;
  3559. mSavedContext.ContextFlags = BF_CONTEXT_ALL;
  3560. BF_GetThreadContext(mActiveThread->mHThread, &mSavedContext);
  3561. }
  3562. void WinDebugger::RestoreAllRegisters()
  3563. {
  3564. BfLogDbg("RestoreAllRegisters setting mIsAtBreakpointAddress = %p\n", mSavedAtBreakpointAddress);
  3565. mActiveThread->mIsAtBreakpointAddress = mSavedAtBreakpointAddress;
  3566. mActiveThread->mBreakpointAddressContinuing = mSavedBreakpointAddressContinuing;
  3567. BF_SetThreadContext(mActiveThread->mHThread, &mSavedContext);
  3568. #ifdef BF_DBG_32
  3569. //TODO: Find the test that this was required for...
  3570. // if (mActiveThread->mIsAtBreakpointAddress == mSavedContext.Eip)
  3571. // {
  3572. // if (mRunState == RunState_Running_ToTempBreakpoint)
  3573. // mRunState = RunState_Paused;
  3574. // }
  3575. // else
  3576. // {
  3577. // SetTempBreakpoint(mSavedContext.Eip);
  3578. // mRunState = RunState_Running_ToTempBreakpoint;
  3579. // mStepType = StepType_ToTempBreakpoint;
  3580. // mSteppingThread = mActiveThread;
  3581. // }
  3582. #endif
  3583. }
  3584. void WinDebugger::OutputMessage(const StringImpl& msg)
  3585. {
  3586. if (this == NULL)
  3587. return;
  3588. AutoCrit autoCrit(mDebugManager->mCritSect);
  3589. mDebugManager->mOutMessages.push_back("msg " + msg);
  3590. }
  3591. void WinDebugger::OutputRawMessage(const StringImpl& msg)
  3592. {
  3593. if (this == NULL)
  3594. return;
  3595. AutoCrit autoCrit(mDebugManager->mCritSect);
  3596. mDebugManager->mOutMessages.push_back(msg);
  3597. }
  3598. void WinDebugger::SetRunState(RunState runState)
  3599. {
  3600. mRunState = runState;
  3601. }
  3602. bool WinDebugger::TryRunContinue()
  3603. {
  3604. if (mRunState == RunState_Exception)
  3605. {
  3606. mIsContinuingFromException = true;
  3607. mRunState = RunState_Paused;
  3608. }
  3609. if (((mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint)) && (mNeedsRehupBreakpoints))
  3610. RehupBreakpoints(true);
  3611. return true;
  3612. }
  3613. void WinDebugger::ClearStep()
  3614. {
  3615. BfLogDbg("ClearStep\n");
  3616. RemoveTempBreakpoints();
  3617. mOrigStepType = StepType_None;
  3618. mStepType = StepType_None;
  3619. mStepStartPC = 0;
  3620. mStepSP = 0;
  3621. mStepPC = 0;
  3622. mIsStepIntoSpecific = false;
  3623. mStepIsRecursing = false;
  3624. mStepStopOnNextInstruction = false;
  3625. mStepLineData = DbgLineDataEx();
  3626. }
  3627. bool WinDebugger::SetupStep(StepType stepType)
  3628. {
  3629. BP_ZONE("SetupStep");
  3630. RemoveTempBreakpoints();
  3631. if (mNeedsRehupBreakpoints)
  3632. RehupBreakpoints(true);
  3633. if (mOrigStepType == StepType_None)
  3634. mOrigStepType = stepType;
  3635. mStepType = stepType;
  3636. mSteppingThread = mActiveThread;
  3637. mStepSwitchedThreads = false;
  3638. mContinueFromBreakpointFailed = false;
  3639. CPURegisters registers;
  3640. PopulateRegisters(&registers);
  3641. addr_target pcAddress = registers.GetPC();
  3642. if (mStepLineData.IsNull())
  3643. {
  3644. DbgSubprogram* dbgSubprogram = NULL;
  3645. auto dbgLineData = FindLineDataAtAddress(pcAddress, &dbgSubprogram);
  3646. mStepLineData = DbgLineDataEx(dbgLineData, dbgSubprogram);
  3647. mStepStartPC = registers.GetPC();
  3648. }
  3649. bool isDeeper = mStepSP > registers.GetSP();
  3650. 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);
  3651. mStepSP = registers.GetSP();
  3652. mStepPC = registers.GetPC();
  3653. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_NoFrame) || (mStepType == StepType_StepOut_ThenInto))
  3654. {
  3655. if (mStepType != StepType_StepOut_NoFrame)
  3656. {
  3657. // Test for stepping out of an inline method
  3658. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3659. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL))
  3660. {
  3661. DbgSubprogram* topSubprogram = dwSubprogram->GetRootInlineParent();
  3662. if ((mOrigStepType == StepType_StepInto) || (mOrigStepType == StepType_StepInto_Unfiltered))
  3663. {
  3664. mStepType = mOrigStepType;
  3665. }
  3666. else
  3667. {
  3668. mStepType = StepType_StepOut_Inline;
  3669. // Set up pcAddress to detect recursion
  3670. //TODO: We can't set a physical breakpoint here because we will immediately hit it when attempting to step over an inlined method.
  3671. // An inlined method can't recurse anyway, but store the pcAddress in mTempBreakpoints because we still check that for recursion
  3672. // SetTempBreakpoint(pcAddress);
  3673. //mTempBreakpoint.push_back(pcAddress);
  3674. mStepBreakpointAddrs.push_back(pcAddress);
  3675. }
  3676. addr_target endAddress = dwSubprogram->mBlock.mHighPC;
  3677. if (dwSubprogram->mHasLineAddrGaps)
  3678. {
  3679. // Keep bumping out the address as long as we can find lines that contain the nextPC
  3680. addr_target nextAddr = pcAddress;
  3681. for (auto& lineInfo : topSubprogram->mLineInfo->mLines)
  3682. {
  3683. auto lineAddr = topSubprogram->GetLineAddr(lineInfo);
  3684. if ((nextAddr >= lineAddr) && (nextAddr < lineAddr + lineInfo.mContribSize))
  3685. {
  3686. auto ctx = topSubprogram->mLineInfo->mContexts[lineInfo.mCtxIdx];
  3687. if (ctx.mInlinee == dwSubprogram)
  3688. {
  3689. nextAddr = lineAddr + lineInfo.mContribSize;
  3690. }
  3691. }
  3692. }
  3693. if (nextAddr != pcAddress)
  3694. endAddress = nextAddr;
  3695. }
  3696. BfLogDbg("Stepping out of inlined method, end address: %p\n", endAddress);
  3697. SetTempBreakpoint(endAddress);
  3698. mStepBreakpointAddrs.push_back(endAddress);
  3699. addr_target decodeAddress = dwSubprogram->mBlock.mLowPC;
  3700. while (decodeAddress < endAddress)
  3701. {
  3702. CPUInst inst;
  3703. if (!mDebugTarget->DecodeInstruction(decodeAddress, &inst))
  3704. break;
  3705. addr_target targetAddress = inst.GetTarget();
  3706. // We need to find a targetAddress
  3707. if ((targetAddress != 0) &&
  3708. !((targetAddress >= dwSubprogram->mBlock.mLowPC) && (targetAddress < dwSubprogram->mBlock.mHighPC)) &&
  3709. ((targetAddress >= topSubprogram->mBlock.mLowPC) && (targetAddress < topSubprogram->mBlock.mHighPC)))
  3710. {
  3711. BfLogDbg("Stepping out of inlined method, branch address: %p\n", targetAddress);
  3712. SetTempBreakpoint(targetAddress);
  3713. mStepBreakpointAddrs.push_back(targetAddress);
  3714. }
  3715. decodeAddress += inst.GetLength();
  3716. }
  3717. return true;
  3718. }
  3719. }
  3720. if ((mStepType != StepType_StepOut_NoFrame) && (RollBackStackFrame(&registers, true)))
  3721. {
  3722. bool isStackAdjust = false;
  3723. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3724. if (dwSubprogram != NULL)
  3725. {
  3726. if ((strcmp(dwSubprogram->mName, "_chkstk") == 0) ||
  3727. (strcmp(dwSubprogram->mName, "__chkstk") == 0) ||
  3728. (strcmp(dwSubprogram->mName, "_alloca_probe") == 0))
  3729. isStackAdjust = true;
  3730. }
  3731. pcAddress = registers.GetPC();
  3732. if (isStackAdjust)
  3733. {
  3734. // We set it to zero so we never detect an "isDeeper" condition which would skip over the return-location breakpoint
  3735. mStepSP = 0;
  3736. }
  3737. else
  3738. {
  3739. addr_target oldAddress = pcAddress;
  3740. CPUInst inst;
  3741. while (true)
  3742. {
  3743. if (mStepInAssembly)
  3744. break;
  3745. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  3746. break;
  3747. if ((inst.IsBranch()) || (inst.IsCall()) || (inst.IsReturn()))
  3748. break;
  3749. #ifdef BF_DBG_32
  3750. if (!inst.StackAdjust(mStepSP))
  3751. break;
  3752. #endif
  3753. DbgSubprogram* checkSubprogram = NULL;
  3754. auto checkLineData = FindLineDataAtAddress(pcAddress, &checkSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  3755. if (checkLineData == NULL)
  3756. break;
  3757. if (checkSubprogram->GetLineAddr(*checkLineData) == pcAddress)
  3758. break;
  3759. pcAddress += inst.GetLength();
  3760. }
  3761. if (pcAddress != oldAddress)
  3762. {
  3763. BfLogDbg("Adjusting stepout address from %p to %p\n", oldAddress, pcAddress);
  3764. }
  3765. }
  3766. BfLogDbg("SetupStep Stepout SetTempBreakpoint %p\n", pcAddress);
  3767. SetTempBreakpoint(pcAddress);
  3768. mStepBreakpointAddrs.push_back(pcAddress);
  3769. if (mStepType != StepType_StepOut_ThenInto)
  3770. mStepType = StepType_StepOut;
  3771. }
  3772. else
  3773. {
  3774. // Try to handle the case where we just entered this call so the return address is the first entry on the stack
  3775. addr_target* regSP = registers.GetSPRegisterRef();
  3776. pcAddress = ReadMemory<addr_target>(*regSP);
  3777. *regSP += sizeof(addr_target);
  3778. if (mDebugTarget->FindSubProgram(pcAddress) != NULL)
  3779. {
  3780. BfLogDbg("SetupStep Stepout SetTempBreakpoint (2) %p\n", pcAddress);
  3781. SetTempBreakpoint(pcAddress);
  3782. mStepBreakpointAddrs.push_back(pcAddress);
  3783. if (mOrigStepType == StepType_StepInto)
  3784. mStepType = StepType_StepInto;
  3785. else
  3786. mStepType = StepType_StepOver;
  3787. return true;
  3788. }
  3789. else
  3790. {
  3791. // Just do stepovers until we eventually step out
  3792. //BF_DBG_FATAL("StepOut Failed");
  3793. BfLogDbg("StepOut Failed\n");
  3794. if (mLastValidStepIntoPC != 0)
  3795. {
  3796. BfLogDbg("Using mLastValidStepIntoPC: %p\n", mLastValidStepIntoPC);
  3797. if (mOrigStepType == StepType_StepInto)
  3798. mStepType = StepType_StepInto;
  3799. else
  3800. mStepType = StepType_StepOver;
  3801. SetTempBreakpoint(mLastValidStepIntoPC);
  3802. mStepBreakpointAddrs.push_back(0);
  3803. mStepBreakpointAddrs.push_back(mLastValidStepIntoPC);
  3804. mLastValidStepIntoPC = 0;
  3805. return true;
  3806. }
  3807. else
  3808. {
  3809. BfLogDbg("Stopping");
  3810. mStepType = StepType_None;
  3811. mRunState = RunState_Paused;
  3812. return true;
  3813. }
  3814. }
  3815. }
  3816. }
  3817. if ((mStepType != StepType_StepOut) && (mStepType != StepType_StepOut_ThenInto))
  3818. {
  3819. if (mDebuggerWaitingThread != mSteppingThread)
  3820. {
  3821. // We've switched threads, so there's a possible race condition:
  3822. // This new thread may already have an EXCEPTION_BREAKPOINT queued up so the PC is actually
  3823. // located one byte past the BREAK instruction, which is one byte into whatever instruction
  3824. // was previously there. We can't insert normal BREAK instructions because we don't know
  3825. // if the current PC is actually at an instruction start, so we do a single step with a
  3826. // slower stack call check to see if we need to step out after a "step over"
  3827. BfLogDbg("Step - switched threads mIsAtBreakpointAddress:%p\n", mSteppingThread->mIsAtBreakpointAddress);
  3828. mStepSwitchedThreads = true;
  3829. SingleStepX86();
  3830. return true;
  3831. }
  3832. bool breakOnNext = false;
  3833. int instIdx = 0;
  3834. for (instIdx = 0; true; instIdx++)
  3835. {
  3836. bool isAtLine = false;
  3837. DbgSubprogram* dwSubprogram = NULL;
  3838. auto dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  3839. isAtLine = (instIdx > 0) && (dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dwSubprogram->GetLineAddr(*dwLineData) == pcAddress);
  3840. // "Never step into" line
  3841. if ((dwLineData != NULL) && (dwLineData->mColumn == -2) && (stepType == StepType_StepInto))
  3842. stepType = StepType_StepOver;
  3843. CPUInst inst;
  3844. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  3845. {
  3846. BfLogDbg("Decode failed, set up SingleStepX86 %p\n", pcAddress);
  3847. SingleStepX86();
  3848. mStepStopOnNextInstruction = true;
  3849. return true;
  3850. }
  3851. if (instIdx > 256)
  3852. {
  3853. BfLogDbg("Too many SetupStep iterations");
  3854. breakOnNext = true;
  3855. }
  3856. if ((inst.IsReturn()) && (instIdx == 0) && (!mStepInAssembly))
  3857. {
  3858. // Do actual STEP OUT so we set up proper "stepping over unimportant post-return instructions"
  3859. if (stepType == StepType_StepInto)
  3860. return SetupStep(StepType_StepOut_ThenInto);
  3861. else
  3862. return SetupStep(StepType_StepOut);
  3863. }
  3864. if ((breakOnNext) || (mStepInAssembly) || (isAtLine) || (inst.IsBranch()) || (inst.IsCall()) || (inst.IsReturn()))
  3865. {
  3866. if (((instIdx == 0) || (mStepInAssembly)) && (!breakOnNext))
  3867. {
  3868. if ((stepType == StepType_StepOver) && (inst.IsCall()))
  3869. {
  3870. // Continue - sets a breakpoint on the call line to detect recursion.
  3871. // The next loop through will set a breakpoint on the line after the return
  3872. BfLogDbg("StepHadCall\n");
  3873. breakOnNext = true;
  3874. BfLogDbg("StepHadCall setting mIsAtBreakpointAddress = %p\n", pcAddress);
  3875. mSteppingThread->mIsAtBreakpointAddress = pcAddress;
  3876. SetTempBreakpoint(pcAddress);
  3877. mStepBreakpointAddrs.push_back(pcAddress);
  3878. }
  3879. else
  3880. {
  3881. if (inst.IsCall())
  3882. {
  3883. if ((mLastValidStepIntoPC == 0) || (dwSubprogram != NULL))
  3884. mLastValidStepIntoPC = pcAddress + inst.mSize;
  3885. }
  3886. if ((dwLineData != NULL) && (inst.IsBranch()))
  3887. {
  3888. addr_target targetAddr = inst.GetTarget();
  3889. if (targetAddr < dwSubprogram->GetLineAddr(*dwLineData))
  3890. {
  3891. // Jumping backwards, stop at next instruction
  3892. mStepStopOnNextInstruction = true;
  3893. }
  3894. }
  3895. bool isPrefixOnly = false;
  3896. if ((mStepInAssembly) && (stepType == StepType_StepOver) && (inst.IsRep(isPrefixOnly)))
  3897. {
  3898. if (isPrefixOnly)
  3899. {
  3900. CPUInst nextInst;
  3901. if (mDebugTarget->DecodeInstruction(pcAddress + inst.GetLength(), &nextInst))
  3902. {
  3903. if (nextInst.IsBranch())
  3904. {
  3905. // repne jmp - this appears in __chkstk (for example)
  3906. // We don't have a good way to "step over" this one, so just do a single step
  3907. }
  3908. else
  3909. {
  3910. // Step over the rep + target instruction
  3911. auto doneAddr = pcAddress + inst.GetLength() + nextInst.GetLength();
  3912. BfLogDbg("SetupStep SetTempBreakpoint %p\n", doneAddr);
  3913. SetTempBreakpoint(doneAddr);
  3914. mStepBreakpointAddrs.push_back(doneAddr);
  3915. break;
  3916. }
  3917. }
  3918. }
  3919. else
  3920. {
  3921. // Step over the instruction
  3922. auto doneAddr = pcAddress + inst.GetLength();
  3923. BfLogDbg("SetupStep SetTempBreakpoint %p\n", doneAddr);
  3924. SetTempBreakpoint(doneAddr);
  3925. mStepBreakpointAddrs.push_back(doneAddr);
  3926. break;
  3927. }
  3928. }
  3929. // Just step a single instruction
  3930. BfLogDbg("SetupStep SingleStepX86 %p\n", pcAddress);
  3931. SingleStepX86();
  3932. if (inst.IsReturn())
  3933. mStepStopOnNextInstruction = true;
  3934. break;
  3935. }
  3936. }
  3937. else
  3938. {
  3939. // Move us to this instruction so we can hardware single-step into it
  3940. BfLogDbg("SetupStep SetTempBreakpoint %p\n", pcAddress);
  3941. SetTempBreakpoint(pcAddress);
  3942. mStepBreakpointAddrs.push_back(pcAddress);
  3943. break;
  3944. }
  3945. }
  3946. // Not an interesting instruction - move to next
  3947. pcAddress += inst.mSize;
  3948. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress >= dwSubprogram->mBlock.mHighPC))
  3949. {
  3950. auto endAddress = dwSubprogram->mBlock.mHighPC;
  3951. BfLogDbg("Stepping past end of inlined method, end address: %p\n", endAddress);
  3952. mStepType = StepType_StepOut_Inline;
  3953. SetTempBreakpoint(endAddress);
  3954. mStepBreakpointAddrs.push_back(endAddress);
  3955. return true;
  3956. }
  3957. }
  3958. if (instIdx > 1)
  3959. BfLogDbg("SetupStep instIdx: %d\n", instIdx);
  3960. }
  3961. return true;
  3962. }
  3963. void WinDebugger::CheckNonDebuggerBreak()
  3964. {
  3965. enum MessageType
  3966. {
  3967. MessageType_None = 0,
  3968. MessageType_Error = 1,
  3969. MessageType_ProfilerCmd = 2
  3970. };
  3971. CPURegisters registers;
  3972. PopulateRegisters(&registers);
  3973. addr_target pcAddress = registers.GetPC();
  3974. addr_target debugMessageDataAddr = (addr_target)-1;
  3975. if (mDebugTarget->mTargetBinary != NULL)
  3976. {
  3977. mDebugTarget->mTargetBinary->ParseSymbolData();
  3978. debugMessageDataAddr = mDebugTarget->FindSymbolAddr("gBfDebugMessageData");
  3979. }
  3980. if (debugMessageDataAddr != (addr_target)-1)
  3981. {
  3982. struct BfDebugMessageData
  3983. {
  3984. int mMessageType; // 0 = none, 1 = error
  3985. int mStackWindbackCount;
  3986. int mBufParamLen;
  3987. addr_target mBufParam;
  3988. addr_target mPCOverride;
  3989. };
  3990. BfDebugMessageData messageData = ReadMemory<BfDebugMessageData>(debugMessageDataAddr);
  3991. WriteMemory<int>(debugMessageDataAddr, 0); // Zero out type so we won't trigger again
  3992. if (messageData.mMessageType != 0)
  3993. {
  3994. llvm::SmallVector<char, 4096> strBuf;
  3995. int strLen = messageData.mBufParamLen;
  3996. strBuf.resize(strLen + 1);
  3997. char* str = &strBuf[0];
  3998. str[strLen] = 0;
  3999. if (ReadMemory(messageData.mBufParam, strLen, str))
  4000. {
  4001. if (messageData.mMessageType == MessageType_Error)
  4002. {
  4003. mRequestedStackFrameIdx = messageData.mStackWindbackCount;
  4004. if (messageData.mPCOverride != 0)
  4005. {
  4006. mShowPCOverride = messageData.mPCOverride;
  4007. mRequestedStackFrameIdx = -2;
  4008. }
  4009. mDebugManager->mOutMessages.push_back(StrFormat("error %s", str));
  4010. }
  4011. else if (messageData.mMessageType == MessageType_ProfilerCmd)
  4012. {
  4013. // It's important to set this here, because we unlock the critSect during StopSampling and we can't have the
  4014. // IDE thinking that we're actually paused when it checks the mRunState
  4015. mRunState = RunState_Running;
  4016. char* cmd = strtok(str, "\t");
  4017. if (strcmp(cmd, "StartSampling") == 0)
  4018. {
  4019. char* sessionIdStr = strtok(NULL, "\t");
  4020. char* threadIdStr = strtok(NULL, "\t");
  4021. char* sampleRateStr = strtok(NULL, "\t");
  4022. char* descStr = strtok(NULL, "\t");
  4023. if (threadIdStr != NULL)
  4024. {
  4025. int threadId = atoi(threadIdStr);
  4026. int sampleRate = atoi(sampleRateStr);
  4027. int sessionId = atoi(sessionIdStr);
  4028. Profiler** profilerPtr;
  4029. if (mPendingProfilerMap.TryAdd(sessionId, NULL, &profilerPtr))
  4030. {
  4031. DbgProfiler* profiler = new DbgProfiler(this);
  4032. if (descStr != NULL)
  4033. profiler->mDescription = descStr;
  4034. if (sampleRate > 0)
  4035. profiler->mSamplesPerSecond = sampleRate;
  4036. profiler->Start();
  4037. *profilerPtr = profiler;
  4038. mDebugManager->mOutMessages.push_back("newProfiler");
  4039. mNewProfilerList.push_back(profiler);
  4040. }
  4041. }
  4042. }
  4043. else if (strcmp(cmd, "StopSampling") == 0)
  4044. {
  4045. char* sessionIdStr = strtok(NULL, "\t");
  4046. if (sessionIdStr != NULL)
  4047. {
  4048. int sessionId = atoi(sessionIdStr);
  4049. Profiler* profiler;
  4050. if (mPendingProfilerMap.Remove(sessionId, &profiler))
  4051. {
  4052. if (profiler->IsSampling())
  4053. {
  4054. // Need to unlock so we don't deadlock
  4055. mDebugManager->mCritSect.Unlock();
  4056. profiler->Stop();
  4057. mDebugManager->mCritSect.Lock();
  4058. }
  4059. }
  4060. }
  4061. }
  4062. else if (strcmp(cmd, "ClearSampling") == 0)
  4063. {
  4064. for (auto& kv : mPendingProfilerMap)
  4065. {
  4066. auto profiler = kv.mValue;
  4067. profiler->Clear();
  4068. }
  4069. }
  4070. else if (strcmp(cmd, "ClearOutput") == 0)
  4071. {
  4072. mDebugManager->mOutMessages.push_back("clearOutput");
  4073. }
  4074. }
  4075. return;
  4076. }
  4077. }
  4078. }
  4079. intptr_target objAddr;
  4080. if (mDebugTarget->IsObjectAccessBreak(pcAddress, &registers, &objAddr))
  4081. {
  4082. String errorStr = "error Attempted to access deleted object";
  4083. String objectAddr = EncodeDataPtr((addr_target)objAddr, true);
  4084. errorStr += StrFormat("\x1LEAK\t(System.Object)%s\n (%s)%s\n", objectAddr.c_str(), "System.Object", objectAddr.c_str());
  4085. mDebugManager->mOutMessages.push_back(errorStr);
  4086. return;
  4087. }
  4088. bool showMainThread = false;
  4089. String symbol;
  4090. addr_target offset;
  4091. DbgModule* dbgModule;
  4092. if (mDebugTarget->FindSymbolAt(pcAddress, &symbol, &offset, &dbgModule))
  4093. {
  4094. if ((symbol == "DbgBreakPoint") || (symbol == "RtlUserThreadStart") || (symbol == "RtlUserThreadStart@8"))
  4095. {
  4096. showMainThread = true;
  4097. }
  4098. }
  4099. #ifdef BF_DBG_32
  4100. else if ((dbgModule != NULL) && (dbgModule->mDisplayName.Equals("kernel32.dll", StringImpl::CompareKind_OrdinalIgnoreCase)))
  4101. {
  4102. showMainThread = true;
  4103. }
  4104. #endif
  4105. if (showMainThread)
  4106. {
  4107. // This is a manual break, show the main thread
  4108. mActiveThread = mThreadList.front();
  4109. if (mDebugPendingExpr != NULL)
  4110. {
  4111. for (auto thread : mThreadList)
  4112. {
  4113. if (thread->mThreadId == mDebugEvalThreadInfo.mThreadId)
  4114. {
  4115. mActiveThread = thread;
  4116. break;
  4117. }
  4118. }
  4119. }
  4120. }
  4121. }
  4122. bool WinDebugger::HasSteppedIntoCall()
  4123. {
  4124. // Some calls (like __chkstk) actually push results to the stack, so we need to check
  4125. // if we're REALLY deeper or not, by rolling back the callstack once
  4126. CPURegisters registers;
  4127. PopulateRegisters(&registers);
  4128. if (RollBackStackFrame(&registers, true))
  4129. {
  4130. // If the previous frames SP is equal or deeper than our step start then we are indeed inside a call!
  4131. if (mStepSP >= registers.GetSP())
  4132. return true;
  4133. }
  4134. return false;
  4135. }
  4136. void WinDebugger::StepOver(bool inAssembly)
  4137. {
  4138. AutoCrit autoCrit(mDebugManager->mCritSect);
  4139. BfLogDbg("StepOver\n");
  4140. if (!TryRunContinue())
  4141. return;
  4142. mCurNoInfoStepTries = 0; // Reset
  4143. mStepInAssembly = inAssembly;
  4144. SetupStep(StepType_StepOver);
  4145. ContinueDebugEvent();
  4146. }
  4147. void WinDebugger::StepOut(bool inAssembly)
  4148. {
  4149. AutoCrit autoCrit(mDebugManager->mCritSect);
  4150. BfLogDbg("StepOut\n");
  4151. if (!TryRunContinue())
  4152. return;
  4153. mCurNoInfoStepTries = 0; // Reset
  4154. mStepInAssembly = inAssembly;
  4155. SetupStep(StepType_StepOut);
  4156. ContinueDebugEvent();
  4157. }
  4158. void WinDebugger::SetNextStatement(bool inAssembly, const StringImpl& fileName, int64 lineNumOrAsmAddr, int wantColumn)
  4159. {
  4160. AutoCrit autoCrit(mDebugManager->mCritSect);
  4161. DbgSubprogram* subProgram = NULL;
  4162. if (!inAssembly)
  4163. {
  4164. if (mCallStack.size() == 0)
  4165. UpdateCallStack();
  4166. if (mCallStack.size() > 0)
  4167. {
  4168. UpdateCallStackMethod(0);
  4169. subProgram = mCallStack[0]->mSubProgram;
  4170. }
  4171. if (subProgram == NULL)
  4172. return;
  4173. }
  4174. DbgSubprogram* rootInlineParent = NULL;
  4175. if (subProgram != NULL)
  4176. rootInlineParent = subProgram->GetRootInlineParent();
  4177. String result;
  4178. if (mDebugTarget == NULL)
  4179. return;
  4180. DbgSrcFile* srcFile = NULL;
  4181. if (!fileName.IsEmpty())
  4182. {
  4183. srcFile = mDebugTarget->GetSrcFile(fileName);
  4184. if (srcFile == NULL)
  4185. return;
  4186. }
  4187. addr_target pcAddress = 0;
  4188. if (inAssembly)
  4189. {
  4190. pcAddress = lineNumOrAsmAddr;
  4191. }
  4192. else
  4193. {
  4194. int lineNum = (int)lineNumOrAsmAddr;
  4195. addr_target bestAddr[2] = { 0, 0 };
  4196. int checkLineNum[2] = { lineNum - 1, lineNum };
  4197. auto _CheckLineInfo = [&](DbgSubprogram* dbgSubprogram, DbgLineInfo* dbgLineInfo)
  4198. {
  4199. for (int iPass = 0; iPass < 2; ++iPass)
  4200. {
  4201. int bestLineOffset = 0x7FFFFFFF;
  4202. for (auto& lineData : dbgLineInfo->mLines)
  4203. {
  4204. auto addr = dbgSubprogram->GetLineAddr(lineData);
  4205. if ((addr < subProgram->mBlock.mLowPC) || (addr >= subProgram->mBlock.mHighPC))
  4206. continue;
  4207. int lineOffset = lineData.mLine - checkLineNum[iPass];
  4208. if ((lineOffset >= 0) && (lineOffset <= 6) && (lineOffset <= bestLineOffset))
  4209. {
  4210. if (lineOffset < bestLineOffset)
  4211. {
  4212. bestLineOffset = lineOffset;
  4213. bestAddr[iPass] = addr;
  4214. }
  4215. }
  4216. }
  4217. }
  4218. };
  4219. for (int checkHotIdx = -1; checkHotIdx < (int)srcFile->mHotReplacedDbgLineInfo.size(); checkHotIdx++)
  4220. {
  4221. if (checkHotIdx >= 0)
  4222. {
  4223. auto hotReplacedLineInfo = srcFile->mHotReplacedDbgLineInfo[checkHotIdx];
  4224. for (auto& hotReplacedEntry : hotReplacedLineInfo->mEntries)
  4225. {
  4226. _CheckLineInfo(hotReplacedEntry.mSubprogram, hotReplacedEntry.mLineInfo);
  4227. }
  4228. }
  4229. else
  4230. {
  4231. for (auto subprogram : srcFile->mLineDataRefs)
  4232. _CheckLineInfo(subprogram, subprogram->mLineInfo);
  4233. }
  4234. if (bestAddr[1] != 0)
  4235. break;
  4236. }
  4237. if (bestAddr[1] != 0)
  4238. {
  4239. const int kMaxAddrDist = 64; // within reasonable range
  4240. if ((bestAddr[0] != 0) && (bestAddr[1] - bestAddr[0] <= kMaxAddrDist))
  4241. {
  4242. addr_target addrStart = bestAddr[0];
  4243. addr_target addrEnd = bestAddr[1];
  4244. addr_target addr = addrStart;
  4245. BF_ASSERT(addrEnd - addr <= kMaxAddrDist);
  4246. addr_target lastOp = 0;
  4247. while (addr < addrEnd)
  4248. {
  4249. CPUInst inst;
  4250. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  4251. break;
  4252. lastOp = addr;
  4253. addr += inst.GetLength();
  4254. }
  4255. }
  4256. pcAddress = (uint64)bestAddr[1];
  4257. }
  4258. }
  4259. if (pcAddress)
  4260. {
  4261. BF_ASSERT(mActiveThread->mBreakpointAddressContinuing == 0);
  4262. mActiveThread->mIsAtBreakpointAddress = 0;
  4263. mActiveThread->mStoppedAtAddress = pcAddress;
  4264. if (mCallStack.size() == 0)
  4265. UpdateCallStack();
  4266. CPURegisters* regs = &mCallStack.front()->mRegisters;
  4267. *regs->GetPCRegisterRef() = pcAddress;
  4268. SetRegisters(regs);
  4269. WdBreakpoint* breakpoint = (WdBreakpoint*)FindBreakpointAt(pcAddress);
  4270. if (breakpoint != NULL)
  4271. {
  4272. BfLogDbg("SetNextStatement setting mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  4273. mActiveThread->mIsAtBreakpointAddress = breakpoint->mAddr;
  4274. }
  4275. }
  4276. }
  4277. bool WinDebugger::PopulateRegisters(CPURegisters* registers, BF_CONTEXT& lcContext)
  4278. {
  4279. #ifdef BF_DBG_32
  4280. registers->mIntRegs.eax = lcContext.Eax;
  4281. registers->mIntRegs.ecx = lcContext.Ecx;
  4282. registers->mIntRegs.edx = lcContext.Edx;
  4283. registers->mIntRegs.ebx = lcContext.Ebx;
  4284. registers->mIntRegs.esp = lcContext.Esp;
  4285. registers->mIntRegs.ebp = lcContext.Ebp;
  4286. registers->mIntRegs.esi = lcContext.Esi;
  4287. registers->mIntRegs.edi = lcContext.Edi;
  4288. registers->mIntRegs.eip = lcContext.Eip;
  4289. registers->mIntRegs.efl = lcContext.EFlags;
  4290. BF_ASSERT(sizeof(lcContext.FloatSave.RegisterArea) == sizeof(registers->mFpMmRegsArray));
  4291. memcpy(registers->mFpMmRegsArray, lcContext.FloatSave.RegisterArea, sizeof(lcContext.FloatSave.RegisterArea));
  4292. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 32 * sizeof(float));
  4293. memcpy(registers->mXmmRegsArray, &lcContext.ExtendedRegisters[160], sizeof(registers->mXmmRegsArray));
  4294. #else
  4295. registers->mIntRegs.rax = lcContext.Rax;
  4296. registers->mIntRegs.rcx = lcContext.Rcx;
  4297. registers->mIntRegs.rdx = lcContext.Rdx;
  4298. registers->mIntRegs.rbx = lcContext.Rbx;
  4299. registers->mIntRegs.rsp = lcContext.Rsp;
  4300. registers->mIntRegs.rbp = lcContext.Rbp;
  4301. registers->mIntRegs.rsi = lcContext.Rsi;
  4302. registers->mIntRegs.rdi = lcContext.Rdi;
  4303. registers->mIntRegs.rip = lcContext.Rip;
  4304. registers->mIntRegs.efl = lcContext.EFlags;
  4305. registers->mIntRegs.r8 = lcContext.R8;
  4306. registers->mIntRegs.r9 = lcContext.R9;
  4307. registers->mIntRegs.r10 = lcContext.R10;
  4308. registers->mIntRegs.r11 = lcContext.R11;
  4309. registers->mIntRegs.r12 = lcContext.R12;
  4310. registers->mIntRegs.r13 = lcContext.R13;
  4311. registers->mIntRegs.r14 = lcContext.R14;
  4312. registers->mIntRegs.r15 = lcContext.R15;
  4313. registers->mIntRegs.gs = lcContext.SegGs;
  4314. for (int i = 0; i < 8; i++)
  4315. {
  4316. memcpy(&registers->mFpMmRegsArray[i], &lcContext.FltSave.FloatRegisters[i], 10);
  4317. }
  4318. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 64 * sizeof(float));
  4319. memcpy(registers->mXmmRegsArray, BF_CONTEXT_XMMDATA(lcContext), sizeof(registers->mXmmRegsArray));
  4320. #endif
  4321. return (lcContext.ContextFlags & (BF_CONTEXT_EXCEPTION_ACTIVE | BF_CONTEXT_SERVICE_ACTIVE)) == 0;
  4322. }
  4323. bool WinDebugger::PopulateRegisters(CPURegisters* registers)
  4324. {
  4325. /*static bool sCheckedProcessorFeatures = false;
  4326. static bool sMmxAvailable = false;
  4327. static bool sXmmAvailable = false;
  4328. if (!sCheckedProcessorFeatures)
  4329. {
  4330. //CDH we don't do anything with these yet since we grab BF_CONTEXT_ALL anyway, but could be useful
  4331. sMmxAvailable = ::IsProcessorFeaturePresent(PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  4332. sXmmAvailable = ::IsProcessorFeaturePresent(PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  4333. sCheckedProcessorFeatures = true;
  4334. }*/
  4335. BF_ASSERT(registers != nullptr);
  4336. BF_CONTEXT lcContext;
  4337. lcContext.ContextFlags = BF_CONTEXT_ALL | BF_CONTEXT_EXCEPTION_REQUEST;
  4338. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4339. return PopulateRegisters(registers, lcContext);
  4340. }
  4341. bool WinDebugger::RollBackStackFrame(CPURegisters* registers, bool isStackStart)
  4342. {
  4343. BF_ASSERT(registers != nullptr);
  4344. return mDebugTarget->RollBackStackFrame(registers, NULL, isStackStart);
  4345. }
  4346. bool WinDebugger::SetHotJump(DbgSubprogram* oldSubprogram, addr_target newTarget, int newTargetSize)
  4347. {
  4348. BfLogDbg("SetHotJump %s %p->%p\n", oldSubprogram->mName, oldSubprogram->mBlock.mLowPC, newTarget);
  4349. //AutoCrit autoCrit(mDebugManager->mCritSect);
  4350. BF_ASSERT(mDebugManager->mCritSect.mLockCount == 1);
  4351. addr_target jmpInstStart = oldSubprogram->mBlock.mLowPC;
  4352. addr_target jmpInstEnd = jmpInstStart + sizeof(HotJumpOp);
  4353. if (jmpInstEnd > oldSubprogram->mBlock.mHighPC)
  4354. {
  4355. if ((oldSubprogram->mBlock.mHighPC - oldSubprogram->mBlock.mLowPC == 1) &&
  4356. (newTargetSize == 1))
  4357. return true; // Special case for just stub 'ret' methods
  4358. String err = StrFormat("Failed to hot replace method, method '%s' too small to insert hot thunk", oldSubprogram->ToString().c_str());
  4359. Fail(err);
  4360. return false;
  4361. }
  4362. if (oldSubprogram->mHotReplaceKind != DbgSubprogram::HotReplaceKind_Replaced)
  4363. {
  4364. for (int hotThreadIdx = 0; hotThreadIdx < (int)mHotThreadStates.size(); hotThreadIdx++)
  4365. {
  4366. auto& hotThreadState = mHotThreadStates[hotThreadIdx];
  4367. WdThreadInfo* threadInfo = NULL;
  4368. if (!mThreadMap.TryGetValue((uint32)hotThreadState.mThreadId, &threadInfo))
  4369. continue;
  4370. int tryStart = GetTickCount();
  4371. while ((hotThreadState.mRegisters.GetPC() >= jmpInstStart) && (hotThreadState.mRegisters.GetPC() < jmpInstEnd))
  4372. {
  4373. if (GetTickCount() - tryStart >= 8000)
  4374. {
  4375. Fail("Failed to hot replace method, can't move past prelude");
  4376. return false;
  4377. }
  4378. BfLogDbg("SetHotJump skipping through %p\n", hotThreadState.mRegisters.GetPC());
  4379. bool removedBreakpoint = false;
  4380. mActiveThread = threadInfo;
  4381. if ((mActiveThread->mStoppedAtAddress >= jmpInstStart) && (mActiveThread->mStoppedAtAddress < jmpInstEnd))
  4382. {
  4383. for (addr_target addr = jmpInstStart; addr < jmpInstEnd; addr++)
  4384. {
  4385. if (mPhysBreakpointAddrMap.ContainsKey(addr))
  4386. {
  4387. removedBreakpoint = true;
  4388. RemoveBreakpoint(addr);
  4389. }
  4390. }
  4391. }
  4392. RunState oldRunState = mRunState;
  4393. mRunState = RunState_HotStep;
  4394. if (mWantsDebugContinue)
  4395. {
  4396. mWantsDebugContinue = false;
  4397. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4398. mContinueEvent.Set();
  4399. }
  4400. BF_CONTEXT lcContext;
  4401. lcContext.ContextFlags = BF_CONTEXT_ALL;
  4402. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4403. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  4404. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  4405. ::ResumeThread(mActiveThread->mHThread);
  4406. BfLogDbg("ResumeThread %d\n", mActiveThread->mThreadId);
  4407. while (mRunState != RunState_Terminated)
  4408. {
  4409. mDebugManager->mCritSect.Unlock();
  4410. Sleep(0);
  4411. mDebugManager->mCritSect.Lock();
  4412. if (IsPaused())
  4413. break;
  4414. if (mWantsDebugContinue)
  4415. {
  4416. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4417. mWantsDebugContinue = false;
  4418. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4419. mContinueEvent.Set();
  4420. }
  4421. }
  4422. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4423. ::SuspendThread(mActiveThread->mHThread);
  4424. BfLogDbg("SuspendThread %d\n", mActiveThread->mThreadId);
  4425. mRunState = oldRunState;
  4426. if ((mRunState != RunState_Terminated) && (mRunState != RunState_Terminating))
  4427. {
  4428. if (!IsPaused())
  4429. {
  4430. BF_ASSERT(mWantsDebugContinue);
  4431. mWantsDebugContinue = false;
  4432. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4433. mContinueEvent.Set();
  4434. }
  4435. }
  4436. PopulateRegisters(&hotThreadState.mRegisters);
  4437. }
  4438. }
  4439. }
  4440. HotJumpOp jumpOp;
  4441. jumpOp.mOpCode = 0xE9;
  4442. jumpOp.mRelTarget = newTarget - oldSubprogram->mBlock.mLowPC - sizeof(HotJumpOp);
  4443. WriteMemory(oldSubprogram->mBlock.mLowPC, jumpOp);
  4444. ::FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)oldSubprogram->mBlock.mLowPC, sizeof(HotJumpOp));
  4445. return true;
  4446. }
  4447. DbgSubprogram* WinDebugger::TryFollowHotJump(DbgSubprogram* subprogram, addr_target addr)
  4448. {
  4449. if (subprogram->mHotReplaceKind != DbgSubprogram::HotReplaceKind_Replaced)
  4450. return subprogram;
  4451. if (addr != subprogram->mBlock.mLowPC)
  4452. return subprogram;
  4453. auto dbgModule = subprogram->mCompileUnit->mDbgModule;
  4454. HotJumpOp jumpOp = ReadMemory<HotJumpOp>(addr);
  4455. if (jumpOp.mOpCode != 0xE9)
  4456. return subprogram;
  4457. addr_target jumpAddr = addr + jumpOp.mRelTarget + sizeof(HotJumpOp);
  4458. auto jumpSubprogram = mDebugTarget->FindSubProgram(jumpAddr);
  4459. if (jumpSubprogram == NULL)
  4460. return subprogram;
  4461. return jumpSubprogram;
  4462. }
  4463. bool WinDebugger::ShouldShowStaticMember(DbgType* dbgType, DbgVariable* member)
  4464. {
  4465. // If locationData is non-null, that means it was added in addition to the static declaration in the CV type info,
  4466. // so only add the names from the type definition
  4467. auto flavor = dbgType->mCompileUnit->mDbgModule->mDbgFlavor;
  4468. return ((((dbgType->IsNamespace()) || (flavor != DbgFlavor_MS)) && ((member->mLocationData != NULL) || member->mIsConst)) ||
  4469. ((flavor == DbgFlavor_MS) && (member->mLocationData == NULL)));
  4470. }
  4471. String WinDebugger::GetMemberList(DbgType* dbgType, const StringImpl& expr, bool isPtr, bool isStatic, bool forceCast, bool isSplat, bool isReadOnly)
  4472. {
  4473. auto dbgModule = dbgType->GetDbgModule();
  4474. dbgType->PopulateType();
  4475. auto language = dbgType->GetLanguage();
  4476. if (!isStatic)
  4477. {
  4478. String retVal;
  4479. bool needsNewline = false;
  4480. bool isBfObject = false;
  4481. if (dbgType->IsBfObjectPtr())
  4482. {
  4483. isBfObject = true;
  4484. dbgType = dbgType->mTypeParam;
  4485. }
  4486. int baseIdx = 0;
  4487. for (auto baseTypeEntry : dbgType->mBaseTypes)
  4488. {
  4489. auto baseType = baseTypeEntry->mBaseType;
  4490. if ((baseType->mSize > 0) || (baseType->mTypeCode != DbgType_Struct) || (strcmp(baseType->mTypeName, "ValueType") != 0))
  4491. {
  4492. String baseTypeStr = baseType->ToStringRaw(language);
  4493. if (baseIdx > 0)
  4494. retVal += "\n";
  4495. if (isSplat)
  4496. retVal += "[base]\t((" + baseTypeStr + ")" + expr + "), nv";
  4497. else if (dbgType->WantsRefThis())
  4498. retVal += "[base]\t((" + baseTypeStr + ")this), nd, na, nv, this=" + expr;
  4499. else
  4500. retVal += "[base]\t((" + baseTypeStr + "*)this), nd, na, nv, this=" + expr;
  4501. if (isReadOnly)
  4502. retVal += ", ne";
  4503. }
  4504. needsNewline = true;
  4505. baseIdx++;
  4506. }
  4507. String thisExpr = expr;
  4508. String castString;
  4509. if (dbgType->IsBfObject())
  4510. {
  4511. auto ptrType = dbgType->GetDbgModule()->GetPointerType(dbgType);
  4512. castString = ptrType->ToStringRaw(language);
  4513. }
  4514. else
  4515. castString = dbgType->ToStringRaw(language);
  4516. bool hadStatics = false;
  4517. for (auto member : dbgType->mMemberList)
  4518. {
  4519. if (member->mMemberOffset < 0)
  4520. continue;
  4521. if (member->mIsStatic)
  4522. {
  4523. if (ShouldShowStaticMember(dbgType, member))
  4524. hadStatics = true;
  4525. }
  4526. else
  4527. {
  4528. bool ignoreMember = false;
  4529. if (member->mName != NULL)
  4530. {
  4531. if ((member->mName[0] == '?') ||
  4532. (strncmp(member->mName, "_vptr$", 6) == 0))
  4533. ignoreMember = true;
  4534. }
  4535. if (!ignoreMember)
  4536. {
  4537. if (needsNewline)
  4538. retVal += "\n";
  4539. if (member->mName == NULL)
  4540. {
  4541. retVal += GetMemberList(member->mType, expr, isPtr, isStatic, forceCast, isSplat, isReadOnly);
  4542. }
  4543. else
  4544. {
  4545. retVal += String(member->mName);
  4546. if (isSplat)
  4547. {
  4548. retVal += "\t(" + thisExpr + ")." + String(member->mName);
  4549. // We don't want to rely on this being enforced here. For one, ref types shouldn't get ", ne" added,
  4550. // and this doesn't solve the issue of attempting to assign via the Immediate window
  4551. /*if (isReadOnly)
  4552. retVal += ", ne";*/
  4553. }
  4554. else
  4555. {
  4556. if (forceCast)
  4557. retVal += "\t((" + castString + ")this)." + String(member->mName);
  4558. else if ((member->mName[0] >= '0') && (member->mName[0] <= '9')) // Numbered tuple member?
  4559. retVal += "\tthis." + String(member->mName);
  4560. else
  4561. retVal += "\t" + String(member->mName);
  4562. retVal += ", this=" + thisExpr;
  4563. // if (isReadOnly)
  4564. // retVal += ", ne";
  4565. }
  4566. }
  4567. needsNewline = true;
  4568. }
  4569. }
  4570. }
  4571. if (hadStatics)
  4572. {
  4573. if (needsNewline)
  4574. retVal += "\n";
  4575. retVal += "Static values\t" + castString;
  4576. }
  4577. return retVal;
  4578. }
  4579. else
  4580. {
  4581. if (dbgType->IsBfObjectPtr())
  4582. dbgType = dbgType->mTypeParam;
  4583. String retVal;
  4584. String memberPrefix = expr;
  4585. bool needsNewline = false;
  4586. bool hadStatics = false;
  4587. for (auto member : dbgType->mMemberList)
  4588. {
  4589. if (member->mIsStatic)
  4590. {
  4591. if (ShouldShowStaticMember(dbgType, member))
  4592. {
  4593. if (needsNewline)
  4594. retVal += "\n";
  4595. retVal += String(member->mName) + "\t" + memberPrefix + "." + String(member->mName);
  4596. needsNewline = true;
  4597. }
  4598. }
  4599. }
  4600. return retVal;
  4601. }
  4602. return "";
  4603. }
  4604. bool WinDebugger::ParseFormatInfo(DbgModule* dbgModule, const StringImpl& formatInfoStr, DwFormatInfo* formatInfo, BfPassInstance* bfPassInstance, int* assignExprOffset, String* assignExprString, String* errorString, DbgTypedValue contextTypedValue)
  4605. {
  4606. String formatFlags = formatInfoStr;
  4607. if (assignExprOffset != NULL)
  4608. *assignExprOffset = -1;
  4609. while (formatFlags.length() > 0)
  4610. {
  4611. formatFlags = Trim(formatFlags);
  4612. if (formatFlags.IsEmpty())
  4613. break;
  4614. if (formatFlags[0] != ',')
  4615. {
  4616. return false;
  4617. }
  4618. else
  4619. {
  4620. int nextComma = formatFlags.IndexOf(',', 1);
  4621. int quotePos = formatFlags.IndexOf('"', 1);
  4622. if ((quotePos != -1) && (quotePos < nextComma))
  4623. {
  4624. int nextQuotePos = formatFlags.IndexOf('"', quotePos + 1);
  4625. if (nextQuotePos != -1)
  4626. nextComma = formatFlags.IndexOf(',', nextQuotePos + 1);
  4627. }
  4628. if (nextComma == -1)
  4629. nextComma = formatFlags.length();
  4630. String formatCmd = formatFlags.Substring(1, nextComma - 1);
  4631. formatCmd = Trim(formatCmd);
  4632. bool hadError = false;
  4633. if (strncmp(formatCmd.c_str(), "this=", 5) == 0)
  4634. {
  4635. formatCmd = formatFlags.Substring(1);
  4636. formatCmd = Trim(formatCmd);
  4637. String thisExpr = formatCmd.Substring(5);
  4638. if (thisExpr.empty())
  4639. break;
  4640. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, thisExpr, formatInfo);
  4641. formatInfo->mExplicitThis = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4642. if (dbgEvaluationContext.HadError())
  4643. {
  4644. if (errorString != NULL)
  4645. *errorString = dbgEvaluationContext.GetErrorStr();
  4646. return false;
  4647. }
  4648. formatFlags = thisExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4649. continue;
  4650. }
  4651. else if (strncmp(formatCmd.c_str(), "count=", 6) == 0)
  4652. {
  4653. formatCmd = formatFlags.Substring(1);
  4654. formatCmd = Trim(formatCmd);
  4655. String countExpr = formatCmd.Substring(6);
  4656. if (countExpr.empty())
  4657. break;
  4658. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4659. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4660. if ((countValue) && (countValue.mType->IsInteger()))
  4661. formatInfo->mOverrideCount = (intptr)countValue.GetInt64();
  4662. if (dbgEvaluationContext.HadError())
  4663. {
  4664. if (errorString != NULL)
  4665. *errorString = dbgEvaluationContext.GetErrorStr();
  4666. return false;
  4667. }
  4668. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4669. continue;
  4670. }
  4671. else if (strncmp(formatCmd.c_str(), "maxcount=", 9) == 0)
  4672. {
  4673. formatCmd = formatFlags.Substring(1);
  4674. formatCmd = Trim(formatCmd);
  4675. String countExpr = formatCmd.Substring(9);
  4676. if (countExpr.empty())
  4677. break;
  4678. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4679. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4680. if ((countValue) && (countValue.mType->IsInteger()))
  4681. formatInfo->mMaxCount = (intptr)countValue.GetInt64();
  4682. if (dbgEvaluationContext.HadError())
  4683. {
  4684. if (errorString != NULL)
  4685. *errorString = dbgEvaluationContext.GetErrorStr();
  4686. return false;
  4687. }
  4688. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4689. continue;
  4690. }
  4691. else if (strncmp(formatCmd.c_str(), "arraysize=", 10) == 0)
  4692. {
  4693. formatCmd = formatFlags.Substring(1);
  4694. formatCmd = Trim(formatCmd);
  4695. String countExpr = formatCmd.Substring(10);
  4696. if (countExpr.empty())
  4697. break;
  4698. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4699. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4700. if ((countValue) && (countValue.mType->IsInteger()))
  4701. formatInfo->mArrayLength = (intptr)countValue.GetInt64();
  4702. if (dbgEvaluationContext.HadError())
  4703. {
  4704. if (errorString != NULL)
  4705. *errorString = dbgEvaluationContext.GetErrorStr();
  4706. return false;
  4707. }
  4708. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4709. continue;
  4710. }
  4711. else if (strncmp(formatCmd.c_str(), "assign=", 7) == 0)
  4712. {
  4713. formatCmd = formatFlags.Substring(1);
  4714. formatCmd = Trim(formatCmd);
  4715. String assignExpr = formatCmd.Substring(7);
  4716. if (assignExpr.empty())
  4717. break;
  4718. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, assignExpr, formatInfo);
  4719. if (dbgEvaluationContext.HadError())
  4720. {
  4721. if (errorString != NULL)
  4722. *errorString = dbgEvaluationContext.GetErrorStr();
  4723. return false;
  4724. }
  4725. if (assignExprOffset != NULL)
  4726. {
  4727. //TODO: Keep track of the offset directly, this is a hack
  4728. *assignExprOffset = (int)formatInfoStr.IndexOf("assign=") + 7;
  4729. }
  4730. if (assignExprString != NULL)
  4731. *assignExprString = dbgEvaluationContext.mExprNode->ToString();
  4732. formatFlags = assignExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4733. continue;
  4734. }
  4735. else if (strncmp(formatCmd.c_str(), "refid=", 6) == 0)
  4736. {
  4737. formatInfo->mReferenceId = formatCmd.Substring(6);
  4738. if (formatInfo->mReferenceId[0] == '\"')
  4739. formatInfo->mReferenceId = formatInfo->mReferenceId.Substring(1, formatInfo->mReferenceId.length() - 2);
  4740. }
  4741. else if (strncmp(formatCmd.c_str(), "_=", 2) == 0)
  4742. {
  4743. formatInfo->mSubjectExpr = formatCmd.Substring(2);
  4744. if (formatInfo->mSubjectExpr[0] == '\"')
  4745. formatInfo->mSubjectExpr = formatInfo->mSubjectExpr.Substring(1, formatInfo->mSubjectExpr.length() - 2);
  4746. }
  4747. else if (strncmp(formatCmd.c_str(), "expectedType=", 13) == 0)
  4748. {
  4749. formatInfo->mExpectedType = formatCmd.Substring(13);
  4750. if (formatInfo->mExpectedType[0] == '\"')
  4751. formatInfo->mExpectedType = formatInfo->mExpectedType.Substring(1, formatInfo->mExpectedType.length() - 2);
  4752. }
  4753. else if (strncmp(formatCmd.c_str(), "namespaceSearch=", 16) == 0)
  4754. {
  4755. formatInfo->mNamespaceSearch = formatCmd.Substring(16);
  4756. if (formatInfo->mNamespaceSearch[0] == '\"')
  4757. formatInfo->mNamespaceSearch = formatInfo->mNamespaceSearch.Substring(1, formatInfo->mNamespaceSearch.length() - 2);
  4758. }
  4759. else if (formatCmd == "d")
  4760. {
  4761. formatInfo->mDisplayType = DwDisplayType_Decimal;
  4762. }
  4763. else if (formatCmd == "x")
  4764. {
  4765. formatInfo->mDisplayType = DwDisplayType_HexLower;
  4766. }
  4767. else if (formatCmd == "X")
  4768. {
  4769. formatInfo->mDisplayType = DwDisplayType_HexUpper;
  4770. }
  4771. else if (formatCmd == "s")
  4772. {
  4773. formatInfo->mHidePointers = true;
  4774. formatInfo->mDisplayType = DwDisplayType_Ascii;
  4775. }
  4776. else if (formatCmd == "s8")
  4777. {
  4778. formatInfo->mHidePointers = true;
  4779. formatInfo->mDisplayType = DwDisplayType_Utf8;
  4780. }
  4781. else if (formatCmd == "s16")
  4782. {
  4783. formatInfo->mHidePointers = true;
  4784. formatInfo->mDisplayType = DwDisplayType_Utf16;
  4785. }
  4786. else if (formatCmd == "s32")
  4787. {
  4788. formatInfo->mHidePointers = true;
  4789. formatInfo->mDisplayType = DwDisplayType_Utf32;
  4790. }
  4791. else if (formatCmd == "nd")
  4792. {
  4793. formatInfo->mIgnoreDerivedClassInfo = true;
  4794. }
  4795. else if (formatCmd == "na")
  4796. {
  4797. formatInfo->mHidePointers = true;
  4798. }
  4799. else if (formatCmd == "nm")
  4800. {
  4801. formatInfo->mNoMembers = true;
  4802. }
  4803. else if (formatCmd == "ne")
  4804. {
  4805. formatInfo->mNoEdit = true;
  4806. }
  4807. else if (formatCmd == "nv")
  4808. {
  4809. formatInfo->mNoVisualizers = true;
  4810. }
  4811. else if (formatCmd == "rawStr")
  4812. {
  4813. formatInfo->mRawString = true;
  4814. }
  4815. else if (((!formatCmd.IsEmpty()) && ((formatCmd[0] >= '0') && (formatCmd[0] <= '9'))) ||
  4816. (formatCmd.StartsWith("(")))
  4817. {
  4818. String countExpr = formatCmd;
  4819. if (countExpr.empty())
  4820. break;
  4821. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4822. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4823. if ((countValue) && (countValue.mType->IsInteger()))
  4824. formatInfo->mArrayLength = (intptr)countValue.GetInt64();
  4825. if (dbgEvaluationContext.HadError())
  4826. {
  4827. if (errorString != NULL)
  4828. *errorString = dbgEvaluationContext.GetErrorStr();
  4829. return false;
  4830. }
  4831. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4832. continue;
  4833. }
  4834. else
  4835. hadError = true;
  4836. if (hadError)
  4837. {
  4838. if (errorString != NULL)
  4839. *errorString = "Invalid format flags";
  4840. return false;
  4841. }
  4842. formatFlags = formatFlags.Substring(nextComma);
  4843. }
  4844. }
  4845. return true;
  4846. }
  4847. String WinDebugger::MaybeQuoteFormatInfoParam(const StringImpl& str)
  4848. {
  4849. bool needsQuote = false;
  4850. for (int i = 0; i < (int)str.length(); i++)
  4851. {
  4852. char c = str[i];
  4853. if (c == ',')
  4854. needsQuote = true;
  4855. }
  4856. if (!needsQuote)
  4857. return str;
  4858. String qStr = "\"";
  4859. qStr += str;
  4860. qStr += "\"";
  4861. return qStr;
  4862. }
  4863. DbgTypedValue WinDebugger::EvaluateInContext(DbgCompileUnit* dbgCompileUnit, const DbgTypedValue& contextTypedValue, const StringImpl& subExpr, DwFormatInfo* formatInfo, String* outReferenceId, String* outErrors)
  4864. {
  4865. DbgEvaluationContext dbgEvaluationContext(this, dbgCompileUnit->mDbgModule, subExpr, formatInfo, contextTypedValue);
  4866. dbgEvaluationContext.mDbgExprEvaluator->mDbgCompileUnit = dbgCompileUnit;
  4867. if (formatInfo != NULL)
  4868. {
  4869. dbgEvaluationContext.mDbgExprEvaluator->mLanguage = formatInfo->mLanguage;
  4870. dbgEvaluationContext.mDbgExprEvaluator->mSubjectExpr = formatInfo->mSubjectExpr;
  4871. }
  4872. dbgEvaluationContext.mDbgExprEvaluator->mReferenceId = outReferenceId;
  4873. auto result = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4874. if ((formatInfo != NULL) && (dbgEvaluationContext.mDbgExprEvaluator->mCountResultOverride != -1))
  4875. formatInfo->mOverrideCount = dbgEvaluationContext.mDbgExprEvaluator->mCountResultOverride;
  4876. if (dbgEvaluationContext.mPassInstance->HasFailed())
  4877. {
  4878. if (outErrors != NULL)
  4879. {
  4880. int errIdx = 0;
  4881. for (auto err : dbgEvaluationContext.mPassInstance->mErrors)
  4882. {
  4883. if (errIdx > 0)
  4884. (*outErrors) += "\n";
  4885. (*outErrors) += err->mError;
  4886. errIdx++;
  4887. }
  4888. }
  4889. return DbgTypedValue();
  4890. }
  4891. return result;
  4892. }
  4893. void WinDebugger::DbgVisFailed(DebugVisualizerEntry* debugVis, const StringImpl& evalString, const StringImpl& errors)
  4894. {
  4895. bool onlyMemError = errors.StartsWith("Failed to read") && !errors.Contains('\n');
  4896. if ((!debugVis->mShowedError) && (!onlyMemError))
  4897. {
  4898. debugVis->mShowedError = true;
  4899. String errStr = StrFormat("DbgVis '%s' failed while evaluating condition '%s'\n", debugVis->mName.c_str(), evalString.c_str());
  4900. String spacedErrors = errors;
  4901. spacedErrors.Insert(0, " ");
  4902. spacedErrors.Replace("\n", "\n ");
  4903. errStr += spacedErrors;
  4904. OutputMessage(errStr);
  4905. }
  4906. }
  4907. bool WinDebugger::EvalCondition(DebugVisualizerEntry* debugVis, DbgCompileUnit* dbgCompileUnit, DbgTypedValue typedVal, DwFormatInfo& formatInfo, const StringImpl& condition, const Array<String>& dbgVisWildcardCaptures, String& errorStr)
  4908. {
  4909. DwFormatInfo displayStrFormatInfo = formatInfo;
  4910. displayStrFormatInfo.mHidePointers = false;
  4911. displayStrFormatInfo.mRawString = false;
  4912. String errors;
  4913. const String conditionStr = mDebugManager->mDebugVisualizers->DoStringReplace(condition, dbgVisWildcardCaptures);
  4914. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, typedVal, conditionStr, &displayStrFormatInfo, NULL, &errors);
  4915. if ((!evalResult) || (!evalResult.mType->IsBoolean()))
  4916. {
  4917. if (formatInfo.mRawString)
  4918. return false;
  4919. errorStr += "<DbgVis Failed>";
  4920. DbgVisFailed(debugVis, conditionStr, errors);
  4921. return false;
  4922. }
  4923. return evalResult.mBool;
  4924. }
  4925. String WinDebugger::GetArrayItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgType* valueType, DbgTypedValue& curNode, int& count, String* outContinuationData)
  4926. {
  4927. DbgEvaluationContext conditionEvaluationContext(this, dbgCompileUnit, debugVis->mCondition);
  4928. String addrs;
  4929. bool checkLeft = true;
  4930. int usedCount = 0;
  4931. while (usedCount < count)
  4932. {
  4933. DbgTypedValue condVal = conditionEvaluationContext.EvaluateInContext(curNode);
  4934. if (!condVal)
  4935. break;
  4936. if (condVal.mBool)
  4937. {
  4938. auto val = curNode;
  4939. if (valueType == NULL)
  4940. {
  4941. String typeAddr = val.mType->ToStringRaw();
  4942. // RPad
  4943. typeAddr.Append(' ', sizeof(addr_target) * 2 - typeAddr.length());
  4944. addrs += typeAddr;
  4945. }
  4946. String addr = EncodeDataPtr(val.mPtr, false);
  4947. addrs += addr;
  4948. usedCount++;
  4949. }
  4950. curNode.mPtr += curNode.mType->mTypeParam->GetStride();
  4951. }
  4952. count = usedCount;
  4953. if (outContinuationData != NULL)
  4954. {
  4955. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(valueType, false) +
  4956. EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  4957. }
  4958. return addrs;
  4959. }
  4960. String WinDebugger::GetLinkedListItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, addr_target endNodePtr, DbgType* valueType, DbgTypedValue& curNode, int& count, String* outContinuationData)
  4961. {
  4962. DbgEvaluationContext nextEvaluationContext(this, dbgCompileUnit, debugVis->mNextPointer);
  4963. DbgEvaluationContext valueEvaluationContext(this, dbgCompileUnit, debugVis->mValuePointer);
  4964. String addrs;
  4965. bool checkLeft = true;
  4966. int mapIdx;
  4967. for (mapIdx = 0; mapIdx < count; mapIdx++)
  4968. {
  4969. if (curNode.mPtr == endNodePtr)
  4970. break;
  4971. DbgTypedValue val = valueEvaluationContext.EvaluateInContext(curNode);
  4972. if (!val)
  4973. break;
  4974. if (val.mPtr == 0)
  4975. break;
  4976. if (valueType == NULL)
  4977. {
  4978. String typeAddr = val.mType->ToStringRaw();
  4979. // RPad
  4980. typeAddr.Append(' ', sizeof(addr_target)*2 - typeAddr.length());
  4981. addrs += typeAddr;
  4982. }
  4983. String addr = EncodeDataPtr(val.mPtr, false);
  4984. addrs += addr;
  4985. curNode = nextEvaluationContext.EvaluateInContext(curNode);
  4986. }
  4987. count = mapIdx;
  4988. if (outContinuationData != NULL)
  4989. {
  4990. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(endNodePtr, false) + EncodeDataPtr(valueType, false) +
  4991. EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  4992. }
  4993. return addrs;
  4994. }
  4995. String WinDebugger::GetDictionaryItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgTypedValue dictValue, int bucketIdx, int nodeIdx, int& count, String* outContinuationData)
  4996. {
  4997. //DbgEvaluationContext bucketsEvaluationContext(this, dbgModule, debugVis->mBuckets);
  4998. DbgEvaluationContext nextEvaluationContext(this, dbgCompileUnit->mDbgModule, debugVis->mNextPointer);
  4999. DbgTypedValue bucketsPtr = EvaluateInContext(dbgCompileUnit, dictValue, debugVis->mBuckets);
  5000. DbgTypedValue entriesPtr = EvaluateInContext(dbgCompileUnit, dictValue, debugVis->mEntries);
  5001. if ((!bucketsPtr) || (!entriesPtr))
  5002. {
  5003. count = -1;
  5004. return "";
  5005. }
  5006. int entrySize = entriesPtr.mType->mTypeParam->GetStride();
  5007. int bucketIdxSize = bucketsPtr.mType->mTypeParam->GetStride();
  5008. String addrs;
  5009. bool checkLeft = true;
  5010. int encodeCount = 0;
  5011. while (encodeCount < count)
  5012. {
  5013. if (nodeIdx != -1)
  5014. {
  5015. DbgTypedValue entryValue;
  5016. entryValue.mSrcAddress = entriesPtr.mPtr + (nodeIdx * entrySize);
  5017. entryValue.mType = entriesPtr.mType->mTypeParam;
  5018. addrs += EncodeDataPtr(entryValue.mSrcAddress, false);
  5019. DbgTypedValue nextValue = nextEvaluationContext.EvaluateInContext(entryValue);
  5020. if ((!nextValue) || (!nextValue.mType->IsInteger()))
  5021. {
  5022. break;
  5023. }
  5024. nodeIdx = (int)nextValue.GetInt64();
  5025. encodeCount++;
  5026. }
  5027. else
  5028. {
  5029. if (bucketIdxSize == 4)
  5030. nodeIdx = ReadMemory<int>(bucketsPtr.mPtr + bucketIdx * sizeof(int32));
  5031. else
  5032. nodeIdx = (int)ReadMemory<int64>(bucketsPtr.mPtr + bucketIdx * sizeof(int64));
  5033. bucketIdx++;
  5034. }
  5035. }
  5036. count = encodeCount;
  5037. //count = mapIdx;
  5038. if (outContinuationData != NULL)
  5039. {
  5040. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(dictValue.mType, false) + EncodeDataPtr(dictValue.mSrcAddress, false) +
  5041. EncodeDataPtr((addr_target)bucketIdx, false) + EncodeDataPtr((addr_target)nodeIdx, false);
  5042. }
  5043. return addrs;
  5044. }
  5045. String WinDebugger::GetTreeItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, Array<addr_target>& parentList, DbgType*& valueType, DbgTypedValue& curNode, int count, String* outContinuationData)
  5046. {
  5047. DbgEvaluationContext leftEvaluationContext(this, dbgCompileUnit, debugVis->mLeftPointer);
  5048. DbgEvaluationContext rightEvaluationContext(this, dbgCompileUnit, debugVis->mRightPointer);
  5049. DbgEvaluationContext valueEvaluationContext(this, dbgCompileUnit, debugVis->mValuePointer);
  5050. DbgEvaluationContext conditionEvaluationContext(this, dbgCompileUnit, debugVis->mCondition);
  5051. String addrs;
  5052. bool checkLeft = true;
  5053. if ((curNode.mPtr & 2) != 0) // Flag from continuation
  5054. {
  5055. checkLeft = false;
  5056. curNode.mPtr &= (addr_target)~2;
  5057. }
  5058. HashSet<intptr> seenAddrs;
  5059. for (int mapIdx = 0; mapIdx < count; mapIdx++)
  5060. {
  5061. DbgTypedValue readNode;
  5062. while (true)
  5063. {
  5064. bool checkNode = (curNode.mPtr & 1) == 0;
  5065. readNode = curNode;
  5066. readNode.mPtr &= (addr_target)~1;
  5067. if (checkLeft)
  5068. {
  5069. DbgTypedValue leftValue = leftEvaluationContext.EvaluateInContext(readNode);
  5070. bool isEmpty = leftValue.mPtr == NULL;
  5071. if ((leftValue) && (conditionEvaluationContext.HasExpression()))
  5072. {
  5073. auto condValue = conditionEvaluationContext.EvaluateInContext(leftValue);
  5074. if (condValue)
  5075. isEmpty = !condValue.mBool;
  5076. }
  5077. if (isEmpty)
  5078. {
  5079. checkLeft = false;
  5080. break; // Handle node
  5081. }
  5082. parentList.push_back(curNode.mPtr);
  5083. curNode = leftValue;
  5084. }
  5085. else if (checkNode)
  5086. {
  5087. break; // Handle node
  5088. }
  5089. else
  5090. {
  5091. DbgTypedValue rightValue = rightEvaluationContext.EvaluateInContext(readNode);
  5092. bool isEmpty = rightValue.mPtr == NULL;
  5093. if ((rightValue) && (conditionEvaluationContext.HasExpression()))
  5094. {
  5095. auto condValue = conditionEvaluationContext.EvaluateInContext(rightValue);
  5096. if (condValue)
  5097. isEmpty = !condValue.mBool;
  5098. }
  5099. if (!isEmpty)
  5100. {
  5101. curNode = rightValue;
  5102. checkLeft = true;
  5103. }
  5104. else
  5105. {
  5106. if (parentList.size() == 0)
  5107. {
  5108. // Failed
  5109. break;
  5110. }
  5111. curNode.mPtr = parentList.back();
  5112. parentList.pop_back();
  5113. continue; // Don't check against seenAddrs
  5114. }
  5115. }
  5116. if (!seenAddrs.Add(curNode.mPtr))
  5117. {
  5118. // Failed!
  5119. return "";
  5120. }
  5121. }
  5122. DbgTypedValue val = valueEvaluationContext.EvaluateInContext(readNode);
  5123. if (valueType == NULL)
  5124. valueType = val.mType;
  5125. String addr = EncodeDataPtr(val.mPtr, false);
  5126. addrs += addr;
  5127. curNode.mPtr |= 1; // Node handled
  5128. }
  5129. if (!checkLeft)
  5130. curNode.mPtr |= 2;
  5131. if (outContinuationData != NULL)
  5132. {
  5133. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(valueType, false) + EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  5134. for (auto parent : parentList)
  5135. *outContinuationData += EncodeDataPtr(parent, false);
  5136. }
  5137. return addrs;
  5138. }
  5139. String WinDebugger::GetCollectionContinuation(const StringImpl& continuationData, int callStackIdx, int count)
  5140. {
  5141. DbgCompileUnit* dbgCompileUnit = GetCallStackCompileUnit(callStackIdx);;
  5142. if (!IsPaused())
  5143. return "";
  5144. const char* dataPtr = continuationData.c_str();
  5145. DebugVisualizerEntry* debugVis = (DebugVisualizerEntry*)DecodeLocalDataPtr(dataPtr);
  5146. if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_TreeItems)
  5147. {
  5148. DbgType* valueType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5149. DbgTypedValue curNode;
  5150. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5151. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5152. Array<addr_target> parentList;
  5153. String newContinuationData;
  5154. while (*dataPtr != 0)
  5155. parentList.push_back(DecodeTargetDataPtr(dataPtr));
  5156. String retVal = GetTreeItems(dbgCompileUnit, debugVis, parentList, valueType, curNode, count, &newContinuationData);
  5157. retVal += "\n" + newContinuationData;
  5158. return retVal;
  5159. }
  5160. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_LinkedList)
  5161. {
  5162. addr_target endNodePtr = DecodeTargetDataPtr(dataPtr);
  5163. DbgType* valueType = (DbgType*) DecodeLocalDataPtr(dataPtr);
  5164. DbgTypedValue curNode;
  5165. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5166. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5167. String newContinuationData;
  5168. if (count < 0)
  5169. count = 3;
  5170. String retVal = GetLinkedListItems(dbgCompileUnit, debugVis, endNodePtr, valueType, curNode, count, &newContinuationData);
  5171. retVal += "\n" + newContinuationData;
  5172. return retVal;
  5173. }
  5174. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Array)
  5175. {
  5176. DbgType* valueType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5177. DbgTypedValue curNode;
  5178. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5179. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5180. String newContinuationData;
  5181. if (count < 0)
  5182. count = 3;
  5183. String retVal = GetArrayItems(dbgCompileUnit, debugVis, valueType, curNode, count, &newContinuationData);
  5184. retVal += "\n" + newContinuationData;
  5185. return retVal;
  5186. }
  5187. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Dictionary)
  5188. {
  5189. DbgTypedValue dictValue;
  5190. dictValue.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5191. dictValue.mSrcAddress = DecodeTargetDataPtr(dataPtr);
  5192. int bucketIdx = (int)DecodeTargetDataPtr(dataPtr);
  5193. int nodeIdx = (int)DecodeTargetDataPtr(dataPtr);
  5194. String newContinuationData;
  5195. String retVal = GetDictionaryItems(dbgCompileUnit, debugVis, dictValue, bucketIdx, nodeIdx, count, &newContinuationData);
  5196. retVal += "\n" + newContinuationData;
  5197. return retVal;
  5198. }
  5199. return "";
  5200. }
  5201. template <typename T>
  5202. static String IntTypeToString(T val, const StringImpl& name, DwDisplayInfo* displayInfo, DwFormatInfo& formatInfo)
  5203. {
  5204. auto intDisplayType = displayInfo->mIntDisplayType;
  5205. if (formatInfo.mDisplayType == DwDisplayType_Decimal)
  5206. intDisplayType = DwIntDisplayType_Decimal;
  5207. else if (formatInfo.mDisplayType == DwDisplayType_HexUpper)
  5208. intDisplayType = DwIntDisplayType_HexadecimalUpper;
  5209. else if (formatInfo.mDisplayType == DwDisplayType_HexLower)
  5210. intDisplayType = DwIntDisplayType_HexadecimalLower;
  5211. if (intDisplayType == DwIntDisplayType_Binary)
  5212. {
  5213. String binary;
  5214. for (int i = 0; i < sizeof(T) * 8; i++)
  5215. {
  5216. if ((i != 0) && (i % 4 == 0))
  5217. binary = "'" + binary;
  5218. if ((i != 0) && (i % 16 == 0))
  5219. binary = "'" + binary;
  5220. binary = ((val & ((T)1 << i)) ? "1" : "0") + binary;
  5221. }
  5222. return StrFormat("0b'%s\n%s", binary.c_str(), name.c_str());
  5223. }
  5224. if (intDisplayType == DwIntDisplayType_Octal)
  5225. {
  5226. String format;
  5227. if (sizeof(T) == 8)
  5228. {
  5229. format = StrFormat("0o%%lo\n%s", name.c_str());
  5230. }
  5231. else
  5232. format = StrFormat("0o%%0%do\n%s", sizeof(val) * 2, name.c_str());
  5233. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5234. }
  5235. if (intDisplayType == DwIntDisplayType_HexadecimalUpper)
  5236. {
  5237. String format;
  5238. if (sizeof(T) == 8)
  5239. {
  5240. format = StrFormat("0x%%l@\n%s", name.c_str());
  5241. }
  5242. else
  5243. format = StrFormat("0x%%0%dX\n%s", sizeof(val) * 2, name.c_str());
  5244. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5245. }
  5246. //TODO: Implement HexadecimalLower
  5247. if (intDisplayType == DwIntDisplayType_HexadecimalLower)
  5248. {
  5249. String format;
  5250. if (sizeof(T) == 8)
  5251. {
  5252. format = StrFormat("0x%%l@\n%s", name.c_str());
  5253. }
  5254. else
  5255. format = StrFormat("0x%%0%dX\n%s", sizeof(val) * 2, name.c_str());
  5256. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5257. }
  5258. if (std::is_unsigned<T>::value)
  5259. {
  5260. if (sizeof(T) == 8)
  5261. {
  5262. if (val > 0x7FFFFFFFF)
  5263. return StrFormat("%llu\n%s\n:editVal\t%lluUL", val, name.c_str(), val);
  5264. else
  5265. return StrFormat("%llu\n%s", val, name.c_str());
  5266. }
  5267. else
  5268. return StrFormat("%u\n%s", val, name.c_str());
  5269. }
  5270. else
  5271. {
  5272. if (sizeof(T) == 8)
  5273. {
  5274. if ((val > 0x7FFFFFFFF) || (val < -0x80000000LL))
  5275. return StrFormat("%lld\n%s\n:editVal\t%lldL", val, name.c_str(), val);
  5276. else
  5277. return StrFormat("%lld\n%s", val, name.c_str(), val);
  5278. }
  5279. else
  5280. return StrFormat("%d\n%s", val, name.c_str());
  5281. }
  5282. }
  5283. DwDisplayInfo* WinDebugger::GetDisplayInfo(const StringImpl& referenceId)
  5284. {
  5285. DwDisplayInfo* displayInfo = &mDebugManager->mDefaultDisplayInfo;
  5286. if (!referenceId.empty())
  5287. {
  5288. mDebugManager->mDisplayInfos.TryGetValue(referenceId, &displayInfo);
  5289. }
  5290. return displayInfo;
  5291. }
  5292. static String WrapWithModifiers(const StringImpl& origName, DbgType* dbgType, DbgLanguage language)
  5293. {
  5294. if (language == DbgLanguage_Unknown)
  5295. language = dbgType->GetLanguage();
  5296. String name = origName;
  5297. while (true)
  5298. {
  5299. if (dbgType->mTypeCode == DbgType_Const)
  5300. {
  5301. if (language == DbgLanguage_Beef)
  5302. name = "readonly " + name;
  5303. else
  5304. name = "const " + name;
  5305. dbgType = dbgType->mTypeParam;
  5306. }
  5307. else if (dbgType->mTypeCode == DbgType_Volatile)
  5308. {
  5309. name = "volatile " + name;
  5310. dbgType = dbgType->mTypeParam;
  5311. }
  5312. else if (dbgType->mTypeCode == DbgType_TypeDef)
  5313. {
  5314. dbgType = dbgType->mTypeParam;
  5315. }
  5316. else if (dbgType->mTypeCode == DbgType_Ref)
  5317. {
  5318. if (language == DbgLanguage_Beef)
  5319. name = "ref " + name;
  5320. else
  5321. name = name + "&";
  5322. dbgType = dbgType->mTypeParam;
  5323. }
  5324. else if (dbgType->mTypeCode == DbgType_Bitfield)
  5325. {
  5326. return dbgType->ToString(language);
  5327. }
  5328. else
  5329. return name;
  5330. }
  5331. }
  5332. DebugVisualizerEntry* WinDebugger::FindVisualizerForType(DbgType* dbgType, Array<String>* wildcardCaptures)
  5333. {
  5334. auto entry = mDebugManager->mDebugVisualizers->FindEntryForType(dbgType->ToString(DbgLanguage_Unknown, true), dbgType->mCompileUnit->mDbgModule->mDbgFlavor, wildcardCaptures);
  5335. if (entry == NULL)
  5336. {
  5337. dbgType = dbgType->GetPrimaryType();
  5338. dbgType->PopulateType();
  5339. for (auto baseTypeEntry : dbgType->mBaseTypes)
  5340. {
  5341. entry = FindVisualizerForType(baseTypeEntry->mBaseType, wildcardCaptures);
  5342. if (entry != NULL)
  5343. break;
  5344. }
  5345. }
  5346. return entry;
  5347. }
  5348. #define GET_FROM(ptr, T) *((T*)(ptr += sizeof(T)) - 1)
  5349. String WinDebugger::ReadString(DbgTypeCode charType, intptr addr, bool isLocalAddr, intptr maxLength, DwFormatInfo& formatInfo)
  5350. {
  5351. int origMaxLength = maxLength;
  5352. if (addr == 0)
  5353. return "";
  5354. BP_ZONE("WinDebugger::ReadString");
  5355. String retVal = "\"";
  5356. bool wasTerminated = false;
  5357. String valString;
  5358. intptr maxShowSize = 255;
  5359. if (maxLength == -1)
  5360. maxLength = formatInfo.mOverrideCount;
  5361. else if (formatInfo.mOverrideCount != -1)
  5362. maxLength = BF_MIN(formatInfo.mOverrideCount, maxLength);
  5363. if (formatInfo.mMaxCount != -1)
  5364. maxLength = BF_MIN(formatInfo.mMaxCount, maxLength);
  5365. if (maxLength == -1)
  5366. maxLength = 8 * 1024 * 1024; // Is 8MB crazy?
  5367. if (!formatInfo.mRawString)
  5368. maxLength = BF_MIN(maxLength, maxShowSize);
  5369. //EnableMemCache();
  5370. bool readFailed = false;
  5371. intptr strPtr = addr;
  5372. int charLen = 1;
  5373. if ((charType == DbgType_SChar16) || (charType == DbgType_UChar16))
  5374. charLen = 2;
  5375. else if ((charType == DbgType_SChar32) || (charType == DbgType_UChar32))
  5376. charLen = 4;
  5377. bool isUTF8 = formatInfo.mDisplayType == DwDisplayType_Utf8;
  5378. int readSize = BF_MIN(1024, maxLength * charLen);
  5379. uint8 buf[1024];
  5380. uint8* bufPtr = NULL;
  5381. uint8* bufEnd = NULL;
  5382. bool hasHighAscii = false;
  5383. int i;
  5384. for (i = 0; i < maxLength; i++)
  5385. {
  5386. if (bufPtr >= bufEnd)
  5387. {
  5388. while (true)
  5389. {
  5390. if (readSize < charLen)
  5391. {
  5392. readFailed = true;
  5393. break;
  5394. }
  5395. if (ReadMemory(strPtr, readSize, buf, isLocalAddr))
  5396. break;
  5397. readSize /= 2;
  5398. }
  5399. if (readFailed)
  5400. break;
  5401. bufPtr = buf;
  5402. bufEnd = buf + readSize;
  5403. }
  5404. switch (charLen)
  5405. {
  5406. case 1:
  5407. {
  5408. char c = GET_FROM(bufPtr, char);
  5409. if ((c != 0) || (formatInfo.mOverrideCount != -1))
  5410. {
  5411. if ((uint8)c >= 0x80)
  5412. hasHighAscii = true;
  5413. valString.Append(c);
  5414. }
  5415. else
  5416. wasTerminated = true;
  5417. }
  5418. break;
  5419. case 2:
  5420. {
  5421. uint16 c16 = GET_FROM(bufPtr, uint16);
  5422. if ((c16 != 0) || (formatInfo.mOverrideCount != -1))
  5423. {
  5424. char str[8];
  5425. u8_toutf8(str, 8, c16);
  5426. valString += str;
  5427. }
  5428. else
  5429. wasTerminated = true;
  5430. }
  5431. break;
  5432. case 4:
  5433. {
  5434. uint32 c32 = GET_FROM(bufPtr, uint32);
  5435. if ((c32 != 0) || (formatInfo.mOverrideCount != -1))
  5436. {
  5437. char str[8];
  5438. u8_toutf8(str, 8, c32);
  5439. valString += str;
  5440. }
  5441. else
  5442. wasTerminated = true;
  5443. }
  5444. break;
  5445. }
  5446. if ((wasTerminated) && (formatInfo.mOverrideCount != -1))
  5447. {
  5448. valString += '\x00';
  5449. wasTerminated = false;
  5450. }
  5451. if ((wasTerminated) || (readFailed))
  5452. {
  5453. break;
  5454. }
  5455. strPtr += charLen;
  5456. }
  5457. //DisableMemCache();
  5458. if (formatInfo.mOverrideCount != -1)
  5459. {
  5460. if (i == formatInfo.mOverrideCount)
  5461. wasTerminated = true;
  5462. }
  5463. if (strPtr == addr + origMaxLength)
  5464. wasTerminated = true;
  5465. if (valString.length() == formatInfo.mOverrideCount)
  5466. wasTerminated = true;
  5467. // if (formatInfo.mDisplayType == DwDisplayType_Ascii)
  5468. // {
  5469. // // Our encoding for retVal is already assumed to be UTF8, so the special case here actually Ascii
  5470. // valString = UTF8Encode(ToWString(valString));
  5471. // }
  5472. if (formatInfo.mRawString)
  5473. {
  5474. if ((formatInfo.mDisplayType == DwDisplayType_Utf8) || (!hasHighAscii))
  5475. return valString;
  5476. String utf8Str;
  5477. for (int i = 0; i < (int)valString.length(); i++)
  5478. {
  5479. char c = valString[i];
  5480. if ((uint8)c >= 0x80)
  5481. {
  5482. utf8Str += (char)(0xC0 | (((uint8)c & 0xFF) >> 6));
  5483. utf8Str += (char)(0x80 | ((uint8)c & 0x3F));
  5484. }
  5485. else
  5486. utf8Str += c;
  5487. }
  5488. return utf8Str;
  5489. }
  5490. if ((readFailed) && (valString.IsEmpty()))
  5491. return "< Failed to read string >";
  5492. retVal += SlashString(valString, true, true, formatInfo.mLanguage == DbgLanguage_Beef);
  5493. // We could go over 'maxShowSize' if we have a lot of slashed chars. An uninitialized string can be filled with '\xcc' chars
  5494. if ((!formatInfo.mRawString) && ((int)retVal.length() > maxShowSize))
  5495. {
  5496. retVal = retVal.Substring(0, maxShowSize);
  5497. wasTerminated = false;
  5498. }
  5499. if (wasTerminated)
  5500. retVal += "\"";
  5501. else
  5502. retVal += "...";
  5503. return retVal;
  5504. }
  5505. void WinDebugger::ProcessEvalString(DbgCompileUnit* dbgCompileUnit, DbgTypedValue useTypedValue, String& evalStr, String& displayString, DwFormatInfo& formatInfo, DebugVisualizerEntry* debugVis, bool limitLength)
  5506. {
  5507. for (int i = 0; i < (int)evalStr.length(); i++)
  5508. {
  5509. char c = evalStr[i];
  5510. char nextC = 0;
  5511. if (i < (int)evalStr.length() - 1)
  5512. nextC = evalStr[i + 1];
  5513. if ((c == '{') && (nextC != '{'))
  5514. {
  5515. // Evaluate
  5516. int endIdx = i;
  5517. for (; endIdx < (int)evalStr.length(); endIdx++)
  5518. {
  5519. //TODO: Do better parsing - this paren could be inside a string, for example
  5520. if (evalStr[endIdx] == '}')
  5521. break;
  5522. }
  5523. DwFormatInfo displayStrFormatInfo = formatInfo;
  5524. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + (int)displayString.length();
  5525. displayStrFormatInfo.mHidePointers = false;
  5526. if ((limitLength) && (displayStrFormatInfo.mTotalSummaryLength > 255))
  5527. {
  5528. displayString += "...";
  5529. }
  5530. else
  5531. {
  5532. String evalString = evalStr.Substring(i + 1, endIdx - i - 1);
  5533. String errors;
  5534. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, useTypedValue, evalString, &displayStrFormatInfo, NULL, &errors);
  5535. if (evalResult)
  5536. {
  5537. if (displayStrFormatInfo.mNoEdit)
  5538. formatInfo.mNoEdit = true;
  5539. String result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  5540. if ((formatInfo.mRawString) && (limitLength))
  5541. {
  5542. displayString = result;
  5543. return;
  5544. }
  5545. int crPos = result.IndexOf('\n');
  5546. if (crPos != -1)
  5547. displayString += result.Substring(0, crPos);
  5548. else
  5549. displayString += result;
  5550. }
  5551. else if (debugVis != NULL)
  5552. {
  5553. displayString += "<DbgVis Failed>";
  5554. DbgVisFailed(debugVis, evalString, errors);
  5555. }
  5556. else
  5557. {
  5558. displayString += "<Eval Failed>";
  5559. }
  5560. }
  5561. i = endIdx;
  5562. continue;
  5563. }
  5564. else if ((c == '{') && (nextC == '{'))
  5565. {
  5566. // Skip next paren
  5567. i++;
  5568. }
  5569. else if ((c == '}') && (nextC == '}'))
  5570. {
  5571. // Skip next paren
  5572. i++;
  5573. }
  5574. displayString += c;
  5575. }
  5576. }
  5577. static bool IsNormalChar(uint32 c)
  5578. {
  5579. return (c < 0x80);
  5580. }
  5581. String WinDebugger::DbgTypedValueToString(const DbgTypedValue& origTypedValue, const StringImpl& expr, DwFormatInfo& formatInfo, DbgExprEvaluator* optEvaluator, bool fullPrecision)
  5582. {
  5583. BP_ZONE("WinDebugger::DbgTypedValueToString");
  5584. DbgTypedValue typedValue = origTypedValue;
  5585. auto dbgCompileUnit = typedValue.mType->mCompileUnit;
  5586. auto dbgModule = typedValue.mType->GetDbgModule();
  5587. auto language = origTypedValue.mType->GetLanguage();
  5588. if (language == DbgLanguage_Unknown)
  5589. language = formatInfo.mLanguage;
  5590. formatInfo.mLanguage = language;
  5591. bool isBeef = language == DbgLanguage_Beef;
  5592. char str[32];
  5593. bool readFailed = false;
  5594. bool isCompositeType = false;
  5595. bool isSizedArray = false;
  5596. bool isEnum = false;
  5597. int64 enumVal = 0;
  5598. String result;
  5599. DwDisplayInfo* displayInfo = GetDisplayInfo(formatInfo.mReferenceId);
  5600. DbgType* origValueType = typedValue.mType;
  5601. bool origHadRef = false;
  5602. DbgType* dwValueType = typedValue.mType->RemoveModifiers(&origHadRef);
  5603. if (dwValueType == NULL)
  5604. dwValueType = dbgModule->GetPrimitiveType(DbgType_Void, language);
  5605. else
  5606. dwValueType = dwValueType->GetPrimaryType();
  5607. if (dwValueType->mTypeCode == DbgType_TypeDef)
  5608. {
  5609. DbgTypedValue realTypedVal = typedValue;
  5610. realTypedVal.mType = dwValueType->mTypeParam;
  5611. return DbgTypedValueToString(realTypedVal, expr, formatInfo, optEvaluator);
  5612. }
  5613. if (formatInfo.mRawString)
  5614. {
  5615. if ((dwValueType->mTypeCode != DbgType_Struct) && (dwValueType->mTypeCode != DbgType_Class) && (dwValueType->mTypeCode != DbgType_Ptr) && (dwValueType->mTypeCode != DbgType_SizedArray))
  5616. return "";
  5617. }
  5618. auto _ShowArraySummary = [&](String& retVal, addr_target ptrVal, int64 arraySize, DbgType* innerType)
  5619. {
  5620. String displayString;
  5621. displayString += "{";
  5622. for (int idx = 0; idx < arraySize; idx++)
  5623. {
  5624. if (formatInfo.mTotalSummaryLength + retVal.length() + displayString.length() > 255)
  5625. {
  5626. displayString += "...";
  5627. break;
  5628. }
  5629. if ((idx != 0) && (!displayString.EndsWith('{')))
  5630. displayString += ", ";
  5631. DwFormatInfo displayStrFormatInfo = formatInfo;
  5632. displayStrFormatInfo.mExpandItemDepth = 1;
  5633. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + retVal.length() + displayString.length();
  5634. displayStrFormatInfo.mHidePointers = false;
  5635. displayStrFormatInfo.mArrayLength = -1;
  5636. // Why did we have this "na" on here? It made "void*[3]" type things show up as "{,,}"
  5637. //String evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + StrFormat(")[%d], na", idx);
  5638. String evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + StrFormat(")[%lld]", idx);
  5639. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, typedValue, evalStr, &displayStrFormatInfo);
  5640. String result;
  5641. if (evalResult)
  5642. {
  5643. result = DbgTypedValueToString(evalResult, evalStr, displayStrFormatInfo, NULL);
  5644. int crPos = result.IndexOf('\n');
  5645. if (crPos != -1)
  5646. result.RemoveToEnd(crPos);
  5647. }
  5648. else
  5649. result = "???";
  5650. displayString += result;
  5651. }
  5652. displayString += "}";
  5653. retVal += displayString;
  5654. };
  5655. if (formatInfo.mArrayLength != -1)
  5656. {
  5657. if (formatInfo.mRawString)
  5658. return "";
  5659. if (dwValueType->IsPointer())
  5660. {
  5661. String retVal;
  5662. addr_target ptrVal = (addr_target)typedValue.mPtr;
  5663. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  5664. {
  5665. retVal = EncodeDataPtr(ptrVal, true) + " ";
  5666. retVal += dwValueType->mTypeParam->ToString(language);
  5667. retVal += StrFormat("[%lld] ", (int64)formatInfo.mArrayLength);
  5668. }
  5669. _ShowArraySummary(retVal, ptrVal, formatInfo.mArrayLength, dwValueType->mTypeParam);
  5670. String idxStr = "[{0}]";
  5671. DbgType* innerType = dwValueType->mTypeParam;
  5672. retVal += "\n" + dwValueType->ToString(language);
  5673. String evalStr = "*((" + typedValue.mType->ToStringRaw(language) + ")" + EncodeDataPtr(ptrVal, true) + " + {0})";
  5674. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, (int)BF_MAX(formatInfo.mArrayLength, 0), 10000) +
  5675. "\t" + idxStr + "\t" + evalStr;
  5676. return retVal;
  5677. }
  5678. else
  5679. {
  5680. DwFormatInfo newFormatInfo = formatInfo;
  5681. newFormatInfo.mArrayLength = -1;
  5682. String retVal = DbgTypedValueToString(typedValue, expr, newFormatInfo, optEvaluator);
  5683. int crPos = (int)retVal.IndexOf('\n');
  5684. if (crPos != -1)
  5685. retVal = "!Array length flag not valid with this type" + retVal.Substring(crPos);
  5686. return retVal;
  5687. }
  5688. }
  5689. switch (dwValueType->mTypeCode)
  5690. {
  5691. case DbgType_Void:
  5692. return "\nvoid";
  5693. case DbgType_Bool:
  5694. {
  5695. if (typedValue.mUInt8 == 0)
  5696. return "false\n" + WrapWithModifiers("bool", origValueType, language);
  5697. else if (typedValue.mUInt8 == 1)
  5698. return "true\n" + WrapWithModifiers("bool", origValueType, language);
  5699. else
  5700. return StrFormat("true (%d)\n", typedValue.mUInt8) + WrapWithModifiers("bool", origValueType, language);
  5701. }
  5702. break;
  5703. case DbgType_UChar:
  5704. if (language != DbgLanguage_Beef)
  5705. return IntTypeToString<uint8>(typedValue.mUInt8, WrapWithModifiers("uint8_t", origValueType, language), displayInfo, formatInfo);
  5706. case DbgType_SChar:
  5707. {
  5708. if (typedValue.mInt8 != 0)
  5709. {
  5710. char str[2] = {(char)typedValue.mInt8};
  5711. result = SlashString(str, formatInfo.mDisplayType == DwDisplayType_Utf8, true);
  5712. if (!IsNormalChar(typedValue.mUInt8))
  5713. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt8);
  5714. else
  5715. result = StrFormat("'%s'\n", result.c_str());
  5716. }
  5717. else
  5718. result = "'\\0'\n";
  5719. return result + WrapWithModifiers("char", origValueType, language);
  5720. }
  5721. break;
  5722. case DbgType_UChar16:
  5723. if (language != DbgLanguage_Beef)
  5724. return IntTypeToString<int16>(typedValue.mUInt8, WrapWithModifiers("uint16_t", origValueType, language), displayInfo, formatInfo);
  5725. case DbgType_SChar16:
  5726. {
  5727. if (typedValue.mInt16 != 0)
  5728. {
  5729. u8_toutf8(str, 8, typedValue.mUInt32);
  5730. result = SlashString(str, true, true);
  5731. if (!IsNormalChar(typedValue.mUInt32))
  5732. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt16);
  5733. else
  5734. result = StrFormat("'%s'\n", result.c_str());
  5735. }
  5736. else
  5737. result = "'\\0'\n";
  5738. return result + WrapWithModifiers(isBeef ? "char16" : "int16_t", origValueType, language);
  5739. }
  5740. break;
  5741. case DbgType_UChar32:
  5742. case DbgType_SChar32:
  5743. {
  5744. if (typedValue.mInt32 != 0)
  5745. {
  5746. u8_toutf8(str, 8, typedValue.mUInt32);
  5747. result = SlashString(str, true, true);
  5748. if (!IsNormalChar(typedValue.mUInt32))
  5749. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt32);
  5750. else
  5751. result = StrFormat("'%s'\n", result.c_str());
  5752. }
  5753. else
  5754. result = "'\\0'\n";
  5755. return result + WrapWithModifiers(isBeef ? "char32" : "int32_t", origValueType, language);
  5756. }
  5757. break;
  5758. case DbgType_i8:
  5759. return IntTypeToString<int8>(typedValue.mInt8, WrapWithModifiers(isBeef ? "int8" : "int8_t", origValueType, language), displayInfo, formatInfo);
  5760. case DbgType_u8:
  5761. return IntTypeToString<uint8>(typedValue.mUInt8, WrapWithModifiers(isBeef ? "uint8" : "uint8_t", origValueType, language), displayInfo, formatInfo);
  5762. case DbgType_i16:
  5763. return IntTypeToString<int16>(typedValue.mInt16, WrapWithModifiers(isBeef ? "int16" : "int16_t", origValueType, language), displayInfo, formatInfo);
  5764. case DbgType_u16:
  5765. return IntTypeToString<uint16>(typedValue.mUInt16, WrapWithModifiers(isBeef ? "uint16" : "uint16_t", origValueType, language), displayInfo, formatInfo);
  5766. case DbgType_i32:
  5767. return IntTypeToString<int32>(typedValue.mInt32, WrapWithModifiers(isBeef ? "int32" : "int32_t", origValueType, language), displayInfo, formatInfo);
  5768. case DbgType_u32:
  5769. return IntTypeToString<uint32>(typedValue.mUInt32, WrapWithModifiers(isBeef ? "uint32" : "uint32_t", origValueType, language), displayInfo, formatInfo);
  5770. case DbgType_i64:
  5771. return IntTypeToString<int64>(typedValue.mInt64, WrapWithModifiers(isBeef ? "int64" : "int64_t", origValueType, language), displayInfo, formatInfo);
  5772. case DbgType_u64:
  5773. return IntTypeToString<uint64>(typedValue.mUInt64, WrapWithModifiers(isBeef ? "uint64" : "uint64_t", origValueType, language), displayInfo, formatInfo);
  5774. case DbgType_RegGroup:
  5775. {
  5776. if ((typedValue.mRegNum >= CPUReg_M128_XMMREG_FIRST) && (typedValue.mRegNum <= CPUReg_M128_XMMREG_LAST))
  5777. {
  5778. int callStackIdx = formatInfo.mCallStackIdx;
  5779. FixCallStackIdx(callStackIdx);
  5780. UpdateRegisterUsage(callStackIdx);
  5781. WdStackFrame* wdStackFrame = mCallStack[callStackIdx];
  5782. RegForm regForm = RegForm_Unknown;
  5783. if (typedValue.mRegNum < (int)wdStackFrame->mRegForms.size())
  5784. regForm = wdStackFrame->mRegForms[typedValue.mRegNum];
  5785. int xmmMajor = typedValue.mRegNum - CPUReg_M128_XMMREG_FIRST;
  5786. String headerStr;
  5787. String xmmType = "__m128";
  5788. int xmmCount = 4;
  5789. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2) ||
  5790. (regForm == RegForm_Long) || (regForm == RegForm_Long2) ||
  5791. (regForm == RegForm_ULong) || (regForm == RegForm_ULong2))
  5792. xmmCount = 2;
  5793. //TODO: add byte, short, int, etc...
  5794. if (optEvaluator)
  5795. {
  5796. DwMmDisplayType mmDwMmDisplayType = displayInfo->mMmDisplayType;
  5797. if (mmDwMmDisplayType == DwMmDisplayType_Default)
  5798. {
  5799. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2))
  5800. mmDwMmDisplayType = DwMmDisplayType_Double;
  5801. else if (regForm == RegForm_Int4)
  5802. mmDwMmDisplayType = DwMmDisplayType_Int;
  5803. }
  5804. //TODO: Add support for int types
  5805. if (mmDwMmDisplayType == DwMmDisplayType_Double)
  5806. {
  5807. xmmType = "__m128d";
  5808. xmmCount = 2;
  5809. double xmmRegVals[2];
  5810. CPURegisters* regs = optEvaluator->GetRegisters();
  5811. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5812. {
  5813. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5814. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_Double);
  5815. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5816. xmmRegVals[xmmMinor] = xmmReg.mDouble;
  5817. }
  5818. headerStr = StrFormat("(%f, %f)", xmmRegVals[0], xmmRegVals[1]);
  5819. }
  5820. else if (mmDwMmDisplayType == DwMmDisplayType_Int)
  5821. {
  5822. int xmmRegVals[4];
  5823. xmmCount = 4;
  5824. CPURegisters* regs = optEvaluator->GetRegisters();
  5825. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5826. {
  5827. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5828. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i32);
  5829. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5830. xmmRegVals[xmmMinor] = xmmReg.mInt32;
  5831. }
  5832. headerStr = StrFormat("(%d, %d, %d, %d)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  5833. }
  5834. else // Float
  5835. {
  5836. float xmmRegVals[4];
  5837. xmmCount = 4;
  5838. CPURegisters* regs = optEvaluator->GetRegisters();
  5839. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5840. {
  5841. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5842. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_Single);
  5843. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5844. xmmRegVals[xmmMinor] = xmmReg.mSingle;
  5845. }
  5846. headerStr = StrFormat("(%f, %f, %f, %f)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  5847. }
  5848. }
  5849. else
  5850. {
  5851. headerStr = StrFormat("XMM%d", xmmMajor);
  5852. }
  5853. result = headerStr + "\n" + xmmType;
  5854. for (int i = 0; i < xmmCount; i++)
  5855. result += WrapWithModifiers(StrFormat("\n[%d]\t$xmm%d_%d", i, xmmMajor, i, language), origValueType, language);
  5856. return result;
  5857. }
  5858. else
  5859. {
  5860. switch (typedValue.mRegNum)
  5861. {
  5862. case CPUReg_CAT_ALLREGS:
  5863. {
  5864. return "ALLREGS\n__allregs\niregs\t$iregs\nflags\t$flags\nfpregs\t$fpregs\nmmregs\t$mmregs\nxmmregs\t$xmmregs";
  5865. }
  5866. break;
  5867. case CPUReg_CAT_IREGS:
  5868. {
  5869. #ifdef BF_DBG_32
  5870. String headerStr;
  5871. if (optEvaluator)
  5872. {
  5873. CPURegisters* regs = optEvaluator->GetRegisters();
  5874. 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)",
  5875. (uint32)regs->mIntRegs.eax, (uint32)regs->mIntRegs.ebx, (uint32)regs->mIntRegs.ecx, (uint32)regs->mIntRegs.edx,
  5876. (uint32)regs->mIntRegs.esi, (uint32)regs->mIntRegs.edi, (uint32)regs->mIntRegs.esp, (uint32)regs->mIntRegs.ebp,
  5877. (uint32)regs->mIntRegs.eip, (uint32)regs->mIntRegs.efl);
  5878. }
  5879. else
  5880. {
  5881. headerStr = "IREGS";
  5882. }
  5883. 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());
  5884. #else
  5885. String headerStr;
  5886. if (optEvaluator)
  5887. {
  5888. CPURegisters* regs = optEvaluator->GetRegisters();
  5889. 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)",
  5890. (uint64)regs->mIntRegs.rax, (uint64)regs->mIntRegs.rbx, (uint64)regs->mIntRegs.rcx, (uint64)regs->mIntRegs.rdx,
  5891. (uint64)regs->mIntRegs.rsi, (uint64)regs->mIntRegs.rdi, (uint64)regs->mIntRegs.rsp, (uint64)regs->mIntRegs.rbp,
  5892. (uint64)regs->mIntRegs.rip,
  5893. (uint64)regs->mIntRegs.r8, (uint64)regs->mIntRegs.r9, (uint64)regs->mIntRegs.r10, (uint64)regs->mIntRegs.r11,
  5894. (uint64)regs->mIntRegs.r12, (uint64)regs->mIntRegs.r13, (uint64)regs->mIntRegs.r14, (uint64)regs->mIntRegs.r15,
  5895. (uint32)regs->mIntRegs.efl);
  5896. }
  5897. else
  5898. {
  5899. headerStr = "IREGS";
  5900. }
  5901. 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());
  5902. #endif
  5903. }
  5904. break;
  5905. case CPUReg_CAT_FPREGS:
  5906. {
  5907. String headerStr;
  5908. if (optEvaluator)
  5909. {
  5910. CPURegisters* regs = optEvaluator->GetRegisters();
  5911. headerStr = "(";
  5912. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  5913. {
  5914. if (i)
  5915. headerStr += ", ";
  5916. double val = ConvertFloat80ToDouble(regs->mFpMmRegsArray[i].fp.fp80);
  5917. headerStr += StrFormat("%f", val);
  5918. }
  5919. headerStr += ")";
  5920. }
  5921. else
  5922. {
  5923. headerStr = "FPREGS";
  5924. }
  5925. result = StrFormat("%s\n__fpregs", headerStr.c_str());
  5926. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  5927. result += StrFormat("\n[%d]\t$st%d", i, i);
  5928. return result;
  5929. }
  5930. break;
  5931. case CPUReg_CAT_MMREGS:
  5932. {
  5933. String headerStr;
  5934. if (optEvaluator)
  5935. {
  5936. CPURegisters* regs = optEvaluator->GetRegisters();
  5937. headerStr = "(";
  5938. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  5939. {
  5940. if (i)
  5941. headerStr += ", ";
  5942. uint64 val = regs->mFpMmRegsArray[i].mm;
  5943. headerStr += StrFormat("0x%016llx", val);
  5944. }
  5945. headerStr += ")";
  5946. }
  5947. else
  5948. {
  5949. headerStr = "MMREGS";
  5950. }
  5951. result = StrFormat("%s\n__mmregs", headerStr.c_str());
  5952. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  5953. result += StrFormat("\n[%d]\t$mm%d", i, i);
  5954. return result;
  5955. }
  5956. break;
  5957. case CPUReg_CAT_XMMREGS:
  5958. {
  5959. String headerStr = StrFormat("XMMREGS[%d]", CPURegisters::kNumXmmRegs); // these are too big to put a useful header for the entire category
  5960. result = StrFormat("%s\n__xmmregs", headerStr.c_str());
  5961. for (int i = 0; i < CPURegisters::kNumXmmRegs; ++i)
  5962. result += StrFormat("\n[%d]\t$xmm%d", i, i);
  5963. return result;
  5964. }
  5965. break;
  5966. case CPUReg_CAT_FLAGS:
  5967. {
  5968. String headerStr;
  5969. if (optEvaluator)
  5970. {
  5971. CPURegisters* regs = optEvaluator->GetRegisters();
  5972. #ifdef BF_DBG_32
  5973. #define FLAGVAR(abbr, name) int flag##abbr = ((regs->mIntRegs.efl & ((uint64)1 << CPURegisters::GetFlagBitForRegister(X86Reg_FLAG_##abbr##_##name))) != 0) ? 1 : 0
  5974. FLAGVAR(CF, CARRY);
  5975. FLAGVAR(PF, PARITY);
  5976. FLAGVAR(AF, ADJUST);
  5977. FLAGVAR(ZF, ZERO);
  5978. FLAGVAR(SF, SIGN);
  5979. FLAGVAR(IF, INTERRUPT);
  5980. FLAGVAR(DF, DIRECTION);
  5981. FLAGVAR(OF, OVERFLOW);
  5982. #undef FLAGVAR
  5983. #else
  5984. #define FLAGVAR(abbr, name) int flag##abbr = ((regs->mIntRegs.efl & ((uint64)1 << CPURegisters::GetFlagBitForRegister(X64Reg_FLAG_##abbr##_##name))) != 0) ? 1 : 0
  5985. FLAGVAR(CF, CARRY);
  5986. FLAGVAR(PF, PARITY);
  5987. FLAGVAR(AF, ADJUST);
  5988. FLAGVAR(ZF, ZERO);
  5989. FLAGVAR(SF, SIGN);
  5990. FLAGVAR(IF, INTERRUPT);
  5991. FLAGVAR(DF, DIRECTION);
  5992. FLAGVAR(OF, OVERFLOW);
  5993. #undef FLAGVAR
  5994. #endif
  5995. headerStr = StrFormat("(CF=%d, PF=%d, AF=%d, ZF=%d, SF=%d, IF=%d, DF=%d, OF=%d)",
  5996. flagCF, flagPF, flagAF, flagZF, flagSF, flagIF, flagDF, flagOF);
  5997. }
  5998. else
  5999. {
  6000. headerStr = "FLAGS";
  6001. }
  6002. 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",
  6003. headerStr.c_str());
  6004. }
  6005. break;
  6006. default:
  6007. BF_ASSERT(false && "unknown category register");
  6008. return "UNKNOWNCATEGORY\n__unknown\n";
  6009. }
  6010. }
  6011. }
  6012. break;
  6013. case DbgType_Single:
  6014. {
  6015. DwFloatDisplayType floatDisplayType = displayInfo->mFloatDisplayType;
  6016. if (floatDisplayType == DwFloatDisplayType_Default)
  6017. floatDisplayType = DwFloatDisplayType_Minimal;
  6018. if (floatDisplayType == DwFloatDisplayType_Minimal)
  6019. ExactMinimalFloatToStr(typedValue.mSingle, str);
  6020. else if (floatDisplayType == DwFloatDisplayType_Full)
  6021. sprintf(str, "%1.9g", (float)typedValue.mDouble);
  6022. else if (floatDisplayType == DwFloatDisplayType_HexUpper)
  6023. sprintf(str, "0x%04X", typedValue.mUInt32);
  6024. else //if (floatDisplayType == DwFloatDisplayType_HexLower)
  6025. sprintf(str, "0x%04x", typedValue.mUInt32);
  6026. return StrFormat("%s\n%s", str, WrapWithModifiers("float", origValueType, language).c_str());
  6027. }
  6028. case DbgType_Double:
  6029. {
  6030. DwFloatDisplayType floatDisplayType = displayInfo->mFloatDisplayType;
  6031. if (floatDisplayType == DwFloatDisplayType_Default)
  6032. floatDisplayType = DwFloatDisplayType_Minimal;
  6033. if (floatDisplayType == DwFloatDisplayType_Minimal)
  6034. ExactMinimalDoubleToStr(typedValue.mDouble, str);
  6035. else if (floatDisplayType == DwFloatDisplayType_Full)
  6036. sprintf(str, "%1.17g", typedValue.mDouble);
  6037. else if (floatDisplayType == DwFloatDisplayType_HexUpper)
  6038. sprintf(str, "0x%08llX", typedValue.mUInt64);
  6039. else //if (floatDisplayType == DwFloatDisplayType_HexLower)
  6040. sprintf(str, "0x%08llx", typedValue.mUInt64);
  6041. return StrFormat("%s\n%s", str, WrapWithModifiers("double", origValueType, language).c_str());
  6042. }
  6043. case DbgType_Subroutine:
  6044. if (typedValue.mCharPtr != NULL)
  6045. return StrFormat("%s\nfunc", typedValue.mCharPtr);
  6046. else
  6047. return "\nfunc";
  6048. case DbgType_RawText:
  6049. return StrFormat("%s\nrawtext", typedValue.mCharPtr);
  6050. case DbgType_Ptr:
  6051. {
  6052. addr_target ptrVal = (addr_target)typedValue.mPtr;
  6053. String retVal;
  6054. DbgType* innerType = dwValueType->mTypeParam;
  6055. if (innerType == NULL)
  6056. return EncodeDataPtr(ptrVal, true) + "\nvoid*";
  6057. bool isChar = false;
  6058. DbgType* unmodInnerType = innerType->RemoveModifiers();
  6059. if (unmodInnerType != NULL)
  6060. {
  6061. if (language == DbgLanguage_Beef)
  6062. {
  6063. if ((unmodInnerType->mTypeCode == DbgType_UChar) ||
  6064. (unmodInnerType->mTypeCode == DbgType_UChar16) ||
  6065. (unmodInnerType->mTypeCode == DbgType_UChar32))
  6066. isChar = true;
  6067. }
  6068. else
  6069. {
  6070. if ((unmodInnerType->mTypeCode == DbgType_SChar) ||
  6071. (unmodInnerType->mTypeCode == DbgType_SChar16) ||
  6072. (unmodInnerType->mTypeCode == DbgType_SChar32))
  6073. isChar = true;
  6074. }
  6075. }
  6076. if ((isChar) && (formatInfo.mArrayLength == -1))
  6077. {
  6078. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6079. retVal = EncodeDataPtr(ptrVal, true);
  6080. int strLen = formatInfo.mOverrideCount;
  6081. if (typedValue.mIsLiteral)
  6082. {
  6083. if (strLen == -1)
  6084. strLen = 0x7FFFFFFF;
  6085. if (typedValue.mDataLen > 0)
  6086. strLen = BF_MIN(strLen, typedValue.mDataLen);
  6087. else
  6088. strLen = BF_MIN(strLen, strlen(typedValue.mCharPtr));
  6089. }
  6090. SetAndRestoreValue<intptr> prevOverrideLen(formatInfo.mOverrideCount, strLen);
  6091. String strResult = ReadString(unmodInnerType->mTypeCode, typedValue.mLocalIntPtr, typedValue.mIsLiteral, strLen, formatInfo);
  6092. if (formatInfo.mRawString)
  6093. return strResult;
  6094. if (!strResult.IsEmpty())
  6095. {
  6096. if (!retVal.IsEmpty())
  6097. retVal += " ";
  6098. retVal += strResult;
  6099. }
  6100. retVal += "\n" + origValueType->ToString(language);
  6101. return retVal;
  6102. }
  6103. else if ((unmodInnerType != NULL) &&
  6104. ((unmodInnerType->mTypeCode == DbgType_Class) || (unmodInnerType->mTypeCode == DbgType_Struct) || (unmodInnerType->mTypeCode == DbgType_Union)))
  6105. {
  6106. isCompositeType = true;
  6107. }
  6108. else if ((unmodInnerType != NULL) && (unmodInnerType->mTypeCode == DbgType_SizedArray))
  6109. {
  6110. isSizedArray = true;
  6111. }
  6112. else if (unmodInnerType->mTypeCode == DbgType_Subroutine)
  6113. {
  6114. if (formatInfo.mRawString)
  6115. return "";
  6116. addr_target funcPtr = (addr_target)typedValue.mPtr;
  6117. String retVal;
  6118. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6119. retVal = EncodeDataPtr(funcPtr, true);
  6120. String symbolName;
  6121. addr_target offset;
  6122. DbgModule* dwarf;
  6123. static String demangledName;
  6124. auto subProgram = mDebugTarget->FindSubProgram(funcPtr);
  6125. if (subProgram != NULL)
  6126. {
  6127. demangledName = subProgram->ToString();
  6128. }
  6129. else if (mDebugTarget->FindSymbolAt(funcPtr, &symbolName, &offset, &dwarf))
  6130. {
  6131. demangledName = BfDemangler::Demangle(symbolName, language);
  6132. if (offset != 0)
  6133. demangledName += StrFormat("+%d", offset);
  6134. }
  6135. else
  6136. {
  6137. auto dbgModule = mDebugTarget->FindDbgModuleForAddress(funcPtr);
  6138. if (dbgModule != NULL)
  6139. demangledName += dbgModule->GetLinkedModule()->mDisplayName + "!";
  6140. demangledName += StrFormat("0x%@", funcPtr);
  6141. }
  6142. retVal += " {";
  6143. retVal += demangledName;
  6144. retVal += "}";
  6145. retVal += "\n" + origValueType->ToString(language);
  6146. return retVal;
  6147. }
  6148. else if (unmodInnerType->mTypeCode == DbgType_Void)
  6149. {
  6150. if (formatInfo.mRawString)
  6151. return "";
  6152. addr_target ptr = (addr_target)typedValue.mPtr;
  6153. String symbolName;
  6154. addr_target offset;
  6155. DbgModule* dwarf;
  6156. String demangledName;
  6157. retVal += demangledName = StrFormat("0x%@", ptr);
  6158. if (mDebugTarget->FindSymbolAt(ptr, &symbolName, &offset, &dwarf))
  6159. {
  6160. if (offset == 0)
  6161. {
  6162. retVal += " {";
  6163. retVal += BfDemangler::Demangle(symbolName, language);
  6164. retVal += "}";
  6165. }
  6166. }
  6167. retVal += "\n" + origValueType->ToString(language);
  6168. return retVal;
  6169. }
  6170. else
  6171. {
  6172. if (formatInfo.mRawString)
  6173. return "";
  6174. addr_target ptrVal = (addr_target)typedValue.mPtr;
  6175. String retVal;
  6176. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6177. retVal = EncodeDataPtr(ptrVal, true);
  6178. if (ptrVal != 0)
  6179. {
  6180. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, NULL, -1, -1);
  6181. DbgTypedValue innerTypedVal = dbgExprEvaluator.ReadTypedValue(NULL, innerType, typedValue.mPtr, DbgAddrType_Target);
  6182. if (innerTypedVal)
  6183. {
  6184. DwFormatInfo defaultFormatInfo;
  6185. defaultFormatInfo.mLanguage = formatInfo.mLanguage;
  6186. defaultFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + 2; // Take into accout the necessary {}'s
  6187. defaultFormatInfo.mExpandItemDepth++;
  6188. String innerStr = DbgTypedValueToString(innerTypedVal, "", defaultFormatInfo, &dbgExprEvaluator);
  6189. int crIdx = innerStr.IndexOf('\n');
  6190. if (crIdx != -1)
  6191. {
  6192. String innerDataStr = innerStr.Substring(0, crIdx);
  6193. if (!innerDataStr.empty())
  6194. {
  6195. if (!retVal.empty())
  6196. retVal += " ";
  6197. retVal += "{" + innerDataStr + "}";
  6198. }
  6199. }
  6200. else
  6201. {
  6202. retVal += "{ ??? }";
  6203. }
  6204. }
  6205. }
  6206. retVal += "\n" + origValueType->ToString(language);
  6207. innerType->PopulateType();
  6208. if ((ptrVal != 0) &&
  6209. ((!innerType->mMemberList.IsEmpty()) || (innerType->mSize > 0) || (innerType->mTypeParam != NULL)))
  6210. {
  6211. String ptrDataStr = StrFormat("(%s)", dwValueType->ToStringRaw(language).c_str()) + EncodeDataPtr(typedValue.mPtr, true);
  6212. retVal += "\n*\t";
  6213. // Why did we have this? It messed up a pointer to sized array
  6214. /*if (language == DbgLanguage_Beef)
  6215. retVal += "this";
  6216. else*/
  6217. retVal += "*this";
  6218. if (!formatInfo.mReferenceId.empty())
  6219. retVal += ", refid=" + MaybeQuoteFormatInfoParam(formatInfo.mReferenceId);
  6220. retVal += ", this=" + ptrDataStr;
  6221. }
  6222. return retVal;
  6223. }
  6224. break;
  6225. }
  6226. case DbgType_Union:
  6227. case DbgType_Class:
  6228. case DbgType_Struct:
  6229. isCompositeType = true;
  6230. break;
  6231. case DbgType_Enum:
  6232. enumVal = typedValue.GetInt64();
  6233. isEnum = true;
  6234. break;
  6235. case DbgType_SizedArray:
  6236. {
  6237. isSizedArray = true;
  6238. }
  6239. break;
  6240. default:
  6241. break;
  6242. }
  6243. if (isSizedArray)
  6244. {
  6245. String retVal;
  6246. addr_target ptrVal = 0;
  6247. DbgType* arrayType = dwValueType;
  6248. DbgType* innerType = dwValueType->mTypeParam;
  6249. if (dwValueType->mTypeCode == DbgType_SizedArray)
  6250. {
  6251. ptrVal = (addr_target)typedValue.mSrcAddress;
  6252. }
  6253. else
  6254. {
  6255. BF_ASSERT(dwValueType->mTypeCode == DbgType_Ptr);
  6256. arrayType = innerType;
  6257. innerType = arrayType->mTypeParam;
  6258. ptrVal = typedValue.mPtr;
  6259. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6260. retVal = EncodeDataPtr(ptrVal, true) + " ";
  6261. }
  6262. if (ptrVal == 0)
  6263. ptrVal = typedValue.mPtr;
  6264. intptr arraySize = 0;
  6265. intptr innerSize = innerType->GetStride();
  6266. if (innerSize > 0)
  6267. arraySize = arrayType->GetStride() / innerSize;
  6268. else
  6269. {
  6270. // Failure!
  6271. }
  6272. String idxStr = "[{0}]";
  6273. if (innerType->IsChar(language))
  6274. {
  6275. String strVal = ReadString(innerType->mTypeCode, typedValue.mSrcAddress, false, arraySize, formatInfo);
  6276. if (formatInfo.mRawString)
  6277. return strVal;
  6278. retVal += strVal;
  6279. }
  6280. else
  6281. {
  6282. if (formatInfo.mRawString)
  6283. return "";
  6284. _ShowArraySummary(retVal, ptrVal, arraySize, innerType);
  6285. }
  6286. retVal += "\n" + origValueType->ToString(language);
  6287. String referenceId = dwValueType->ToString(language);
  6288. String evalStr;
  6289. // Why did we have the "na"? Do we not want to show addresses for all members?
  6290. evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + ")[{0}], refid=" + MaybeQuoteFormatInfoParam(referenceId + ".[]");
  6291. if (typedValue.mIsReadOnly)
  6292. evalStr += ", ne";
  6293. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, (int)BF_MAX(arraySize, 0), 10000) +
  6294. "\t" + idxStr + "\t" + evalStr;
  6295. return retVal;
  6296. }
  6297. dwValueType->PopulateType();
  6298. if (isEnum)
  6299. {
  6300. String retVal;
  6301. int64 bitsLeft = enumVal;
  6302. int valueCount = 0;
  6303. String editVal;
  6304. dwValueType = dwValueType->GetPrimaryType();
  6305. dwValueType->PopulateType();
  6306. while ((bitsLeft != 0) || (valueCount == 0))
  6307. {
  6308. DbgVariable* bestMatch = NULL;
  6309. for (auto member : dwValueType->mMemberList)
  6310. {
  6311. if (member->mConstValue == bitsLeft)
  6312. {
  6313. bestMatch = member;
  6314. break;
  6315. }
  6316. }
  6317. if (bestMatch == NULL)
  6318. {
  6319. for (auto member : dwValueType->mMemberList)
  6320. {
  6321. if ((member->mConstValue != 0) &&
  6322. ((member->mConstValue & bitsLeft) == member->mConstValue))
  6323. {
  6324. bestMatch = member;
  6325. break;
  6326. }
  6327. }
  6328. }
  6329. if (bestMatch == NULL)
  6330. break;
  6331. if (valueCount > 0)
  6332. {
  6333. retVal += " | ";
  6334. if (language == DbgLanguage_C)
  6335. editVal += " | ";
  6336. }
  6337. if (language == DbgLanguage_Beef)
  6338. retVal += ".";
  6339. retVal += bestMatch->mName;
  6340. if (language == DbgLanguage_C)
  6341. {
  6342. if (dwValueType->mParent != NULL)
  6343. {
  6344. editVal += dwValueType->mParent->ToString(language);
  6345. editVal += "::";
  6346. }
  6347. editVal += bestMatch->mName;
  6348. }
  6349. valueCount++;
  6350. bitsLeft &= ~bestMatch->mConstValue;
  6351. }
  6352. if ((valueCount == 0) || (bitsLeft != 0))
  6353. {
  6354. if (valueCount > 0)
  6355. retVal += " | ";
  6356. retVal += StrFormat("%d", bitsLeft);
  6357. if (language == DbgLanguage_C)
  6358. {
  6359. if (valueCount > 0)
  6360. editVal += " | ";
  6361. editVal += StrFormat("%d", bitsLeft);
  6362. }
  6363. }
  6364. retVal += "\n" + origValueType->ToString();
  6365. if (language == DbgLanguage_C)
  6366. {
  6367. retVal += "\n:editVal\t";
  6368. retVal += editVal;
  6369. }
  6370. retVal += "\n:canEdit";
  6371. return retVal;
  6372. }
  6373. else if (isCompositeType)
  6374. {
  6375. addr_target ptrVal;
  6376. if (dwValueType->IsPointer())
  6377. ptrVal = (addr_target)typedValue.mPtr;
  6378. else
  6379. ptrVal = (addr_target)typedValue.mSrcAddress;
  6380. String retVal;
  6381. if ((!typedValue.mIsLiteral) && (dwValueType->IsPointer()) &&
  6382. ((!formatInfo.mHidePointers) || (ptrVal == 0)))
  6383. retVal = EncodeDataPtr(ptrVal, true);
  6384. DbgType* innerType = dwValueType;
  6385. bool wasPtr = false;
  6386. if (innerType->mTypeCode == DbgType_Ptr)
  6387. {
  6388. wasPtr = true;
  6389. innerType = dwValueType->mTypeParam;
  6390. innerType = innerType->RemoveModifiers();
  6391. }
  6392. innerType = innerType->GetPrimaryType();
  6393. addr_target dataPtr = wasPtr ? typedValue.mPtr : typedValue.mSrcAddress;
  6394. DbgType* actualType = NULL;
  6395. bool useActualRawType = false;
  6396. bool isBfObject = innerType->IsBfObject();
  6397. bool hasCPPVTable = false;
  6398. if (!isBfObject)
  6399. hasCPPVTable = innerType->HasCPPVTable();
  6400. int bfObjectFlags = 0;
  6401. addr_target classVDataPtr = 0;
  6402. bool isAppendBfObject = false;
  6403. bool isStackBfObject = false;
  6404. bool isDeletedBfObject = false;
  6405. bool isCompositeWithoutAddress = false;
  6406. if (innerType->IsBfPayloadEnum())
  6407. {
  6408. if (formatInfo.mRawString)
  6409. return "";
  6410. auto tagMember = innerType->mMemberList.mTail;
  6411. int tagIdx = 0;
  6412. if (dataPtr == -1)
  6413. {
  6414. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, "(int)" + expr, &formatInfo);
  6415. auto dscValue = dbgEvaluationContext.EvaluateInContext(DbgTypedValue());
  6416. tagIdx = dscValue.mInt32;
  6417. }
  6418. else if (!ReadMemory((intptr)ptrVal + tagMember->mMemberOffset, tagMember->mType->mSize, (void*)&tagIdx))
  6419. {
  6420. return StrFormat("!Failed to read from 0x%@", ptrVal);
  6421. }
  6422. char findStr[16];
  6423. findStr[0] = '_';
  6424. itoa(tagIdx, findStr + 1, 10);
  6425. int len = strlen(findStr);
  6426. findStr[len] = '_';
  6427. len++;
  6428. if (!retVal.empty())
  6429. retVal += " ";
  6430. int startIdx = 0;
  6431. for (auto member : innerType->mMemberList)
  6432. {
  6433. if (strncmp(member->mName, findStr, len) == 0)
  6434. {
  6435. retVal += ".";
  6436. retVal += member->mName + len;
  6437. String tupleExpr;
  6438. DbgTypedValue tupleVal;
  6439. if (dataPtr == -1)
  6440. {
  6441. tupleVal.mSrcAddress = -1;
  6442. tupleVal.mType = member->mType;
  6443. //tupleExpr = "$" + expr + "$u";
  6444. tupleVal.mVariable = typedValue.mVariable;
  6445. tupleExpr = "(" + member->mType->ToStringRaw() + ")(" + expr + ")";
  6446. }
  6447. else
  6448. {
  6449. tupleVal.mType = member->mType;
  6450. tupleVal.mSrcAddress = ptrVal;
  6451. }
  6452. DwFormatInfo displayStrFormatInfo = formatInfo;
  6453. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + (int)retVal.length();
  6454. displayStrFormatInfo.mExpandItemDepth++;
  6455. displayStrFormatInfo.mHidePointers = false;
  6456. retVal += DbgTypedValueToString(tupleVal, tupleExpr, displayStrFormatInfo, NULL);
  6457. int idx = (int)retVal.IndexOf('\n');
  6458. if (idx != -1)
  6459. {
  6460. if ((idx > 2) && (strncmp(retVal.c_str() + idx - 2, "()", 2) == 0))
  6461. {
  6462. // Take off a terminating "()" on the value, if there is one
  6463. retVal.Remove(idx - 2, 2);
  6464. }
  6465. String typeName = innerType->ToString(DbgLanguage_Unknown, true);
  6466. typeName += " ";
  6467. retVal.Insert(idx + 1, typeName);
  6468. }
  6469. return retVal;
  6470. }
  6471. }
  6472. }
  6473. if (isBfObject)
  6474. {
  6475. classVDataPtr = ReadMemory<addr_target>(ptrVal);
  6476. mDebugTarget->GetCompilerSettings();
  6477. if (mDebugTarget->mBfObjectHasFlags)
  6478. {
  6479. bfObjectFlags = ((int)classVDataPtr) & 0xFF;
  6480. if ((bfObjectFlags & BfObjectFlag_Deleted) != 0)
  6481. isDeletedBfObject = true;
  6482. if ((bfObjectFlags & BfObjectFlag_AppendAlloc) != 0)
  6483. isAppendBfObject = true;
  6484. if ((bfObjectFlags & (BfObjectFlag_StackAlloc | BfObjectFlag_Allocated)) == BfObjectFlag_StackAlloc)
  6485. isStackBfObject = true;
  6486. classVDataPtr &= ~0xFF;
  6487. }
  6488. }
  6489. if (!formatInfo.mIgnoreDerivedClassInfo)
  6490. {
  6491. if (isBfObject)
  6492. {
  6493. dbgModule->ParseSymbolData();
  6494. String symbolName;
  6495. addr_target symOffset;
  6496. if ((mDebugTarget->FindSymbolAt(classVDataPtr, &symbolName, &symOffset)) && (symOffset < 0x100))
  6497. {
  6498. String mangledClassName;
  6499. const char* symEnd = "sBfClassVData";
  6500. int symEndLen = strlen(symEnd);
  6501. if (((int)symbolName.length() > symEndLen) && (strstr(symbolName.c_str(), symEnd) != NULL))
  6502. mangledClassName = symbolName;
  6503. // If we have flags then we may be pointing past the _typeData, actually. We could fix this by masking out
  6504. // the flags area, but we need to be sure we are running a build that supports flags
  6505. symEnd = "sBfTypeData";
  6506. symEndLen = strlen(symEnd);
  6507. if (((int) symbolName.length() > symEndLen) && (strstr(symbolName.c_str(), symEnd) != NULL))
  6508. mangledClassName = symbolName;
  6509. if (mangledClassName.length() > 0)
  6510. {
  6511. String className = BfDemangler::Demangle(mangledClassName, innerType->GetLanguage(), BfDemangler::Flag_RawDemangle);
  6512. for (int i = 0; i < className.length() - 3; i++)
  6513. {
  6514. if ((className[i] == 'b') &&
  6515. (className[i + 1] == 'f') &&
  6516. (className[i + 2] == '.'))
  6517. {
  6518. bool matches;
  6519. if (i == 0)
  6520. matches = true;
  6521. else
  6522. {
  6523. char prevC = className[i - 1];
  6524. if ((prevC == ' ') ||
  6525. (prevC == ',') ||
  6526. (prevC == '<'))
  6527. {
  6528. matches = true;
  6529. }
  6530. }
  6531. if (matches)
  6532. className.Remove(i, 3);
  6533. }
  6534. }
  6535. int lastDot = (int)className.LastIndexOf('.');
  6536. if (lastDot > 0)
  6537. className = className.Substring(0, lastDot);
  6538. const char* arrPrefix = "System.Array1<";
  6539. if (strncmp(className.c_str(), arrPrefix, strlen(arrPrefix)) == 0)
  6540. {
  6541. className = className.Substring(strlen(arrPrefix), className.length() - strlen(arrPrefix) - 1);
  6542. className += "[]";
  6543. }
  6544. auto typeEntry = dbgModule->GetLinkedModule()->mTypeMap.Find(className.c_str(), DbgLanguage_BeefUnfixed);
  6545. if (typeEntry != NULL)
  6546. {
  6547. actualType = typeEntry->mValue;
  6548. if (!actualType->IsBfObject())
  6549. {
  6550. if (actualType->mTypeCode == DbgType_Ptr)
  6551. {
  6552. actualType = actualType->mTypeParam;
  6553. }
  6554. }
  6555. }
  6556. }
  6557. }
  6558. }
  6559. else if (hasCPPVTable)
  6560. {
  6561. dbgModule->ParseSymbolData();
  6562. addr_target classVDataPtr = ReadMemory<addr_target>(ptrVal);
  6563. String symbolName;
  6564. addr_target offset = 0;
  6565. if (mDebugTarget->FindSymbolAt(classVDataPtr, &symbolName, &offset, NULL))
  6566. {
  6567. // On GNU, vtable indices can "go negative" for things like RTTI and virtual inheritance, so
  6568. // we can't rely on an exact vtable address lookup
  6569. if (offset < 0x200)
  6570. {
  6571. DbgLanguage lang = innerType->GetLanguage();
  6572. const char* symStart = (innerType->mCompileUnit->mDbgModule->mDbgFlavor == DbgFlavor_GNU) ? "_ZTV" : "??_7";
  6573. if (strncmp(symbolName.c_str(), symStart, strlen(symStart)) == 0)
  6574. {
  6575. //String mangledClassName = symbolName.Substring(1);
  6576. String className = BfDemangler::Demangle(symbolName, lang);
  6577. int vtableNameIdx = (int)className.IndexOf("::`vftable'");
  6578. if (vtableNameIdx != -1)
  6579. className = className.Substring(0, vtableNameIdx);
  6580. auto typeEntry = dbgModule->mTypeMap.Find(className.c_str(), DbgLanguage_C);
  6581. if (typeEntry != NULL)
  6582. {
  6583. actualType = typeEntry->mValue;
  6584. if ((int)className.IndexOf('<') != -1)
  6585. useActualRawType = true;
  6586. int thisOffset = 0;
  6587. if (!DbgExprEvaluator::TypeIsSubTypeOf(actualType, innerType, &thisOffset))
  6588. {
  6589. // This catches virtual inheritance cases where we can't downcast
  6590. actualType = NULL;
  6591. }
  6592. }
  6593. }
  6594. }
  6595. }
  6596. }
  6597. }
  6598. DbgType* displayType = origValueType;
  6599. String displayString;
  6600. bool wantsCustomExpandedItems = false;
  6601. DebugVisualizerEntry* debugVis = NULL;
  6602. Array<String> dbgVisWildcardCaptures;
  6603. DbgType* dwUseType = (actualType != NULL) ? actualType : innerType;
  6604. //auto ptrDataType = dwValueType;
  6605. //TODO: Changed this from the above to account for COFF types where 'this' is always a fwd reference, does this cause any issues?
  6606. auto ptrDataType = innerType;
  6607. String ptrDataStr;
  6608. if (/*(!innerType->IsBfObject()) &&*/ (!ptrDataType->IsPointer()))
  6609. {
  6610. if ((dataPtr != 0) || (ptrDataType->GetByteCount() > sizeof(addr_target)))
  6611. {
  6612. bool wantsRefThis = ptrDataType->WantsRefThis();
  6613. ptrDataType = ptrDataType->GetDbgModule()->GetPointerType(ptrDataType);
  6614. if (wantsRefThis)
  6615. ptrDataStr += "*";
  6616. }
  6617. else
  6618. {
  6619. // Data is inline - must be int-sized or less
  6620. isCompositeWithoutAddress = true;
  6621. dataPtr = typedValue.mPtr;
  6622. }
  6623. }
  6624. String ptrDataTypeStr = ptrDataType->ToStringRaw();
  6625. ptrDataStr += StrFormat("(%s)", ptrDataTypeStr.c_str()) + EncodeDataPtr(dataPtr, true);
  6626. DbgType* dwUsePtrType = dwUseType;
  6627. String ptrUseDataStr;
  6628. if (!dwUsePtrType->IsPointer())
  6629. {
  6630. bool wantsRefThis = dwUsePtrType->WantsRefThis();
  6631. dwUsePtrType = dwUsePtrType->GetDbgModule()->GetPointerType(dwUsePtrType);
  6632. if (wantsRefThis)
  6633. ptrUseDataStr += "*";
  6634. }
  6635. String ptrUseDataTypeStr = dwUsePtrType->ToStringRaw();
  6636. ptrUseDataStr += StrFormat("(%s)", ptrUseDataTypeStr.c_str()) + EncodeDataPtr(dataPtr, true);
  6637. if ((origTypedValue.mSrcAddress == -1) && (origTypedValue.mVariable != NULL))
  6638. {
  6639. ptrDataStr = origTypedValue.mVariable->mName;
  6640. if (!origTypedValue.mType->RemoveModifiers()->Equals(origTypedValue.mVariable->mType->RemoveModifiers()))
  6641. {
  6642. //ptrDataStr = StrFormat("(%s)%s", origTypedValue.mType->ToString().c_str(), origTypedValue.mVariable->mName);
  6643. ptrDataStr = expr;
  6644. }
  6645. ptrUseDataStr = ptrDataStr;
  6646. }
  6647. bool isNull = wasPtr && (dataPtr == 0);
  6648. bool isBadSrc = !wasPtr && (dataPtr == 0) && (!dwValueType->IsValuelessType());
  6649. if ((ptrVal == 0) && (dwValueType->IsTypedPrimitive()))
  6650. {
  6651. DbgTypedValue rawVal;
  6652. rawVal.mInt64 = origTypedValue.mInt64;
  6653. rawVal.mType = dwValueType->GetRootBaseType();
  6654. ptrDataStr = "(" + dwUseType->ToStringRaw() + ")";
  6655. ptrDataStr += DbgTypedValueToString(rawVal, expr, formatInfo, optEvaluator, fullPrecision);
  6656. int editValIdx = ptrDataStr.IndexOf(":editVal");
  6657. if (editValIdx != -1)
  6658. ptrDataStr.Remove(0, editValIdx + 9);
  6659. int crPos = (int)ptrDataStr.IndexOf('\n');
  6660. if (crPos != -1)
  6661. ptrDataStr.RemoveToEnd(crPos);
  6662. ptrUseDataStr = ptrDataStr;
  6663. if ((origTypedValue.mRegNum != -1) && (!expr.IsEmpty()) && (!formatInfo.mExplicitThis))
  6664. {
  6665. // There's no address, use direct local identifier
  6666. ptrDataStr = expr;
  6667. ptrUseDataStr = expr;
  6668. }
  6669. // This keeps 'function' types from showing null as "<null parent>"
  6670. isBadSrc = false;
  6671. }
  6672. else if ((ptrVal == 0) && (dwValueType->IsCompositeType()))
  6673. {
  6674. }
  6675. DbgTypedValue useTypedValue = typedValue;
  6676. if ((origHadRef) || ((typedValue.mType->HasPointer()) && (!dwUseType->HasPointer())))
  6677. {
  6678. useTypedValue.mSrcAddress = useTypedValue.mPtr;
  6679. useTypedValue.mPtr = 0;
  6680. if (dwUseType->IsTypedPrimitive())
  6681. {
  6682. int byteCount = dwUseType->GetByteCount();
  6683. if (byteCount <= sizeof(intptr))
  6684. {
  6685. ReadMemory(useTypedValue.mSrcAddress, byteCount, &useTypedValue.mPtr);
  6686. }
  6687. }
  6688. }
  6689. useTypedValue.mType = dwUseType;
  6690. if ((!formatInfo.mNoVisualizers) && (!isNull) && (!isBadSrc))
  6691. {
  6692. if (language == DbgLanguage_Beef)
  6693. dwUseType->FixName();
  6694. debugVis = FindVisualizerForType(dwUseType, &dbgVisWildcardCaptures);
  6695. }
  6696. bool hadCustomDisplayString = false;
  6697. if (debugVis != NULL)
  6698. {
  6699. auto& displayStringList = formatInfo.mRawString ? debugVis->mStringViews : debugVis->mDisplayStrings;
  6700. for (auto displayEntry : displayStringList)
  6701. {
  6702. if (!displayEntry->mCondition.empty())
  6703. {
  6704. if (!EvalCondition(debugVis, dbgCompileUnit, useTypedValue, formatInfo, displayEntry->mCondition, dbgVisWildcardCaptures, displayString))
  6705. continue;
  6706. }
  6707. hadCustomDisplayString = true;
  6708. String displayStr = mDebugManager->mDebugVisualizers->DoStringReplace(displayEntry->mString, dbgVisWildcardCaptures);
  6709. if (displayString.length() > 0)
  6710. displayString += " ";
  6711. ProcessEvalString(dbgCompileUnit, useTypedValue, displayStr, displayString, formatInfo, debugVis, true);
  6712. if (formatInfo.mRawString)
  6713. return displayString;
  6714. break;
  6715. }
  6716. if ((!debugVis->mExpandItems.empty()) || (debugVis->mCollectionType != DebugVisualizerEntry::CollectionType_None))
  6717. {
  6718. wantsCustomExpandedItems = true;
  6719. }
  6720. }
  6721. if (formatInfo.mRawString)
  6722. return "";
  6723. bool isTuple = (dwUseType->mName != NULL) && (dwUseType->mName[0] == '(') && (language == DbgLanguage_Beef);
  6724. if (isBadSrc)
  6725. {
  6726. displayString += "<null parent>";
  6727. }
  6728. else if ((!isNull) && (!formatInfo.mNoVisualizers) && (!hadCustomDisplayString))
  6729. {
  6730. // Create our own custom display
  6731. String firstRet;
  6732. String bigRet = isTuple ? "(" : "{ ";
  6733. int memberIdx = 0;
  6734. DbgType* summaryType = dwUseType;
  6735. bool summaryDone = false;
  6736. bool truncatedMemberList = false;
  6737. DbgTypedValue summaryTypedValue = useTypedValue;
  6738. String summaryDataStr = ptrDataStr;
  6739. String splatStr;
  6740. if (dataPtr == -1)
  6741. splatStr = expr;
  6742. while (summaryType != NULL)
  6743. {
  6744. summaryType->PopulateType();
  6745. if (summaryType->IsTypedPrimitive())
  6746. {
  6747. if (formatInfo.mTotalSummaryLength + (int)displayString.length() > 255)
  6748. {
  6749. truncatedMemberList = true;
  6750. summaryDone = true;
  6751. bigRet += "...";
  6752. }
  6753. else
  6754. {
  6755. DwFormatInfo displayStrFormatInfo = formatInfo;
  6756. displayStrFormatInfo.mExpandItemDepth = 1;
  6757. displayStrFormatInfo.mTotalSummaryLength += (int)displayString.length();
  6758. displayStrFormatInfo.mHidePointers = false;
  6759. DbgType* primType = summaryType->mTypeParam;
  6760. String result;
  6761. if (primType->IsInteger())
  6762. formatInfo.mTypeKindFlags = (DbgTypeKindFlags)(formatInfo.mTypeKindFlags | DbgTypeKindFlag_Int);
  6763. if ((dataPtr != 0) && (dataPtr != -1))
  6764. {
  6765. String evalString = "(" + primType->ToString() + ")" + ptrDataStr;
  6766. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, origTypedValue, evalString, &displayStrFormatInfo);
  6767. if (evalResult)
  6768. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  6769. }
  6770. else
  6771. {
  6772. DbgTypedValue evalResult = origTypedValue;
  6773. evalResult.mType = primType;
  6774. String evalString = "(" + primType->ToString() + ")" + expr;
  6775. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  6776. }
  6777. if (formatInfo.mRawString)
  6778. return result;
  6779. int crPos = result.IndexOf('\n');
  6780. if (crPos != -1)
  6781. result.RemoveToEnd(crPos);
  6782. if (memberIdx == 0)
  6783. firstRet = result;
  6784. bigRet += result;
  6785. memberIdx++;
  6786. }
  6787. }
  6788. for (auto member : summaryType->mMemberList)
  6789. {
  6790. if (!member->mIsStatic)
  6791. {
  6792. if (formatInfo.mTotalSummaryLength + retVal.length() + bigRet.length() > 255)
  6793. {
  6794. truncatedMemberList = true;
  6795. summaryDone = true;
  6796. bigRet += "...";
  6797. break;
  6798. }
  6799. if (member->mName != NULL)
  6800. {
  6801. if (!isdigit(*member->mName))
  6802. {
  6803. if (memberIdx != 0)
  6804. bigRet += isTuple ? ", " : " ";
  6805. if ((!isTuple) || (member->mName[0] != '_'))
  6806. {
  6807. bigRet += String(member->mName);
  6808. bigRet += isTuple ? ":" : "=";
  6809. }
  6810. }
  6811. else
  6812. {
  6813. if (memberIdx != 0)
  6814. bigRet += ", ";
  6815. }
  6816. DwFormatInfo displayStrFormatInfo = formatInfo;
  6817. displayStrFormatInfo.mExpandItemDepth = 1;
  6818. displayStrFormatInfo.mHidePointers = false;
  6819. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + retVal.length() + bigRet.length();
  6820. String evalString;
  6821. if (dataPtr != -1)
  6822. {
  6823. if ((member->mName[0] >= '0') && (member->mName[0] <= '9'))
  6824. evalString += "this.";
  6825. evalString += String(member->mName); // +", this=" + summaryDataStr;
  6826. }
  6827. else
  6828. {
  6829. evalString = "(";
  6830. evalString += splatStr;
  6831. evalString += ").";
  6832. evalString += member->mName;
  6833. }
  6834. String referenceId;
  6835. String result;
  6836. if (!member->mType->IsValuelessType())
  6837. {
  6838. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, summaryTypedValue, evalString, &displayStrFormatInfo, &referenceId);
  6839. if (evalResult)
  6840. {
  6841. displayStrFormatInfo.mReferenceId = referenceId;
  6842. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  6843. int crPos = result.IndexOf('\n');
  6844. if (crPos != -1)
  6845. result.RemoveToEnd(crPos);
  6846. }
  6847. else
  6848. result = "???";
  6849. }
  6850. if (member->mType->IsInteger())
  6851. formatInfo.mTypeKindFlags = (DbgTypeKindFlags)(formatInfo.mTypeKindFlags | DbgTypeKindFlag_Int);
  6852. if (formatInfo.mRawString)
  6853. return result;
  6854. if (memberIdx == 0)
  6855. firstRet = result;
  6856. bigRet += result;
  6857. //formatInfo.mEmbeddedDisplayCount = displayStrFormatInfo.mEmbeddedDisplayCount;
  6858. memberIdx++;
  6859. }
  6860. else
  6861. {
  6862. //TODO: Handle C++ unions?
  6863. }
  6864. }
  6865. }
  6866. if (truncatedMemberList)
  6867. break;
  6868. // Find first base class with members
  6869. DbgType* nextSummaryType = NULL;
  6870. for (auto checkBase : summaryType->mBaseTypes)
  6871. {
  6872. auto checkBaseType = checkBase->mBaseType;
  6873. checkBaseType = checkBaseType->GetPrimaryType();
  6874. checkBaseType->PopulateType();
  6875. if ((checkBaseType->GetByteCount() > 0) || (checkBaseType->IsPrimitiveType()))
  6876. {
  6877. if (!splatStr.empty())
  6878. {
  6879. splatStr = "(" + checkBaseType->ToString() + ")" + splatStr;
  6880. }
  6881. else
  6882. {
  6883. summaryTypedValue.mType = checkBaseType;
  6884. }
  6885. nextSummaryType = checkBaseType;
  6886. break;
  6887. }
  6888. }
  6889. summaryType = nextSummaryType;
  6890. if (summaryType == NULL)
  6891. break;
  6892. // Don't add the Object members
  6893. if ((summaryType->GetBaseType() == NULL) && (summaryType->IsBfObject()))
  6894. break;
  6895. // If we don't have many members then find a base class with some members to show
  6896. if ((memberIdx != 0) && (displayString.length() >= 255))
  6897. {
  6898. truncatedMemberList = true;
  6899. bigRet += "...";
  6900. break;
  6901. }
  6902. }
  6903. bigRet += isTuple ? ")" : " }";
  6904. if (displayString.length() > 0)
  6905. displayString += " ";
  6906. if ((memberIdx == 1) && (!truncatedMemberList) && (firstRet.IndexOf('{') == -1) && (!isTuple))
  6907. displayString += "{ " + firstRet + " }";
  6908. else
  6909. displayString += bigRet;
  6910. }
  6911. DbgType* memberListType = actualType;
  6912. bool memberListForceCast = false;
  6913. if (actualType != NULL)
  6914. {
  6915. String valTypeName = displayType->ToString();
  6916. String actualTypeName = actualType->ToString(DbgLanguage_Unknown, true);
  6917. String actualUseTypeName = actualTypeName;
  6918. if ((int)actualTypeName.IndexOf('^') != -1)
  6919. useActualRawType = true;
  6920. if (useActualRawType)
  6921. actualUseTypeName = actualType->ToStringRaw();
  6922. if (displayString.empty())
  6923. {
  6924. // Nothing to display
  6925. }
  6926. else
  6927. {
  6928. if (!retVal.empty())
  6929. retVal += " ";
  6930. retVal += displayString;
  6931. }
  6932. retVal += "\n" + valTypeName;
  6933. if ((innerType->IsBaseBfObject()) || (innerType->IsInterface()))
  6934. {
  6935. if (actualType != innerType)
  6936. {
  6937. retVal += " {" + actualTypeName + "}";
  6938. memberListForceCast = true;
  6939. }
  6940. }
  6941. else
  6942. {
  6943. if (actualType != innerType)
  6944. {
  6945. retVal += " {" + actualTypeName + "}";
  6946. retVal += "\n";
  6947. if (!wantsCustomExpandedItems)
  6948. {
  6949. retVal += "[" + actualTypeName + "]\t((" + actualUseTypeName;
  6950. if (!actualType->IsBfObject())
  6951. retVal += "*";
  6952. retVal += ")this), nd, na, nv, this=" + ptrDataStr;
  6953. memberListType = innerType;
  6954. }
  6955. }
  6956. }
  6957. }
  6958. else
  6959. {
  6960. if ((formatInfo.mHidePointers) && (formatInfo.mIgnoreDerivedClassInfo))
  6961. {
  6962. displayType = innerType;
  6963. if (displayString.empty())
  6964. retVal += displayType->ToString(DbgLanguage_Unknown, true);
  6965. }
  6966. if (!displayString.empty())
  6967. {
  6968. if (!retVal.empty())
  6969. retVal += " ";
  6970. retVal += displayString;
  6971. }
  6972. else
  6973. {
  6974. if (formatInfo.mRawString)
  6975. return "";
  6976. }
  6977. retVal += "\n" + displayType->ToString(DbgLanguage_Unknown, true);
  6978. memberListType = innerType;
  6979. }
  6980. if ((isBfObject) && (mDebugTarget->mBfObjectHasFlags) && (!formatInfo.mNoVisualizers) && (!formatInfo.mRawString))
  6981. {
  6982. int stackTraceLen = 1;
  6983. addr_target stackTraceAddr = ptrVal + sizeof(addr_target);
  6984. if ((bfObjectFlags & BfObjectFlag_AllocInfo) != 0)
  6985. {
  6986. addr_target objectSize = ReadMemory<addr_target>(ptrVal + sizeof(addr_target));
  6987. addr_target largeAllocInfo = ReadMemory<addr_target>(ptrVal + objectSize);
  6988. stackTraceLen = largeAllocInfo & 0xFFFF;
  6989. stackTraceAddr = ptrVal + objectSize + sizeof(addr_target);
  6990. }
  6991. else if ((bfObjectFlags & BfObjectFlag_AllocInfo_Short) != 0)
  6992. {
  6993. addr_target dbgAllocInfo = ReadMemory<addr_target>(ptrVal + sizeof(addr_target));
  6994. stackTraceLen = dbgAllocInfo & 0xFF;
  6995. stackTraceAddr = ptrVal + (dbgAllocInfo >> 16);
  6996. }
  6997. if (stackTraceLen == 1)
  6998. {
  6999. retVal += StrFormat("\n[AllocStackTrace]\t*(System.CallStackAddr*)%s, nm", EncodeDataPtr(stackTraceAddr, true).c_str());
  7000. }
  7001. else if (stackTraceLen > 0)
  7002. {
  7003. retVal += StrFormat("\n[AllocStackTrace]\t(System.CallStackAddr*)%s, %d, na", EncodeDataPtr(stackTraceAddr, true).c_str(), stackTraceLen);
  7004. }
  7005. }
  7006. retVal += StrFormat("\n:language\t%d", language);
  7007. if (formatInfo.mNoMembers)
  7008. {
  7009. //
  7010. }
  7011. else if (wantsCustomExpandedItems)
  7012. {
  7013. HandleCustomExpandedItems(retVal, dbgCompileUnit, debugVis, dwUseType, dwValueType, ptrUseDataStr, ptrDataStr, useTypedValue, dbgVisWildcardCaptures, formatInfo);
  7014. }
  7015. else if ((!isNull) && (!isBadSrc))
  7016. {
  7017. if (dataPtr == -1)
  7018. {
  7019. //String splatName = ((origTypedValue.mSrcAddress == -1) && (origTypedValue.mVariable != NULL)) ? origTypedValue.mVariable->mName : expr;
  7020. String splatName = expr;
  7021. retVal += "\n" + GetMemberList(memberListType, splatName, wasPtr, false, false, true, origTypedValue.mIsReadOnly);
  7022. }
  7023. else
  7024. {
  7025. retVal += "\n" + GetMemberList(memberListType, ptrDataStr, wasPtr, false, memberListForceCast, isCompositeWithoutAddress, origTypedValue.mIsReadOnly);
  7026. }
  7027. }
  7028. if (formatInfo.mExpandItemDepth > 0)
  7029. return retVal;
  7030. if (isAppendBfObject)
  7031. retVal += "\n:appendAlloc";
  7032. if (isStackBfObject)
  7033. retVal += "\n:stack";
  7034. if (isDeletedBfObject)
  7035. retVal += "\n:deleted";
  7036. if ((debugVis != NULL) && (!debugVis->mAction.empty()))
  7037. {
  7038. String rawActionStr = mDebugManager->mDebugVisualizers->DoStringReplace(debugVis->mAction, dbgVisWildcardCaptures);
  7039. String actionStr;
  7040. ProcessEvalString(dbgCompileUnit, useTypedValue, rawActionStr, actionStr, formatInfo, debugVis, true);
  7041. retVal += "\n:action\t" + actionStr;
  7042. }
  7043. if ((!typedValue.mIsLiteral) && (dwValueType->IsPointer()))
  7044. {
  7045. retVal += "\n:editVal\t" + EncodeDataPtr(ptrVal, true);
  7046. }
  7047. return retVal;
  7048. }
  7049. return "Unknown Type\n" + origValueType->ToString();
  7050. }
  7051. void WinDebugger::HandleCustomExpandedItems(String& retVal, DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgType* dwUseType, DbgType* dwValueType, String& ptrUseDataStr, String& ptrDataStr, DbgTypedValue useTypedValue, Array<String>& dbgVisWildcardCaptures, DwFormatInfo& formatInfo)
  7052. {
  7053. auto debugVisualizers = mDebugManager->mDebugVisualizers;
  7054. auto dbgModule = dbgCompileUnit->mDbgModule;
  7055. if (formatInfo.mExpandItemDepth > 10) // Avoid crashing on circular ExpandItems
  7056. return;
  7057. auto language = formatInfo.mLanguage;
  7058. bool isReadOnly = false;
  7059. if (useTypedValue.mIsReadOnly)
  7060. isReadOnly = true;
  7061. for (auto entry : debugVis->mExpandItems)
  7062. {
  7063. if (!entry->mCondition.empty())
  7064. {
  7065. String error;
  7066. if (!EvalCondition(debugVis, dbgCompileUnit, useTypedValue, formatInfo, entry->mCondition, dbgVisWildcardCaptures, error))
  7067. {
  7068. if (!error.empty())
  7069. retVal += "\n" + entry->mName + "\t@!<DbgVis Failed>@!";
  7070. continue;
  7071. }
  7072. }
  7073. String replacedStr = debugVisualizers->DoStringReplace(entry->mValue, dbgVisWildcardCaptures);
  7074. retVal += "\n" + entry->mName + "\t" + replacedStr + ", this=(" + ptrUseDataStr + ")";
  7075. }
  7076. String referenceId = dwUseType->ToString();
  7077. if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_ExpandedItem)
  7078. {
  7079. DbgTypedValue itemValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7080. if (itemValue)
  7081. {
  7082. DwFormatInfo itemFormatInfo = formatInfo;
  7083. itemFormatInfo.mExpandItemDepth++;
  7084. String itemRetVal = DbgTypedValueToString(itemValue, "", itemFormatInfo, NULL);
  7085. int crIdx = (int)itemRetVal.IndexOf('\n');
  7086. if (crIdx != -1)
  7087. {
  7088. crIdx = (int)itemRetVal.IndexOf('\n', crIdx + 1);
  7089. if (crIdx != -1)
  7090. retVal += itemRetVal.Substring(crIdx);
  7091. }
  7092. }
  7093. }
  7094. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Array)
  7095. {
  7096. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7097. Array<int> lowerDimSizes;
  7098. for (auto lowerDim : debugVis->mLowerDimSizes)
  7099. {
  7100. DbgTypedValue lowerDimValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(lowerDim, dbgVisWildcardCaptures), &formatInfo);
  7101. int dimSize = 0;
  7102. if ((lowerDimValue) && (lowerDimValue.mType->IsInteger()))
  7103. dimSize = (int)lowerDimValue.GetInt64();
  7104. dimSize = BF_MAX(dimSize, 1);
  7105. lowerDimSizes.push_back(dimSize);
  7106. }
  7107. if ((sizeValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7108. {
  7109. if (!debugVis->mCondition.IsEmpty())
  7110. {
  7111. int size = (int)sizeValue.GetInt64();
  7112. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7113. DbgTypedValue curNode = headPointer;
  7114. Array<addr_target> parentList;
  7115. String continuationData;
  7116. int totalSize = 2;
  7117. auto valueType = headPointer.mType;
  7118. String addrs = GetArrayItems(dbgCompileUnit, debugVis, valueType, headPointer, totalSize, &continuationData);
  7119. String firstAddr;
  7120. String secondAddr;
  7121. bool hasSecondAddr = valueType == NULL;
  7122. if (addrs.length() > 0)
  7123. {
  7124. const char* addrsPtr = addrs.c_str();
  7125. firstAddr = addrs.Substring(0, sizeof(addr_target) * 2);
  7126. if (hasSecondAddr)
  7127. secondAddr = addrs.Substring(sizeof(addr_target) * 2, sizeof(addr_target) * 2);
  7128. }
  7129. String evalStr;
  7130. if (valueType != NULL)
  7131. {
  7132. evalStr = "(" + valueType->ToStringRaw();
  7133. if (!valueType->IsPointer())
  7134. evalStr += "*";
  7135. evalStr += ")0x{1}";
  7136. }
  7137. else
  7138. {
  7139. evalStr += "({1})0x{2}";
  7140. }
  7141. if (!debugVis->mShowElementAddrs)
  7142. evalStr.Insert(0, "*");
  7143. if (addrs.length() > 0)
  7144. {
  7145. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7146. if (isReadOnly)
  7147. evalStr += ", ne";
  7148. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, BF_MAX(size, 0), 10000) +
  7149. "\t[{0}]\t" + evalStr + "\t" + firstAddr;
  7150. if (hasSecondAddr)
  7151. retVal += "\t" + secondAddr;
  7152. if (size != 0)
  7153. {
  7154. retVal += "\n:addrs\t" + addrs;
  7155. if (valueType == NULL)
  7156. retVal += "\n:addrsEntrySize\t2";
  7157. if (continuationData.length() > 0)
  7158. retVal += "\n:continuation\t" + continuationData;
  7159. }
  7160. }
  7161. }
  7162. else if (lowerDimSizes.size() == 1)
  7163. {
  7164. int dimSize1 = lowerDimSizes[0];
  7165. String evalStr = "(" + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7166. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7167. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7168. if (isReadOnly)
  7169. evalStr += ", ne";
  7170. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64() / dimSize1, 50000) +
  7171. "\t[{0}]\t" + evalStr;
  7172. }
  7173. else if (lowerDimSizes.size() == 2)
  7174. {
  7175. int dimSize1 = lowerDimSizes[0];
  7176. int dimSize2 = lowerDimSizes[1];
  7177. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7178. if ((headPointer.mType != NULL) && (headPointer.mType->IsPointer()))
  7179. {
  7180. String evalStr = StrFormat("((%s[%d]*)", headPointer.mType->mTypeParam->ToStringRaw(language).c_str(), dimSize2) + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7181. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7182. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7183. if (isReadOnly)
  7184. evalStr += ", ne";
  7185. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64() / dimSize1 / dimSize2, 50000) +
  7186. "\t[{0}]\t" + evalStr;
  7187. }
  7188. }
  7189. else if (lowerDimSizes.size() == 3)
  7190. {
  7191. int dimSize1 = lowerDimSizes[0];
  7192. int dimSize2 = lowerDimSizes[1];
  7193. int dimSize3 = lowerDimSizes[2];
  7194. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7195. if ((headPointer.mType != NULL) && (headPointer.mType->IsPointer()))
  7196. {
  7197. String evalStr = StrFormat("((%s[%d][%d]*)", headPointer.mType->mTypeParam->ToStringRaw(language).c_str(), dimSize2, dimSize3) + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7198. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7199. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7200. if (isReadOnly)
  7201. evalStr += ", ne";
  7202. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64() / dimSize1 / dimSize2 / dimSize3, 50000) +
  7203. "\t[{0}]\t" + evalStr;
  7204. }
  7205. }
  7206. else
  7207. {
  7208. String evalStr = "*(" + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) + " + {0}), this=" + ptrUseDataStr;
  7209. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7210. if (isReadOnly)
  7211. evalStr += ", ne";
  7212. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64(), 50000) +
  7213. "\t[{0}]\t" + evalStr;
  7214. }
  7215. }
  7216. }
  7217. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_IndexItems)
  7218. {
  7219. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7220. if ((sizeValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7221. {
  7222. String evalStr = debugVis->mValuePointer + ", this=" + ptrUseDataStr;
  7223. evalStr.Replace("$i", "{0}");
  7224. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7225. if (isReadOnly)
  7226. evalStr += ", ne";
  7227. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64(), 50000) +
  7228. "\t[{0}]\t" + evalStr;
  7229. }
  7230. }
  7231. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_LinkedList)
  7232. {
  7233. DbgType* valueType = NULL;
  7234. if (!debugVis->mValueType.empty())
  7235. {
  7236. valueType = dbgModule->FindType(debugVisualizers->DoStringReplace(debugVis->mValueType, dbgVisWildcardCaptures), dwValueType);
  7237. if (valueType != NULL)
  7238. valueType = valueType->ResolveTypeDef();
  7239. }
  7240. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mHeadPointer, dbgVisWildcardCaptures), &formatInfo);
  7241. if (headPointer)
  7242. {
  7243. DbgTypedValue endPointer;
  7244. if (!debugVis->mEndPointer.empty())
  7245. endPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mEndPointer, dbgVisWildcardCaptures), &formatInfo);
  7246. DbgTypedValue nextPointer = EvaluateInContext(dbgCompileUnit, headPointer, debugVisualizers->DoStringReplace(debugVis->mNextPointer, dbgVisWildcardCaptures), &formatInfo);
  7247. int size = -1;
  7248. if (!debugVis->mSize.empty())
  7249. {
  7250. auto sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7251. if (sizeValue)
  7252. size = (int)sizeValue.GetInt64();
  7253. }
  7254. DbgTypedValue curNode = headPointer;
  7255. Array<addr_target> parentList;
  7256. String continuationData;
  7257. int totalSize = 2;
  7258. String addrs = GetLinkedListItems(dbgCompileUnit, debugVis, endPointer.mPtr, valueType, curNode, totalSize, &continuationData);
  7259. String firstAddr;
  7260. String secondAddr;
  7261. bool hasSecondAddr = valueType == NULL;
  7262. if (addrs.length() > 0)
  7263. {
  7264. const char* addrsPtr = addrs.c_str();
  7265. firstAddr = addrs.Substring(0, sizeof(addr_target)*2);
  7266. if (hasSecondAddr)
  7267. secondAddr = addrs.Substring(sizeof(addr_target)*2, sizeof(addr_target)*2);
  7268. }
  7269. String evalStr;
  7270. if (valueType != NULL)
  7271. {
  7272. evalStr = "(" + valueType->ToStringRaw();
  7273. if (!valueType->IsPointer())
  7274. evalStr += "*";
  7275. evalStr += ")0x{1}";
  7276. }
  7277. else
  7278. {
  7279. evalStr += "({1})0x{2}";
  7280. }
  7281. if (!debugVis->mShowElementAddrs)
  7282. evalStr.Insert(0, "*");
  7283. if (addrs.length() > 0)
  7284. {
  7285. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7286. if (isReadOnly)
  7287. evalStr += ", ne";
  7288. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, size, 10000) +
  7289. "\t[{0}]\t" + evalStr + "\t" + firstAddr;
  7290. if (hasSecondAddr)
  7291. retVal += "\t" + secondAddr;
  7292. if (size != 0)
  7293. {
  7294. retVal += "\n:addrs\t" + addrs;
  7295. if (valueType == NULL)
  7296. retVal += "\n:addrsEntrySize\t2";
  7297. if (continuationData.length() > 0)
  7298. retVal += "\n:continuation\t" + continuationData;
  7299. }
  7300. }
  7301. }
  7302. }
  7303. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_TreeItems)
  7304. {
  7305. DbgType* valueType = NULL;
  7306. if (!debugVis->mValueType.empty())
  7307. {
  7308. valueType = dbgModule->FindType(debugVisualizers->DoStringReplace(debugVis->mValueType, dbgVisWildcardCaptures), dwValueType);
  7309. if (valueType != NULL)
  7310. valueType = valueType->ResolveTypeDef();
  7311. }
  7312. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7313. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mHeadPointer, dbgVisWildcardCaptures), &formatInfo);
  7314. if (sizeValue)
  7315. sizeValue.mType = sizeValue.mType->RemoveModifiers();
  7316. if ((sizeValue) && (headPointer) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7317. {
  7318. DbgTypedValue curNode = headPointer;
  7319. Array<addr_target> parentList;
  7320. String continuationData;
  7321. int getItemCount = (int)BF_MIN(sizeValue.GetInt64(), 32LL);
  7322. String addrs = GetTreeItems(dbgCompileUnit, debugVis, parentList, valueType, curNode, getItemCount, &continuationData);
  7323. addr_target firstAddr = 0;
  7324. addr_target secondAddr = 0;
  7325. bool hasSecondAddr = valueType == NULL;
  7326. if (addrs.length() > 0)
  7327. {
  7328. const char* addrsPtr = addrs.c_str();
  7329. firstAddr = DecodeTargetDataPtr(addrsPtr);
  7330. if (hasSecondAddr)
  7331. secondAddr = DecodeTargetDataPtr(addrsPtr);
  7332. }
  7333. String evalStr;
  7334. if (valueType != NULL)
  7335. {
  7336. evalStr = "*(" + valueType->ToStringRaw();
  7337. if (!valueType->IsPointer())
  7338. evalStr += "*";
  7339. evalStr += ")0x{1}";
  7340. }
  7341. else
  7342. {
  7343. evalStr += "*(_T_{1}*)0x{2}";
  7344. }
  7345. int size = (int)sizeValue.GetInt64();
  7346. if (addrs.length() == 0)
  7347. {
  7348. evalStr = ""; // Failed
  7349. }
  7350. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7351. if (isReadOnly)
  7352. evalStr += ", ne";
  7353. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, size, 10000) +
  7354. "\t[{0}]\t" + evalStr + "\t" + EncodeDataPtr(firstAddr, false);
  7355. if (hasSecondAddr)
  7356. retVal += "\t" + EncodeDataPtr(secondAddr, false);
  7357. if (addrs.length() > 0)
  7358. {
  7359. retVal += "\n:addrs\t" + addrs;
  7360. if (continuationData.length() > 0)
  7361. retVal += "\n:continuation\t" + continuationData;
  7362. }
  7363. }
  7364. }
  7365. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Dictionary)
  7366. {
  7367. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7368. DbgTypedValue entriesPtrValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mEntries, dbgVisWildcardCaptures), &formatInfo);
  7369. if (sizeValue)
  7370. sizeValue.mType = sizeValue.mType->RemoveModifiers();
  7371. if ((sizeValue) && (entriesPtrValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7372. {
  7373. String continuationData;
  7374. DbgType* valueType = entriesPtrValue.mType;
  7375. int getItemCount = (int)std::min(sizeValue.GetInt64(), 2LL);
  7376. DbgType* useTypedValType = useTypedValue.mType;
  7377. addr_target useTypedValPtr = useTypedValue.mPtr;
  7378. addr_target useTypedValAddr = useTypedValue.mSrcAddress;
  7379. String addrs = GetDictionaryItems(dbgCompileUnit, debugVis, useTypedValue, 0, -1, getItemCount, &continuationData);
  7380. addr_target firstAddr = 0;
  7381. if (addrs.length() > 0)
  7382. {
  7383. const char* addrsPtr = addrs.c_str();
  7384. firstAddr = DecodeTargetDataPtr(addrsPtr);
  7385. }
  7386. String evalStr = "((" + valueType->ToStringRaw() + ")0x{1}), na";
  7387. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7388. if (isReadOnly)
  7389. evalStr += ", ne";
  7390. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64(), 10000) +
  7391. "\t[{0}]\t" + evalStr + "\t" + EncodeDataPtr(firstAddr, false);
  7392. if (addrs.length() > 0)
  7393. {
  7394. retVal += "\n:addrs\t" + addrs;
  7395. if (continuationData.length() > 0)
  7396. retVal += "\n:continuation\t" + continuationData;
  7397. }
  7398. }
  7399. }
  7400. if (formatInfo.mExpandItemDepth == 0)
  7401. {
  7402. //retVal += "\n[Raw View]\tthis, this=" + ptrDataStr + ", nv";
  7403. retVal += "\n[Raw View]\t" + ptrDataStr + ", nv";
  7404. }
  7405. }
  7406. bool WinDebugger::IsPaused()
  7407. {
  7408. return (mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint) || (mRunState == RunState_Exception) || (mRunState == RunState_DebugEval_Done);
  7409. }
  7410. DbgTypedValue WinDebugger::GetRegister(const StringImpl& regName, DbgLanguage language, CPURegisters* registers, Array<RegForm>* regForms)
  7411. {
  7412. int regNum = -1;
  7413. String lwrRegName(regName);
  7414. _strlwr((char*)lwrRegName.c_str());
  7415. // int regs
  7416. #ifdef BF_DBG_32
  7417. DbgTypeCode regType = DbgType_i32;
  7418. if (lwrRegName == "eax")
  7419. regNum = X86Reg_EAX;
  7420. else if (lwrRegName == "ecx")
  7421. regNum = X86Reg_ECX;
  7422. else if (lwrRegName == "edx")
  7423. regNum = X86Reg_EDX;
  7424. else if (lwrRegName == "ebx")
  7425. regNum = X86Reg_EBX;
  7426. else if (lwrRegName == "esp")
  7427. regNum = X86Reg_ESP;
  7428. else if (lwrRegName == "ebp")
  7429. regNum = X86Reg_EBP;
  7430. else if (lwrRegName == "esi")
  7431. regNum = X86Reg_ESI;
  7432. else if (lwrRegName == "edi")
  7433. regNum = X86Reg_EDI;
  7434. else if (lwrRegName == "eip")
  7435. regNum = X86Reg_EIP;
  7436. else if (lwrRegName == "efl")
  7437. regNum = X86Reg_EFL;
  7438. #else
  7439. DbgTypeCode regType = DbgType_i64;
  7440. if (lwrRegName == "rax")
  7441. regNum = X64Reg_RAX;
  7442. else if (lwrRegName == "rcx")
  7443. regNum = X64Reg_RCX;
  7444. else if (lwrRegName == "rdx")
  7445. regNum = X64Reg_RDX;
  7446. else if (lwrRegName == "rbx")
  7447. regNum = X64Reg_RBX;
  7448. else if (lwrRegName == "rsp")
  7449. regNum = X64Reg_RSP;
  7450. else if (lwrRegName == "rbp")
  7451. regNum = X64Reg_RBP;
  7452. else if (lwrRegName == "rsi")
  7453. regNum = X64Reg_RSI;
  7454. else if (lwrRegName == "rdi")
  7455. regNum = X64Reg_RDI;
  7456. else if (lwrRegName == "rip")
  7457. regNum = X64Reg_RIP;
  7458. else if (lwrRegName == "r8")
  7459. regNum = X64Reg_R8;
  7460. else if (lwrRegName == "r9")
  7461. regNum = X64Reg_R9;
  7462. else if (lwrRegName == "r10")
  7463. regNum = X64Reg_R10;
  7464. else if (lwrRegName == "r11")
  7465. regNum = X64Reg_R11;
  7466. else if (lwrRegName == "r12")
  7467. regNum = X64Reg_R12;
  7468. else if (lwrRegName == "r13")
  7469. regNum = X64Reg_R13;
  7470. else if (lwrRegName == "r14")
  7471. regNum = X64Reg_R14;
  7472. else if (lwrRegName == "r15")
  7473. regNum = X64Reg_R15;
  7474. else
  7475. {
  7476. regType = DbgType_i32;
  7477. if (lwrRegName == "eax")
  7478. regNum = X64Reg_RAX;
  7479. else if (lwrRegName == "ecx")
  7480. regNum = X64Reg_RCX;
  7481. else if (lwrRegName == "edx")
  7482. regNum = X64Reg_RDX;
  7483. else if (lwrRegName == "ebx")
  7484. regNum = X64Reg_RBX;
  7485. else if (lwrRegName == "efl")
  7486. regNum = X64Reg_EFL;
  7487. else if (lwrRegName == "esi")
  7488. regNum = X64Reg_RSI;
  7489. else if (lwrRegName == "edi")
  7490. regNum = X64Reg_RDI;
  7491. else if (lwrRegName == "r8d")
  7492. regNum = X64Reg_R8;
  7493. else if (lwrRegName == "r9d")
  7494. regNum = X64Reg_R9;
  7495. else if (lwrRegName == "r10d")
  7496. regNum = X64Reg_R10;
  7497. else if (lwrRegName == "r11d")
  7498. regNum = X64Reg_R11;
  7499. else if (lwrRegName == "r12d")
  7500. regNum = X64Reg_R12;
  7501. else if (lwrRegName == "r13d")
  7502. regNum = X64Reg_R13;
  7503. else if (lwrRegName == "r14d")
  7504. regNum = X64Reg_R14;
  7505. else if (lwrRegName == "r15d")
  7506. regNum = X64Reg_R15;
  7507. else
  7508. {
  7509. regType = DbgType_i16;
  7510. if (lwrRegName == "ax")
  7511. regNum = X64Reg_RAX;
  7512. else if (lwrRegName == "cx")
  7513. regNum = X64Reg_RCX;
  7514. else if (lwrRegName == "dx")
  7515. regNum = X64Reg_RDX;
  7516. else if (lwrRegName == "bx")
  7517. regNum = X64Reg_RBX;
  7518. else if (lwrRegName == "si")
  7519. regNum = X64Reg_RSI;
  7520. else if (lwrRegName == "di")
  7521. regNum = X64Reg_RDI;
  7522. else if (lwrRegName == "r8w")
  7523. regNum = X64Reg_R8;
  7524. else if (lwrRegName == "r9w")
  7525. regNum = X64Reg_R9;
  7526. else if (lwrRegName == "r10w")
  7527. regNum = X64Reg_R10;
  7528. else if (lwrRegName == "r11w")
  7529. regNum = X64Reg_R11;
  7530. else if (lwrRegName == "r12w")
  7531. regNum = X64Reg_R12;
  7532. else if (lwrRegName == "r13w")
  7533. regNum = X64Reg_R13;
  7534. else if (lwrRegName == "r14w")
  7535. regNum = X64Reg_R14;
  7536. else if (lwrRegName == "r15w")
  7537. regNum = X64Reg_R15;
  7538. else
  7539. {
  7540. regType = DbgType_i8;
  7541. if (lwrRegName == "al")
  7542. regNum = X64Reg_RAX;
  7543. else if (lwrRegName == "cl")
  7544. regNum = X64Reg_RCX;
  7545. else if (lwrRegName == "dl")
  7546. regNum = X64Reg_RDX;
  7547. else if (lwrRegName == "bl")
  7548. regNum = X64Reg_RBX;
  7549. else if (lwrRegName == "sil")
  7550. regNum = X64Reg_RSI;
  7551. else if (lwrRegName == "dil")
  7552. regNum = X64Reg_RDI;
  7553. else if (lwrRegName == "r8b")
  7554. regNum = X64Reg_R8;
  7555. else if (lwrRegName == "r9b")
  7556. regNum = X64Reg_R9;
  7557. else if (lwrRegName == "r10b")
  7558. regNum = X64Reg_R10;
  7559. else if (lwrRegName == "r11b")
  7560. regNum = X64Reg_R11;
  7561. else if (lwrRegName == "r12b")
  7562. regNum = X64Reg_R12;
  7563. else if (lwrRegName == "r13b")
  7564. regNum = X64Reg_R13;
  7565. else if (lwrRegName == "r14b")
  7566. regNum = X64Reg_R14;
  7567. else if (lwrRegName == "r15b")
  7568. regNum = X64Reg_R15;
  7569. }
  7570. }
  7571. }
  7572. #endif
  7573. auto dbgModule = mDebugTarget->GetMainDbgModule();
  7574. if (regNum != -1)
  7575. {
  7576. DbgTypedValue typedVal;
  7577. typedVal.mType = dbgModule->GetPrimitiveType(regType, language);
  7578. typedVal.mInt64 = registers->mIntRegsArray[regNum];
  7579. typedVal.mRegNum = regNum;
  7580. return typedVal;
  7581. }
  7582. // st regs
  7583. if ((lwrRegName.length() == 3) && (lwrRegName[0] == 's') && (lwrRegName[1] == 't') && (lwrRegName[2] >= '0') && (lwrRegName[2] <= '7'))
  7584. {
  7585. regNum = CPUReg_FPSTREG_FIRST + (lwrRegName[2] - '0');
  7586. }
  7587. if (regNum != -1)
  7588. {
  7589. DbgTypedValue typedVal;
  7590. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Double, language);
  7591. typedVal.mDouble = ConvertFloat80ToDouble(registers->mFpMmRegsArray[regNum - CPUReg_FPSTREG_FIRST].fp.fp80);
  7592. typedVal.mRegNum = regNum;
  7593. return typedVal;
  7594. }
  7595. // mm regs
  7596. if ((lwrRegName.length() == 3) && (lwrRegName[0] == 'm') && (lwrRegName[1] == 'm') && (lwrRegName[2] >= '0') && (lwrRegName[2] <= '7'))
  7597. {
  7598. regNum = CPUReg_MMREG_FIRST + (lwrRegName[2] - '0');
  7599. }
  7600. if (regNum != -1)
  7601. {
  7602. DbgTypedValue typedVal;
  7603. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_i64, language);
  7604. typedVal.mInt64 = registers->mFpMmRegsArray[regNum - CPUReg_MMREG_FIRST].mm;
  7605. typedVal.mRegNum = regNum;
  7606. return typedVal;
  7607. }
  7608. // xmm regs
  7609. #ifdef BF_DBG_32
  7610. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '7') &&
  7611. (lwrRegName[4] == '_') && (lwrRegName[5] >= '0') && (lwrRegName[5] <= '3'))
  7612. {
  7613. regNum = CPUReg_XMMREG_FIRST + ((lwrRegName[3] - '0') * 4) + (lwrRegName[5] - '0');
  7614. }
  7615. #else
  7616. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '9') &&
  7617. (lwrRegName[4] == '_') && (lwrRegName[5] >= '0') && (lwrRegName[5] <= '3'))
  7618. {
  7619. regNum = CPUReg_XMMREG_FIRST + ((lwrRegName[3] - '0') * 4) + (lwrRegName[5] - '0');
  7620. }
  7621. if ((lwrRegName.length() == 7) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] == '1') && (lwrRegName[4] >= '0') && (lwrRegName[4] <= '9') &&
  7622. (lwrRegName[5] == '_') && (lwrRegName[6] >= '0') && (lwrRegName[6] <= '3'))
  7623. {
  7624. regNum = CPUReg_XMMREG_FIRST + ((10 + (lwrRegName[4] - '0')) * 4) + (lwrRegName[6] - '0');
  7625. }
  7626. #endif
  7627. if (regNum != -1)
  7628. {
  7629. int xmmMajor = (regNum - CPUReg_XMMREG_FIRST) >> 2;
  7630. int xmmMinor = (regNum - CPUReg_XMMREG_FIRST) & 3;
  7631. DwMmDisplayType mmDisplayType = GetDisplayInfo(StrFormat("$XMM%d", xmmMajor))->mMmDisplayType;
  7632. RegForm regForm = RegForm_Unknown;
  7633. if (regForms != NULL)
  7634. {
  7635. int regFormIdx = CPUReg_M128_XMMREG_FIRST + xmmMajor;
  7636. if (regFormIdx < (int)regForms->size())
  7637. regForm = (*regForms)[regFormIdx];
  7638. }
  7639. if (mmDisplayType == DwMmDisplayType_Default)
  7640. {
  7641. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2))
  7642. mmDisplayType = DwMmDisplayType_Double;
  7643. else if (regForm == RegForm_Int4)
  7644. mmDisplayType = DwMmDisplayType_Int;
  7645. }
  7646. //TODO: Add int types
  7647. if (mmDisplayType == DwMmDisplayType_Double)
  7648. {
  7649. DbgTypedValue typedVal;
  7650. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Double, language);
  7651. typedVal.mDouble = registers->mXmmDRegsArray[xmmMajor].d[xmmMinor];
  7652. typedVal.mRegNum = regNum;
  7653. return typedVal;
  7654. }
  7655. if (mmDisplayType == DwMmDisplayType_Int)
  7656. {
  7657. DbgTypedValue typedVal;
  7658. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_i32, language);
  7659. typedVal.mInt32 = registers->mXmmIRegsARray[xmmMajor].i[xmmMinor];
  7660. typedVal.mRegNum = regNum;
  7661. return typedVal;
  7662. }
  7663. DbgTypedValue typedVal;
  7664. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Single, language);
  7665. typedVal.mSingle = registers->mXmmRegsArray[xmmMajor].f[xmmMinor];
  7666. typedVal.mRegNum = regNum;
  7667. return typedVal;
  7668. }
  7669. #ifdef BF_DBG_32
  7670. if ((lwrRegName.length() == 4) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '7'))
  7671. {
  7672. regNum = CPUReg_M128_XMMREG_FIRST + (lwrRegName[3] - '0');
  7673. }
  7674. #else
  7675. if ((lwrRegName.length() == 4) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '9'))
  7676. {
  7677. regNum = CPUReg_M128_XMMREG_FIRST + (lwrRegName[3] - '0');
  7678. }
  7679. if ((lwrRegName.length() == 5) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] == '1') && (lwrRegName[4] >= '0') && (lwrRegName[4] <= '5'))
  7680. {
  7681. regNum = CPUReg_M128_XMMREG_FIRST + 10 + (lwrRegName[4] - '0');
  7682. }
  7683. #endif
  7684. if (regNum != -1)
  7685. {
  7686. DbgTypedValue typedVal;
  7687. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_RegGroup, language);
  7688. 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)
  7689. typedVal.mRegNum = regNum;
  7690. return typedVal;
  7691. }
  7692. // flags
  7693. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'f') && (lwrRegName[1] == 'l') && (lwrRegName[2] == 'a') && (lwrRegName[3] == 'g') && (lwrRegName[5] == 'f'))
  7694. {
  7695. switch(lwrRegName[4])
  7696. {
  7697. case 'c': regNum = CPUReg_FLAG_CF_CARRY; break;
  7698. case 'p': regNum = CPUReg_FLAG_PF_PARITY; break;
  7699. case 'a': regNum = CPUReg_FLAG_AF_ADJUST; break;
  7700. case 'z': regNum = CPUReg_FLAG_ZF_ZERO; break;
  7701. case 's': regNum = CPUReg_FLAG_SF_SIGN; break;
  7702. case 'i': regNum = CPUReg_FLAG_IF_INTERRUPT; break;
  7703. case 'd': regNum = CPUReg_FLAG_DF_DIRECTION; break;
  7704. case 'o': regNum = CPUReg_FLAG_OF_OVERFLOW; break;
  7705. default: break;
  7706. }
  7707. }
  7708. if (regNum != -1)
  7709. {
  7710. int flagBit = CPURegisters::GetFlagBitForRegister(regNum);
  7711. BF_ASSERT(flagBit >= 0);
  7712. DbgTypedValue typedVal;
  7713. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Bool, language);
  7714. typedVal.mBool = (registers->mIntRegs.efl & ((uint64)1 << flagBit)) != 0;
  7715. typedVal.mRegNum = regNum;
  7716. return typedVal;
  7717. }
  7718. // categories
  7719. if (lwrRegName == "allregs")
  7720. regNum = CPUReg_CAT_ALLREGS;
  7721. else if (lwrRegName == "iregs")
  7722. regNum = CPUReg_CAT_IREGS;
  7723. else if (lwrRegName == "fpregs")
  7724. regNum = CPUReg_CAT_FPREGS;
  7725. else if (lwrRegName == "mmregs")
  7726. regNum = CPUReg_CAT_MMREGS;
  7727. else if (lwrRegName == "xmmregs")
  7728. regNum = CPUReg_CAT_XMMREGS;
  7729. else if (lwrRegName == "flags")
  7730. regNum = CPUReg_CAT_FLAGS;
  7731. if (regNum != -1)
  7732. {
  7733. DbgTypedValue typedVal;
  7734. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_RegGroup, language);
  7735. 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)
  7736. typedVal.mRegNum = regNum;
  7737. return typedVal;
  7738. }
  7739. return DbgTypedValue();
  7740. }
  7741. DbgModule* WinDebugger::GetCallStackDbgModule(int callStackIdx)
  7742. {
  7743. if ((mRunState == RunState_NotStarted) || (!IsPaused()))
  7744. return mEmptyDebugTarget->GetMainDbgModule();
  7745. if (callStackIdx == -1)
  7746. return mDebugTarget->GetMainDbgModule();
  7747. FixCallStackIdx(callStackIdx);
  7748. if (callStackIdx >= mCallStack.size())
  7749. return mDebugTarget->GetMainDbgModule();
  7750. UpdateCallStackMethod(callStackIdx);
  7751. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  7752. if (subProgram != NULL)
  7753. return subProgram->mCompileUnit->mDbgModule;
  7754. auto dbgModule = mDebugTarget->FindDbgModuleForAddress(mCallStack[callStackIdx]->mRegisters.GetPC());
  7755. if (dbgModule != NULL)
  7756. return dbgModule;
  7757. return mDebugTarget->GetMainDbgModule();
  7758. }
  7759. DbgSubprogram* WinDebugger::GetCallStackSubprogram(int callStackIdx)
  7760. {
  7761. if ((IsInRunState()) || (mRunState == RunState_NotStarted) || (callStackIdx == -1))
  7762. return NULL;
  7763. if (callStackIdx >= (int)mCallStack.size())
  7764. UpdateCallStack();
  7765. if (mCallStack.IsEmpty())
  7766. return NULL;
  7767. if (callStackIdx >= (int)mCallStack.size())
  7768. callStackIdx = 0;
  7769. UpdateCallStackMethod(callStackIdx);
  7770. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  7771. return subProgram;
  7772. }
  7773. DbgCompileUnit* WinDebugger::GetCallStackCompileUnit(int callStackIdx)
  7774. {
  7775. if ((IsInRunState()) || (mRunState == RunState_NotStarted) || (callStackIdx == -1))
  7776. return NULL;
  7777. if (callStackIdx >= (int)mCallStack.size())
  7778. UpdateCallStack();
  7779. if (mCallStack.IsEmpty())
  7780. return NULL;
  7781. if (callStackIdx >= (int)mCallStack.size())
  7782. callStackIdx = 0;
  7783. UpdateCallStackMethod(callStackIdx);
  7784. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  7785. if (subProgram == NULL)
  7786. return NULL;
  7787. return subProgram->mCompileUnit;
  7788. }
  7789. String WinDebugger::EvaluateContinue(DbgPendingExpr* pendingExpr, BfPassInstance& bfPassInstance)
  7790. {
  7791. DbgModule* dbgModule = NULL;
  7792. DbgCompileUnit* dbgCompileUnit = NULL;
  7793. if (pendingExpr->mThreadId == -1)
  7794. {
  7795. if ((pendingExpr->mFormatInfo.mLanguage == DbgLanguage_Beef) && (mDebugTarget != NULL) && (mDebugTarget->mTargetBinary != NULL))
  7796. dbgModule = mDebugTarget->mTargetBinary;
  7797. else
  7798. dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  7799. }
  7800. else
  7801. {
  7802. dbgModule = GetCallStackDbgModule(pendingExpr->mCallStackIdx);
  7803. if ((dbgModule != NULL) &&(!dbgModule->mDebugTarget->mIsEmpty))
  7804. dbgCompileUnit = GetCallStackCompileUnit(pendingExpr->mCallStackIdx);
  7805. }
  7806. if (dbgModule == NULL)
  7807. dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  7808. if (!pendingExpr->mException.empty())
  7809. {
  7810. RestoreAllRegisters();
  7811. return "!" + pendingExpr->mException;
  7812. }
  7813. DwAutoComplete autoComplete;
  7814. if (bfPassInstance.HasFailed())
  7815. {
  7816. // Don't allow pending calls if we've already failed in the calling Evaluate()
  7817. pendingExpr->mExpressionFlags = (DwEvalExpressionFlags)(pendingExpr->mExpressionFlags & ~DwEvalExpressionFlag_AllowCalls);
  7818. }
  7819. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, pendingExpr->mCallStackIdx, pendingExpr->mCursorPos);
  7820. dbgExprEvaluator.mLanguage = pendingExpr->mFormatInfo.mLanguage;
  7821. dbgExprEvaluator.mReferenceId = &pendingExpr->mReferenceId;
  7822. dbgExprEvaluator.mExpressionFlags = pendingExpr->mExpressionFlags;
  7823. dbgExprEvaluator.mExplicitThis = pendingExpr->mFormatInfo.mExplicitThis;
  7824. dbgExprEvaluator.mSubjectExpr = pendingExpr->mFormatInfo.mSubjectExpr;
  7825. dbgExprEvaluator.mNamespaceSearchStr = pendingExpr->mFormatInfo.mNamespaceSearch;
  7826. dbgExprEvaluator.mExpectingTypeName = pendingExpr->mFormatInfo.mExpectedType;
  7827. dbgExprEvaluator.mCallResults = &pendingExpr->mCallResults;
  7828. if ((pendingExpr->mExpressionFlags & DwEvalExpressionFlag_ValidateOnly) != 0)
  7829. {
  7830. dbgExprEvaluator.mValidateOnly = true;
  7831. }
  7832. if (pendingExpr->mCursorPos != -1)
  7833. {
  7834. dbgExprEvaluator.mAutoComplete = &autoComplete;
  7835. }
  7836. dbgExprEvaluator.mDbgCompileUnit = dbgCompileUnit;
  7837. DbgTypedValue exprResult;
  7838. if (pendingExpr->mExplitType != NULL)
  7839. {
  7840. exprResult.mHasNoValue = true;
  7841. exprResult.mType = pendingExpr->mExplitType;
  7842. }
  7843. else if (pendingExpr->mExprNode != NULL)
  7844. {
  7845. exprResult = dbgExprEvaluator.Resolve(pendingExpr->mExprNode);
  7846. }
  7847. if (dbgExprEvaluator.mCreatedPendingCall)
  7848. {
  7849. BF_ASSERT(mRunState == RunState_DebugEval);
  7850. //ContinueDebugEvent();
  7851. return "!pending";
  7852. }
  7853. if (dbgExprEvaluator.mCountResultOverride != -1)
  7854. pendingExpr->mFormatInfo.mOverrideCount = dbgExprEvaluator.mCountResultOverride;
  7855. String val;
  7856. if (bfPassInstance.HasFailed())
  7857. {
  7858. BfLogDbgExpr("Evaluate Failed: %s\n", bfPassInstance.mErrors[0]->mError.c_str());
  7859. val = StrFormat("!%d\t%d\t%s", bfPassInstance.mErrors[0]->GetSrcStart(), bfPassInstance.mErrors[0]->GetSrcLength(), bfPassInstance.mErrors[0]->mError.c_str());
  7860. }
  7861. else if (dbgExprEvaluator.mBlockedSideEffects)
  7862. {
  7863. BfLogDbgExpr("Evaluate blocked side effects\n");
  7864. val = "!sideeffects";
  7865. }
  7866. else if (!exprResult)
  7867. {
  7868. if (exprResult.mType != NULL)
  7869. {
  7870. BfLogDbgExpr("Evaluate success\n");
  7871. String typeName = exprResult.mType->ToString();
  7872. DbgType* rawType = exprResult.mType;
  7873. if (rawType->IsBfObjectPtr())
  7874. rawType = rawType->mTypeParam;
  7875. String typeNameRaw = rawType->ToStringRaw();
  7876. val = typeName + "\n" + typeName;
  7877. val += "\n" + GetMemberList(exprResult.mType, typeNameRaw, false, true, false, false, exprResult.mIsReadOnly);
  7878. if (exprResult.mType->mTypeCode == DbgType_Namespace)
  7879. {
  7880. val += "\n:type\tnamespace";
  7881. }
  7882. else
  7883. {
  7884. auto type = exprResult.mType;
  7885. if (type->IsPointer())
  7886. type = type->mTypeParam;
  7887. if (type->IsBfObject())
  7888. val += "\n:type\tclass";
  7889. else
  7890. val += "\n:type\tvaluetype";
  7891. }
  7892. if (!pendingExpr->mReferenceId.empty())
  7893. val += "\n:referenceId\t" + pendingExpr->mReferenceId;
  7894. }
  7895. else
  7896. val = "!";
  7897. }
  7898. else if ((pendingExpr->mExpressionFlags & (DwEvalExpressionFlag_MemoryAddress)) != 0)
  7899. {
  7900. DbgType* resultType = exprResult.mType->RemoveModifiers();
  7901. if ((resultType->IsInteger()) || (resultType->IsPointerOrRef()))
  7902. {
  7903. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", 0);
  7904. }
  7905. else
  7906. {
  7907. if (exprResult.mSrcAddress != 0)
  7908. val = StrFormat("!Type '%s' is invalid. A pointer or address value is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  7909. else
  7910. val = StrFormat("!Type '%s' is invalid. A pointer or address value is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  7911. }
  7912. }
  7913. else if ((pendingExpr->mExpressionFlags & (DwEvalExpressionFlag_MemoryWatch)) != 0)
  7914. {
  7915. DbgType* resultType = exprResult.mType->RemoveModifiers();
  7916. bool isMemoryWatch = (pendingExpr->mExpressionFlags & DwEvalExpressionFlag_MemoryWatch) != 0;
  7917. if (!resultType->IsPointerOrRef())
  7918. {
  7919. if (exprResult.mSrcAddress != 0)
  7920. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  7921. else
  7922. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  7923. }
  7924. else
  7925. {
  7926. auto innerType = resultType->mTypeParam;
  7927. int byteCount = innerType->GetByteCount();
  7928. if (pendingExpr->mFormatInfo.mArrayLength != -1)
  7929. byteCount *= pendingExpr->mFormatInfo.mArrayLength;
  7930. if (byteCount == 0)
  7931. {
  7932. 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());
  7933. }
  7934. #ifdef BF_DBG_32
  7935. else if ((isMemoryWatch) && (!IsMemoryBreakpointSizeValid(exprResult.mPtr, byteCount)))
  7936. {
  7937. if (innerType->mSize > 16)
  7938. 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);
  7939. else if (!IsMemoryBreakpointSizeValid(0, byteCount))
  7940. 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);
  7941. else
  7942. 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);
  7943. }
  7944. #else
  7945. else if ((isMemoryWatch) && (!IsMemoryBreakpointSizeValid(exprResult.mPtr, byteCount)))
  7946. {
  7947. if (innerType->mSize > 32)
  7948. 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);
  7949. else if (!IsMemoryBreakpointSizeValid(0, byteCount))
  7950. 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);
  7951. else
  7952. 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);
  7953. }
  7954. #endif
  7955. else
  7956. {
  7957. auto language = dbgExprEvaluator.GetLanguage();
  7958. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", byteCount) + "\n" + StrFormat("%d\t", language) + innerType->ToStringRaw(language);
  7959. }
  7960. }
  7961. }
  7962. else
  7963. {
  7964. if (pendingExpr->mFormatInfo.mNoEdit)
  7965. exprResult.mIsReadOnly = true;
  7966. if (!pendingExpr->mReferenceId.empty())
  7967. pendingExpr->mFormatInfo.mReferenceId = pendingExpr->mReferenceId;
  7968. val = DbgTypedValueToString(exprResult, pendingExpr->mExprNode->ToString(), pendingExpr->mFormatInfo, &dbgExprEvaluator, (pendingExpr->mExpressionFlags & DwEvalExpressionFlag_FullPrecision) != 0);
  7969. if ((!val.empty()) && (val[0] == '!'))
  7970. return val;
  7971. if (pendingExpr->mFormatInfo.mRawString)
  7972. return val;
  7973. if (exprResult.mIsLiteral)
  7974. val += "\n:literal";
  7975. if (bfPassInstance.HasMessages())
  7976. {
  7977. for (auto error : bfPassInstance.mErrors)
  7978. {
  7979. if (error->mIsWarning)
  7980. {
  7981. val += "\n:warn\t";
  7982. val += error->mError;
  7983. }
  7984. }
  7985. }
  7986. if (!pendingExpr->mFormatInfo.mReferenceId.empty())
  7987. val += "\n:referenceId\t" + pendingExpr->mFormatInfo.mReferenceId;
  7988. if ((exprResult.mSrcAddress != 0) && (HasMemoryBreakpoint(exprResult.mSrcAddress, exprResult.mType->GetByteCount())))
  7989. val += StrFormat("\n:break\t%@", exprResult.mSrcAddress);
  7990. auto checkType = exprResult.mType->RemoveModifiers();
  7991. if (checkType->IsBfObjectPtr())
  7992. val += "\n:type\tobject";
  7993. else if ((checkType->IsPointer()) || (checkType->mTypeCode == DbgType_Subroutine))
  7994. val += "\n:type\tpointer";
  7995. else if (checkType->IsInteger())
  7996. val += "\n:type\tint";
  7997. else if (checkType->IsFloat())
  7998. val += "\n:type\tfloat";
  7999. else if ((exprResult.mRegNum >= X64Reg_M128_XMM0) && (exprResult.mRegNum <= X64Reg_M128_XMM15))
  8000. val += "\n:type\tmm128";
  8001. else
  8002. val += "\n:type\tvaluetype";
  8003. if ((pendingExpr->mFormatInfo.mTypeKindFlags & DbgTypeKindFlag_Int) != 0)
  8004. val += "\n:type\tint";
  8005. if (dbgExprEvaluator.mHadSideEffects)
  8006. val += "\n:sideeffects";
  8007. auto underlyingType = exprResult.mType->RemoveModifiers();
  8008. bool canEdit = true;
  8009. if (pendingExpr->mFormatInfo.mLanguage == DbgLanguage_Beef)
  8010. {
  8011. if (exprResult.mType->IsConst())
  8012. canEdit = false;
  8013. }
  8014. if (pendingExpr->mFormatInfo.mNoEdit)
  8015. canEdit = false;
  8016. if (exprResult.mIsReadOnly)
  8017. canEdit = false;
  8018. if (val[0] == '!')
  8019. {
  8020. // Already has an error embedded, can't edit
  8021. }
  8022. else if ((exprResult.mSrcAddress != 0) && (underlyingType->mTypeCode >= DbgType_i8) && (underlyingType->mTypeCode <= DbgType_Ptr) &&
  8023. (underlyingType->mTypeCode != DbgType_Class) && (underlyingType->mTypeCode != DbgType_Struct))
  8024. {
  8025. if (canEdit)
  8026. val += "\n:canEdit";
  8027. if (exprResult.mType->mTypeCode == DbgType_Ptr)
  8028. {
  8029. val += "\n:editVal\t" + EncodeDataPtr(exprResult.mPtr, true);
  8030. }
  8031. }
  8032. else if ((underlyingType->IsStruct()) && (exprResult.mSrcAddress != 0) && (underlyingType->IsTypedPrimitive()))
  8033. {
  8034. auto primType = underlyingType->GetRootBaseType();
  8035. DbgTypedValue primVal = dbgExprEvaluator.ReadTypedValue(NULL, primType, exprResult.mSrcAddress, DbgAddrType_Target);
  8036. String primResult = DbgTypedValueToString(primVal, "", pendingExpr->mFormatInfo, NULL);
  8037. int crPos = (int)primResult.IndexOf('\n');
  8038. if (crPos != -1)
  8039. primResult.RemoveToEnd(crPos);
  8040. if (canEdit)
  8041. val += "\n:canEdit";
  8042. val += "\n:editVal\t" + primResult;
  8043. }
  8044. else if (exprResult.mRegNum >= 0)
  8045. {
  8046. bool isPseudoReg = ( ((exprResult.mRegNum >= X86Reg_M128_XMMREG_FIRST) && (exprResult.mRegNum <= X86Reg_M128_XMMREG_LAST))
  8047. || ((exprResult.mRegNum >= X86Reg_CAT_FIRST) && (exprResult.mRegNum <= X86Reg_CAT_LAST)) );
  8048. if (!isPseudoReg)
  8049. {
  8050. if (canEdit)
  8051. val += "\n:canEdit";
  8052. }
  8053. }
  8054. }
  8055. if (pendingExpr->mFormatInfo.mRawString)
  8056. return "";
  8057. if (pendingExpr->mCursorPos != -1)
  8058. val += GetAutocompleteOutput(autoComplete);
  8059. return val;
  8060. }
  8061. String WinDebugger::EvaluateContinue()
  8062. {
  8063. BP_ZONE("WinDebugger::EvaluateContinue");
  8064. AutoCrit autoCrit(mDebugManager->mCritSect);
  8065. if (mDebugPendingExpr == NULL)
  8066. return "!Evaluation canceled";
  8067. if (!IsPaused())
  8068. return "!Not paused";
  8069. if (mRunState == RunState_DebugEval_Done)
  8070. mRunState = RunState_Paused;
  8071. BfPassInstance bfPassInstance(mBfSystem);
  8072. String result = EvaluateContinue(mDebugPendingExpr, bfPassInstance);
  8073. if (result != "!pending")
  8074. {
  8075. BfLogDbg("EvaluateContinue finishing pending expr in thread %d\n", mDebugEvalThreadInfo.mThreadId);
  8076. CleanupDebugEval();
  8077. }
  8078. return result;
  8079. }
  8080. void WinDebugger::EvaluateContinueKeep()
  8081. {
  8082. if (mDebugPendingExpr != NULL)
  8083. mDebugPendingExpr->mIdleTicks = 0;
  8084. }
  8085. String WinDebugger::Evaluate(const StringImpl& expr, DwFormatInfo formatInfo, int callStackIdx, int cursorPos, int language, DwEvalExpressionFlags expressionFlags)
  8086. {
  8087. BP_ZONE_F("WinDebugger::Evaluate %s", BP_DYN_STR(expr.c_str()));
  8088. AutoCrit autoCrit(mDebugManager->mCritSect);
  8089. if ((expressionFlags & DwEvalExpressionFlag_Symbol) != 0)
  8090. {
  8091. DwAutoComplete autoComplete;
  8092. String retVal;
  8093. retVal += GetAutocompleteOutput(autoComplete);
  8094. return retVal;
  8095. }
  8096. UpdateCallStackMethod(callStackIdx);
  8097. BfLogDbgExpr("Evaluate %s in thread %d\n", expr.c_str(), (mActiveThread != NULL) ? mActiveThread->mThreadId : 0);
  8098. if (language != -1)
  8099. formatInfo.mLanguage = (DbgLanguage)language;
  8100. auto activeThread = mActiveThread;
  8101. if ((!IsPaused()) && (mRunState != RunState_NotStarted) && (mRunState != RunState_DebugEval))
  8102. {
  8103. activeThread = NULL;
  8104. callStackIdx = -1;
  8105. }
  8106. if (mDebugPendingExpr != NULL)
  8107. {
  8108. // We already have a pending call
  8109. expressionFlags = (DwEvalExpressionFlags)(expressionFlags & ~DwEvalExpressionFlag_AllowCalls);
  8110. }
  8111. auto dbgModule = GetCallStackDbgModule(callStackIdx);
  8112. auto dbgSubprogram = GetCallStackSubprogram(callStackIdx);
  8113. DbgCompileUnit* dbgCompileUnit = NULL;
  8114. if (dbgSubprogram != NULL)
  8115. dbgCompileUnit = dbgSubprogram->mCompileUnit;
  8116. auto terminatedExpr = expr + ";";
  8117. if ((expr.length() > 0) && (expr[0] == '!'))
  8118. {
  8119. if (expr.StartsWith("!step "))
  8120. {
  8121. expressionFlags = (DwEvalExpressionFlags)(expressionFlags | DwEvalExpressionFlag_StepIntoCalls);
  8122. for (int i = 0; i < 5; i++)
  8123. terminatedExpr[i] = ' ';
  8124. }
  8125. else
  8126. {
  8127. String cmd = expr;
  8128. int commaPos = (int)cmd.IndexOf(',');
  8129. if (commaPos != -1)
  8130. cmd.RemoveToEnd(commaPos);
  8131. if (cmd == "!info")
  8132. {
  8133. OutputMessage(StrFormat("Module: %s\n", dbgModule->mDisplayName.c_str()));
  8134. if (dbgSubprogram == NULL)
  8135. {
  8136. //
  8137. }
  8138. else if (dbgSubprogram->mLinkName != NULL)
  8139. {
  8140. OutputMessage(StrFormat("Link Name: %s\n", dbgSubprogram->mLinkName));
  8141. }
  8142. else
  8143. {
  8144. String outSymbol;
  8145. if (mDebugTarget->FindSymbolAt(dbgSubprogram->mBlock.mLowPC, &outSymbol))
  8146. {
  8147. OutputMessage(StrFormat("Link Name: %s\n", outSymbol.c_str()));
  8148. }
  8149. }
  8150. return "";
  8151. }
  8152. else if (cmd == "!dbg")
  8153. {
  8154. mDbgBreak = true;
  8155. return "";
  8156. }
  8157. }
  8158. }
  8159. bool valIsAddr = false;
  8160. BfParser* parser = new BfParser(mBfSystem);
  8161. parser->mCompatMode = true;
  8162. BfPassInstance bfPassInstance(mBfSystem);
  8163. if ((terminatedExpr.length() > 2) && (terminatedExpr[0] == '@'))
  8164. {
  8165. if (terminatedExpr[1] == '!') // Return string as error
  8166. {
  8167. int errorEnd = (int)terminatedExpr.IndexOf("@!", 2);
  8168. if (errorEnd != -1)
  8169. return terminatedExpr.Substring(1, errorEnd - 1);
  8170. else
  8171. return terminatedExpr.Substring(1);
  8172. }
  8173. else if (terminatedExpr[1] == '>') // Return string as text
  8174. {
  8175. int errorEnd = (int)terminatedExpr.IndexOf("@>", 2);
  8176. if (errorEnd != -1)
  8177. return terminatedExpr.Substring(2, errorEnd - 1);
  8178. else
  8179. return terminatedExpr.Substring(2);
  8180. }
  8181. else // Look for "@:" or "@Beef:" style
  8182. {
  8183. int colonIdx = terminatedExpr.IndexOf(':');
  8184. if (colonIdx > 0)
  8185. {
  8186. bool isValid = true;
  8187. DbgLanguage language = DbgLanguage_Unknown;
  8188. String lang = terminatedExpr.Substring(1, colonIdx - 1);
  8189. lang = ToUpper(lang);
  8190. if ((lang == "") || (lang == "BEEF"))
  8191. {
  8192. language = DbgLanguage_Beef;
  8193. }
  8194. else if (lang == "C")
  8195. {
  8196. language = DbgLanguage_C;
  8197. }
  8198. if (language != DbgLanguage_Unknown)
  8199. {
  8200. for (int i = 0; i < colonIdx + 1; i++)
  8201. terminatedExpr[i] = ' ';
  8202. DbgLanguage curLanguage = DbgLanguage_Unknown;
  8203. if (dbgSubprogram != NULL)
  8204. curLanguage = dbgSubprogram->GetLanguage();
  8205. if (language != curLanguage)
  8206. {
  8207. dbgModule = mDebugTarget->mTargetBinary;
  8208. dbgSubprogram = NULL;
  8209. formatInfo.mLanguage = language;
  8210. callStackIdx = -1;
  8211. }
  8212. }
  8213. }
  8214. }
  8215. }
  8216. parser->SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  8217. parser->Parse(&bfPassInstance);
  8218. BfReducer bfReducer;
  8219. bfReducer.mAlloc = parser->mAlloc;
  8220. bfReducer.mSystem = mBfSystem;
  8221. bfReducer.mPassInstance = &bfPassInstance;
  8222. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser->mRootNode);
  8223. bfReducer.mVisitorPos.MoveNext();
  8224. bfReducer.mCompatMode = parser->mCompatMode;
  8225. bfReducer.mSource = parser;
  8226. auto exprNode = bfReducer.CreateExpression(parser->mRootNode->mChildArr.GetAs<BfAstNode*>(0));
  8227. parser->Close();
  8228. formatInfo.mCallStackIdx = callStackIdx;
  8229. if ((formatInfo.mLanguage == DbgLanguage_Unknown) && (dbgSubprogram != NULL))
  8230. formatInfo.mLanguage = dbgSubprogram->GetLanguage();
  8231. DbgPendingExpr* pendingExpr = new DbgPendingExpr();
  8232. if (activeThread != NULL)
  8233. pendingExpr->mThreadId = activeThread->mThreadId;
  8234. pendingExpr->mParser = parser;
  8235. pendingExpr->mCallStackIdx = callStackIdx;
  8236. pendingExpr->mCursorPos = cursorPos;
  8237. pendingExpr->mExpressionFlags = expressionFlags;
  8238. pendingExpr->mExprNode = exprNode;
  8239. DbgType* explicitType = NULL;
  8240. String formatFlags;
  8241. String assignExpr;
  8242. int assignExprOffset = -1;
  8243. if ((exprNode != NULL) && (exprNode->GetSrcEnd() < (int)expr.length()))
  8244. {
  8245. int formatOffset = exprNode->GetSrcEnd();
  8246. while (formatOffset < (int)expr.length())
  8247. {
  8248. char c = expr[formatOffset];
  8249. if (c == ' ')
  8250. formatOffset++;
  8251. else
  8252. break;
  8253. }
  8254. formatFlags = Trim(expr.Substring(formatOffset));
  8255. bool isComplexType = false;
  8256. for (char c : formatFlags)
  8257. if (c == '>')
  8258. isComplexType = true;
  8259. if (isComplexType)
  8260. {
  8261. explicitType = dbgModule->FindType(expr);
  8262. }
  8263. if ((explicitType == NULL) && (formatFlags.length() > 0))
  8264. {
  8265. String errorString = "Invalid expression";
  8266. if (!ParseFormatInfo(dbgModule, formatFlags, &formatInfo, &bfPassInstance, &assignExprOffset, &assignExpr, &errorString))
  8267. {
  8268. if (formatInfo.mRawString)
  8269. return "";
  8270. bfPassInstance.FailAt(errorString, parser->mSourceData, exprNode->GetSrcEnd(), (int) expr.length() - exprNode->GetSrcEnd());
  8271. formatFlags = "";
  8272. }
  8273. if (assignExprOffset != -1)
  8274. assignExprOffset += formatOffset;
  8275. }
  8276. }
  8277. if (assignExpr.length() > 0)
  8278. {
  8279. String newEvalStr = exprNode->ToString() + " = ";
  8280. int errorOffset = (int)newEvalStr.length();
  8281. newEvalStr += assignExpr;
  8282. String result = Evaluate(newEvalStr, formatInfo, callStackIdx, cursorPos, language, expressionFlags);
  8283. if (result[0] == '!')
  8284. {
  8285. int tabPos = (int)result.IndexOf('\t');
  8286. if (tabPos > 0)
  8287. {
  8288. int errorStart = atoi(result.Substring(1, tabPos - 1).c_str());
  8289. if (errorStart >= errorOffset)
  8290. {
  8291. result = StrFormat("!%d", errorStart - errorOffset + assignExprOffset) + result.Substring(tabPos);
  8292. }
  8293. }
  8294. }
  8295. return result;
  8296. }
  8297. pendingExpr->mExplitType = explicitType;
  8298. pendingExpr->mFormatInfo = formatInfo;
  8299. String result = EvaluateContinue(pendingExpr, bfPassInstance);
  8300. if (result == "!pending")
  8301. {
  8302. BF_ASSERT(mDebugPendingExpr == NULL);
  8303. if (mDebugPendingExpr != NULL)
  8304. {
  8305. return "!retry"; // We already have a pending
  8306. }
  8307. mDebugPendingExpr = pendingExpr;
  8308. mDebugEvalThreadInfo = *mActiveThread;
  8309. mActiveThread->mIsAtBreakpointAddress = 0;
  8310. mActiveThread->mStoppedAtAddress = 0;
  8311. mActiveThread->mBreakpointAddressContinuing = 0;
  8312. }
  8313. else
  8314. delete pendingExpr;
  8315. return result;
  8316. }
  8317. String WinDebugger::Evaluate(const StringImpl& expr, int callStackIdx, int cursorPos, int language, DwEvalExpressionFlags expressionFlags)
  8318. {
  8319. DwFormatInfo formatInfo;
  8320. return Evaluate(expr, formatInfo, callStackIdx, cursorPos, language, expressionFlags);
  8321. }
  8322. static void ConvertDoubleToFloat80(double d, byte fp80[10])
  8323. {
  8324. uint64 di = *reinterpret_cast<uint64*>(&d);
  8325. uint64 m = di & (((uint64)1 << 52) - 1);
  8326. uint64 e = (di >> 52) & 0x7ff;
  8327. memset(fp80, 0, 10);
  8328. // sign bit is directly transferred
  8329. if (di & ((uint64)1 << 63))
  8330. fp80[9] |= 0x80;
  8331. if (!e && !m)
  8332. return; // zero
  8333. fp80[7] |= 0x80; // leading integer bit in mantissa (always 1 in normalized numbers)
  8334. if (e == 0x7ff)
  8335. {
  8336. fp80[9] |= 0x7f;
  8337. fp80[8] = 0xff;
  8338. if (m == 0)
  8339. return; // inf
  8340. fp80[7] |= 0x3f; // any nonzero value will be a NaN (SNaN or QNaN)
  8341. if (m & ((uint64)1 << 51))
  8342. fp80[7] |= 0x40; // QNaN
  8343. return;
  8344. }
  8345. int useExponent = (int)e - 1023;
  8346. if (!e)
  8347. {
  8348. // denormal; can renormalize though since fp80 supports lower exponents
  8349. BF_ASSERT(m != 0); // we should have trapped zero above
  8350. while (!(m & ((uint64)1 << 51)))
  8351. {
  8352. m <<= 1;
  8353. --useExponent;
  8354. }
  8355. // finally we have our leading 1 bit; strip that off and we have a normalized number again
  8356. m <<= 1;
  8357. --useExponent;
  8358. m &= (((uint64)1 << 52) - 1);
  8359. }
  8360. useExponent += 16383;
  8361. BF_ASSERT((useExponent > 0) && (useExponent < 0x7fff));
  8362. *reinterpret_cast<uint16*>(&fp80[8]) |= (uint16)useExponent;
  8363. *reinterpret_cast<uint64*>(&fp80[0]) |= (m << 11);
  8364. }
  8365. bool WinDebugger::AssignToReg(int callStackIdx, DbgTypedValue regVal, DbgTypedValue value, String& outError)
  8366. {
  8367. BF_ASSERT(regVal.mRegNum >= 0);
  8368. if (mCallStack.size() == 0)
  8369. {
  8370. outError = "No call stack";
  8371. return false;
  8372. }
  8373. if (callStackIdx >= (int)mCallStack.size())
  8374. {
  8375. outError = "Invalid call stack index";
  8376. return false;
  8377. }
  8378. auto registers = &mCallStack[callStackIdx]->mRegisters;
  8379. void* regPtr = NULL;
  8380. #ifdef BF_DBG_32
  8381. if ((regVal.mRegNum >= X86Reg_INTREG_FIRST) && (regVal.mRegNum <= X86Reg_INTREG_LAST))
  8382. {
  8383. BF_ASSERT(regVal.mType->mSize == sizeof(int32));
  8384. registers->mIntRegsArray[regVal.mRegNum - X86Reg_INTREG_FIRST] = (uint64)value.mUInt32; // don't sign-extend
  8385. }
  8386. else if ((regVal.mRegNum >= X86Reg_FPSTREG_FIRST) && (regVal.mRegNum <= X86Reg_FPSTREG_LAST))
  8387. {
  8388. BF_ASSERT(regVal.mType->mSize == sizeof(float) || regVal.mType->mSize == sizeof(double));
  8389. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X86Reg_FPSTREG_FIRST];
  8390. double d;
  8391. if (regVal.mType->mSize == sizeof(float))
  8392. d = (double)value.mSingle;
  8393. else
  8394. d = value.mDouble;
  8395. ConvertDoubleToFloat80(d, reg->fp.fp80);
  8396. }
  8397. else if ((regVal.mRegNum >= X86Reg_MMREG_FIRST) && (regVal.mRegNum <= X86Reg_MMREG_LAST))
  8398. {
  8399. BF_ASSERT(regVal.mType->mSize == sizeof(int32) || regVal.mType->mSize == sizeof(int64));
  8400. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X86Reg_MMREG_FIRST];
  8401. if (regVal.mType->mSize == sizeof(int32))
  8402. reg->mm = (uint64)value.mUInt32; // don't sign-extend
  8403. else if (regVal.mType->mSize == sizeof(int64))
  8404. reg->mm = value.mInt64;
  8405. // 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
  8406. reg->fp.fp80[8] = reg->fp.fp80[9] = 0xFF;
  8407. }
  8408. else if ((regVal.mRegNum >= X86Reg_XMMREG_FIRST) && (regVal.mRegNum <= X86Reg_XMMREG_LAST))
  8409. {
  8410. int xmmMajor = (regVal.mRegNum - X86Reg_XMMREG_FIRST) >> 2;
  8411. int xmmMinor = (regVal.mRegNum - X86Reg_XMMREG_FIRST) & 3;
  8412. registers->mXmmRegsArray[xmmMajor].f[xmmMinor] = value.mSingle;
  8413. }
  8414. else if ((regVal.mRegNum >= X86Reg_M128_XMMREG_FIRST) && (regVal.mRegNum <= X86Reg_M128_XMMREG_LAST))
  8415. {
  8416. outError = "Cannot write directly to 128-bit XMM register, please use inner float components";
  8417. return false;
  8418. }
  8419. else if ((regVal.mRegNum >= X86Reg_FLAG_FIRST) && (regVal.mRegNum <= X86Reg_FLAG_LAST))
  8420. {
  8421. int flagBit = CPURegisters::GetFlagBitForRegister(regVal.mRegNum);
  8422. if (flagBit >= 0)
  8423. {
  8424. if (value.mBool)
  8425. registers->mIntRegs.efl |= ((uint64)1 << flagBit);
  8426. else
  8427. registers->mIntRegs.efl &= ~((uint64)1 << flagBit);
  8428. }
  8429. else
  8430. {
  8431. outError = "Unrecognized flag";
  8432. return false;
  8433. }
  8434. }
  8435. else if ((regVal.mRegNum >= X86Reg_CAT_FIRST) && (regVal.mRegNum <= X86Reg_CAT_LAST))
  8436. {
  8437. outError = "Cannot write directly to register categories, please use inner float components";
  8438. return false;
  8439. }
  8440. #else
  8441. if ((regVal.mRegNum >= X64Reg_INTREG_FIRST) && (regVal.mRegNum <= X64Reg_INTREG_LAST))
  8442. {
  8443. //BF_ASSERT(regVal.mType->mSize == sizeof(addr_target));
  8444. registers->mIntRegsArray[regVal.mRegNum - X64Reg_INTREG_FIRST] = value.GetInt64(); // don't sign-extend
  8445. regPtr = &registers->mIntRegsArray[regVal.mRegNum - X64Reg_INTREG_FIRST];
  8446. }
  8447. else if ((regVal.mRegNum >= X64Reg_FPSTREG_FIRST) && (regVal.mRegNum <= X64Reg_FPSTREG_LAST))
  8448. {
  8449. BF_ASSERT(regVal.mType->mSize == sizeof(float) || regVal.mType->mSize == sizeof(double));
  8450. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X64Reg_FPSTREG_FIRST];
  8451. double d;
  8452. if (regVal.mType->mSize == sizeof(float))
  8453. d = (double)value.mSingle;
  8454. else
  8455. d = value.mDouble;
  8456. ConvertDoubleToFloat80(d, reg->fp.fp80);
  8457. regPtr = reg;
  8458. }
  8459. else if ((regVal.mRegNum >= X64Reg_MMREG_FIRST) && (regVal.mRegNum <= X64Reg_MMREG_LAST))
  8460. {
  8461. BF_ASSERT(regVal.mType->mSize == sizeof(int32) || regVal.mType->mSize == sizeof(int64));
  8462. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X64Reg_MMREG_FIRST];
  8463. if (regVal.mType->mSize == sizeof(int32))
  8464. reg->mm = (uint64)value.mUInt32; // don't sign-extend
  8465. else if (regVal.mType->mSize == sizeof(int64))
  8466. reg->mm = value.mInt64;
  8467. // 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
  8468. reg->fp.fp80[8] = reg->fp.fp80[9] = 0xFF;
  8469. regPtr = reg;
  8470. }
  8471. else if ((regVal.mRegNum >= X64Reg_XMMREG_FIRST) && (regVal.mRegNum <= X64Reg_XMMREG_LAST))
  8472. {
  8473. int xmmMajor = (regVal.mRegNum - X64Reg_XMMREG_FIRST) >> 2;
  8474. int xmmMinor = (regVal.mRegNum - X64Reg_XMMREG_FIRST) & 3;
  8475. if (value.mType->GetByteCount() == 4)
  8476. registers->mXmmRegsArray[xmmMajor].f[xmmMinor] = value.mSingle;
  8477. else if (value.mType->GetByteCount() == 8)
  8478. registers->mXmmDRegsArray[xmmMajor].d[xmmMinor] = value.mDouble;
  8479. else
  8480. BF_FATAL("Invalid XMM set value type");
  8481. regPtr = &registers->mXmmRegsArray[xmmMajor];
  8482. }
  8483. else if ((regVal.mRegNum >= X64Reg_M128_XMMREG_FIRST) && (regVal.mRegNum <= X64Reg_M128_XMMREG_LAST))
  8484. {
  8485. outError = "Cannot write directly to 128-bit XMM register, please use inner float components";
  8486. return false;
  8487. }
  8488. else if ((regVal.mRegNum >= X64Reg_FLAG_FIRST) && (regVal.mRegNum <= X64Reg_FLAG_LAST))
  8489. {
  8490. int flagBit = CPURegisters::GetFlagBitForRegister(regVal.mRegNum);
  8491. if (flagBit >= 0)
  8492. {
  8493. if (value.mBool)
  8494. registers->mIntRegs.efl |= ((uint64)1 << flagBit);
  8495. else
  8496. registers->mIntRegs.efl &= ~((uint64)1 << flagBit);
  8497. regPtr = &registers->mIntRegs.efl;
  8498. }
  8499. else
  8500. {
  8501. outError = "Unrecognized flag";
  8502. return false;
  8503. }
  8504. }
  8505. else if ((regVal.mRegNum >= X64Reg_CAT_FIRST) && (regVal.mRegNum <= X64Reg_CAT_LAST))
  8506. {
  8507. outError = "Cannot write directly to register categories, please use inner float components";
  8508. return false;
  8509. }
  8510. else
  8511. BF_FATAL("Not implemented");
  8512. #endif
  8513. if (callStackIdx == 0)
  8514. {
  8515. SetRegisters(&mCallStack[0]->mRegisters);
  8516. return true;
  8517. }
  8518. else
  8519. {
  8520. bool wasSaved = false;
  8521. for (int calleeStackIdx = callStackIdx - 1; calleeStackIdx >= 0; calleeStackIdx--)
  8522. {
  8523. auto calleeRegisters = &mCallStack[calleeStackIdx]->mRegisters;
  8524. if (!mDebugTarget->PropogateRegisterUpCallStack(registers, calleeRegisters, regPtr, wasSaved))
  8525. {
  8526. outError = "Failed to set register";
  8527. return false;
  8528. }
  8529. if (wasSaved)
  8530. return true;
  8531. }
  8532. // This register wasn't saved, so commit it to the callstack top
  8533. return AssignToReg(0, regVal, value, outError);
  8534. }
  8535. }
  8536. String WinDebugger::GetAutocompleteOutput(DwAutoComplete& autoComplete)
  8537. {
  8538. String val = "\n:autocomplete\n";
  8539. if (autoComplete.mInsertStartIdx != -1)
  8540. {
  8541. val += StrFormat("insertRange\t%d %d\n", autoComplete.mInsertStartIdx, autoComplete.mInsertEndIdx);
  8542. }
  8543. Array<AutoCompleteEntry*> entries;
  8544. for (auto& entry : autoComplete.mEntriesSet)
  8545. {
  8546. entries.Add(&entry);
  8547. }
  8548. std::sort(entries.begin(), entries.end(), [](AutoCompleteEntry* lhs, AutoCompleteEntry* rhs)
  8549. {
  8550. return stricmp(lhs->mDisplay, rhs->mDisplay) < 0;
  8551. });
  8552. for (auto entry : entries)
  8553. {
  8554. val += String(entry->mEntryType);
  8555. val += "\t";
  8556. val += String(entry->mDisplay);
  8557. val += "\n";
  8558. }
  8559. /*if (autoComplete.mEntries.size() != 0)
  8560. {
  8561. for (auto& entry : autoComplete.mEntries)
  8562. {
  8563. val += String(entry.mEntryType) + "\t" + String(entry.mDisplay) + "\n";
  8564. }
  8565. }*/
  8566. return val;
  8567. }
  8568. String WinDebugger::EvaluateToAddress(const StringImpl& expr, int callStackIdx, int cursorPos)
  8569. {
  8570. AutoCrit autoCrit(mDebugManager->mCritSect);
  8571. if (IsInRunState())
  8572. return "!Target not paused";
  8573. auto dbgModule = GetCallStackDbgModule(callStackIdx);
  8574. auto dbgCompileUnit = GetCallStackCompileUnit(callStackIdx);
  8575. BfParser parser(mBfSystem);
  8576. parser.mCompatMode = true;
  8577. BfPassInstance bfPassInstance(mBfSystem);
  8578. auto terminatedExpr = expr + ";";
  8579. parser.SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  8580. parser.Parse(&bfPassInstance);
  8581. BfReducer bfReducer;
  8582. bfReducer.mAlloc = parser.mAlloc;
  8583. bfReducer.mSystem = mBfSystem;
  8584. bfReducer.mPassInstance = &bfPassInstance;
  8585. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser.mRootNode);
  8586. bfReducer.mVisitorPos.MoveNext();
  8587. bfReducer.mSource = &parser;
  8588. auto exprNode = bfReducer.CreateExpression(parser.mRootNode->GetFirst());
  8589. parser.Close();
  8590. DwAutoComplete autoComplete;
  8591. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, callStackIdx, cursorPos);
  8592. if (cursorPos != -1)
  8593. dbgExprEvaluator.mAutoComplete = &autoComplete;
  8594. dbgExprEvaluator.mDbgCompileUnit = dbgCompileUnit;
  8595. DwFormatInfo formatInfo;
  8596. formatInfo.mCallStackIdx = callStackIdx;
  8597. DbgTypedValue exprResult;
  8598. if (exprNode != NULL)
  8599. exprResult = dbgExprEvaluator.Resolve(exprNode);
  8600. DbgType* resultType = exprResult.mType->RemoveModifiers();
  8601. String val;
  8602. if (bfPassInstance.HasFailed())
  8603. {
  8604. val = StrFormat("!%d\t%d\t%s", bfPassInstance.mErrors[0]->mSrcStart, bfPassInstance.mErrors[0]->GetSrcLength(), bfPassInstance.mErrors[0]->mError.c_str());
  8605. }
  8606. else if (exprResult.mType == NULL)
  8607. {
  8608. val = "!Invalid expression";
  8609. }
  8610. else if (!resultType->IsPointerOrRef())
  8611. {
  8612. if (exprResult.mSrcAddress != 0)
  8613. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  8614. else
  8615. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  8616. }
  8617. else
  8618. {
  8619. auto innerType = resultType->mTypeParam;
  8620. int byteCount = innerType->GetByteCount();
  8621. if (byteCount == 0)
  8622. {
  8623. 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());
  8624. }
  8625. #ifdef BF_DBG_32
  8626. else if ((byteCount != 1) && (byteCount != 2) && (byteCount != 4))
  8627. {
  8628. 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);
  8629. }
  8630. #else
  8631. else if ((byteCount != 1) && (byteCount != 2) && (byteCount != 4) && (byteCount != 8))
  8632. {
  8633. 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);
  8634. }
  8635. #endif
  8636. else
  8637. {
  8638. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", byteCount);
  8639. }
  8640. }
  8641. if (cursorPos != -1)
  8642. val += GetAutocompleteOutput(autoComplete);
  8643. return val;
  8644. }
  8645. // This is currently only used for autocomplete during conditional breakpoint expression entry.
  8646. // If we want to use it for more than that then remove DwEvalExpressionFlags_ValidateOnly
  8647. String WinDebugger::EvaluateAtAddress(const StringImpl& expr, intptr atAddr, int cursorPos)
  8648. {
  8649. AutoCrit autoCrit(mDebugManager->mCritSect);
  8650. if (IsInRunState())
  8651. return "!Target not paused";
  8652. if (!IsPaused())
  8653. return "!Target not running";
  8654. WdStackFrame stackFrame;
  8655. memset(&stackFrame.mRegisters, 0, sizeof(stackFrame.mRegisters));
  8656. stackFrame.mHasGottenSubProgram = true;
  8657. *stackFrame.mRegisters.GetPCRegisterRef() = (intptr_target)atAddr;
  8658. stackFrame.mSubProgram = mDebugTarget->FindSubProgram((addr_target)atAddr);
  8659. if (stackFrame.mSubProgram == NULL)
  8660. return "!Invalid address";
  8661. mCallStack.push_back(&stackFrame);
  8662. int callStackIdx = (int)mCallStack.size() - 1;
  8663. String val = Evaluate(expr, callStackIdx, cursorPos, -1, DwEvalExpressionFlag_ValidateOnly);
  8664. mCallStack.pop_back();
  8665. return val;
  8666. }
  8667. String WinDebugger::GetAutoExpressions(int callStackIdx, uint64 memoryRangeStart, uint64 memoryRangeLen)
  8668. {
  8669. BP_ZONE("WinDebugger::GetAutoExpressions");
  8670. AutoCrit autoCrit(mDebugManager->mCritSect);
  8671. if (IsInRunState())
  8672. return "!Not paused";
  8673. if (!IsPaused())
  8674. return "!Not running";
  8675. if (!FixCallStackIdx(callStackIdx))
  8676. return "";
  8677. CPUStackFrame* stackFrame = (callStackIdx >= 0) ? mCallStack[callStackIdx] : mCallStack.front();
  8678. String result;
  8679. DbgAutoValueMapType dwarfAutos;
  8680. mDebugTarget->GetAutoValueNames(dwarfAutos, stackFrame, memoryRangeStart, memoryRangeLen);
  8681. for (auto const &a : dwarfAutos)
  8682. {
  8683. std::pair<uint64, uint64> varRange = a.mValue;
  8684. if (varRange.first != 0)
  8685. result += StrFormat("&%s\t%llu\t%llu\n", a.mKey.c_str(), varRange.second, varRange.first);
  8686. else
  8687. result += StrFormat("?%s\t%llu\n", a.mKey.c_str(), varRange.second);
  8688. }
  8689. #ifdef BF_DBG_64
  8690. // add int regs
  8691. const char* regStrs[] = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "rip", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", 0 };
  8692. #else
  8693. // add int regs
  8694. const char* regStrs[] = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "eip", 0 };
  8695. #endif
  8696. for (const char** p = regStrs; *p; ++p)
  8697. result += StrFormat("$%s\t%d\n", *p, sizeof(addr_target));
  8698. if (callStackIdx < (int)mCallStack.size() - 2)
  8699. {
  8700. WdStackFrame* prevStackFrame = mCallStack[callStackIdx + 1];
  8701. // Inlined methods have no stack frame
  8702. int stackSize = prevStackFrame->mRegisters.GetSP() - stackFrame->mRegisters.GetSP();
  8703. result += StrFormat("&$StackFrame\t%llu\t%llu\n", stackSize, stackFrame->mRegisters.GetSP());
  8704. }
  8705. return result;
  8706. }
  8707. String WinDebugger::GetAutoLocals(int stackFrameIdx, bool showRegs)
  8708. {
  8709. BP_ZONE("WinDebugger::GetAutoExpressions");
  8710. AutoCrit autoCrit(mDebugManager->mCritSect);
  8711. if (IsInRunState())
  8712. return "";
  8713. if (!IsPaused())
  8714. return "";
  8715. if (mCallStack.size() == 0)
  8716. UpdateCallStack();
  8717. String result;
  8718. Array<String> localList;
  8719. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  8720. UpdateCallStackMethod(actualStackFrameIdx);
  8721. if (actualStackFrameIdx >= mCallStack.size())
  8722. return "";
  8723. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  8724. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  8725. if (dwSubprogram == NULL)
  8726. return "";
  8727. auto langage = dwSubprogram->GetLanguage();
  8728. DbgLineData* dwLineData = FindLineDataInSubprogram(wdStackFrame->GetSourcePC(), dwSubprogram);
  8729. if (dwLineData == NULL)
  8730. return "";
  8731. dwSubprogram->PopulateSubprogram();
  8732. mDebugTarget->GetAutoLocalsInBlock(localList, dwSubprogram, &dwSubprogram->mBlock, wdStackFrame, dwLineData);
  8733. String lastLocal;
  8734. for (auto local : localList)
  8735. {
  8736. if (langage == DbgLanguage_C)
  8737. {
  8738. if ((local == "this") && (strncmp(dwSubprogram->mName, "<lambda_", 8) == 0))
  8739. {
  8740. // Use explicit "$this" so we can see the actual capture
  8741. result += "$this\n";
  8742. continue;
  8743. }
  8744. }
  8745. bool wasAlias = false;
  8746. for (int i = 0; i < (int)local.length() - 1; i++)
  8747. {
  8748. if ((local[i] == '$') && (local[i + 1] == 'a'))
  8749. {
  8750. // Alias
  8751. wasAlias = true;
  8752. String localName = local.Substring(0, i) + "\n";
  8753. if (localName != lastLocal)
  8754. {
  8755. result += localName;
  8756. lastLocal = localName;
  8757. }
  8758. break;
  8759. }
  8760. }
  8761. if (!wasAlias)
  8762. result += local + "\n";
  8763. }
  8764. if (showRegs)
  8765. {
  8766. result += "$FLAGS\n";
  8767. UpdateRegisterUsage(stackFrameIdx);
  8768. for (int regIdx = 0; regIdx < (int)wdStackFrame->mRegForms.size(); regIdx++)
  8769. {
  8770. if (wdStackFrame->mRegForms[regIdx] != RegForm_Invalid)
  8771. result += "$" + String(CPURegisters::GetRegisterName(regIdx)) + "\n";
  8772. }
  8773. }
  8774. return result;
  8775. }
  8776. String WinDebugger::CompactChildExpression(const StringImpl& expr, const StringImpl& parentExpr, int callStackIdx)
  8777. {
  8778. DbgCompileUnit* compileUnit = GetCallStackCompileUnit(callStackIdx);
  8779. DbgModule* dbgModule = GetCallStackDbgModule(callStackIdx);
  8780. if (dbgModule == NULL)
  8781. return "!failed";
  8782. DbgLanguage language = DbgLanguage_Unknown;
  8783. if (compileUnit != NULL)
  8784. language = compileUnit->mLanguage;
  8785. BfPassInstance bfPassInstance(mBfSystem);
  8786. BfParser parser(mBfSystem);
  8787. parser.mCompatMode = language != DbgLanguage_Beef;
  8788. auto terminatedExpr = expr + ";";
  8789. parser.SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  8790. parser.Parse(&bfPassInstance);
  8791. BfParser parentParser(mBfSystem);
  8792. auto terminatedParentExpr = parentExpr + ";";
  8793. parentParser.mCompatMode = language != DbgLanguage_Beef;
  8794. parentParser.SetSource(terminatedParentExpr.c_str(), terminatedParentExpr.length());
  8795. parentParser.Parse(&bfPassInstance);
  8796. BfReducer bfReducer;
  8797. bfReducer.mCompatMode = true;
  8798. bfReducer.mAlloc = parser.mAlloc;
  8799. bfReducer.mSystem = mBfSystem;
  8800. bfReducer.mPassInstance = &bfPassInstance;
  8801. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser.mRootNode);
  8802. bfReducer.mVisitorPos.MoveNext();
  8803. bfReducer.mSource = &parser;
  8804. auto exprNode = bfReducer.CreateExpression(parser.mRootNode->GetFirst());
  8805. bfReducer.mAlloc = parentParser.mAlloc;
  8806. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parentParser.mRootNode);
  8807. bfReducer.mVisitorPos.MoveNext();
  8808. auto parentExprNode = bfReducer.CreateExpression(parentParser.mRootNode->GetFirst());
  8809. parser.Close();
  8810. if ((exprNode == NULL) || (parentExprNode == NULL))
  8811. return "!failed";
  8812. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, callStackIdx, -1);
  8813. DwFormatInfo formatInfo;
  8814. formatInfo.mCallStackIdx = callStackIdx;
  8815. String formatFlags;
  8816. String assignExpr;
  8817. if ((exprNode != NULL) && (exprNode->GetSrcEnd() < (int) expr.length()))
  8818. {
  8819. formatFlags = Trim(expr.Substring(exprNode->GetSrcEnd()));
  8820. if (formatFlags.length() > 0)
  8821. {
  8822. String errorString = "Invalid expression";
  8823. if (!ParseFormatInfo(dbgModule, formatFlags, &formatInfo, &bfPassInstance, NULL, &assignExpr, &errorString))
  8824. {
  8825. bfPassInstance.FailAt(errorString, parser.mSourceData, exprNode->GetSrcEnd(), (int) expr.length() - exprNode->GetSrcEnd());
  8826. formatFlags = "";
  8827. }
  8828. }
  8829. }
  8830. dbgExprEvaluator.mExplicitThis = formatInfo.mExplicitThis;
  8831. dbgExprEvaluator.mExplicitThisExpr = parentExprNode;
  8832. DbgTypedValue exprResult = dbgExprEvaluator.Resolve(exprNode);
  8833. BfAstNode* headNode = dbgExprEvaluator.FinalizeExplicitThisReferences(exprNode);
  8834. BfPrinter printer(parser.mRootNode, NULL, NULL);
  8835. printer.mIgnoreTrivia = true;
  8836. printer.mReformatting = true;
  8837. printer.VisitChild(headNode);
  8838. auto result = printer.mOutString;
  8839. if (formatInfo.mNoVisualizers)
  8840. result += ", nv";
  8841. if (formatInfo.mNoMembers)
  8842. result += ", nm";
  8843. if (formatInfo.mNoEdit)
  8844. result += ", ne";
  8845. if (formatInfo.mIgnoreDerivedClassInfo)
  8846. result += ", nd";
  8847. if (formatInfo.mDisplayType == DwDisplayType_Ascii)
  8848. result += ", s";
  8849. if (formatInfo.mDisplayType == DwDisplayType_Utf8)
  8850. result += ", s8";
  8851. if (formatInfo.mDisplayType == DwDisplayType_Utf16)
  8852. result += ", s16";
  8853. if (formatInfo.mDisplayType == DwDisplayType_Utf32)
  8854. result += ", s32";
  8855. return result;
  8856. }
  8857. String WinDebugger::GetThreadInfo()
  8858. {
  8859. AutoCrit autoCrit(mDebugManager->mCritSect);
  8860. String retStr;
  8861. if ((mActiveThread == NULL) && (!mIsRunning))
  8862. {
  8863. retStr = "";
  8864. }
  8865. else
  8866. {
  8867. if (mActiveThread != NULL)
  8868. retStr = StrFormat("%d", mActiveThread->mThreadId);
  8869. for (auto threadInfo : mThreadList)
  8870. {
  8871. SetAndRestoreValue<WdThreadInfo*> prevThread(mActiveThread, threadInfo);
  8872. retStr += "\n";
  8873. for (int pass = 0; pass < 2; pass++)
  8874. {
  8875. CPURegisters registers;
  8876. PopulateRegisters(&registers);
  8877. String locString = EncodeDataPtr((addr_target)registers.GetPC(), true);
  8878. TryGetThreadName(threadInfo);
  8879. bool hadThreadName = true;
  8880. String threadName = threadInfo->mName;
  8881. if (threadName.IsEmpty())
  8882. {
  8883. hadThreadName = false;
  8884. if (threadInfo->mThreadId == mProcessInfo.dwThreadId)
  8885. threadName = "Main Thread";
  8886. else
  8887. threadName = "Worker Thread";
  8888. }
  8889. bool isInvalid = false;
  8890. addr_target appendAddr = 0;
  8891. for (int stackIdx = 0; true; stackIdx++)
  8892. {
  8893. auto subProgram = mDebugTarget->FindSubProgram(registers.GetPC(), DbgOnDemandKind_LocalOnly);
  8894. if (subProgram != NULL)
  8895. {
  8896. if (subProgram->mLineInfo != NULL)
  8897. {
  8898. DbgModule* module = subProgram->mCompileUnit->mDbgModule;
  8899. DbgModule* linkedModule = module->GetLinkedModule();
  8900. if (linkedModule->mDisplayName.length() > 0)
  8901. {
  8902. locString = linkedModule->mDisplayName + "!" + subProgram->ToString();
  8903. if (!hadThreadName)
  8904. threadName = module->mDisplayName + " thread";
  8905. }
  8906. else
  8907. {
  8908. locString = subProgram->ToString();
  8909. }
  8910. appendAddr = 0;
  8911. break;
  8912. }
  8913. }
  8914. DbgModule* module = mDebugTarget->FindDbgModuleForAddress(registers.GetPC());
  8915. if (module == NULL)
  8916. {
  8917. isInvalid = true;
  8918. break;
  8919. }
  8920. DbgModule* linkedModule = module->GetLinkedModule();
  8921. appendAddr = (addr_target)registers.GetPC();
  8922. locString = linkedModule->mDisplayName + "!" + EncodeDataPtr((addr_target)registers.GetPC(), true);
  8923. if (!hadThreadName)
  8924. threadName = linkedModule->mDisplayName + " thread";
  8925. if ((mActiveThread == mExplicitStopThread) && (mActiveBreakpoint != NULL))
  8926. {
  8927. if ((subProgram == NULL) ||
  8928. (mActiveBreakpoint->mAddr < subProgram->mBlock.mLowPC) ||
  8929. (mActiveBreakpoint->mAddr >= subProgram->mBlock.mHighPC))
  8930. break;
  8931. }
  8932. if (pass == 1) // Just take the first item
  8933. break;
  8934. if (stackIdx == 128)
  8935. break; // Too many!
  8936. addr_target returnAddr;
  8937. if (!mDebugTarget->RollBackStackFrame(&registers, &returnAddr, true))
  8938. {
  8939. isInvalid = true;
  8940. break;
  8941. }
  8942. }
  8943. if ((isInvalid) && (pass == 0))
  8944. continue;
  8945. if (appendAddr != 0)
  8946. {
  8947. String symbolName;
  8948. addr_target offset;
  8949. DbgModule* dwarf;
  8950. if (mDebugTarget->FindSymbolAt(appendAddr, &symbolName, &offset, &dwarf))
  8951. {
  8952. DbgModule* linkedModule = dwarf->GetLinkedModule();
  8953. String demangledName = BfDemangler::Demangle(symbolName, DbgLanguage_Unknown);
  8954. if (!linkedModule->mDisplayName.empty())
  8955. {
  8956. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  8957. }
  8958. locString = demangledName + StrFormat("+0x%X", offset);
  8959. }
  8960. }
  8961. retStr += StrFormat("%d\t%s\t%s", threadInfo->mThreadId, threadName.c_str(), locString.c_str());
  8962. String attrs;
  8963. if (threadInfo->mFrozen)
  8964. {
  8965. attrs += "Fr";
  8966. }
  8967. if (!attrs.IsEmpty())
  8968. {
  8969. retStr += "\t";
  8970. retStr += attrs;
  8971. }
  8972. break;
  8973. }
  8974. }
  8975. }
  8976. return retStr;
  8977. }
  8978. void WinDebugger::SetActiveThread(int threadId)
  8979. {
  8980. AutoCrit autoCrit(mDebugManager->mCritSect);
  8981. if (mThreadMap.TryGetValue(threadId, &mActiveThread))
  8982. {
  8983. BfLogDbg("SetActiveThread %d\n", threadId);
  8984. ClearCallStack();
  8985. }
  8986. else
  8987. {
  8988. BfLogDbg("SetActiveThread %d FAILED\n", threadId);
  8989. }
  8990. }
  8991. int WinDebugger::GetActiveThread()
  8992. {
  8993. AutoCrit autoCrit(mDebugManager->mCritSect);
  8994. if (mActiveThread == NULL)
  8995. return -1;
  8996. return mActiveThread->mThreadId;
  8997. }
  8998. void WinDebugger::FreezeThread(int threadId)
  8999. {
  9000. AutoCrit autoCrit(mDebugManager->mCritSect);
  9001. BF_ASSERT(!IsInRunState());
  9002. auto thread = mThreadMap[threadId];
  9003. if (!thread->mFrozen)
  9004. {
  9005. thread->mFrozen = true;
  9006. ::SuspendThread(thread->mHThread);
  9007. BfLogDbg("SuspendThread %d from FreezeThread\n", thread->mThreadId);
  9008. }
  9009. }
  9010. void WinDebugger::ThawThread(int threadId)
  9011. {
  9012. AutoCrit autoCrit(mDebugManager->mCritSect);
  9013. BF_ASSERT(!IsInRunState());
  9014. auto thread = mThreadMap[threadId];
  9015. if (thread->mFrozen)
  9016. {
  9017. thread->mFrozen = false;
  9018. ::ResumeThread(thread->mHThread);
  9019. BfLogDbg("ResumeThread %d from ThawThread\n", thread->mThreadId);
  9020. }
  9021. }
  9022. bool WinDebugger::IsActiveThreadWaiting()
  9023. {
  9024. AutoCrit autoCrit(mDebugManager->mCritSect);
  9025. return mActiveThread == mDebuggerWaitingThread;
  9026. }
  9027. void WinDebugger::ClearCallStack()
  9028. {
  9029. AutoCrit autoCrit(mDebugManager->mCritSect);
  9030. BfLogDbg("ClearCallstack\n");
  9031. BF_ASSERT(mRunState != RunState_DebugEval);
  9032. for (auto wdStackFrame : mCallStack)
  9033. delete wdStackFrame;
  9034. mCallStack.Clear();
  9035. mIsPartialCallStack = true;
  9036. }
  9037. void WinDebugger::UpdateCallStack(bool slowEarlyOut)
  9038. {
  9039. AutoCrit autoCrit(mDebugManager->mCritSect);
  9040. if (!mIsPartialCallStack)
  9041. return;
  9042. BF_ASSERT(!IsInRunState());
  9043. uint32 tickStart = BFTickCount();
  9044. CPURegisters registers;
  9045. if (mCallStack.size() > 0)
  9046. {
  9047. WdStackFrame* wdStackFrame = mCallStack.back();
  9048. if (wdStackFrame->mIsEnd)
  9049. {
  9050. return;
  9051. }
  9052. memcpy(&registers, &wdStackFrame->mRegisters, sizeof(registers));
  9053. bool regsRolledBack = RollBackStackFrame(&registers, mCallStack.size() == 1);
  9054. // If we can't roll them back then mIsEnd should have been set for the previous frame
  9055. BF_ASSERT(regsRolledBack);
  9056. }
  9057. else
  9058. {
  9059. BF_ASSERT(mIsPartialCallStack);
  9060. mCallStack.Reserve(1024);
  9061. PopulateRegisters(&registers);
  9062. BfLogDbg("UpdateCallStack starting. Thread=%d PC=0x%p\n", mActiveThread->mThreadId, registers.GetPC());
  9063. }
  9064. bool isPartial = false;
  9065. // Incrementally fill callstack structure to avoid stepping slowdown during deep nesting
  9066. for (int fillIdx = 0; fillIdx < (slowEarlyOut ? 10000 : 100000); fillIdx++)
  9067. {
  9068. WdStackFrame* wdStackFrame = new WdStackFrame();
  9069. memcpy(&wdStackFrame->mRegisters, &registers, sizeof(registers));
  9070. wdStackFrame->mIsStart = mCallStack.size() == 0;
  9071. wdStackFrame->mIsEnd = false;
  9072. bool rollbackSuccess = false;
  9073. for (int tryCount = 0; tryCount < 16; tryCount++)
  9074. {
  9075. if (!RollBackStackFrame(&registers, wdStackFrame->mIsStart))
  9076. {
  9077. break;
  9078. }
  9079. if (registers.GetPC() > 0xFFFF)
  9080. {
  9081. rollbackSuccess = true;
  9082. break;
  9083. }
  9084. if (mCallStack.size() > 0)
  9085. break; // Only retry for the first frame
  9086. }
  9087. if (!rollbackSuccess)
  9088. wdStackFrame->mIsEnd = true;
  9089. if (registers.GetSP() <= wdStackFrame->mRegisters.GetSP())
  9090. {
  9091. // SP went the wrong direction, stop rolling back
  9092. wdStackFrame->mIsEnd = true;
  9093. }
  9094. mCallStack.push_back(wdStackFrame);
  9095. if (IsMiniDumpDebugger())
  9096. {
  9097. // Make sure to queue up any debug stuff we need
  9098. UpdateCallStackMethod((int)mCallStack.size() - 1);
  9099. }
  9100. if (wdStackFrame->mIsEnd)
  9101. break;
  9102. // Time-limit callstack generation. Most useful for debug mode.
  9103. if ((slowEarlyOut) && ((fillIdx % 100) == 0))
  9104. {
  9105. uint32 tickEnd = BFTickCount();
  9106. if (tickEnd - tickStart >= 10)
  9107. {
  9108. isPartial = true;
  9109. break;
  9110. }
  9111. }
  9112. }
  9113. if (!isPartial)
  9114. mIsPartialCallStack = false;
  9115. }
  9116. int WinDebugger::GetCallStackCount()
  9117. {
  9118. AutoCrit autoCrit(mDebugManager->mCritSect);
  9119. return (int)mCallStack.size();
  9120. }
  9121. int WinDebugger::GetRequestedStackFrameIdx()
  9122. {
  9123. AutoCrit autoCrit(mDebugManager->mCritSect);
  9124. if ((mActiveThread == mExplicitStopThread) && (mRequestedStackFrameIdx >= -1))
  9125. {
  9126. if (mActiveBreakpoint != NULL)
  9127. mRequestedStackFrameIdx = GetBreakStackFrameIdx();
  9128. if (mRequestedStackFrameIdx == -1)
  9129. mRequestedStackFrameIdx = 0;
  9130. return mRequestedStackFrameIdx;
  9131. }
  9132. int newCallStackIdx = 0;
  9133. while (true)
  9134. {
  9135. if (newCallStackIdx >= (int)mCallStack.size() - 1)
  9136. UpdateCallStack();
  9137. if (newCallStackIdx >= (int)mCallStack.size() - 1)
  9138. break;
  9139. intptr addr;
  9140. String file;
  9141. int hotIdx;
  9142. int defLineStart;
  9143. int defLineEnd;
  9144. int line;
  9145. int column;
  9146. int language;
  9147. int stackSize;
  9148. int8 flags;
  9149. GetStackFrameInfo(newCallStackIdx, &addr, &file, &hotIdx, &defLineStart, &defLineEnd, &line, &column, &language, &stackSize, &flags);
  9150. if (!file.empty())
  9151. return newCallStackIdx;
  9152. newCallStackIdx++;
  9153. }
  9154. return 0;
  9155. }
  9156. int WinDebugger::GetBreakStackFrameIdx()
  9157. {
  9158. AutoCrit autoCrit(mDebugManager->mCritSect);
  9159. if ((mActiveBreakpoint == NULL) || (mRunState != RunState_Breakpoint))
  9160. return -1;
  9161. if ((mBreakStackFrameIdx != -1) || (mActiveThread != mExplicitStopThread))
  9162. return mBreakStackFrameIdx;
  9163. mBreakStackFrameIdx = 0;
  9164. BF_ASSERT(mActiveBreakpoint != NULL);
  9165. if (mCallStack.IsEmpty())
  9166. UpdateCallStack();
  9167. if (!mCallStack.IsEmpty())
  9168. {
  9169. UpdateCallStackMethod(0);
  9170. for (int stackIdx = 0; stackIdx < (int)mCallStack.size(); stackIdx++)
  9171. {
  9172. auto callStackEntry = mCallStack[stackIdx];
  9173. if (callStackEntry->mSubProgram == NULL)
  9174. break;
  9175. if ((mActiveBreakpoint->mAddr < callStackEntry->mSubProgram->mBlock.mLowPC) ||
  9176. (mActiveBreakpoint->mAddr >= callStackEntry->mSubProgram->mBlock.mHighPC))
  9177. break;
  9178. DbgSubprogram* specificSubprogram = callStackEntry->mSubProgram;
  9179. auto dwLineData = callStackEntry->mSubProgram->FindClosestLine(mActiveBreakpoint->mAddr, &specificSubprogram);
  9180. if (dwLineData == NULL)
  9181. break;
  9182. if (mActiveBreakpoint->mLineData == dwLineData)
  9183. {
  9184. mBreakStackFrameIdx = stackIdx;
  9185. break;
  9186. }
  9187. }
  9188. }
  9189. return mBreakStackFrameIdx;
  9190. }
  9191. static const char* SafeString(const char* str)
  9192. {
  9193. if (str == NULL)
  9194. return "???";
  9195. return str;
  9196. }
  9197. void WinDebugger::UpdateRegisterUsage(int stackFrameIdx)
  9198. {
  9199. WdStackFrame* wdStackFrame = mCallStack[stackFrameIdx];
  9200. if (wdStackFrame->mRegForms.size() != 0)
  9201. return;
  9202. auto dwSubprogram = wdStackFrame->mSubProgram;
  9203. if (dwSubprogram == NULL)
  9204. return;
  9205. addr_target addr = dwSubprogram->mBlock.mLowPC;
  9206. const uint8* baseOp = nullptr;
  9207. while (addr < dwSubprogram->mBlock.mHighPC)
  9208. {
  9209. CPUInst inst;
  9210. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  9211. break;
  9212. bool overrideForm = inst.mAddress <= (addr_target)wdStackFrame->mRegisters.GetPC();
  9213. inst.MarkRegsUsed(wdStackFrame->mRegForms, overrideForm);
  9214. addr += inst.GetLength();
  9215. }
  9216. }
  9217. // It's safe to pass an invalid idx in here
  9218. void WinDebugger::UpdateCallStackMethod(int stackFrameIdx)
  9219. {
  9220. if (mCallStack.empty())
  9221. return;
  9222. int startIdx = std::min(stackFrameIdx, (int)mCallStack.size() - 1);
  9223. while (startIdx >= 0)
  9224. {
  9225. WdStackFrame* wdStackFrame = mCallStack[startIdx];
  9226. if (wdStackFrame->mHasGottenSubProgram)
  9227. break;
  9228. startIdx--;
  9229. }
  9230. startIdx++;
  9231. for (int checkFrameIdx = startIdx; checkFrameIdx <= stackFrameIdx; checkFrameIdx++)
  9232. {
  9233. //BF_ASSERT(checkFrameIdx < mCallStack.size());
  9234. if (checkFrameIdx >= mCallStack.size())
  9235. break;
  9236. WdStackFrame* wdStackFrame = mCallStack[checkFrameIdx];
  9237. wdStackFrame->mHasGottenSubProgram = true;
  9238. addr_target pcAddress = (addr_target)wdStackFrame->GetSourcePC();
  9239. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress, DbgOnDemandKind_LocalOnly);
  9240. wdStackFrame->mHasGottenSubProgram = true;
  9241. wdStackFrame->mSubProgram = dwSubprogram;
  9242. if ((dwSubprogram == NULL) && (IsMiniDumpDebugger()))
  9243. {
  9244. // FindSymbolAt will queue up debug info if necessary...
  9245. String symbolName;
  9246. addr_target offset;
  9247. DbgModule* dbgModule;
  9248. mDebugTarget->FindSymbolAt(pcAddress, &symbolName, &offset, &dbgModule);
  9249. }
  9250. // Insert inlines
  9251. int insertIdx = checkFrameIdx + 1;
  9252. while ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL))
  9253. {
  9254. WdStackFrame* inlineStackFrame = new WdStackFrame();
  9255. *inlineStackFrame = *wdStackFrame;
  9256. inlineStackFrame->mInInlineMethod = true;
  9257. wdStackFrame->mInInlineCall = true;
  9258. inlineStackFrame->mSubProgram = dwSubprogram->mInlineeInfo->mInlineParent;
  9259. mCallStack.Insert(insertIdx, inlineStackFrame);
  9260. dwSubprogram = dwSubprogram->mInlineeInfo->mInlineParent;
  9261. insertIdx++;
  9262. checkFrameIdx++;
  9263. }
  9264. }
  9265. }
  9266. void WinDebugger::GetCodeAddrInfo(intptr addr, String* outFile, int* outHotIdx, int* outDefLineStart, int* outDefLineEnd, int* outLine, int* outColumn)
  9267. {
  9268. AutoCrit autoCrit(mDebugManager->mCritSect);
  9269. DbgSubprogram* subProgram = NULL;
  9270. DbgLineData* callingLineData = FindLineDataAtAddress((addr_target)addr, &subProgram);
  9271. if (subProgram != NULL)
  9272. {
  9273. *outHotIdx = subProgram->mCompileUnit->mDbgModule->mHotIdx;
  9274. *outFile = subProgram->GetLineSrcFile(*callingLineData)->GetLocalPath();
  9275. *outLine = callingLineData->mLine;
  9276. *outColumn = callingLineData->mColumn;
  9277. FixupLineDataForSubprogram(subProgram);
  9278. DbgLineData* dwStartLineData = NULL;
  9279. DbgLineData* dwEndLineData = NULL;
  9280. if (subProgram->mLineInfo != NULL)
  9281. {
  9282. if (subProgram->mLineInfo->mLines.size() > 0)
  9283. {
  9284. dwStartLineData = &subProgram->mLineInfo->mLines[0];
  9285. dwEndLineData = &subProgram->mLineInfo->mLines.back();
  9286. }
  9287. }
  9288. else
  9289. {
  9290. if (subProgram->mInlineeInfo != NULL)
  9291. {
  9292. dwStartLineData = &subProgram->mInlineeInfo->mFirstLineData;
  9293. dwEndLineData = &subProgram->mInlineeInfo->mLastLineData;
  9294. }
  9295. }
  9296. if (dwEndLineData != NULL)
  9297. {
  9298. *outDefLineStart = dwStartLineData->mLine;
  9299. *outDefLineEnd = dwEndLineData->mLine;
  9300. }
  9301. }
  9302. }
  9303. void WinDebugger::GetStackAllocInfo(intptr addr, int* outThreadId, int* outStackIdx)
  9304. {
  9305. AutoCrit autoCrit(mDebugManager->mCritSect);
  9306. *outThreadId = 0;
  9307. if (outStackIdx != NULL)
  9308. *outStackIdx = -1;
  9309. if (!IsPaused())
  9310. return;
  9311. for (auto thread : mThreadList)
  9312. {
  9313. NT_TIB64 tib = { 0 };
  9314. if (!ReadMemory((intptr)thread->mThreadLocalBase, sizeof(tib), &tib))
  9315. continue;
  9316. MEMORY_BASIC_INFORMATION stackInfo = { 0 };
  9317. if (VirtualQueryEx(mProcessInfo.hProcess, (void*)(tib.StackBase - 1), &stackInfo, sizeof(MEMORY_BASIC_INFORMATION)) == 0)
  9318. continue;
  9319. if ((addr >= (intptr)stackInfo.AllocationBase) && (addr < (intptr)tib.StackBase))
  9320. {
  9321. *outThreadId = thread->mThreadId;
  9322. if (outStackIdx == NULL)
  9323. return;
  9324. if (mActiveThread == thread)
  9325. {
  9326. UpdateCallStack(false);
  9327. for (int callStackIdx = 0; callStackIdx < (int)mCallStack.size(); callStackIdx++)
  9328. {
  9329. UpdateCallStackMethod(callStackIdx);
  9330. auto stackFrame = mCallStack[callStackIdx];
  9331. if (addr >= (intptr)stackFrame->mRegisters.GetSP())
  9332. {
  9333. *outStackIdx = callStackIdx;
  9334. }
  9335. }
  9336. }
  9337. return;
  9338. }
  9339. }
  9340. }
  9341. String WinDebugger::GetStackFrameInfo(int stackFrameIdx, intptr* addr, String* outFile, int* outHotIdx, int* outDefLineStart, int* outDefLineEnd,
  9342. int* outLine, int* outColumn, int* outLanguage, int* outStackSize, int8* outFlags)
  9343. {
  9344. enum FrameFlags
  9345. {
  9346. FrameFlags_Optimized = 1,
  9347. FrameFlags_HasPendingDebugInfo = 2,
  9348. FrameFlags_CanGetOldSource = 4,
  9349. FrameFlags_WasHotReplaced = 8,
  9350. };
  9351. AutoCrit autoCrit(mDebugManager->mCritSect);
  9352. if (mCallStack.size() == 0)
  9353. UpdateCallStack();
  9354. *addr = 0;
  9355. *outFile = "";
  9356. *outHotIdx = 0;
  9357. *outDefLineStart = -1;
  9358. *outDefLineEnd = -1;
  9359. *outLine = -1;
  9360. *outColumn = 0;
  9361. *outLanguage = 0;
  9362. *outStackSize = 0;
  9363. *outFlags = 0;
  9364. UpdateCallStackMethod(stackFrameIdx);
  9365. if (stackFrameIdx >= mCallStack.size())
  9366. {
  9367. return "";
  9368. }
  9369. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9370. UpdateCallStackMethod(actualStackFrameIdx);
  9371. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9372. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  9373. if (stackFrameIdx == -1)
  9374. pcAddress = mShowPCOverride;
  9375. *addr = pcAddress;
  9376. if (actualStackFrameIdx < (int)mCallStack.size() - 2)
  9377. {
  9378. WdStackFrame* prevStackFrame = mCallStack[actualStackFrameIdx + 1];
  9379. // Inlined methods have no stack frame
  9380. *outStackSize = prevStackFrame->mRegisters.GetSP() - wdStackFrame->mRegisters.GetSP();
  9381. }
  9382. const auto& _CheckHashSrcFile = [&](String& outStr, DbgModule* dbgModule, DbgSrcFile* srcFile)
  9383. {
  9384. if (srcFile->mHashKind != DbgHashKind_None)
  9385. {
  9386. outStr += "#";
  9387. srcFile->GetHash(outStr);
  9388. }
  9389. };
  9390. auto _SetFlags = [&](DbgSubprogram* dwSubprogram)
  9391. {
  9392. DbgModule* dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  9393. if (dwSubprogram->mIsOptimized)
  9394. *outFlags |= FrameFlags_Optimized;
  9395. if (dbgModule->HasPendingDebugInfo())
  9396. *outFlags |= FrameFlags_HasPendingDebugInfo;
  9397. if (dbgModule->CanGetOldSource())
  9398. *outFlags |= FrameFlags_CanGetOldSource;
  9399. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) || (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid))
  9400. *outFlags |= FrameFlags_WasHotReplaced;
  9401. };
  9402. if (wdStackFrame->mInInlineMethod)
  9403. {
  9404. WdStackFrame* nextStackFrame = mCallStack[actualStackFrameIdx - 1];
  9405. auto subProgram = nextStackFrame->mSubProgram;
  9406. _SetFlags(subProgram);
  9407. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  9408. DbgSubprogram* parentSubprogram = subProgram->mInlineeInfo->mInlineParent; // Require it be in the inline parent
  9409. auto foundLine = parentSubprogram->FindClosestLine(subProgram->mBlock.mLowPC, &parentSubprogram);
  9410. if (foundLine != NULL)
  9411. {
  9412. auto srcFile = parentSubprogram->GetLineSrcFile(*foundLine);
  9413. *outFile = srcFile->GetLocalPath();
  9414. _CheckHashSrcFile(*outFile, subProgram->mCompileUnit->mDbgModule, srcFile);
  9415. *outLine = foundLine->mLine;
  9416. }
  9417. *outLanguage = subProgram->GetLanguage();
  9418. *outHotIdx = subProgram->mCompileUnit->mDbgModule->mHotIdx;
  9419. *outColumn = -1;
  9420. DbgSubprogram* callingSubProgram = NULL;
  9421. DbgLineData* callingLineData = FindLineDataAtAddress(nextStackFrame->mSubProgram->mBlock.mLowPC - 1, &callingSubProgram);
  9422. if ((callingLineData != NULL) && (callingSubProgram == wdStackFrame->mSubProgram))
  9423. {
  9424. auto callingSrcFile = callingSubProgram->GetLineSrcFile(*callingLineData);
  9425. *outLanguage = callingSubProgram->mCompileUnit->mLanguage;
  9426. auto srcFile = callingSrcFile;
  9427. *outFile = srcFile->GetLocalPath();
  9428. _CheckHashSrcFile(*outFile, subProgram->mCompileUnit->mDbgModule, srcFile);
  9429. if (*outLine == callingLineData->mLine)
  9430. *outColumn = callingLineData->mColumn;
  9431. }
  9432. String name = wdStackFrame->mSubProgram->ToString();
  9433. DbgModule* dbgModule = wdStackFrame->mSubProgram->mCompileUnit->mDbgModule;
  9434. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  9435. if (!linkedModule->mDisplayName.empty())
  9436. name = linkedModule->mDisplayName + "!" + name;
  9437. return name;
  9438. }
  9439. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  9440. if (dwSubprogram != NULL)
  9441. {
  9442. String demangledName;
  9443. if ((dwSubprogram->mName != NULL) && (strncmp(dwSubprogram->mName, ":Sep@", 5) == 0))
  9444. {
  9445. char* p;
  9446. auto addr = strtoll(dwSubprogram->mName + 5, &p, 16);
  9447. if (addr != 0)
  9448. {
  9449. auto parentSubprogram = mDebugTarget->FindSubProgram(addr);
  9450. if (parentSubprogram != NULL)
  9451. demangledName = parentSubprogram->ToString();
  9452. }
  9453. }
  9454. if (demangledName.IsEmpty())
  9455. {
  9456. dwSubprogram->ToString(demangledName, true);
  9457. }
  9458. DbgSrcFile* dwSrcFile = NULL;
  9459. DbgLineData* dwLineData = NULL;
  9460. FixupLineDataForSubprogram(dwSubprogram);
  9461. addr_target findAddress = wdStackFrame->GetSourcePC();
  9462. DbgSubprogram* specificSubprogram = dwSubprogram;
  9463. dwLineData = dwSubprogram->FindClosestLine(findAddress, &specificSubprogram);
  9464. if (dwLineData != NULL)
  9465. dwSrcFile = dwSubprogram->GetLineSrcFile(*dwLineData);
  9466. DbgLineData* dwStartLineData = NULL;
  9467. DbgLineData* dwEndLineData = NULL;
  9468. if (dwSubprogram->mLineInfo != NULL)
  9469. {
  9470. if (dwSubprogram->mLineInfo->mLines.size() > 0)
  9471. {
  9472. dwStartLineData = &dwSubprogram->mLineInfo->mLines[0];
  9473. dwEndLineData = &dwSubprogram->mLineInfo->mLines.back();
  9474. }
  9475. }
  9476. else
  9477. {
  9478. if (dwSubprogram->mInlineeInfo != NULL)
  9479. {
  9480. dwStartLineData = &dwSubprogram->mInlineeInfo->mFirstLineData;
  9481. dwEndLineData = &dwSubprogram->mInlineeInfo->mLastLineData;
  9482. }
  9483. }
  9484. DbgModule* dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  9485. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  9486. if (!linkedModule->mDisplayName.empty())
  9487. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  9488. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) || (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid))
  9489. demangledName = "#" + demangledName;
  9490. _SetFlags(dwSubprogram);
  9491. if ((dwLineData != NULL) && (dwSrcFile != NULL))
  9492. {
  9493. *outFile = dwSrcFile->GetLocalPath();
  9494. _CheckHashSrcFile(*outFile, dbgModule, dwSrcFile);
  9495. *outHotIdx = dbgModule->mHotIdx;
  9496. *outLine = dwLineData->mLine;
  9497. *outColumn = dwLineData->mColumn;
  9498. *outLanguage = (int)dwSubprogram->mCompileUnit->mLanguage;
  9499. if (dwEndLineData != NULL)
  9500. {
  9501. *outDefLineStart = dwStartLineData->mLine;
  9502. *outDefLineEnd = dwEndLineData->mLine;
  9503. }
  9504. return demangledName;
  9505. }
  9506. else
  9507. {
  9508. return demangledName + StrFormat("+0x%X", pcAddress - dwSubprogram->mBlock.mLowPC);
  9509. }
  9510. }
  9511. else
  9512. {
  9513. String symbolName;
  9514. addr_target offset;
  9515. DbgModule* dbgModule;
  9516. if (mDebugTarget->FindSymbolAt(pcAddress, &symbolName, &offset, &dbgModule))
  9517. {
  9518. if (dbgModule->HasPendingDebugInfo())
  9519. {
  9520. *outFlags |= FrameFlags_HasPendingDebugInfo;
  9521. if (mPendingDebugInfoLoad.ContainsKey(dbgModule))
  9522. {
  9523. String outName = EncodeDataPtr(pcAddress, true);
  9524. if ((dbgModule != NULL) && (!dbgModule->mDisplayName.empty()))
  9525. outName = dbgModule->mDisplayName + "!<Loading...>" + outName;
  9526. return outName;
  9527. }
  9528. }
  9529. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  9530. String demangledName = BfDemangler::Demangle(symbolName, DbgLanguage_Unknown);
  9531. if (!linkedModule->mDisplayName.empty())
  9532. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  9533. return demangledName + StrFormat("+0x%X", offset);
  9534. }
  9535. }
  9536. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress(pcAddress);
  9537. DbgModule* linkedModule = NULL;
  9538. if (dbgModule != NULL)
  9539. {
  9540. linkedModule = dbgModule->GetLinkedModule();
  9541. if (dbgModule->HasPendingDebugInfo())
  9542. *outFlags |= FrameFlags_HasPendingDebugInfo;
  9543. }
  9544. String outName = EncodeDataPtr(pcAddress, true);
  9545. if ((linkedModule != NULL) && (!linkedModule->mDisplayName.empty()))
  9546. outName = linkedModule->mDisplayName + "!" + outName;
  9547. return outName;
  9548. }
  9549. String WinDebugger::Callstack_GetStackFrameOldFileInfo(int stackFrameIdx)
  9550. {
  9551. AutoCrit autoCrit(mDebugManager->mCritSect);
  9552. if (!FixCallStackIdx(stackFrameIdx))
  9553. return "";
  9554. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9555. UpdateCallStackMethod(actualStackFrameIdx);
  9556. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9557. DbgModule* dbgModule = NULL;
  9558. DbgSrcFile* dbgSrcFile = NULL;
  9559. if (wdStackFrame->mInInlineMethod)
  9560. {
  9561. WdStackFrame* nextStackFrame = mCallStack[actualStackFrameIdx - 1];
  9562. auto subProgram = nextStackFrame->mSubProgram;
  9563. dbgModule = subProgram->mCompileUnit->mDbgModule;
  9564. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  9565. DbgSubprogram* parentSubprogram = subProgram->mInlineeInfo->mInlineParent; // Require it be in the inline parent
  9566. auto foundLine = parentSubprogram->FindClosestLine(subProgram->mBlock.mLowPC, &parentSubprogram);
  9567. if (foundLine != NULL)
  9568. dbgSrcFile = parentSubprogram->GetLineSrcFile(*foundLine);
  9569. DbgSubprogram* callingSubProgram = NULL;
  9570. DbgLineData* callingLineData = FindLineDataAtAddress(nextStackFrame->mSubProgram->mBlock.mLowPC - 1, &callingSubProgram);
  9571. if ((callingLineData != NULL) && (callingSubProgram == wdStackFrame->mSubProgram))
  9572. dbgSrcFile = callingSubProgram->GetLineSrcFile(*callingLineData);
  9573. }
  9574. else
  9575. {
  9576. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  9577. if (dwSubprogram != NULL)
  9578. {
  9579. FixupLineDataForSubprogram(dwSubprogram);
  9580. addr_target findAddress = wdStackFrame->GetSourcePC();
  9581. DbgSubprogram* dbgSubprogram = NULL;
  9582. DbgLineData* dwLineData = dwSubprogram->FindClosestLine(findAddress, &dbgSubprogram, &dbgSrcFile);
  9583. dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  9584. }
  9585. }
  9586. if (dbgSrcFile != NULL)
  9587. {
  9588. // Note: we must use mFilePath here, make sure we don't use GetLocalPath()
  9589. return dbgModule->GetOldSourceCommand(dbgSrcFile->mFilePath);
  9590. }
  9591. return "";
  9592. }
  9593. int WinDebugger::GetJmpState(int stackFrameIdx)
  9594. {
  9595. AutoCrit autoCrit(mDebugManager->mCritSect);
  9596. if (!FixCallStackIdx(stackFrameIdx))
  9597. return -1;
  9598. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9599. UpdateCallStackMethod(actualStackFrameIdx);
  9600. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9601. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  9602. CPUInst inst;
  9603. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  9604. return -1;
  9605. return inst.GetJmpState(wdStackFrame->mRegisters.mIntRegs.efl);
  9606. }
  9607. intptr WinDebugger::GetStackFrameCalleeAddr(int stackFrameIdx)
  9608. {
  9609. AutoCrit autoCrit(mDebugManager->mCritSect);
  9610. if (!FixCallStackIdx(stackFrameIdx))
  9611. return -1;
  9612. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9613. UpdateCallStackMethod(actualStackFrameIdx);
  9614. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9615. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  9616. if (stackFrameIdx == -1)
  9617. pcAddress = mShowPCOverride;
  9618. if (wdStackFrame->mInInlineMethod)
  9619. {
  9620. WdStackFrame* inlineStackFrame = mCallStack[actualStackFrameIdx - 1];
  9621. return inlineStackFrame->mSubProgram->mBlock.mLowPC - 1;
  9622. }
  9623. return pcAddress - 1;
  9624. }
  9625. String WinDebugger::GetStackMethodOwner(int stackFrameIdx, int& language)
  9626. {
  9627. AutoCrit autoCrit(mDebugManager->mCritSect);
  9628. if (!FixCallStackIdx(stackFrameIdx))
  9629. return "";
  9630. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9631. if (actualStackFrameIdx >= (int)mCallStack.size())
  9632. actualStackFrameIdx = 0;
  9633. UpdateCallStackMethod(actualStackFrameIdx);
  9634. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9635. if (wdStackFrame->mSubProgram == NULL)
  9636. return "";
  9637. auto parentType = wdStackFrame->mSubProgram->GetParent();
  9638. if (parentType == NULL)
  9639. return "";
  9640. parentType = parentType->GetPrimaryType();
  9641. language = (int)parentType->GetLanguage();
  9642. return parentType->ToString();
  9643. }
  9644. String WinDebugger::FindCodeAddresses(const StringImpl& fileName, int line, int column, bool allowAutoResolve)
  9645. {
  9646. String result;
  9647. if (mDebugTarget == NULL)
  9648. return "";
  9649. DbgSrcFile* srcFile = mDebugTarget->GetSrcFile(fileName);
  9650. if (srcFile == NULL)
  9651. return result;
  9652. bool foundInSequence = false;
  9653. WdBreakpoint* prevBreakpoint = NULL;
  9654. int bestLineOffset = 0x7FFFFFFF;
  9655. for (auto dbgSubprogram : srcFile->mLineDataRefs)
  9656. {
  9657. for (auto& lineData : dbgSubprogram->mLineInfo->mLines)
  9658. {
  9659. auto lineSrcFile = dbgSubprogram->GetLineSrcFile(lineData);
  9660. if (lineSrcFile != srcFile)
  9661. continue;
  9662. int lineOffset = lineData.mLine - line;
  9663. if ((lineOffset >= 0) && (lineOffset <= 12) && (lineOffset <= bestLineOffset))
  9664. {
  9665. if (lineOffset < bestLineOffset)
  9666. {
  9667. bestLineOffset = lineOffset;
  9668. result = "";
  9669. }
  9670. if (!foundInSequence)
  9671. {
  9672. auto addr = dbgSubprogram->GetLineAddr(lineData);
  9673. result += EncodeDataPtr(addr, false) + "\t" + dbgSubprogram->ToString() + "\n";
  9674. }
  9675. }
  9676. // New sequence?
  9677. if (!lineData.IsStackFrameSetup())
  9678. foundInSequence = false;
  9679. }
  9680. }
  9681. return result;
  9682. }
  9683. String WinDebugger::GetAddressSourceLocation(intptr address)
  9684. {
  9685. DbgSubprogram* subProgram = NULL;
  9686. DbgLineData* lineData = FindLineDataAtAddress(address, &subProgram);
  9687. if (lineData != NULL)
  9688. return StrFormat("%s:%d:%d", subProgram->GetLineSrcFile(*lineData)->GetLocalPath().c_str(), lineData->mLine + 1, lineData->mColumn + 1);
  9689. String outSymbol;
  9690. addr_target offset = 0;
  9691. DbgModule* dbgModule;
  9692. if (mDebugTarget->FindSymbolAt(address, &outSymbol, &offset, &dbgModule))
  9693. {
  9694. if (offset < 0x10000)
  9695. {
  9696. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9697. if (offset > 0)
  9698. outSymbol += StrFormat("+%x", offset);
  9699. return outSymbol;
  9700. }
  9701. }
  9702. return StrFormat("0x%@", address);
  9703. }
  9704. String WinDebugger::GetAddressSymbolName(intptr address, bool demangle)
  9705. {
  9706. String outSymbol;
  9707. addr_target offset = 0;
  9708. DbgModule* dbgModule;
  9709. if (mDebugTarget->FindSymbolAt(address, &outSymbol, &offset, &dbgModule))
  9710. {
  9711. if (offset < 0x10000)
  9712. {
  9713. if (demangle)
  9714. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9715. if (offset > 0)
  9716. outSymbol += StrFormat("+%x", offset);
  9717. return outSymbol;
  9718. }
  9719. }
  9720. return StrFormat("0x%@", address);
  9721. }
  9722. String WinDebugger::DisassembleAtRaw(intptr inAddress)
  9723. {
  9724. addr_target address = (addr_target)inAddress;
  9725. const int addrBorder = 1024;
  9726. for (int offset = 0; offset < 8; offset++)
  9727. {
  9728. String result;
  9729. bool addOffset = true;
  9730. bool hadAddr = false;
  9731. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress(address);
  9732. DbgModuleMemoryCache* memCache = NULL;
  9733. defer
  9734. (
  9735. if (dbgModule == NULL)
  9736. delete memCache;
  9737. );
  9738. if ((dbgModule != NULL) && (dbgModule->mOrigImageData == NULL))
  9739. dbgModule = NULL;
  9740. result += "R\n"; // Raw
  9741. addr_target addrStart = address;
  9742. if (dbgModule != NULL)
  9743. {
  9744. dbgModule->ParseSymbolData();
  9745. memCache = dbgModule->mOrigImageData;
  9746. addrStart = BF_MAX((addr_target)dbgModule->mImageBase, address - addrBorder - offset);
  9747. }
  9748. else
  9749. {
  9750. memCache = new DbgModuleMemoryCache(addrStart & (4096 - 1), 4096 * 2);
  9751. }
  9752. //addr_target imageBase = dbgModule->mImageBase;
  9753. //int imageSize = dbgModule->mImageSize;
  9754. addr_target dataAddr = addrStart;
  9755. addr_target addrEnd = addrStart + addrBorder * 2 + 16;
  9756. while (dataAddr < addrEnd)
  9757. {
  9758. if (dataAddr == address)
  9759. hadAddr = true;
  9760. if (dataAddr > address)
  9761. {
  9762. if (!hadAddr)
  9763. {
  9764. if (offset == 7)
  9765. {
  9766. dataAddr = address;
  9767. }
  9768. break;
  9769. }
  9770. }
  9771. String outSymbol;
  9772. addr_target symOffset = 0;
  9773. DbgModule* symDWARF;
  9774. if (mDebugTarget->FindSymbolAt(dataAddr, &outSymbol, &symOffset, &symDWARF))
  9775. {
  9776. if (symOffset == 0)
  9777. {
  9778. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9779. if ((symDWARF != NULL) && (!symDWARF->mDisplayName.empty()))
  9780. outSymbol = symDWARF->GetLinkedModule()->mDisplayName + "!" + outSymbol;
  9781. result += "T " + outSymbol + ":\n";
  9782. }
  9783. }
  9784. CPUInst inst;
  9785. if (!mCPU->Decode(dataAddr, memCache, &inst))
  9786. {
  9787. if ((offset == 7) && (!hadAddr))
  9788. {
  9789. uint8 instData[1];
  9790. memCache->Read(dataAddr, instData, 1);
  9791. int instLen = 1;
  9792. #ifdef BF_DBG_32
  9793. result += StrFormat("D %08X: ", dataAddr);
  9794. #else
  9795. result += StrFormat("D %@: ", dataAddr);
  9796. #endif
  9797. for (int i = 0; i < instLen; i++)
  9798. result += StrFormat("%02X ", instData[i]);
  9799. for (int i = instLen; i < 8; i++)
  9800. result += " ";
  9801. result += "\n";
  9802. dataAddr++;
  9803. continue;
  9804. }
  9805. break;
  9806. }
  9807. int instLen = inst.GetLength();
  9808. #ifdef BF_DBG_32
  9809. result += StrFormat("D %08X: ", dataAddr);
  9810. #else
  9811. result += StrFormat("D %@: ", dataAddr);
  9812. #endif
  9813. uint8 instData[32];
  9814. int showInstLen = BF_MIN(32, instLen);
  9815. memCache->Read(dataAddr, instData, showInstLen);
  9816. for (int i = 0; i < showInstLen; i++)
  9817. result += StrFormat("%02X ", instData[i]);
  9818. for (int i = instLen; i < 8; i++)
  9819. result += " ";
  9820. result += mCPU->InstructionToString(&inst, dataAddr);
  9821. if ((inst.IsCall()) || (inst.IsBranch()))
  9822. {
  9823. addr_target targetAddr = inst.GetTarget();
  9824. if (targetAddr != 0)
  9825. {
  9826. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &symOffset))
  9827. {
  9828. if (symOffset < 0x10000)
  9829. {
  9830. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  9831. result += " ; " + outSymbol;
  9832. if (symOffset > 0)
  9833. result += StrFormat("+%x", symOffset);
  9834. //result += ">";
  9835. }
  9836. }
  9837. }
  9838. }
  9839. result += "\n";
  9840. dataAddr += instLen;
  9841. }
  9842. if (!hadAddr)
  9843. continue;
  9844. return result;
  9845. }
  9846. return "";
  9847. }
  9848. String WinDebugger::DisassembleAt(intptr inAddress)
  9849. {
  9850. BP_ZONE("WinDebugger::DisassembleAt");
  9851. AutoCrit autoCrit(mDebugManager->mCritSect);
  9852. addr_target address = (addr_target)inAddress;
  9853. if (mDebugTarget == NULL)
  9854. return "";
  9855. String result;
  9856. auto dwSubProgram = mDebugTarget->FindSubProgram(address);
  9857. if (dwSubProgram == NULL)
  9858. return DisassembleAtRaw(address);
  9859. dwSubProgram = dwSubProgram->GetRootInlineParent();
  9860. DbgModule* dwarf = dwSubProgram->mCompileUnit->mDbgModule;
  9861. int frameBaseRegister = mDebugTarget->GetFrameBaseRegister(dwSubProgram);
  9862. addr_target addrStart = dwSubProgram->mBlock.mLowPC;
  9863. addr_target addrEnd = dwSubProgram->mBlock.mHighPC;
  9864. auto dwCompileUnit = dwSubProgram->mCompileUnit;
  9865. {
  9866. FixupLineData(dwCompileUnit);
  9867. }
  9868. DbgSrcFile* dwSrcFile = NULL;
  9869. FixupLineDataForSubprogram(dwSubProgram);
  9870. DbgLineData* dwLineData = NULL;
  9871. if (dwSubProgram->mLineInfo != NULL)
  9872. dwLineData = &dwSubProgram->mLineInfo->mLines[0];
  9873. int nextLineDataIdx = 1;
  9874. if (dwSubProgram->mIsOptimized)
  9875. result += "O\n";
  9876. DbgSrcFile* srcFile = NULL;
  9877. int firstLine = 0;
  9878. int curLine = 0;
  9879. if (dwLineData != NULL)
  9880. {
  9881. srcFile = dwSubProgram->GetLineSrcFile(*dwLineData);
  9882. result += "S " + srcFile->GetLocalPath() + "\n";
  9883. if (srcFile->mHashKind != DbgHashKind_None)
  9884. {
  9885. result += "H ";
  9886. srcFile->GetHash(result);
  9887. result += "\n";
  9888. }
  9889. curLine = BF_MAX(0, dwLineData->mLine - 5);
  9890. //for (; curLine <= dwLineData->mLine; curLine++)
  9891. result += StrFormat("L %d %d\n", curLine, dwLineData->mLine - curLine + 1);
  9892. curLine = dwLineData->mLine + 1;
  9893. firstLine = dwLineData->mLine;
  9894. }
  9895. Array<DbgSubprogram*> inlineStack;
  9896. Array<DbgBlock*> blockList;
  9897. blockList.push_back(&dwSubProgram->mBlock);
  9898. addr_target dataAddr = addrStart;
  9899. int decodeFailureCount = 0;
  9900. auto& _PopInlineStack = [&]()
  9901. {
  9902. int depth = inlineStack.size();
  9903. auto curStackEntry = inlineStack.back();
  9904. if (depth > 1)
  9905. result += StrFormat("T <<<%d Inline End ", depth);
  9906. else
  9907. result += "T <<< Inline End ";
  9908. result += curStackEntry->ToString();
  9909. result += "\n";
  9910. inlineStack.pop_back();
  9911. };
  9912. std::function<void(DbgSubprogram* subprogram, int depth)> _UpdateInlineStackHelper = [&](DbgSubprogram* subprogram, int depth)
  9913. {
  9914. int stackIdx = depth - 1;
  9915. if (stackIdx < inlineStack.size())
  9916. {
  9917. auto curStackEntry = inlineStack[stackIdx];
  9918. if (curStackEntry != subprogram)
  9919. _PopInlineStack();
  9920. }
  9921. if (depth > 1)
  9922. {
  9923. _UpdateInlineStackHelper(subprogram->mInlineeInfo->mInlineParent, depth - 1);
  9924. }
  9925. if (stackIdx >= inlineStack.size())
  9926. {
  9927. if (depth > 1)
  9928. result += StrFormat("T >>>%d Inline ", depth);
  9929. else
  9930. result += "T >>> Inline ";
  9931. result += subprogram->ToString();
  9932. result += "\n";
  9933. inlineStack.push_back(subprogram);
  9934. }
  9935. };
  9936. auto _UpdateInlineStack = [&](DbgSubprogram* subprogram)
  9937. {
  9938. if (subprogram == NULL)
  9939. {
  9940. while (!inlineStack.IsEmpty())
  9941. _PopInlineStack();
  9942. return;
  9943. }
  9944. int inlineDepth = subprogram->GetInlineDepth();
  9945. while (inlineDepth < inlineStack.size())
  9946. _PopInlineStack();
  9947. if (inlineDepth > 0)
  9948. _UpdateInlineStackHelper(subprogram, inlineDepth);
  9949. };
  9950. while (dataAddr < addrEnd)
  9951. {
  9952. // Pop off old scopes
  9953. while (blockList.size() > 0)
  9954. {
  9955. auto lastBlock = blockList.back();
  9956. if (dataAddr < lastBlock->mHighPC)
  9957. break;
  9958. blockList.pop_back();
  9959. }
  9960. // Check entry into new child scopes
  9961. auto lastBlock = blockList.back();
  9962. for (auto checkBlock : lastBlock->mSubBlocks)
  9963. {
  9964. if ((dataAddr >= checkBlock->mLowPC) && (dataAddr < checkBlock->mHighPC))
  9965. {
  9966. blockList.push_back(checkBlock);
  9967. break;
  9968. }
  9969. }
  9970. bool allowSourceJump = false;
  9971. if ((dwLineData != NULL) && (dwLineData->mContribSize != 0) && (dataAddr >= dwSubProgram->GetLineAddr(*dwLineData) + dwLineData->mContribSize))
  9972. {
  9973. DbgSubprogram* inlinedSubprogram = NULL;
  9974. auto inlinedLine = dwSubProgram->FindClosestLine(dataAddr, &inlinedSubprogram);
  9975. _UpdateInlineStack(dwSubProgram);
  9976. }
  9977. // Update line data
  9978. while ((dwLineData != NULL) && (dwSubProgram->GetLineAddr(*dwLineData) <= dataAddr))
  9979. {
  9980. _UpdateInlineStack(dwSubProgram->GetLineInlinee(*dwLineData));
  9981. const int lineLimit = 5; // 15
  9982. if (allowSourceJump)
  9983. curLine = dwLineData->mLine;
  9984. auto lineSrcFile = dwSubProgram->GetLineSrcFile(*dwLineData);
  9985. if (lineSrcFile != srcFile)
  9986. {
  9987. srcFile = lineSrcFile;
  9988. result += "S ";
  9989. result += srcFile->GetLocalPath();
  9990. result += "\n";
  9991. // Just show the one line from the new file
  9992. curLine = dwLineData->mLine;
  9993. }
  9994. if (dwLineData->mLine < curLine - 1)
  9995. {
  9996. // Jumping backwards - possibly into inlined method, or possibly in current method.
  9997. // Show previous 6 lines, for context
  9998. curLine = BF_MAX(0, dwLineData->mLine - lineLimit);
  9999. }
  10000. if ((curLine <= firstLine) && (dwLineData->mLine >= firstLine))
  10001. {
  10002. // Jumping from inlined method (declared above) back into main method
  10003. curLine = dwLineData->mLine;
  10004. }
  10005. if (curLine < dwLineData->mLine - lineLimit)
  10006. {
  10007. // Don't show huge span of source - only show the last 6 lines at maximum
  10008. curLine = dwLineData->mLine - lineLimit;
  10009. }
  10010. //for ( ; curLine <= dwLineData->mLine; curLine++)
  10011. result += StrFormat("L %d %d\n", curLine, dwLineData->mLine - curLine + 1);
  10012. curLine = dwLineData->mLine + 1;
  10013. DbgLineData* nextLineData = NULL;
  10014. while (nextLineDataIdx < dwSubProgram->mLineInfo->mLines.mSize)
  10015. {
  10016. nextLineData = &dwSubProgram->mLineInfo->mLines[nextLineDataIdx];
  10017. //TODO:
  10018. /*{
  10019. result += StrFormat("T LineIdx: %d (%@ to %@)", nextLineDataIdx, dwSubProgram->GetLineAddr(*nextLineData), dwSubProgram->GetLineAddr(*nextLineData) + nextLineData->mContribSize);
  10020. auto inlinee = dwSubProgram->GetLineInlinee(*nextLineData);
  10021. if (inlinee != NULL)
  10022. {
  10023. result += StrFormat(" Inlinee: %s Depth: %d", inlinee->mName, inlinee->GetInlineDepth());
  10024. }
  10025. result += "\n";
  10026. }*/
  10027. auto nextLineAddr = dwSubProgram->GetLineAddr(*nextLineData);
  10028. if (nextLineAddr > dataAddr)
  10029. {
  10030. if (nextLineDataIdx + 1 < dwSubProgram->mLineInfo->mLines.mSize)
  10031. {
  10032. auto peekLineData = &dwSubProgram->mLineInfo->mLines[nextLineDataIdx + 1];
  10033. if (peekLineData->mRelAddress == nextLineData->mRelAddress)
  10034. {
  10035. // Use the later entry
  10036. ++nextLineDataIdx;
  10037. continue;
  10038. }
  10039. }
  10040. break;
  10041. }
  10042. // If we go back to an older entry beacuse of a gap then we need to catch back up...
  10043. ++nextLineDataIdx;
  10044. nextLineData = NULL; // Keep searching...
  10045. }
  10046. dwLineData = nextLineData;
  10047. nextLineDataIdx++;
  10048. }
  10049. // Have we gone off the end of the inline function?
  10050. // We may not have an explicit non-inlined line data at the transition point...
  10051. while (!inlineStack.IsEmpty())
  10052. {
  10053. auto subProgram = inlineStack.back();
  10054. if (dataAddr < subProgram->mBlock.mHighPC)
  10055. break;
  10056. _PopInlineStack();
  10057. }
  10058. bool hadDecodeFailure = false;
  10059. CPUInst inst;
  10060. if (!mCPU->Decode(dataAddr, dwarf->mOrigImageData, &inst))
  10061. hadDecodeFailure = true;
  10062. if ((decodeFailureCount == 8) || ((decodeFailureCount > 0) && (!hadDecodeFailure)))
  10063. {
  10064. for (int i = decodeFailureCount; i < 4 + sizeof(addr_target); i++)
  10065. result += " ";
  10066. result += " ???\n";
  10067. decodeFailureCount = 0;
  10068. }
  10069. if (decodeFailureCount == 0)
  10070. {
  10071. #ifdef BF_DBG_32
  10072. result += StrFormat("D %08X: ", dataAddr);
  10073. #else
  10074. result += StrFormat("D %@: ", dataAddr);
  10075. #endif
  10076. }
  10077. if (hadDecodeFailure)
  10078. {
  10079. uint8 byte = 0;
  10080. dwarf->mOrigImageData->Read(dataAddr, &byte, 1);
  10081. result += StrFormat("%02X ", byte);
  10082. dataAddr++;
  10083. decodeFailureCount++;
  10084. continue;
  10085. }
  10086. int instLen = inst.GetLength();
  10087. uint8 instData[32];
  10088. int showInstLen = BF_MIN(32, instLen);
  10089. dwarf->mOrigImageData->Read(dataAddr, instData, showInstLen);
  10090. for (int i = 0; i < showInstLen; i++)
  10091. result += StrFormat("%02X ", instData[i]);
  10092. for (int i = instLen; i < 4 + sizeof(addr_target); i++)
  10093. result += " ";
  10094. result += " ";
  10095. result += mCPU->InstructionToString(&inst, dataAddr);
  10096. int reg;
  10097. int offset;
  10098. if (inst.GetIndexRegisterAndOffset(&reg, &offset))
  10099. {
  10100. for (int blockIdx = (int)blockList.size() - 1; blockIdx >= 0; blockIdx--)
  10101. {
  10102. auto dwBlock = blockList[blockIdx];
  10103. for (auto variable : dwBlock->mVariables)
  10104. {
  10105. int varRegister;
  10106. int varOffset;
  10107. if (mDebugTarget->GetVariableIndexRegisterAndOffset(variable, &varRegister, &varOffset))
  10108. {
  10109. if (varRegister == -1)
  10110. varRegister = frameBaseRegister;
  10111. if ((reg == varRegister) && (offset == varOffset))
  10112. {
  10113. result += " ; ";
  10114. result += variable->mName;
  10115. break;
  10116. }
  10117. }
  10118. }
  10119. }
  10120. }
  10121. else if ((inst.IsCall()) || (inst.IsBranch()) || (inst.IsLoadAddress()))
  10122. {
  10123. addr_target targetAddr = inst.GetTarget();
  10124. if (targetAddr != 0)
  10125. {
  10126. if ((targetAddr >= addrStart) && (targetAddr < addrEnd))
  10127. {
  10128. result += StrFormat("\nJ %s", EncodeDataPtr(targetAddr, false).c_str());
  10129. }
  10130. else
  10131. {
  10132. String outSymbol;
  10133. addr_target offset = 0;
  10134. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &offset))
  10135. {
  10136. if (offset < 0x10000)
  10137. {
  10138. outSymbol = BfDemangler::Demangle(outSymbol, dwSubProgram->GetLanguage());
  10139. result += " ; " + outSymbol;
  10140. if (offset > 0)
  10141. result += StrFormat("+%x", offset);
  10142. }
  10143. }
  10144. }
  10145. }
  10146. }
  10147. result += "\n";
  10148. dataAddr += instLen;
  10149. }
  10150. // Why did we want to "show lines at end"??
  10151. // Show lines at end
  10152. /*if (curLine > 0)
  10153. {
  10154. for (int i = 0; i < 6; i++, curLine++)
  10155. result += StrFormat("L %d\n", curLine);
  10156. }*/
  10157. return result;
  10158. }
  10159. String WinDebugger::FindLineCallAddresses(intptr inAddress)
  10160. {
  10161. String callAddresses;
  10162. addr_target address = (addr_target)inAddress;
  10163. DbgSubprogram* dwSubprogram = NULL;
  10164. DbgLineData* startLineData = FindLineDataAtAddress(address, &dwSubprogram, NULL);
  10165. if (dwSubprogram == NULL)
  10166. return "";
  10167. CPURegisters registers;
  10168. PopulateRegisters(&registers);
  10169. auto inlinerSubprogram = dwSubprogram->GetRootInlineParent();
  10170. FixupLineDataForSubprogram(inlinerSubprogram);
  10171. if (inlinerSubprogram->mLineInfo->mLines.mSize == 0)
  10172. return "";
  10173. auto lineData = &inlinerSubprogram->mLineInfo->mLines[0];
  10174. addr_target addr = dwSubprogram->mBlock.mLowPC;
  10175. addr_target endAddr = dwSubprogram->mBlock.mHighPC;
  10176. DbgSubprogram* checkSubprogram = dwSubprogram;
  10177. DbgLineData* checkLineData = lineData;
  10178. addr_target checkLineAddr = 0;
  10179. int lineIdx = 0;
  10180. while (checkLineData != NULL)
  10181. {
  10182. //auto nextLineData = dwSubprogram->mCompileUnit->mLineDataMap.GetNext(checkLineData);
  10183. ++lineIdx;
  10184. DbgLineData* nextLineData = NULL;
  10185. addr_target nextLineAddr;
  10186. if (lineIdx < inlinerSubprogram->mLineInfo->mLines.size())
  10187. {
  10188. nextLineData = &inlinerSubprogram->mLineInfo->mLines[lineIdx];
  10189. nextLineAddr = dwSubprogram->GetLineAddr(*nextLineData);
  10190. }
  10191. else
  10192. nextLineAddr = inlinerSubprogram->mBlock.mHighPC;
  10193. // This stuff doesn't make sense...
  10194. DbgSubprogram* nextSubProgram;
  10195. if (nextLineData != NULL)
  10196. {
  10197. if (nextLineAddr > dwSubprogram->mBlock.mHighPC)
  10198. break;
  10199. endAddr = nextLineAddr;
  10200. nextSubProgram = mDebugTarget->FindSubProgram(endAddr);
  10201. if (nextSubProgram != NULL)
  10202. {
  10203. auto dbgModule = nextSubProgram->mCompileUnit->mDbgModule;
  10204. dbgModule->ParseSymbolData();
  10205. }
  10206. }
  10207. else
  10208. {
  10209. nextSubProgram = dwSubprogram;
  10210. endAddr = dwSubprogram->mBlock.mHighPC;
  10211. }
  10212. auto _HandleSection = [&]()
  10213. {
  10214. while (addr < endAddr)
  10215. {
  10216. CPUInst inst;
  10217. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  10218. break;
  10219. *registers.GetPCRegisterRef() = addr;
  10220. if (inst.IsCall())
  10221. {
  10222. bool addSymbol = true;
  10223. if (addr < (addr_target)inAddress)
  10224. callAddresses += "-";
  10225. callAddresses += EncodeDataPtr(addr, false);
  10226. addr_target targetAddr = inst.GetTarget(this, &registers);
  10227. if (targetAddr != 0)
  10228. {
  10229. String outSymbol;
  10230. auto subprogram = mDebugTarget->FindSubProgram(targetAddr);
  10231. if (subprogram != NULL)
  10232. {
  10233. CreateFilterName(outSymbol, subprogram);
  10234. addSymbol = true;
  10235. }
  10236. else
  10237. {
  10238. addr_target offset = 0;
  10239. String fullSymbolName;
  10240. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &offset))
  10241. {
  10242. if (offset < 0x200)
  10243. {
  10244. //outSymbol = BfDemangler::Demangle(outSymbol, dwSubprogram->GetLanguage());
  10245. if (outSymbol == "___chkstk_ms")
  10246. addSymbol = false;
  10247. else
  10248. {
  10249. String demangledName = BfDemangler::Demangle(outSymbol, DbgLanguage_C);
  10250. outSymbol.clear();
  10251. CreateFilterName(outSymbol, demangledName.c_str(), DbgLanguage_C);
  10252. }
  10253. }
  10254. else
  10255. outSymbol.clear();
  10256. }
  10257. }
  10258. if (addSymbol)
  10259. {
  10260. if (outSymbol.empty())
  10261. callAddresses += "\tFunc@" + EncodeDataPtr(targetAddr, false);
  10262. else
  10263. callAddresses += "\t" + outSymbol;
  10264. String attrs;
  10265. bool isFiltered = false;
  10266. if (subprogram != NULL)
  10267. {
  10268. subprogram->PopulateSubprogram();
  10269. isFiltered = subprogram->mIsStepFilteredDefault;
  10270. if (isFiltered)
  10271. attrs += "d"; // 'd' for default filtered
  10272. }
  10273. StepFilter* stepFilterPtr = NULL;
  10274. if (mDebugManager->mStepFilters.TryGetValue(outSymbol, &stepFilterPtr))
  10275. isFiltered = stepFilterPtr->IsFiltered(isFiltered);
  10276. if (isFiltered)
  10277. attrs += "f"; // 'f' for filter
  10278. if (!attrs.IsEmpty())
  10279. callAddresses += "\t" + attrs;
  10280. }
  10281. }
  10282. if (addSymbol)
  10283. callAddresses += "\n";
  10284. }
  10285. inst.PartialSimulate(this, &registers);
  10286. addr += inst.GetLength();
  10287. }
  10288. };
  10289. // For inlining - only add calls that are found either directly in our main block (not an inlined block)
  10290. // But add inlined methods when their parent is our current block
  10291. if ((checkSubprogram == dwSubprogram) && (checkLineData->mLine == startLineData->mLine))
  10292. {
  10293. _HandleSection();
  10294. }
  10295. else if ((checkSubprogram->mInlineeInfo != NULL) && (checkSubprogram->mInlineeInfo->mInlineParent == dwSubprogram))
  10296. {
  10297. if (checkLineAddr == checkSubprogram->mBlock.mLowPC)
  10298. {
  10299. addr_target inlineStartAddr = checkSubprogram->mBlock.mLowPC;
  10300. // Find the calling line
  10301. DbgSubprogram* callingSubprogram = dwSubprogram;
  10302. auto checkLineData = dwSubprogram->FindClosestLine(inlineStartAddr, &callingSubprogram);
  10303. if ((checkLineData != NULL) && (checkLineData->mCtxIdx == startLineData->mCtxIdx) && (checkLineData->mLine == startLineData->mLine))
  10304. {
  10305. if (inlineStartAddr <= (addr_target)inAddress)
  10306. callAddresses += "-";
  10307. callAddresses += EncodeDataPtr(inlineStartAddr, false);
  10308. String outSymbol;
  10309. CreateFilterName(outSymbol, checkSubprogram);
  10310. callAddresses += "\t" + outSymbol;
  10311. bool isFiltered = dwSubprogram->mIsStepFilteredDefault;
  10312. StepFilter* stepFilterPtr;
  10313. if (mDebugManager->mStepFilters.TryGetValue(outSymbol, &stepFilterPtr))
  10314. isFiltered = stepFilterPtr->IsFiltered(isFiltered);
  10315. if (isFiltered)
  10316. callAddresses += "\tf"; // 'f' for filter
  10317. callAddresses += "\n";
  10318. }
  10319. // if (checkSubprogram->mBlock.mHighPC < endAddr)
  10320. // {
  10321. // addr = checkSubprogram->mBlock.mHighPC;
  10322. // _HandleSection();
  10323. // }
  10324. }
  10325. // If we have unattributed data after the end of an inlined method, add that
  10326. if ((endAddr > checkSubprogram->mBlock.mHighPC) && (nextSubProgram == dwSubprogram))
  10327. {
  10328. addr = checkSubprogram->mBlock.mHighPC;
  10329. _HandleSection();
  10330. }
  10331. }
  10332. checkLineData = nextLineData;
  10333. checkSubprogram = nextSubProgram;
  10334. checkLineAddr = nextLineAddr;
  10335. addr = endAddr;
  10336. }
  10337. return callAddresses;
  10338. }
  10339. String WinDebugger::GetCurrentException()
  10340. {
  10341. AutoCrit autoCrit(mDebugManager->mCritSect);
  10342. String result = StrFormat("%s\n%08X",
  10343. EncodeDataPtr((addr_target)(intptr)mCurException.ExceptionAddress, true).c_str(),
  10344. mCurException.ExceptionCode);
  10345. String exStr;
  10346. switch (mCurException.ExceptionCode)
  10347. {
  10348. case EXCEPTION_ACCESS_VIOLATION:
  10349. {
  10350. String accessType;
  10351. if (mCurException.ExceptionInformation[0] == 0)
  10352. accessType = "reading from";
  10353. else if (mCurException.ExceptionInformation[0] == 8)
  10354. accessType = "executing";
  10355. else
  10356. accessType = "writing to";
  10357. exStr = StrFormat("EXCEPTION_ACCESS_VIOLATION %s %s", accessType.c_str(), EncodeDataPtr((addr_target)mCurException.ExceptionInformation[1], true).c_str());
  10358. }
  10359. break;
  10360. case EXCEPTION_DATATYPE_MISALIGNMENT:
  10361. exStr = "EXCEPTION_DATATYPE_MISALIGNMENT";
  10362. case EXCEPTION_SINGLE_STEP:
  10363. exStr = "EXCEPTION_SINGLE_STEP";
  10364. break;
  10365. case EXCEPTION_BREAKPOINT:
  10366. exStr = "EXCEPTION_BREAKPOINT";
  10367. break;
  10368. case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
  10369. exStr = "EXCEPTION_ARRAY_BOUNDS_EXCEEDED";
  10370. break;
  10371. case EXCEPTION_FLT_DENORMAL_OPERAND:
  10372. exStr = "EXCEPTION_FLT_DENORMAL_OPERAND";
  10373. break;
  10374. case EXCEPTION_FLT_DIVIDE_BY_ZERO:
  10375. exStr = "EXCEPTION_FLT_DIVIDE_BY_ZERO";
  10376. break;
  10377. case EXCEPTION_FLT_INEXACT_RESULT:
  10378. exStr = "EXCEPTION_FLT_INEXACT_RESULT";
  10379. break;
  10380. case EXCEPTION_FLT_INVALID_OPERATION:
  10381. exStr = "EXCEPTION_FLT_INVALID_OPERATIO";
  10382. break;
  10383. case EXCEPTION_FLT_OVERFLOW:
  10384. exStr = "EXCEPTION_FLT_OVERFLOW";
  10385. break;
  10386. case EXCEPTION_FLT_STACK_CHECK:
  10387. exStr = "EXCEPTION_FLT_STACK_CHECK";
  10388. break;
  10389. case EXCEPTION_FLT_UNDERFLOW:
  10390. exStr = "EXCEPTION_FLT_UNDERFLOW";
  10391. break;
  10392. case EXCEPTION_INT_DIVIDE_BY_ZERO:
  10393. exStr = "EXCEPTION_INT_DIVIDE_BY_ZERO";
  10394. break;
  10395. case EXCEPTION_INT_OVERFLOW:
  10396. exStr = "EXCEPTION_INT_OVERFLOW";
  10397. break;
  10398. case EXCEPTION_PRIV_INSTRUCTION:
  10399. exStr = "EXCEPTION_PRIV_INSTRUCTION";
  10400. break;
  10401. case EXCEPTION_IN_PAGE_ERROR:
  10402. exStr = "EXCEPTION_IN_PAGE_ERROR";
  10403. break;
  10404. case EXCEPTION_ILLEGAL_INSTRUCTION:
  10405. exStr = "EXCEPTION_ILLEGAL_INSTRUCTION";
  10406. break;
  10407. case EXCEPTION_NONCONTINUABLE_EXCEPTION:
  10408. exStr = "EXCEPTION_NONCONTINUABLE_EXCEPTION";
  10409. break;
  10410. case EXCEPTION_STACK_OVERFLOW:
  10411. exStr = "EXCEPTION_STACK_OVERFLOW";
  10412. break;
  10413. case EXCEPTION_INVALID_DISPOSITION:
  10414. exStr = "EXCEPTION_INVALID_DISPOSITION";
  10415. break;
  10416. case EXCEPTION_GUARD_PAGE:
  10417. exStr = "EXCEPTION_GUARD_PAGE";
  10418. break;
  10419. case EXCEPTION_INVALID_HANDLE:
  10420. exStr = "EXCEPTION_INVALID_HANDLE";
  10421. break;
  10422. case CONTROL_C_EXIT:
  10423. exStr = "CONTROL_C_EXIT";
  10424. break;
  10425. default:
  10426. exStr += StrFormat("EXCEPTION %08X", mCurException.ExceptionCode);
  10427. }
  10428. if (mActiveThread != NULL)
  10429. exStr += StrFormat(" in thread %d", mActiveThread->mThreadId);
  10430. if (!exStr.empty())
  10431. result += "\n" + exStr;
  10432. // After we retrieve the exception then we can go back to just being normal 'paused'
  10433. // This allows us to evaluate stuff, Set Next Statement, etc.
  10434. mRunState = RunState_Paused;
  10435. return result.c_str();
  10436. }
  10437. void WinDebugger::SetAliasPath(const StringImpl& origPath, const StringImpl& localPath)
  10438. {
  10439. AutoCrit autoCrit(mDebugManager->mCritSect);
  10440. String fixedOrigPath = FixPathAndCase(origPath);
  10441. String fixedLocalPath = FixPathAndCase(localPath);
  10442. auto origFile = mDebugTarget->AddSrcFile(origPath);
  10443. origFile->mLocalPath = FixPath(localPath);
  10444. mDebugTarget->mLocalToOrigSrcMap[fixedLocalPath] = fixedOrigPath;
  10445. // We invalidate the step filters, because previously-failing 'CheckSourceFileExist' checks may now succeed
  10446. mDebugManager->mStepFilterVersion++;
  10447. }
  10448. String WinDebugger::GetModulesInfo()
  10449. {
  10450. AutoCrit autoCrit(mDebugManager->mCritSect);
  10451. String str;
  10452. for (auto module : mDebugTarget->mDbgModules)
  10453. {
  10454. COFF* coff = (COFF*)module;
  10455. if (module->mHotIdx > 0)
  10456. continue;
  10457. str += module->mDisplayName;
  10458. str += "\t";
  10459. if (module->mLoadState == DbgModuleLoadState_Loaded)
  10460. {
  10461. str += module->mFilePath;
  10462. }
  10463. else if (module->mLoadState == DbgModuleLoadState_NotLoaded)
  10464. {
  10465. str += module->mFilePath;
  10466. str += " (Loading...)";
  10467. }
  10468. else if (module->mLoadState == DbgModuleLoadState_Failed)
  10469. {
  10470. str += "!";
  10471. str += module->mFilePath;
  10472. }
  10473. if (module->mMappedImageFile != NULL)
  10474. {
  10475. str += " (";
  10476. str += module->mMappedImageFile->mFileName;
  10477. str += ")";
  10478. }
  10479. str += "\t";
  10480. str += coff->mPDBPath;
  10481. str += "\t";
  10482. str += module->mVersion;
  10483. str += StrFormat("\t%@-%@\t%dk\t", module->mImageBase, module->mImageBase + module->mImageSize, module->mImageSize / 1024);
  10484. time_t timestamp = coff->mTimeStamp;
  10485. if (timestamp == 0)
  10486. timestamp = GetFileTimeWrite(coff->mFilePath);
  10487. if (timestamp != 0)
  10488. {
  10489. char timeString[256];
  10490. auto time_info = localtime(&timestamp);
  10491. strftime(timeString, sizeof(timeString), "%D %T", time_info);
  10492. str += timeString;
  10493. }
  10494. str += "\n";
  10495. }
  10496. return str;
  10497. }
  10498. void WinDebugger::CancelSymSrv()
  10499. {
  10500. AutoCrit autoCrit(mDebugManager->mCritSect);
  10501. if (mActiveSymSrvRequest != NULL)
  10502. mActiveSymSrvRequest->Cancel();
  10503. }
  10504. bool WinDebugger::HasPendingDebugLoads()
  10505. {
  10506. AutoCrit autoCrit(mDebugManager->mCritSect);
  10507. return (!mPendingImageLoad.IsEmpty()) || (!mPendingDebugInfoLoad.IsEmpty());
  10508. }
  10509. int WinDebugger::LoadImageForModule(const StringImpl &modulePath, const StringImpl& imagePath)
  10510. {
  10511. AutoCrit autoCrit(mDebugManager->mCritSect);
  10512. for (auto dbgModule : mDebugTarget->mDbgModules)
  10513. {
  10514. if (modulePath.Equals(dbgModule->mFilePath, StringImpl::CompareKind_OrdinalIgnoreCase))
  10515. {
  10516. auto coff = (COFF*)dbgModule;
  10517. if (!coff->LoadModuleImage(imagePath))
  10518. {
  10519. mDebugManager->mOutMessages.push_back("error Failed to load image " + imagePath);
  10520. }
  10521. ModuleChanged(dbgModule);
  10522. return 0;
  10523. }
  10524. }
  10525. return 0;
  10526. }
  10527. int WinDebugger::LoadDebugInfoForModule(DbgModule* dbgModule)
  10528. {
  10529. if (!dbgModule->HasPendingDebugInfo())
  10530. return 0;
  10531. if (dbgModule->RequestDebugInfo())
  10532. {
  10533. ClearCallStack(); // Make this re-resolve with debug info
  10534. return 1;
  10535. }
  10536. DbgPendingDebugInfoLoad* dbgPendingDebugInfoLoad = NULL;
  10537. if (mPendingDebugInfoLoad.TryAdd(dbgModule, NULL, &dbgPendingDebugInfoLoad))
  10538. {
  10539. dbgPendingDebugInfoLoad->mModule = dbgModule;
  10540. dbgPendingDebugInfoLoad->mAllowRemote = true;
  10541. return 2;
  10542. }
  10543. dbgPendingDebugInfoLoad->mAllowRemote = true;
  10544. return 0;
  10545. }
  10546. int WinDebugger::LoadDebugInfoForModule(const StringImpl& moduleName)
  10547. {
  10548. AutoCrit autoCrit(mDebugManager->mCritSect);
  10549. for (auto dbgModule : mDebugTarget->mDbgModules)
  10550. {
  10551. String checkModuleName = GetFileName(dbgModule->mFilePath);
  10552. if (moduleName.Equals(checkModuleName, StringImpl::CompareKind_OrdinalIgnoreCase))
  10553. {
  10554. return LoadDebugInfoForModule(dbgModule);
  10555. }
  10556. }
  10557. return 0;
  10558. }
  10559. int WinDebugger::LoadDebugInfoForModule(const StringImpl& modulePath, const StringImpl& debugFileName)
  10560. {
  10561. AutoCrit autoCrit(mDebugManager->mCritSect);
  10562. for (auto dbgModule : mDebugTarget->mDbgModules)
  10563. {
  10564. if (modulePath.Equals(dbgModule->mFilePath, StringImpl::CompareKind_OrdinalIgnoreCase))
  10565. {
  10566. auto coff = (COFF*)dbgModule;
  10567. String err;
  10568. if (!coff->mPDBLoaded)
  10569. {
  10570. dbgModule->mFailMsgPtr = &err;
  10571. if (coff->TryLoadPDB(debugFileName, coff->mWantPDBGuid, coff->mWantAge))
  10572. {
  10573. ModuleChanged(dbgModule);
  10574. }
  10575. dbgModule->mFailMsgPtr = NULL;
  10576. }
  10577. else
  10578. {
  10579. err = StrFormat("Module '%s' already has debug information loaded", GetFileName(modulePath).c_str());
  10580. }
  10581. if (!err.IsEmpty())
  10582. {
  10583. mDebugManager->mOutMessages.push_back("error " + err);
  10584. }
  10585. return 0;
  10586. }
  10587. }
  10588. return 0;
  10589. }
  10590. void WinDebugger::FixupLineData(DbgCompileUnit* compileUnit)
  10591. {
  10592. if (!compileUnit || !compileUnit->mNeedsLineDataFixup)
  10593. return;
  10594. compileUnit->mNeedsLineDataFixup = false;
  10595. }
  10596. static int CompareLineData(const void* lineDataP1, const void* lineDataP2)
  10597. {
  10598. int cmpResult = (int)(((DbgLineData*)lineDataP1)->mRelAddress - ((DbgLineData*)lineDataP2)->mRelAddress);
  10599. if (cmpResult != 0)
  10600. return cmpResult;
  10601. // A larger contrib size means it's the 'outer' inlinee
  10602. cmpResult = -(((DbgLineData*)lineDataP1)->mContribSize - ((DbgLineData*)lineDataP2)->mContribSize);
  10603. if (cmpResult != 0)
  10604. return cmpResult;
  10605. return -(((DbgLineData*)lineDataP1)->mCtxIdx - ((DbgLineData*)lineDataP2)->mCtxIdx);
  10606. }
  10607. void WinDebugger::FixupLineDataForSubprogram(DbgSubprogram* subProgram)
  10608. {
  10609. if ((subProgram == NULL) || (!subProgram->mNeedLineDataFixup))
  10610. return;
  10611. BP_ZONE("FixupLineDataForSubprogram");
  10612. subProgram->mNeedLineDataFixup = false;
  10613. if (subProgram->mInlineeInfo != NULL)
  10614. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  10615. if ((subProgram->mLineInfo == NULL) || (subProgram->mLineInfo->mLines.mSize == 0))
  10616. return;
  10617. //TODO: I think this was covering up a bug in DWARF line encoding? Figure this out
  10618. // if (subProgram->mLineInfo->mLines.mSize >= 2)
  10619. // {
  10620. // DbgLineData* line0 = &subProgram->mLineInfo->mLines[0];
  10621. // DbgLineData* line1 = &subProgram->mLineInfo->mLines[1];
  10622. //
  10623. //
  10624. // if ((line0->mRelAddress == line1->mRelAddress) && (!line0->IsStackFrameSetup()) && (line1->IsStackFrameSetup()))
  10625. // {
  10626. // CPUInst inst;
  10627. // if (mCPU->Decode(line0->mAddress, subProgram->mCompileUnit->mDbgModule->mOrigImageData, &inst))
  10628. // line1->mAddress += inst.GetLength();
  10629. // }
  10630. // }
  10631. qsort(subProgram->mLineInfo->mLines.mVals, subProgram->mLineInfo->mLines.mSize, sizeof(DbgLineData), CompareLineData);
  10632. // If we have multiple lines with the same line/column/context, merge them
  10633. if (!subProgram->mLineInfo->mLines.IsEmpty())
  10634. {
  10635. auto prevLine = &subProgram->mLineInfo->mLines[0];
  10636. for (int i = 1; i < subProgram->mLineInfo->mLines.mSize; i++)
  10637. {
  10638. auto nextLine = &subProgram->mLineInfo->mLines[i];
  10639. if ((nextLine->mLine == prevLine->mLine) && (nextLine->mColumn == prevLine->mColumn) && (nextLine->mCtxIdx == prevLine->mCtxIdx) &&
  10640. (nextLine->mRelAddress == prevLine->mRelAddress + prevLine->mContribSize))
  10641. {
  10642. prevLine->mContribSize += nextLine->mContribSize;
  10643. // This messed up inline cases because mContribSize actually INCLUDES inlined lines so it caused the address to skip too far
  10644. //nextLine->mRelAddress += nextLine->mContribSize;
  10645. //nextLine->mContribSize = 0;
  10646. }
  10647. else
  10648. {
  10649. prevLine = nextLine;
  10650. }
  10651. }
  10652. }
  10653. }
  10654. void WinDebugger::ReserveHotTargetMemory(int size)
  10655. {
  10656. HotTargetMemory hotTargetMemory;
  10657. hotTargetMemory.mOffset = 0;
  10658. hotTargetMemory.mSize = 0;
  10659. hotTargetMemory.mPtr = NULL;
  10660. if (size > 0)
  10661. {
  10662. // In 64-bit mode we have a reserved region on program load that we commit here because the offsets
  10663. // must be within 32-bits of the original EXE image, but in 32-bit mode we don't reserve anything
  10664. // until here
  10665. #ifdef BF_DBG_32
  10666. //hotTargetMemory.mSize = std::max(1024 * 1024, size);
  10667. BF_ASSERT((size & (mPageSize - 1)) == 0);
  10668. hotTargetMemory.mSize = size;
  10669. hotTargetMemory.mPtr = (addr_target)(intptr)VirtualAllocEx(mProcessInfo.hProcess, NULL, hotTargetMemory.mSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
  10670. mDebugTarget->mHotHeap->AddTrackedRegion(hotTargetMemory.mPtr, hotTargetMemory.mSize);
  10671. #else
  10672. hotTargetMemory.mSize = size;
  10673. hotTargetMemory.mPtr = mDebugTarget->mHotHeap->Alloc(size);
  10674. BF_ASSERT(hotTargetMemory.mPtr != 0);
  10675. auto ptr = ::VirtualAllocEx(mProcessInfo.hProcess, (void*)(intptr)hotTargetMemory.mPtr, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  10676. BF_ASSERT(ptr == (void*)(intptr)hotTargetMemory.mPtr);
  10677. #endif
  10678. }
  10679. BfLogDbg("ReserveHotTargetMemory %p %d", hotTargetMemory.mPtr, hotTargetMemory.mSize);
  10680. int err = GetLastError();
  10681. mHotTargetMemory.push_back(hotTargetMemory);
  10682. }
  10683. addr_target WinDebugger::AllocHotTargetMemory(int size, bool canExecute, bool canWrite, int* outAllocSize)
  10684. {
  10685. int prot = PAGE_READWRITE;
  10686. if (canExecute && canWrite)
  10687. prot = PAGE_EXECUTE_READWRITE;
  10688. else if (canExecute)
  10689. prot = PAGE_EXECUTE_READ;
  10690. auto hotTargetMemory = (HotTargetMemory*)&mHotTargetMemory.back();
  10691. if (hotTargetMemory->mPtr == 0)
  10692. {
  10693. Fail("Failed to allocate memory for hot loading");
  10694. return 0;
  10695. }
  10696. size = (size + (mPageSize - 1)) & ~(mPageSize - 1);
  10697. *outAllocSize = size;
  10698. BF_ASSERT(hotTargetMemory->mOffset + size <= hotTargetMemory->mSize);
  10699. addr_target result = hotTargetMemory->mPtr + hotTargetMemory->mOffset;
  10700. ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)result, size, prot, NULL);
  10701. BfLogDbg("AllocHotTargetMemory: %p %d %d %d\n", result, size, canExecute, canWrite);
  10702. hotTargetMemory->mOffset += size;
  10703. return result;
  10704. }
  10705. void WinDebugger::ReleaseHotTargetMemory(addr_target addr, int size)
  10706. {
  10707. #ifdef BF_DBG_32
  10708. ::VirtualFreeEx(mProcessInfo.hProcess, (void*)(intptr)addr, 0, MEM_RELEASE);
  10709. #else
  10710. mDebugTarget->mHotHeap->Release(addr, size);
  10711. ::VirtualFreeEx(mProcessInfo.hProcess, (void*)(intptr)addr, size, MEM_DECOMMIT);
  10712. #endif
  10713. }
  10714. void WinDebugger::CleanupHotHeap()
  10715. {
  10716. mDebugTarget->mLastHotHeapCleanIdx = mDebugTarget->mHotHeap->mBlockAllocIdx;
  10717. // Our criteria for determining whether a hot loaded file is still being used:
  10718. // 1) If we are currently executing a method from that object file.
  10719. // 2) If the symbol map has a symbol with that address.
  10720. // 3) If the static variable map contains a reference - including a conservative scan of the data
  10721. // This handles vdata references
  10722. // This is a conservative check which won't purge hot reloads that contain deleted
  10723. // methods (for example), but it will purge hot reloads where all the changed
  10724. // data has been overwritten.
  10725. // For delegate bindings, the original module declaring the bind creates a "preserve"
  10726. // global such as "bf_hs_preserve@_ZN5TestO4TestEv", whose preserved symbol ensures it
  10727. // doesn't get unloaded. The current version of that method resides in "_ZN5TestO4TestEv",
  10728. // ensuring that the method pointed to by the global variable is valid
  10729. mDebugTarget->mHotHeap->ClearReferencedFlags();
  10730. addr_target lowAddr = mDebugTarget->mHotHeap->mHotAreaStart;
  10731. addr_target highAddr = lowAddr + mDebugTarget->mHotHeap->mHotAreaSize;
  10732. // Do conservative scan through all thread stacks. Stack traces aren't 100% reliable, so we
  10733. // need to do a full conservative scan of any addresses stored in the stack
  10734. // to ensure we don't miss any return addresses
  10735. for (int threadIdx = 0; threadIdx < (int)mThreadList.size(); threadIdx++)
  10736. {
  10737. WdThreadInfo* threadInfo = mThreadList[threadIdx];
  10738. BF_CONTEXT lcContext;
  10739. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  10740. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  10741. addr_target checkStackAddr = BF_CONTEXT_SP(lcContext);
  10742. checkStackAddr &= ~(sizeof(addr_target) - 1);
  10743. // Conservative check on registers
  10744. for (int regNum = 0; regNum < sizeof(BF_CONTEXT)/sizeof(addr_target); regNum++)
  10745. {
  10746. addr_target checkAddr = ((addr_target*)&lcContext)[regNum];
  10747. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  10748. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  10749. }
  10750. // Conservative check on all stack data
  10751. while (checkStackAddr < threadInfo->mStartSP)
  10752. {
  10753. addr_target checkAddrArr[1024];
  10754. int numAddrsChecking = BF_MIN(1024, (int)((threadInfo->mStartSP - checkStackAddr) / sizeof(addr_target)));
  10755. ReadMemory(checkStackAddr, numAddrsChecking * sizeof(addr_target), checkAddrArr);
  10756. checkStackAddr += numAddrsChecking * sizeof(addr_target);
  10757. for (int addrIdx = 0; addrIdx < numAddrsChecking; addrIdx++)
  10758. {
  10759. addr_target checkAddr = checkAddrArr[addrIdx];
  10760. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  10761. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  10762. }
  10763. }
  10764. }
  10765. auto mainModule = mDebugTarget->mTargetBinary;
  10766. for (auto entry : mainModule->mSymbolNameMap)
  10767. {
  10768. auto dwSymbol = entry->mValue;
  10769. addr_target checkAddr = dwSymbol->mAddress;
  10770. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  10771. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  10772. }
  10773. mDebugTarget->CleanupHotHeap();
  10774. BfLogDbg("Hot load memory used: %dk\n", (int)mDebugTarget->mHotHeap->GetUsedSize() / 1024);
  10775. }
  10776. int WinDebugger::EnableWriting(intptr address, int size)
  10777. {
  10778. DWORD oldProt;
  10779. bool success = ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)address, size, PAGE_READWRITE, &oldProt);
  10780. if (!success)
  10781. {
  10782. int err = GetLastError();
  10783. }
  10784. return (int)oldProt;
  10785. }
  10786. int WinDebugger::SetProtection(intptr address, int size, int prot)
  10787. {
  10788. DWORD oldProt;
  10789. ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)address, size, prot, &oldProt);
  10790. return (int)oldProt;
  10791. }
  10792. void WinDebugger::EnableMemCache()
  10793. {
  10794. mMemCacheAddr = 1;
  10795. }
  10796. void WinDebugger::DisableMemCache()
  10797. {
  10798. mMemCacheAddr = 0;
  10799. }
  10800. bool WinDebugger::ReadMemory(intptr address, uint64 length, void* dest, bool local)
  10801. {
  10802. if (local)
  10803. {
  10804. __try
  10805. {
  10806. memcpy(dest, (void*)address, length);
  10807. return true;
  10808. }
  10809. __except(EXCEPTION_EXECUTE_HANDLER)
  10810. {
  10811. return false;
  10812. }
  10813. }
  10814. if (mMemCacheAddr != 0)
  10815. {
  10816. addr_target targetAddr = (addr_target)address;
  10817. if ((targetAddr >= mMemCacheAddr) && (targetAddr + length <= mMemCacheAddr + WD_MEMCACHE_SIZE) && (mMemCacheAddr > 1))
  10818. {
  10819. memcpy(dest, mMemCacheData + (targetAddr - mMemCacheAddr), length);
  10820. return true;
  10821. }
  10822. // We need a new block
  10823. SIZE_T dwReadBytes;
  10824. if (::ReadProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, mMemCacheData, (SIZE_T)WD_MEMCACHE_SIZE, &dwReadBytes) != 0)
  10825. {
  10826. mMemCacheAddr = targetAddr;
  10827. memcpy(dest, mMemCacheData, length);
  10828. return true;
  10829. }
  10830. // Failed, turn off caching
  10831. mMemCacheAddr = 0;
  10832. }
  10833. SIZE_T dwReadBytes;
  10834. if (::ReadProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, dest, (SIZE_T)length, &dwReadBytes) != 0)
  10835. return true;
  10836. int lastErr = ::GetLastError();
  10837. memset(dest, 0, length);
  10838. return false;
  10839. }
  10840. bool WinDebugger::WriteMemory(intptr address, void* src, uint64 length)
  10841. {
  10842. SIZE_T dwBytesWritten = 0;
  10843. int result = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, src, (SIZE_T)length, &dwBytesWritten);
  10844. return result != 0;
  10845. }
  10846. addr_target WinDebugger::GetTLSOffset(int tlsIndex)
  10847. {
  10848. typedef LONG NTSTATUS;
  10849. typedef DWORD KPRIORITY;
  10850. typedef WORD UWORD;
  10851. enum THREADINFOCLASS
  10852. {
  10853. ThreadBasicInformation,
  10854. };
  10855. struct CLIENT_ID
  10856. {
  10857. HANDLE UniqueProcess;
  10858. HANDLE UniqueThread;
  10859. };
  10860. struct
  10861. {
  10862. NTSTATUS mExitStatus;
  10863. void* mTebBaseAddress;
  10864. CLIENT_ID mClientId;
  10865. KAFFINITY mAffinityMask;
  10866. KPRIORITY mPriority;
  10867. KPRIORITY mBasePriority;
  10868. } threadInfo = { 0 };
  10869. ULONG len = 0;
  10870. bool loadedManually = false;
  10871. static HMODULE module = NULL;
  10872. static NTSTATUS(__stdcall *NtQueryInformationThread)(HANDLE ThreadHandle, THREADINFOCLASS ThreadInformationClass, PVOID ThreadInformation, ULONG ThreadInformationLength, PULONG ReturnLength);
  10873. if (module == NULL)
  10874. {
  10875. module = GetModuleHandleA("ntdll.dll");
  10876. NtQueryInformationThread = reinterpret_cast<decltype(NtQueryInformationThread)>(GetProcAddress(module, "NtQueryInformationThread"));
  10877. }
  10878. if (NtQueryInformationThread == NULL)
  10879. return 0;
  10880. NTSTATUS status = NtQueryInformationThread(mActiveThread->mHThread, (THREADINFOCLASS)0, &threadInfo, sizeof(threadInfo), nullptr);
  10881. if (status < 0)
  10882. return 0;
  10883. #ifdef BF_DBG_32
  10884. addr_target tibAddr = ReadMemory<addr_target>((intptr)threadInfo.mTebBaseAddress + 0x0);
  10885. addr_target tlsTable = ReadMemory<addr_target>((intptr)tibAddr + 0x2C);
  10886. #else
  10887. addr_target tlsTable = ReadMemory<addr_target>((intptr)threadInfo.mTebBaseAddress + 0x58);
  10888. #endif
  10889. return ReadMemory<addr_target>(tlsTable + tlsIndex * sizeof(addr_target));
  10890. }
  10891. bool WinDebugger::WriteInstructions(intptr address, void* src, uint64 length)
  10892. {
  10893. SIZE_T dwBytesWritten = 0;
  10894. bool result = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, src, (SIZE_T)length, &dwBytesWritten) != 0;
  10895. result |= ::FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, (SIZE_T)length) != 0;
  10896. BF_ASSERT(result);
  10897. BfLogDbg("WriteInstructions: %p %d\n", address, length);
  10898. return result;
  10899. }
  10900. DbgMemoryFlags WinDebugger::GetMemoryFlags(intptr address)
  10901. {
  10902. MEMORY_BASIC_INFORMATION memBasicInfo;
  10903. if (::VirtualQueryEx(mProcessInfo.hProcess, (void*)address, &memBasicInfo, sizeof(MEMORY_BASIC_INFORMATION)) == 0)
  10904. {
  10905. //BfLogDbg("VirtualQueryEx failed with %d\n", GetLastError());
  10906. return DbgMemoryFlags_None;
  10907. }
  10908. DbgMemoryFlags flags = DbgMemoryFlags_None;
  10909. if (memBasicInfo.AllocationProtect & PAGE_READWRITE)
  10910. {
  10911. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  10912. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  10913. }
  10914. if (memBasicInfo.AllocationProtect & PAGE_READONLY)
  10915. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  10916. if (memBasicInfo.AllocationProtect & PAGE_WRITECOPY)
  10917. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  10918. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE)
  10919. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  10920. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_READ)
  10921. {
  10922. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  10923. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  10924. }
  10925. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_READWRITE)
  10926. {
  10927. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  10928. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  10929. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  10930. }
  10931. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_WRITECOPY)
  10932. {
  10933. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  10934. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  10935. }
  10936. return flags;
  10937. }
  10938. #ifdef BF_DBG_32
  10939. Debugger* Beefy::CreateDebugger32(DebugManager* debugManager, DbgMiniDump* miniDump)
  10940. #else
  10941. Debugger* Beefy::CreateDebugger64(DebugManager* debugManager, DbgMiniDump* miniDump)
  10942. #endif
  10943. {
  10944. if (miniDump != NULL)
  10945. {
  10946. auto debugger = new MiniDumpDebugger(debugManager, miniDump);
  10947. return debugger;
  10948. }
  10949. return new WinDebugger(debugManager);
  10950. }
  10951. #ifdef BF_DBG_32
  10952. void WdAllocTest()
  10953. {
  10954. Array<BeefyDbg32::WdStackFrame*> stackFrameList;
  10955. for (int i = 0; true; i++)
  10956. {
  10957. WdStackFrame* stackFrame = new WdStackFrame();
  10958. stackFrameList.push_back(stackFrame);
  10959. }
  10960. }
  10961. #endif
  10962. #endif //!defined BF32 || !defined BF_DBG_64