WinDebugger.cpp 388 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394
  1. #pragma warning(disable:4996)
  2. // TODO: Remove for 64-bit
  3. #pragma warning(disable:4244)
  4. #pragma warning(disable:4267)
  5. #define NTDDI_VERSION 0x06020000
  6. #include "WinDebugger.h"
  7. #include "CPU.h"
  8. #include "DbgModule.h"
  9. #include "DebugVisualizers.h"
  10. #include "MiniDumpDebugger.h"
  11. #include "X86.h"
  12. #include "BeefySysLib/Common.h"
  13. #include "BeefySysLib/util/PerfTimer.h"
  14. #include "BeefySysLib/util/BeefPerf.h"
  15. #include "BeefySysLib/util/CritSect.h"
  16. #include "BeefySysLib/util/UTF8.h"
  17. #include "BeefySysLib/FileStream.h"
  18. #include "BeefySysLib/FileHandleStream.h"
  19. #include "BeefySysLib/util/FileEnumerator.h"
  20. #include <inttypes.h>
  21. #include <windows.h>
  22. #include "DbgExprEvaluator.h"
  23. #include "Compiler/BfSystem.h"
  24. #include "Compiler/BfParser.h"
  25. #include "Compiler/BfReducer.h"
  26. #include "Compiler/BfDemangler.h"
  27. #include "Compiler/BfPrinter.h"
  28. #include <Shlobj.h>
  29. #include "NetManager.h"
  30. #include "DebugManager.h"
  31. #include "X86Target.h"
  32. #include "HotHeap.h"
  33. #include "HotScanner.h"
  34. #include "Profiler.h"
  35. #include <float.h>
  36. #include <psapi.h>
  37. #if !defined BF32 || !defined BF_DBG_64
  38. #define STATUS_WX86_CONTINUE 0x4000001DL
  39. #define STATUS_WX86_SINGLE_STEP 0x4000001EL
  40. #define STATUS_WX86_BREAKPOINT 0x4000001FL
  41. #define STATUS_WX86_EXCEPTION_CONTINUE 0x40000020L
  42. #pragma pack(push, 1)
  43. struct HotJumpOp
  44. {
  45. uint8 mOpCode;
  46. int32 mRelTarget;
  47. };
  48. #pragma pack(pop)
  49. #include "BeefySysLib/util/AllocDebug.h"
  50. #include <limits>
  51. USING_NS_BF_DBG;
  52. static void FilterThreadName(String& name)
  53. {
  54. for (int i = 0; i < (int)name.length(); i++)
  55. {
  56. uint8 c = name[i];
  57. if (c == 0)
  58. {
  59. name.RemoveToEnd(i);
  60. return;
  61. }
  62. if (c < 32)
  63. {
  64. name.Remove(i);
  65. i--;
  66. continue;
  67. }
  68. }
  69. }
  70. //////////////////////////////////////////////////////////////////////////
  71. WdBreakpointCondition::~WdBreakpointCondition()
  72. {
  73. delete mDbgEvaluationContext;
  74. }
  75. //////////////////////////////////////////////////////////////////////////
  76. DbgEvaluationContext::DbgEvaluationContext(WinDebugger* winDebugger, DbgModule* dbgModule, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  77. {
  78. Init(winDebugger, dbgModule, expr, formatInfo, contextValue);
  79. }
  80. DbgEvaluationContext::DbgEvaluationContext(WinDebugger* winDebugger, DbgCompileUnit* dbgCompileUnit, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  81. {
  82. DbgModule* dbgModule = NULL;
  83. if (dbgCompileUnit != NULL)
  84. dbgModule = dbgCompileUnit->mDbgModule;
  85. Init(winDebugger, dbgModule, expr, formatInfo, contextValue);
  86. }
  87. void DbgEvaluationContext::Init(WinDebugger* winDebugger, DbgModule* dbgModule, const StringImpl& expr, DwFormatInfo* formatInfo, DbgTypedValue contextValue)
  88. {
  89. if (expr.empty())
  90. {
  91. mParser = NULL;
  92. mReducer = NULL;
  93. mPassInstance = NULL;
  94. mDbgExprEvaluator = NULL;
  95. mExprNode = NULL;
  96. return;
  97. }
  98. mParser = new BfParser(winDebugger->mBfSystem);
  99. mParser->mCompatMode = true;
  100. mPassInstance = new BfPassInstance(winDebugger->mBfSystem);
  101. auto terminatedExpr = expr + ";";
  102. mParser->SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  103. mParser->Parse(mPassInstance);
  104. mReducer = new BfReducer();
  105. mReducer->mAlloc = mParser->mAlloc;
  106. mReducer->mSystem = winDebugger->mBfSystem;
  107. mReducer->mPassInstance = mPassInstance;
  108. mReducer->mVisitorPos = BfReducer::BfVisitorPos(mParser->mRootNode);
  109. mReducer->mVisitorPos.MoveNext();
  110. mReducer->mCompatMode = mParser->mCompatMode;
  111. mReducer->mSource = mParser;
  112. mExprNode = mReducer->CreateExpression(mParser->mRootNode->GetFirst());
  113. mParser->Close();
  114. mDbgExprEvaluator = new DbgExprEvaluator(winDebugger, dbgModule, mPassInstance, -1, -1);
  115. if ((formatInfo != NULL) && (mExprNode != NULL) && (mExprNode->GetSrcEnd() < (int) expr.length()))
  116. {
  117. String formatFlags = expr.Substring(mExprNode->GetSrcEnd());
  118. String errorString = "Invalid expression";
  119. if (!winDebugger->ParseFormatInfo(dbgModule, formatFlags, formatInfo, mPassInstance, NULL, NULL, &errorString, contextValue))
  120. {
  121. mPassInstance->FailAt(errorString, mParser->mSourceData, mExprNode->GetSrcEnd(), (int)expr.length() - mExprNode->GetSrcEnd());
  122. formatFlags = "";
  123. }
  124. }
  125. if (formatInfo != NULL)
  126. {
  127. mDbgExprEvaluator->mExplicitThis = formatInfo->mExplicitThis;
  128. mDbgExprEvaluator->mCallStackIdx = formatInfo->mCallStackIdx;
  129. mDbgExprEvaluator->mLanguage = formatInfo->mLanguage;
  130. }
  131. }
  132. bool DbgEvaluationContext::HasExpression()
  133. {
  134. return mExprNode != NULL;
  135. }
  136. DbgEvaluationContext::~DbgEvaluationContext()
  137. {
  138. delete mParser;
  139. delete mReducer;
  140. delete mDbgExprEvaluator;
  141. delete mPassInstance;
  142. }
  143. DbgTypedValue DbgEvaluationContext::EvaluateInContext(DbgTypedValue contextTypedValue)
  144. {
  145. if (mExprNode == NULL)
  146. return DbgTypedValue();
  147. mPassInstance->ClearErrors();
  148. if (contextTypedValue)
  149. {
  150. mDbgExprEvaluator->mExplicitThis = contextTypedValue;
  151. if ((mDbgExprEvaluator->mExplicitThis.mType->IsPointer()) && (mDbgExprEvaluator->mExplicitThis.mType->mTypeParam->WantsRefThis()))
  152. {
  153. mDbgExprEvaluator->mExplicitThis.mType = mDbgExprEvaluator->mExplicitThis.mType->mTypeParam;
  154. mDbgExprEvaluator->mExplicitThis.mSrcAddress = mDbgExprEvaluator->mExplicitThis.mPtr;
  155. mDbgExprEvaluator->mExplicitThis.mPtr = 0;
  156. }
  157. if ((mDbgExprEvaluator->mExplicitThis.mType->IsCompositeType()) && (!mDbgExprEvaluator->mExplicitThis.mType->WantsRefThis()))
  158. {
  159. if (mDbgExprEvaluator->mExplicitThis.mSrcAddress != 0)
  160. {
  161. mDbgExprEvaluator->mExplicitThis.mType = mDbgExprEvaluator->mDbgModule->GetPointerType(mDbgExprEvaluator->mExplicitThis.mType);
  162. mDbgExprEvaluator->mExplicitThis.mPtr = mDbgExprEvaluator->mExplicitThis.mSrcAddress;
  163. mDbgExprEvaluator->mExplicitThis.mSrcAddress = 0;
  164. }
  165. }
  166. }
  167. if (contextTypedValue.mType != NULL)
  168. mDbgExprEvaluator->mDbgCompileUnit = contextTypedValue.mType->mCompileUnit;
  169. DbgTypedValue exprResult;
  170. auto result = mDbgExprEvaluator->Resolve(mExprNode);
  171. return result;
  172. }
  173. bool DbgEvaluationContext::HadError()
  174. {
  175. return mPassInstance->mFailedIdx != 0;
  176. }
  177. String DbgEvaluationContext::GetErrorStr()
  178. {
  179. String errorStr = mPassInstance->mErrors[0]->mError;
  180. if (mExprNode != NULL)
  181. {
  182. errorStr += ": ";
  183. errorStr += mExprNode->ToString();
  184. }
  185. return errorStr;
  186. }
  187. //////////////////////////////////////////////////////////////////////////
  188. typedef HRESULT(WINAPI* SetThreadDescription_t)(HANDLE hThread, PCWSTR lpThreadDescription);
  189. typedef HRESULT(WINAPI* GetThreadDescription_t)(HANDLE hThread, PWSTR* lpThreadDescription);
  190. static SetThreadDescription_t gSetThreadDescription = NULL;
  191. static GetThreadDescription_t gGetThreadDescription = NULL;
  192. static HMODULE gKernelDll = NULL;
  193. static void ImportKernel()
  194. {
  195. if (gKernelDll != NULL)
  196. return;
  197. WCHAR path[MAX_PATH];
  198. GetSystemDirectory(path, MAX_PATH);
  199. wcscat(path, L"\\kernel32.dll");
  200. gKernelDll = GetModuleHandle(path);
  201. if (gKernelDll == NULL)
  202. {
  203. return;
  204. }
  205. gSetThreadDescription = (SetThreadDescription_t)GetProcAddress(gKernelDll, "SetThreadDescription");
  206. gGetThreadDescription = (GetThreadDescription_t)GetProcAddress(gKernelDll, "GetThreadDescription");
  207. }
  208. void WinDebugger::TryGetThreadName(WdThreadInfo* threadInfo)
  209. {
  210. if (threadInfo->mHThread == NULL)
  211. return;
  212. ImportKernel();
  213. PWSTR wStr = NULL;
  214. if (gGetThreadDescription != NULL)
  215. {
  216. gGetThreadDescription(threadInfo->mHThread, &wStr);
  217. if (wStr == NULL)
  218. return;
  219. threadInfo->mName = UTF8Encode(wStr);
  220. FilterThreadName(threadInfo->mName);
  221. LocalFree(wStr);
  222. }
  223. }
  224. static void CreateFilterName(String& name, DbgType* type)
  225. {
  226. CreateFilterName(name, type->mParent);
  227. switch (type->mTypeCode)
  228. {
  229. case DbgType_Namespace:
  230. case DbgType_Struct:
  231. case DbgType_Class:
  232. name += type->mName;
  233. break;
  234. }
  235. }
  236. static void CreateFilterName(String& name, const char* srcStr, DbgLanguage language)
  237. {
  238. int chevronDepth = 0;
  239. const char* cPtr = srcStr;
  240. for (; true; cPtr++)
  241. {
  242. char c = *cPtr;
  243. if (c == 0)
  244. break;
  245. if (c == '>')
  246. chevronDepth--;
  247. bool inGeneric = chevronDepth > 0;
  248. if (c == '<')
  249. chevronDepth++;
  250. if (inGeneric) // Bundle all generic instances together
  251. continue;
  252. if (c == '[') // Bundle all arrays together
  253. name.clear();
  254. if (c == '(')
  255. return; // Start of params
  256. if ((c == ':') && (cPtr[1] == ':') && (language == DbgLanguage_Beef))
  257. {
  258. name.Append('.');
  259. cPtr++;
  260. }
  261. else
  262. name.Append(c);
  263. }
  264. }
  265. static void CreateFilterName(String& name, DbgSubprogram* subprogram)
  266. {
  267. auto language = subprogram->GetLanguage();
  268. if (subprogram->mName == NULL)
  269. {
  270. if (subprogram->mLinkName[0] == '<')
  271. {
  272. name += subprogram->mLinkName;
  273. return;
  274. }
  275. name = BfDemangler::Demangle(subprogram->mLinkName, language);
  276. // Strip off the params since we need to generate those ourselves
  277. int parenPos = (int)name.IndexOf('(');
  278. if (parenPos != -1)
  279. name.RemoveToEnd(parenPos);
  280. return;
  281. }
  282. else if (subprogram->mHasQualifiedName)
  283. {
  284. const char* cPtr = subprogram->mName;
  285. if (strncmp(cPtr, "_bf::", 5) == 0)
  286. {
  287. CreateFilterName(name, cPtr + 5, DbgLanguage_Beef);
  288. name.Replace(".__BfStaticCtor", ".this$static");
  289. name.Replace(".__BfCtorClear", ".this$clear");
  290. name.Replace(".__BfCtor", ".this");
  291. }
  292. else
  293. CreateFilterName(name, subprogram->mName, language);
  294. return;
  295. }
  296. else
  297. {
  298. if (subprogram->mParentType != NULL)
  299. {
  300. String parentName = subprogram->mParentType->ToString();
  301. CreateFilterName(name, parentName.c_str(), language);
  302. if (!name.empty())
  303. {
  304. if (language == DbgLanguage_Beef)
  305. name += ".";
  306. else
  307. name += "::";
  308. }
  309. }
  310. if ((language == DbgLanguage_Beef) && (subprogram->mParentType != NULL) && (subprogram->mParentType->mTypeName != NULL) &&
  311. (strcmp(subprogram->mName, subprogram->mParentType->mTypeName) == 0))
  312. name += "this";
  313. else if ((language == DbgLanguage_Beef) && (subprogram->mName[0] == '~'))
  314. name += "~this";
  315. else if (strncmp(subprogram->mName, "_bf::", 5) == 0)
  316. {
  317. CreateFilterName(name, subprogram->mName + 5, DbgLanguage_Beef);
  318. }
  319. else
  320. {
  321. CreateFilterName(name, subprogram->mName, language);
  322. }
  323. }
  324. if (name.empty())
  325. name += "`anon";
  326. if ((name[name.length() - 1] == '!') || (name[0] == '<'))
  327. {
  328. if (language == DbgLanguage_Beef)
  329. {
  330. // It's a mixin - assert that there's no params
  331. //BF_ASSERT(subprogram->mParams.Size() == 0);
  332. }
  333. return;
  334. }
  335. }
  336. //////////////////////////////////////////////////////////////////////////
  337. DbgPendingExpr::DbgPendingExpr()
  338. {
  339. mThreadId = -1;
  340. mCallStackIdx = -1;
  341. mParser = NULL;
  342. mCursorPos = -1;
  343. mExprNode = NULL;
  344. mIdleTicks = 0;
  345. mExplitType = NULL;
  346. mExpressionFlags = DwEvalExpressionFlag_None;
  347. mUsedSpecifiedLock = false;
  348. mStackIdxOverride = -1;
  349. }
  350. DbgPendingExpr::~DbgPendingExpr()
  351. {
  352. delete mParser;
  353. }
  354. // conversion logic based on table at http://en.wikipedia.org/wiki/Extended_precision
  355. //CDH TODO put this somewhere more general
  356. static double ConvertFloat80ToDouble(const byte fp80[10])
  357. {
  358. uint16 e = *((uint16*)&fp80[8]);
  359. uint64 m = *((uint64*)&fp80[0]);
  360. uint64 bit63 = (uint64)1 << 63;
  361. uint64 bit62 = (uint64)1 << 62;
  362. bool isNegative = (e & 0x8000) != 0;
  363. double s = isNegative ? -1.0 : 1.0;
  364. e &= 0x7fff;
  365. if (!e)
  366. {
  367. // the high bit and mantissa content will determine whether it's an actual zero, or a denormal or
  368. // pseudo-denormal number with an effective exponent of -16382. But since that exponent is so far
  369. // below anything we can handle in double-precision (even accounting for denormal bit shifts), we're
  370. // effectively still dealing with zero.
  371. return s * 0.0;
  372. }
  373. else if (e == 0x7fff)
  374. {
  375. if (m & bit63)
  376. {
  377. if (m & bit62)
  378. {
  379. return std::numeric_limits<double>::quiet_NaN();
  380. }
  381. else
  382. {
  383. if (m == bit63)
  384. return s * std::numeric_limits<double>::infinity();
  385. else
  386. return std::numeric_limits<double>::signaling_NaN();
  387. }
  388. }
  389. else
  390. {
  391. return std::numeric_limits<double>::quiet_NaN();
  392. }
  393. }
  394. else
  395. {
  396. if (!(m & bit63))
  397. return std::numeric_limits<double>::quiet_NaN(); // unnormal (we don't handle these since 80387 and later treat them as invalid operands anyway)
  398. // else is a normalized value
  399. }
  400. int useExponent = (int)e - 16383;
  401. if (useExponent < -1022)
  402. return s * 0.0; // we could technically support e from -1023 to -1074 as denormals, but don't bother with that for now.
  403. else if (useExponent > 1023)
  404. return s * HUGE_VAL;
  405. useExponent += 1023;
  406. BF_ASSERT((useExponent > 0) && (useExponent < 0x7ff)); // assume we've filtered for valid exponent range
  407. BF_ASSERT(m & bit63); // assume we've filtered out values that aren't normalized by now
  408. uint64 result = 0;
  409. if (isNegative)
  410. result |= bit63;
  411. result |= (uint64)useExponent << 52;
  412. result |= (m & ~bit63) >> 11;
  413. return *reinterpret_cast<double*>(&result);
  414. }
  415. addr_target NS_BF_DBG::DecodeTargetDataPtr(const char*& strRef)
  416. {
  417. addr_target val = (addr_target)stouln(strRef, sizeof(intptr_target) * 2);
  418. strRef += sizeof(intptr_target) * 2;
  419. return val;
  420. }
  421. WinDebugger::WinDebugger(DebugManager* debugManager) : mDbgSymSrv(this)
  422. {
  423. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  424. mActiveHotIdx = -1;
  425. mGotStartupEvent = false;
  426. mIsContinuingFromException = false;
  427. mDestroying = false;
  428. mDebugManager = debugManager;
  429. mNeedsRehupBreakpoints = false;
  430. mStepInAssembly = false;
  431. mStepSP = 0;
  432. mStepIsRecursing = false;
  433. mStepStopOnNextInstruction = false;
  434. mDebugTarget = NULL;
  435. mShuttingDown = false;
  436. mBfSystem = new BfSystem();
  437. mAtBreakThread = NULL;
  438. mActiveThread = NULL;
  439. mActiveBreakpoint = NULL;
  440. mSteppingThread = NULL;
  441. mExplicitStopThread = NULL;
  442. mStepSwitchedThreads = false;
  443. mIsDebuggerWaiting = false;
  444. mWantsDebugContinue = false;
  445. mContinueFromBreakpointFailed = false;
  446. mIsStepIntoSpecific = false;
  447. mDbgBreak = false;
  448. mDebuggerWaitingThread = NULL;
  449. mStepType = StepType_None;
  450. mOrigStepType = StepType_None;
  451. mLastValidStepIntoPC = 0;
  452. mActiveSymSrvRequest = NULL;
  453. mStoredReturnValueAddr = 0;
  454. #ifdef BF_DBG_32
  455. mCPU = gX86Target->mX86CPU;
  456. #else
  457. mCPU = gX86Target->mX64CPU;
  458. #endif
  459. mRunState = RunState_NotStarted;
  460. mIsRunning = false;
  461. mSavedAtBreakpointAddress = 0;
  462. mSavedBreakpointAddressContinuing = 0;
  463. mRequestedStackFrameIdx = 0;
  464. mShowPCOverride = 0;
  465. mCurNoInfoStepTries = 0;
  466. mDbgAttachFlags = BfDbgAttachFlag_None;
  467. mDbgProcessHandle = 0;
  468. mDbgThreadHandle = 0;
  469. mDbgProcessId = 0;
  470. mDbgHeapData = NULL;
  471. mIsPartialCallStack = true;
  472. for (int i = 0; i < 4; i++)
  473. {
  474. mFreeMemoryBreakIndices.push_back(i);
  475. }
  476. mMemoryBreakpointVersion = 0;
  477. SYSTEM_INFO systemInfo;
  478. GetSystemInfo(&systemInfo);
  479. mPageSize = systemInfo.dwPageSize;
  480. mEmptyDebugTarget = new DebugTarget(this);
  481. mEmptyDebugTarget->CreateEmptyTarget();
  482. mEmptyDebugTarget->mIsEmpty = true;
  483. mDebugTarget = mEmptyDebugTarget;
  484. mDebugPendingExpr = NULL;
  485. mDebugEvalThreadInfo = WdThreadInfo();
  486. mMemCacheAddr = 0;
  487. mDebuggerThreadId = 0;
  488. }
  489. WinDebugger::~WinDebugger()
  490. {
  491. mDestroying = true;
  492. delete gDbgPerfManager;
  493. gDbgPerfManager = NULL;
  494. if ((mDebugTarget != NULL) && (mDebugTarget != mEmptyDebugTarget))
  495. Detach();
  496. for (auto breakpoint : mBreakpoints)
  497. {
  498. auto checkBreakpoint = breakpoint->mLinkedSibling;
  499. while (checkBreakpoint != NULL)
  500. {
  501. auto nextBreakpoint = checkBreakpoint->mLinkedSibling;
  502. delete checkBreakpoint;
  503. checkBreakpoint = nextBreakpoint;
  504. }
  505. delete breakpoint;
  506. }
  507. delete mEmptyDebugTarget;
  508. delete mBfSystem;
  509. for (auto kv : mPendingProfilerMap)
  510. delete kv.mValue;
  511. for (auto profiler : mNewProfilerList)
  512. delete profiler;
  513. delete mDebugPendingExpr;
  514. }
  515. void WinDebugger::Fail(const StringImpl& error)
  516. {
  517. if (mIsRunning)
  518. mDebugManager->mOutMessages.push_back(StrFormat("error %s", error.c_str()));
  519. }
  520. // Leave active thread unpaused
  521. void WinDebugger::ThreadRestorePause(WdThreadInfo* onlyPauseThread, WdThreadInfo* dontPauseThread)
  522. {
  523. BfLogDbg("ThreadRestorePause %d %d\n", (onlyPauseThread != NULL) ? onlyPauseThread->mThreadId : 0, (dontPauseThread != NULL) ? dontPauseThread->mThreadId : 0);
  524. for (auto threadInfo : mThreadList)
  525. {
  526. if (((threadInfo != dontPauseThread) && (!threadInfo->mIsBreakRestorePaused)) &&
  527. ((onlyPauseThread == NULL) || (threadInfo == onlyPauseThread)))
  528. {
  529. BF_ASSERT(!threadInfo->mIsBreakRestorePaused);
  530. BfLogDbg("SuspendThread %d\n", threadInfo->mThreadId);
  531. ::SuspendThread(threadInfo->mHThread);
  532. threadInfo->mIsBreakRestorePaused = true;
  533. }
  534. }
  535. }
  536. void WinDebugger::ThreadRestoreUnpause()
  537. {
  538. BfLogDbg("ThreadRestoreUnpause\n");
  539. for (auto threadInfo : mThreadList)
  540. {
  541. if (threadInfo->mIsBreakRestorePaused)
  542. {
  543. BfLogDbg("ResumeThread %d\n", threadInfo->mThreadId);
  544. ::ResumeThread(threadInfo->mHThread);
  545. threadInfo->mIsBreakRestorePaused = false;
  546. }
  547. }
  548. }
  549. void WinDebugger::UpdateThreadDebugRegisters(WdThreadInfo* threadInfo)
  550. {
  551. if (threadInfo->mMemoryBreakpointVersion == mMemoryBreakpointVersion)
  552. return;
  553. auto threadId = threadInfo->mHThread;
  554. BF_CONTEXT lcContext;
  555. lcContext.ContextFlags = BF_CONTEXT_DEBUG_REGISTERS;
  556. BF_GetThreadContext(threadId, &lcContext);
  557. for (int memoryBreakIdx = 0; memoryBreakIdx < 4; memoryBreakIdx++)
  558. {
  559. WdMemoryBreakpointBind memoryBreakpointBind = mMemoryBreakpoints[memoryBreakIdx];
  560. WdBreakpoint* wdBreakpoint = memoryBreakpointBind.mBreakpoint;
  561. if (wdBreakpoint == NULL)
  562. {
  563. *(&lcContext.Dr0 + memoryBreakIdx) = 0;
  564. lcContext.Dr7 &= ~((1 << (memoryBreakIdx * 2)) | (1 << (16 + memoryBreakIdx * 4)) | (3 << (18 + memoryBreakIdx * 4)));
  565. }
  566. else
  567. {
  568. int sizeCode = 0;
  569. if (memoryBreakpointBind.mByteCount == 2)
  570. sizeCode = 1;
  571. else if (memoryBreakpointBind.mByteCount == 4)
  572. sizeCode = 3;
  573. else if (memoryBreakpointBind.mByteCount == 8)
  574. sizeCode = 2;
  575. addr_target calcAddr = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress + memoryBreakpointBind.mOfs;
  576. BF_ASSERT(calcAddr == memoryBreakpointBind.mAddress);
  577. *(&lcContext.Dr0 + memoryBreakIdx) = calcAddr;
  578. lcContext.Dr7 |= (1 << (memoryBreakIdx * 2)) | (1 << (16 + memoryBreakIdx * 4)) | (sizeCode << (18 + memoryBreakIdx * 4));
  579. }
  580. }
  581. bool worked = BF_SetThreadContext(threadId, &lcContext) != 0;
  582. BF_ASSERT(worked || (mRunState == RunState_Terminating) || (mRunState == RunState_Terminated));
  583. threadInfo->mMemoryBreakpointVersion = mMemoryBreakpointVersion;
  584. }
  585. void WinDebugger::UpdateThreadDebugRegisters()
  586. {
  587. for (auto threadInfo : mThreadList)
  588. {
  589. ::SuspendThread(threadInfo->mHThread);
  590. UpdateThreadDebugRegisters(threadInfo);
  591. ::ResumeThread(threadInfo->mHThread);
  592. }
  593. }
  594. void WinDebugger::PhysSetBreakpoint(addr_target address)
  595. {
  596. BfLogDbg("PhysSetBreakpoint %p\n", address);
  597. uint8 newData = 0xCC;
  598. // This ensure that we have the orig image data cached
  599. DbgMemoryFlags flags = mDebugTarget->ReadOrigImageData(address, NULL, 1);
  600. if ((flags & DbgMemoryFlags_Execute) == 0)
  601. {
  602. BfLogDbg("Breakpoint ignored - execute flag NOT set in breakpoint address\n", address);
  603. BfLogDbg("Memory Flags = %d\n", gDebugger->GetMemoryFlags(address));
  604. return;
  605. }
  606. // Replace it with Breakpoint
  607. SIZE_T dwReadBytes;
  608. BOOL worked = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, &newData, 1, &dwReadBytes);
  609. if (!worked)
  610. {
  611. int err = GetLastError();
  612. BfLogDbg("SetBreakpoint FAILED %p\n", address);
  613. }
  614. FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, 1);
  615. {
  616. uint8 mem = ReadMemory<uint8>(address);
  617. BfLogDbg("Breakpoint byte %X\n", mem);
  618. }
  619. }
  620. void WinDebugger::SetBreakpoint(addr_target address, bool fromRehup)
  621. {
  622. int* countPtr = NULL;
  623. if (mPhysBreakpointAddrMap.TryAdd(address, NULL, &countPtr))
  624. {
  625. BfLogDbg("SetBreakpoint %p\n", address);
  626. *countPtr = 1;
  627. }
  628. else
  629. {
  630. if (fromRehup)
  631. {
  632. BfLogDbg("SetBreakpoint %p Count: %d. Rehup (ignored).\n", address, *countPtr);
  633. return;
  634. }
  635. (*countPtr)++;
  636. BfLogDbg("SetBreakpoint %p Count: %d\n", address, *countPtr);
  637. return;
  638. }
  639. PhysSetBreakpoint(address);
  640. }
  641. void WinDebugger::SetTempBreakpoint(addr_target address)
  642. {
  643. BfLogDbg("SetTempBreakpoint %p\n", address);
  644. mTempBreakpoint.push_back(address);
  645. SetBreakpoint(address);
  646. }
  647. void WinDebugger::PhysRemoveBreakpoint(addr_target address)
  648. {
  649. BfLogDbg("PhysRemoveBreakpoint %p\n", address);
  650. uint8 origData;
  651. DbgMemoryFlags flags = mDebugTarget->ReadOrigImageData(address, &origData, 1);
  652. if ((flags & DbgMemoryFlags_Execute) == 0)
  653. {
  654. //BF_ASSERT("Failed" == 0);
  655. return;
  656. }
  657. SIZE_T dwReadBytes;
  658. if (!WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, &origData, 1, &dwReadBytes))
  659. {
  660. int err = GetLastError();
  661. BfLogDbg("RemoveBreakpoint FAILED %p\n", address);
  662. }
  663. FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, 1);
  664. }
  665. void WinDebugger::RemoveBreakpoint(addr_target address)
  666. {
  667. int* countPtr = NULL;
  668. mPhysBreakpointAddrMap.TryGetValue(address, &countPtr);
  669. // This can happen when we shutdown and we're continuing from a breakpoint
  670. //BF_ASSERT(*countPtr != NULL);
  671. if (countPtr == NULL)
  672. {
  673. BfLogDbg("RemoveBreakpoint %p FAILED\n", address);
  674. return;
  675. }
  676. BfLogDbg("RemoveBreakpoint %p count: %d\n", address, *countPtr);
  677. if (*countPtr > 1)
  678. {
  679. (*countPtr)--;
  680. return;
  681. }
  682. mPhysBreakpointAddrMap.Remove(address);
  683. PhysRemoveBreakpoint(address);
  684. }
  685. void WinDebugger::SingleStepX86()
  686. {
  687. // In what cases did this catch bugs?
  688. // This caused other failures (caught in tests)
  689. // if (mActiveThread->mIsAtBreakpointAddress != 0)
  690. // {
  691. // ContinueFromBreakpoint();
  692. // return;
  693. // }
  694. BfLogDbg("Setup SingleStepX86 ActiveThread: %d\n", (mActiveThread != NULL) ? mActiveThread->mThreadId : -1);
  695. BF_CONTEXT lcContext;
  696. lcContext.ContextFlags = BF_CONTEXT_ALL;
  697. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  698. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  699. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  700. }
  701. bool WinDebugger::IsInRunState()
  702. {
  703. return (mRunState == RunState_Running) || (mRunState == RunState_Running_ToTempBreakpoint);
  704. }
  705. bool WinDebugger::ContinueFromBreakpoint()
  706. {
  707. if (mDebuggerWaitingThread->mFrozen)
  708. {
  709. BfLogDbg("ContinueFromBreakpoint bailout on frozen thread\n");
  710. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  711. mDebuggerWaitingThread->mIsAtBreakpointAddress = 0;
  712. return true;
  713. }
  714. mActiveThread = mDebuggerWaitingThread;
  715. mActiveBreakpoint = NULL;
  716. BfLogDbg("ContinueFromBreakpoint. ActiveThread: %d\n", (mActiveThread != NULL) ? mActiveThread->mThreadId : -1);
  717. BfLogDbg("ResumeThread %d\n", mActiveThread->mThreadId);
  718. BOOL success = ::ResumeThread(mActiveThread->mHThread);
  719. if (success)
  720. {
  721. // It's possible the active thread is suspended - possibly by the GC, so we would deadlock if we
  722. // attempted to pause the other threads
  723. BfLogDbg("SuspendThread %d\n", mActiveThread->mThreadId);
  724. BfLogDbg("Thread already paused!\n");
  725. ::SuspendThread(mActiveThread->mHThread);
  726. return false;
  727. }
  728. ThreadRestorePause(NULL, mActiveThread);
  729. PhysRemoveBreakpoint(mActiveThread->mIsAtBreakpointAddress);
  730. BF_CONTEXT lcContext;
  731. lcContext.ContextFlags = BF_CONTEXT_ALL;
  732. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  733. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  734. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  735. mActiveThread->mStoppedAtAddress = 0;
  736. mActiveThread->mBreakpointAddressContinuing = mActiveThread->mIsAtBreakpointAddress;
  737. mActiveThread->mIsAtBreakpointAddress = 0;
  738. BfLogDbg("ContinueFromBreakpoint set mIsAtBreakpointAddress = 0\n");
  739. return true;
  740. }
  741. void WinDebugger::ValidateBreakpoints()
  742. {
  743. HashSet<addr_target> usedBreakpoints;
  744. std::function<void(WdBreakpoint*)> _AddBreakpoint = [&](WdBreakpoint* breakpoint)
  745. {
  746. if (breakpoint->mAddr != 0)
  747. {
  748. usedBreakpoints.Add(breakpoint->mAddr);
  749. WdBreakpoint* foundBreakpoint = NULL;
  750. auto itr = mBreakpointAddrMap.Find(breakpoint->mAddr);
  751. bool found = false;
  752. while (itr != mBreakpointAddrMap.end())
  753. {
  754. WdBreakpoint* foundBreakpoint = itr->mValue;
  755. found |= foundBreakpoint == breakpoint;
  756. itr.NextWithSameKey(breakpoint->mAddr);
  757. }
  758. BF_ASSERT(found);
  759. }
  760. auto checkSibling = (WdBreakpoint*)breakpoint->mLinkedSibling;
  761. while (checkSibling != NULL)
  762. {
  763. _AddBreakpoint(checkSibling);
  764. checkSibling = (WdBreakpoint*)checkSibling->mLinkedSibling;
  765. }
  766. };
  767. for (auto breakpoint : mBreakpoints)
  768. _AddBreakpoint(breakpoint);
  769. for (auto& entry : mBreakpointAddrMap)
  770. {
  771. BF_ASSERT(usedBreakpoints.Contains(entry.mKey));
  772. }
  773. }
  774. Breakpoint* WinDebugger::FindBreakpointAt(intptr address)
  775. {
  776. #ifdef _DEBUG
  777. //ValidateBreakpoints();
  778. #endif
  779. WdBreakpoint* breakpoint = NULL;
  780. mBreakpointAddrMap.TryGetValue(address, &breakpoint);
  781. return breakpoint;
  782. }
  783. Breakpoint* WinDebugger::GetActiveBreakpoint()
  784. {
  785. if ((mActiveBreakpoint != NULL) && (mActiveBreakpoint->mHead != NULL))
  786. return mActiveBreakpoint->mHead;
  787. return mActiveBreakpoint;
  788. }
  789. void WinDebugger::DebugThreadProc()
  790. {
  791. BpSetThreadName("DebugThread");
  792. BfpThread_SetName(NULL, "DebugThread", NULL);
  793. mDebuggerThreadId = GetCurrentThreadId();
  794. if (!IsMiniDumpDebugger())
  795. {
  796. if (!DoOpenFile(mLaunchPath, mArgs, mWorkingDir, mEnvBlock))
  797. {
  798. if (mDbgProcessId != 0)
  799. OutputRawMessage("error Unable to attach to process");
  800. else
  801. OutputRawMessage(StrFormat("error Failed to launch: %s", mLaunchPath.c_str()));
  802. mShuttingDown = true;
  803. mRunState = RunState_Terminated;
  804. }
  805. }
  806. while (!mShuttingDown)
  807. {
  808. DoUpdate();
  809. }
  810. mIsRunning = false;
  811. for (int i = 0; i < (int) mBreakpoints.size(); i++)
  812. {
  813. WdBreakpoint* wdBreakpoint = mBreakpoints[i];
  814. if (wdBreakpoint->mAddr != 0)
  815. mBreakpointAddrMap.Remove(wdBreakpoint->mAddr, wdBreakpoint);
  816. wdBreakpoint->mAddr = 0;
  817. wdBreakpoint->mLineData = DbgLineDataEx();
  818. wdBreakpoint->mSrcFile = NULL;
  819. if (wdBreakpoint->mLinkedSibling != NULL)
  820. {
  821. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  822. wdBreakpoint->mLinkedSibling = NULL;
  823. }
  824. }
  825. if (!IsMiniDumpDebugger())
  826. {
  827. while (true)
  828. {
  829. if (!mIsDebuggerWaiting)
  830. {
  831. if (!WaitForDebugEvent(&mDebugEvent, 0))
  832. break;
  833. }
  834. if (mDebuggerWaitingThread != NULL)
  835. {
  836. BF_ASSERT_REL((mDebuggerWaitingThread->mIsAtBreakpointAddress == 0) || (mShuttingDown));
  837. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_CONTINUE);
  838. BfLogDbg("::ContinueDebugEvent startup ThreadId:%d\n", mDebuggerWaitingThread->mThreadId);
  839. }
  840. mIsDebuggerWaiting = false;
  841. mDebuggerWaitingThread = NULL;
  842. }
  843. }
  844. mDebuggerThreadId = 0;
  845. }
  846. static void DebugThreadProcThunk(void* winDebugger)
  847. {
  848. ((WinDebugger*) winDebugger)->DebugThreadProc();
  849. }
  850. int WinDebugger::GetAddrSize()
  851. {
  852. return sizeof(addr_target);
  853. }
  854. bool WinDebugger::CanOpen(const StringImpl& fileName, DebuggerResult* outResult)
  855. {
  856. FILE* fp = fopen(fileName.c_str(), "rb");
  857. if (fp == NULL)
  858. {
  859. *outResult = DebuggerResult_CannotOpen;
  860. return false;
  861. }
  862. FileStream fs;
  863. fs.mFP = fp;
  864. *outResult = DebuggerResult_Ok;
  865. bool canRead = DbgModule::CanRead(&fs, outResult);
  866. fclose(fp);
  867. return canRead;
  868. }
  869. void WinDebugger::OpenFile(const StringImpl& launchPath, const StringImpl& targetPath, const StringImpl& args, const StringImpl& workingDir, const Array<uint8>& envBlock, bool hotSwapEnabled)
  870. {
  871. BF_ASSERT(!mIsRunning);
  872. mLaunchPath = launchPath;
  873. mTargetPath = targetPath;
  874. mArgs = args;
  875. mWorkingDir = workingDir;
  876. mEnvBlock = envBlock;
  877. mHotSwapEnabled = hotSwapEnabled;
  878. mDebugTarget = new DebugTarget(this);
  879. }
  880. bool WinDebugger::Attach(int processId, BfDbgAttachFlags attachFlags)
  881. {
  882. BF_ASSERT(!mIsRunning);
  883. mDbgAttachFlags = attachFlags;
  884. mDbgProcessHandle = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)processId);
  885. if (mDbgProcessHandle == 0)
  886. return false;
  887. BOOL is32Bit = false;
  888. if (!IsWow64Process(mDbgProcessHandle, &is32Bit))
  889. {
  890. mDbgProcessHandle = 0;
  891. ::CloseHandle(mDbgProcessHandle);
  892. return false;
  893. }
  894. bool want32Bit = sizeof(intptr_target) == 4;
  895. if (want32Bit != (is32Bit != 0))
  896. {
  897. mDbgProcessHandle = 0;
  898. ::CloseHandle(mDbgProcessHandle);
  899. return false;
  900. }
  901. HMODULE mainModule = 0;
  902. DWORD memNeeded = 0;
  903. ::EnumProcessModules(mDbgProcessHandle, &mainModule, sizeof(HMODULE), &memNeeded);
  904. WCHAR fileName[MAX_PATH] = {0};
  905. GetModuleFileNameExW(mDbgProcessHandle, mainModule, fileName, MAX_PATH);
  906. mLaunchPath = UTF8Encode(fileName);
  907. mTargetPath = mLaunchPath;
  908. mDbgProcessId = processId;
  909. mDbgProcessHandle = 0;
  910. ::CloseHandle(mDbgProcessHandle);
  911. mDebugTarget = new DebugTarget(this);
  912. return true;
  913. }
  914. void WinDebugger::Run()
  915. {
  916. mIsRunning = true;
  917. DWORD localThreadId;
  918. HANDLE hThread = ::CreateThread(NULL, 64 * 1024, (LPTHREAD_START_ROUTINE) &DebugThreadProcThunk, (void*)this, 0, &localThreadId);
  919. CloseHandle(hThread);
  920. }
  921. void WinDebugger::HotLoad(const Array<String>& objectFiles, int hotIdx)
  922. {
  923. AutoCrit autoCrit(mDebugManager->mCritSect);
  924. if (mDebugTarget->mTargetBinary == NULL)
  925. {
  926. Fail("Hot swapping failed because the hot target binary has not yet been loaded.");
  927. return;
  928. }
  929. if (mDebugTarget->mHotHeap == NULL)
  930. {
  931. Fail("There is no hot heap space available for hot swapping.");
  932. return;
  933. }
  934. BfLogDbg("WinDebugger::HotLoad Start %d\n", hotIdx);
  935. SetAndRestoreValue<int> prevHotIdx(mActiveHotIdx, hotIdx);
  936. BF_ASSERT(mHotThreadStates.empty());
  937. mHotThreadStates.Resize(mThreadList.size());
  938. for (int threadIdx = 0; threadIdx < (int)mThreadList.size(); threadIdx++)
  939. {
  940. WdThreadInfo* threadInfo = mThreadList[threadIdx];
  941. SetAndRestoreValue<WdThreadInfo*> prevActiveThread(mActiveThread, threadInfo);
  942. BfLogDbg("SuspendThread %d\n", threadInfo->mThreadId);
  943. ::SuspendThread(threadInfo->mHThread);
  944. mHotThreadStates[threadIdx].mThreadId = threadInfo->mThreadId;
  945. PopulateRegisters(&mHotThreadStates[threadIdx].mRegisters);
  946. }
  947. for (auto address : mTempBreakpoint)
  948. RemoveBreakpoint(address);
  949. mTempBreakpoint.Clear();
  950. mStepBreakpointAddrs.Clear();
  951. for (auto breakpoint : mBreakpoints)
  952. {
  953. DetachBreakpoint(breakpoint);
  954. }
  955. int startingModuleIdx = (int)mDebugTarget->mDbgModules.size();
  956. bool failed = false;
  957. for (auto fileName : objectFiles)
  958. {
  959. BfLogDbg("WinDebugger::HotLoad: %s\n", fileName.c_str());
  960. DbgModule* newBinary = mDebugTarget->HotLoad(fileName, hotIdx);
  961. if ((newBinary != NULL) && (newBinary->mFailed))
  962. failed = true;
  963. }
  964. for (int moduleIdx = startingModuleIdx; moduleIdx < (int)mDebugTarget->mDbgModules.size(); moduleIdx++)
  965. {
  966. auto dbgModule = mDebugTarget->mDbgModules[moduleIdx];
  967. BF_ASSERT(dbgModule->IsObjectFile());
  968. BF_ASSERT(dbgModule->mHotIdx == hotIdx);
  969. dbgModule->FinishHotSwap();
  970. }
  971. for (auto dwarf : mDebugTarget->mDbgModules)
  972. dwarf->RevertWritingEnable();
  973. int blockAllocSinceClean = mDebugTarget->mHotHeap->mBlockAllocIdx - mDebugTarget->mLastHotHeapCleanIdx;
  974. // Clean up the hot heap every 64MB
  975. int blocksBetweenCleans = (64 * 1024 * 1024) / HotHeap::BLOCK_SIZE;
  976. #ifdef _DEBUG
  977. //TODO: This is just for testing
  978. blocksBetweenCleans = 1;
  979. #endif
  980. //TODO: Put this back after we fix the cleanup
  981. if (blockAllocSinceClean >= blocksBetweenCleans)
  982. CleanupHotHeap();
  983. mDebugTarget->RehupSrcFiles();
  984. for (int breakIdx = 0; breakIdx < (int)mBreakpoints.size(); breakIdx++)
  985. {
  986. auto breakpoint = mBreakpoints[breakIdx];
  987. CheckBreakpoint(breakpoint);
  988. }
  989. for (int hotThreadIdx = 0; hotThreadIdx < (int)mHotThreadStates.size(); hotThreadIdx++)
  990. {
  991. auto& hotThreadState = mHotThreadStates[hotThreadIdx];
  992. WdThreadInfo* threadInfo = NULL;
  993. if (!mThreadMap.TryGetValue((uint32)hotThreadState.mThreadId, &threadInfo))
  994. continue;
  995. BfLogDbg("ResumeThread %d\n", threadInfo->mThreadId);
  996. ::ResumeThread(threadInfo->mHThread);
  997. }
  998. mHotThreadStates.Clear();
  999. if (IsPaused())
  1000. {
  1001. ClearCallStack();
  1002. UpdateCallStack();
  1003. }
  1004. }
  1005. void WinDebugger::InitiateHotResolve(DbgHotResolveFlags flags)
  1006. {
  1007. AutoCrit autoCrit(mDebugManager->mCritSect);
  1008. delete mHotResolveData;
  1009. mHotResolveData = NULL;
  1010. mHotResolveData = new DbgHotResolveData();
  1011. DbgHotScanner* hotScanner = new DbgHotScanner(this);
  1012. hotScanner->Scan(flags);
  1013. delete hotScanner;
  1014. }
  1015. intptr WinDebugger::GetDbgAllocHeapSize()
  1016. {
  1017. if (mDbgHeapData == NULL)
  1018. {
  1019. Beefy::String memName = StrFormat("BFGC_stats_%d", mProcessInfo.dwProcessId);
  1020. mDbgHeapData = new WinDbgHeapData();
  1021. mDbgHeapData->mFileMapping = ::OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, memName.c_str());
  1022. if (mDbgHeapData->mFileMapping == 0)
  1023. {
  1024. delete mDbgHeapData;
  1025. mDbgHeapData = NULL;
  1026. return 0;
  1027. }
  1028. mDbgHeapData->mStats = (WinDbgHeapData::Stats*)MapViewOfFile(mDbgHeapData->mFileMapping, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(WinDbgHeapData::Stats));
  1029. }
  1030. if (mDbgHeapData->mStats == NULL)
  1031. return 0;
  1032. return mDbgHeapData->mStats->mHeapSize;
  1033. }
  1034. String WinDebugger::GetDbgAllocInfo()
  1035. {
  1036. AutoCrit autoCrit(mDebugManager->mCritSect);
  1037. for (auto threadInfo : mThreadList)
  1038. ::SuspendThread(threadInfo->mHThread);
  1039. delete mHotResolveData;
  1040. mHotResolveData = NULL;
  1041. mHotResolveData = new DbgHotResolveData();
  1042. DbgHotScanner* hotScanner = new DbgHotScanner(this);
  1043. hotScanner->Scan((DbgHotResolveFlags)(DbgHotResolveFlag_Allocations | DbgHotResolveFlag_KeepThreadState));
  1044. delete hotScanner;
  1045. String result;
  1046. if (mHotResolveData != NULL)
  1047. {
  1048. DbgExprEvaluator exprEvaluator(this, NULL, NULL, -1, -1);
  1049. exprEvaluator.mDebugTarget = mDebugTarget;
  1050. String typeName;
  1051. result += ":types\n";
  1052. for (int typeId = 0; typeId < mHotResolveData->mTypeData.size(); typeId++)
  1053. {
  1054. auto& typeData = mHotResolveData->mTypeData[typeId];
  1055. if (typeData.mCount > 0)
  1056. {
  1057. auto type = exprEvaluator.GetBeefTypeById(typeId);
  1058. typeName.Clear();
  1059. exprEvaluator.BeefTypeToString(type, typeName);
  1060. if (typeName.IsEmpty())
  1061. typeName = StrFormat("Type #%d", typeId);
  1062. result += StrFormat("type\t%d\t%s\t%lld\t%lld\n", typeId, typeName.c_str(), typeData.mCount, typeData.mSize);
  1063. }
  1064. }
  1065. }
  1066. for (auto threadInfo : mThreadList)
  1067. ::ResumeThread(threadInfo->mHThread);
  1068. return result;
  1069. }
  1070. bool WinDebugger::DoOpenFile(const StringImpl& fileName, const StringImpl& args, const StringImpl& workingDir, const Array<uint8>& envBlock)
  1071. {
  1072. BP_ZONE("WinDebugger::DoOpenFile");
  1073. AutoCrit autoCrit(mDebugManager->mCritSect);
  1074. //gDbgPerfManager->StartRecording();
  1075. STARTUPINFOW si;
  1076. ZeroMemory(&si, sizeof(si));
  1077. si.cb = sizeof(si);
  1078. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  1079. if (mDbgProcessId != 0)
  1080. {
  1081. BOOL success = ::DebugActiveProcess(mDbgProcessId);
  1082. if (!success)
  1083. return false;
  1084. mProcessInfo.dwProcessId = mDbgProcessId;
  1085. }
  1086. else
  1087. {
  1088. BP_ZONE("DoOpenFile_CreateProcessW");
  1089. UTF16String envW;
  1090. DWORD flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS | CREATE_DEFAULT_ERROR_MODE;
  1091. void* envPtr = NULL;
  1092. if (!envBlock.IsEmpty())
  1093. {
  1094. //UTF16?
  1095. if (envBlock[1] == 0)
  1096. {
  1097. envPtr = (void*)&envBlock[0];
  1098. flags |= CREATE_UNICODE_ENVIRONMENT;
  1099. }
  1100. else
  1101. {
  1102. String str8((char*)&envBlock[0], (int)envBlock.size());
  1103. envW = UTF8Decode(str8);
  1104. envPtr = (void*)envW.c_str();
  1105. flags |= CREATE_UNICODE_ENVIRONMENT;
  1106. }
  1107. }
  1108. String cmdLine = "\"";
  1109. cmdLine += fileName;
  1110. cmdLine += "\"";
  1111. if (!args.IsEmpty())
  1112. {
  1113. cmdLine += " ";
  1114. cmdLine += args;
  1115. }
  1116. BOOL worked = CreateProcessW(NULL, (WCHAR*)UTF8Decode(cmdLine).c_str(), NULL, NULL, FALSE,
  1117. flags, envPtr, (WCHAR*)UTF8Decode(workingDir).c_str(), &si, &mProcessInfo);
  1118. if (!worked)
  1119. {
  1120. auto lastError = ::GetLastError();
  1121. if (lastError == ERROR_DIRECTORY)
  1122. {
  1123. mDebugManager->mOutMessages.push_back(StrFormat("error Unable to locate specified working directory '%s'", SlashString(workingDir, false, false).c_str()));
  1124. }
  1125. return false;
  1126. }
  1127. WdThreadInfo* threadInfo = new WdThreadInfo();
  1128. threadInfo->mProcessId = mProcessInfo.dwProcessId;
  1129. threadInfo->mThreadId = mProcessInfo.dwThreadId;
  1130. threadInfo->mHThread = mProcessInfo.hThread;
  1131. threadInfo->mThreadLocalBase = NULL;
  1132. threadInfo->mStartAddress = NULL;
  1133. mThreadMap[mProcessInfo.dwThreadId] = threadInfo;
  1134. mThreadList.push_back(threadInfo);
  1135. }
  1136. mRunState = RunState_Running;
  1137. while (true)
  1138. {
  1139. BP_ZONE("DoOpenFile_WaitForImageBase");
  1140. autoCrit.mCritSect->Unlock();
  1141. DoUpdate();
  1142. autoCrit.mCritSect->Lock();
  1143. ContinueDebugEvent();
  1144. if ((mDebugTarget->mLaunchBinary != NULL) && (mDebugTarget->mLaunchBinary->mOrigImageData != NULL))
  1145. break;
  1146. }
  1147. RehupBreakpoints(true);
  1148. //gDbgPerfManager->StopRecording();
  1149. //gDbgPerfManager->DbgPrint();
  1150. return true;
  1151. }
  1152. void WinDebugger::StopDebugging()
  1153. {
  1154. AutoCrit autoCrit(mDebugManager->mCritSect);
  1155. BfLogDbg("WinDebugger::Terminate\n");
  1156. if (mActiveSymSrvRequest != NULL)
  1157. mActiveSymSrvRequest->Cancel();
  1158. if ((mRunState == RunState_NotStarted) || (mRunState == RunState_Terminated) || (mRunState == RunState_Terminating))
  1159. return;
  1160. if ((mDbgProcessId != 0) && ((mDbgAttachFlags & BfDbgAttachFlag_ShutdownOnExit) == 0))
  1161. {
  1162. for (auto address : mTempBreakpoint)
  1163. RemoveBreakpoint(address);
  1164. for (auto breakpoint : mBreakpoints)
  1165. DetachBreakpoint(breakpoint);
  1166. BfLogDbg("StopDebugging\n");
  1167. ::DebugActiveProcessStop(mDbgProcessId);
  1168. mRunState = RunState_Terminated;
  1169. BfLogDbg("mRunState = RunState_Terminated\n");
  1170. }
  1171. else
  1172. {
  1173. TerminateProcess(mProcessInfo.hProcess, 0);
  1174. mRunState = RunState_Terminating;
  1175. BfLogDbg("mRunState = RunState_Terminating\n");
  1176. }
  1177. }
  1178. void WinDebugger::Terminate()
  1179. {
  1180. AutoCrit autoCrit(mDebugManager->mCritSect);
  1181. BfLogDbg("WinDebugger::Terminate\n");
  1182. if (mActiveSymSrvRequest != NULL)
  1183. mActiveSymSrvRequest->Cancel();
  1184. if ((mRunState == RunState_NotStarted) || (mRunState == RunState_Terminated) || (mRunState == RunState_Terminating))
  1185. return;
  1186. TerminateProcess(mProcessInfo.hProcess, 0);
  1187. mRunState = RunState_Terminating;
  1188. BfLogDbg("mRunState = RunState_Terminating\n");
  1189. }
  1190. static int gDebugUpdateCnt = 0;
  1191. void WinDebugger::Detach()
  1192. {
  1193. BfLogDbg("Debugger Detach\n");
  1194. mDebugManager->mNetManager->CancelAll();
  1195. while ((mIsRunning) || (mDebuggerThreadId != 0))
  1196. {
  1197. mShuttingDown = true;
  1198. Sleep(1);
  1199. }
  1200. for (auto profiler : mProfilerSet)
  1201. profiler->Stop();
  1202. BfLogDbg("Debugger Detach - thread finished\n");
  1203. mPendingProfilerMap.Clear();
  1204. for (auto profiler : mNewProfilerList)
  1205. delete profiler;
  1206. mNewProfilerList.Clear();
  1207. mPendingImageLoad.Clear();
  1208. mPendingDebugInfoLoad.Clear();
  1209. RemoveTempBreakpoints();
  1210. mContinueEvent.Reset();
  1211. if (mDebugTarget != mEmptyDebugTarget)
  1212. delete mDebugTarget;
  1213. mDebugTarget = mEmptyDebugTarget;
  1214. mShuttingDown = false;
  1215. mStepSP = 0;
  1216. ClearCallStack();
  1217. mRunState = RunState_NotStarted;
  1218. mStepType = StepType_None;
  1219. mHadImageFindError = false;
  1220. mIsPartialCallStack = true;
  1221. delete mDebugPendingExpr;
  1222. mDebugPendingExpr = NULL;
  1223. for (auto threadPair : mThreadMap)
  1224. {
  1225. auto threadInfo = threadPair.mValue;
  1226. delete threadInfo;
  1227. }
  1228. mThreadMap.Clear();
  1229. mThreadList.Clear();
  1230. mHotTargetMemory.Clear();
  1231. // We don't need to close the hThread when we have attached to a process
  1232. if (mDbgProcessId == 0)
  1233. {
  1234. CloseHandle(mProcessInfo.hThread);
  1235. CloseHandle(mProcessInfo.hProcess);
  1236. }
  1237. for (auto breakpoint : mBreakpoints)
  1238. {
  1239. if (!mDestroying)
  1240. {
  1241. BF_FATAL("Breakpoints should be deleted already");
  1242. }
  1243. if (breakpoint->mMemoryBreakpointInfo != NULL)
  1244. {
  1245. DetachBreakpoint(breakpoint);
  1246. }
  1247. }
  1248. ZeroMemory(&mProcessInfo, sizeof(mProcessInfo));
  1249. mStepBreakpointAddrs.Clear();
  1250. mIsRunning = false;
  1251. mDbgAttachFlags = BfDbgAttachFlag_None;
  1252. mDbgProcessId = 0;
  1253. delete mDbgHeapData;
  1254. mDbgHeapData = NULL;
  1255. mDbgProcessHandle = 0;
  1256. ClearCallStack();
  1257. mWantsDebugContinue = false;
  1258. mAtBreakThread = NULL;
  1259. mActiveThread = NULL;
  1260. mActiveBreakpoint = NULL;
  1261. mSteppingThread = NULL;
  1262. mExplicitStopThread = NULL;
  1263. mIsContinuingFromException = false;
  1264. mGotStartupEvent = false;
  1265. mIsDebuggerWaiting = false;
  1266. mPhysBreakpointAddrMap.Clear();
  1267. mBreakpointAddrMap.Clear();
  1268. gDebugUpdateCnt = 0;
  1269. }
  1270. Profiler* WinDebugger::StartProfiling()
  1271. {
  1272. return new DbgProfiler(this);
  1273. }
  1274. Profiler* WinDebugger::PopProfiler()
  1275. {
  1276. AutoCrit autoCrit(mDebugManager->mCritSect);
  1277. if (mNewProfilerList.IsEmpty())
  1278. return NULL;
  1279. auto profiler = (DbgProfiler*)mNewProfilerList[0];
  1280. mNewProfilerList.erase(mNewProfilerList.begin());
  1281. return profiler;
  1282. }
  1283. void WinDebugger::AddProfiler(DbgProfiler * profiler)
  1284. {
  1285. AutoCrit autoCrit(mDebugManager->mCritSect);
  1286. mProfilerSet.Add(profiler);
  1287. }
  1288. void WinDebugger::RemoveProfiler(DbgProfiler * profiler)
  1289. {
  1290. AutoCrit autoCrit(mDebugManager->mCritSect);
  1291. mProfilerSet.Remove(profiler);
  1292. }
  1293. void WinDebugger::ReportMemory(MemReporter* memReporter)
  1294. {
  1295. mEmptyDebugTarget->ReportMemory(memReporter);
  1296. if (mDebugTarget != mEmptyDebugTarget)
  1297. mDebugTarget->ReportMemory(memReporter);
  1298. }
  1299. bool WinDebugger::GetEmitSource(const StringImpl& filePath, String& outText)
  1300. {
  1301. if (!filePath.StartsWith("$Emit"))
  1302. return false;
  1303. int dollarPos = filePath.IndexOf('$', 1);
  1304. String numStr = filePath.Substring(5, dollarPos - 5);
  1305. int id = atoi(numStr.c_str());
  1306. for (auto dbgModule : mDebugTarget->mDbgModules)
  1307. {
  1308. if (dbgModule->mId == id)
  1309. return dbgModule->GetEmitSource(filePath, outText);
  1310. }
  1311. return false;
  1312. }
  1313. void WinDebugger::ModuleChanged(DbgModule* dbgModule)
  1314. {
  1315. mDebugManager->mOutMessages.push_back(String("dbgInfoLoaded ") + dbgModule->mFilePath);
  1316. }
  1317. bool WinDebugger::DoUpdate()
  1318. {
  1319. if ((mDbgProcessId != 0) && ((mDbgAttachFlags & BfDbgAttachFlag_ShutdownOnExit) == 0))
  1320. ::DebugSetProcessKillOnExit(FALSE);
  1321. else
  1322. ::DebugSetProcessKillOnExit(TRUE);
  1323. //
  1324. {
  1325. AutoCrit autoCrit(mDebugManager->mCritSect);
  1326. auto _ModuleChanged = [&](DbgModule* dbgModule)
  1327. {
  1328. ModuleChanged(dbgModule);
  1329. ClearCallStack(); // We may have actual dbgSubprograms and stuff now...
  1330. };
  1331. for (auto dbgModule : mPendingImageLoad)
  1332. {
  1333. dbgModule->PreCacheImage();
  1334. }
  1335. for (auto kv : mPendingDebugInfoLoad)
  1336. {
  1337. kv.mKey->PreCacheDebugInfo();
  1338. }
  1339. while (!mPendingImageLoad.IsEmpty())
  1340. {
  1341. auto dbgModule = mPendingImageLoad.back();
  1342. mPendingImageLoad.pop_back();
  1343. dbgModule->RequestImage();
  1344. _ModuleChanged(dbgModule);
  1345. }
  1346. if (!mPendingDebugInfoLoad.IsEmpty())
  1347. {
  1348. Array<DbgPendingDebugInfoLoad> pendingList;
  1349. for (auto kv : mPendingDebugInfoLoad)
  1350. pendingList.Add(kv.mValue);
  1351. mPendingDebugInfoLoad.Clear();
  1352. for (auto& entry : pendingList)
  1353. {
  1354. auto dbgModule = entry.mModule;
  1355. entry.mModule->RequestDebugInfo(entry.mAllowRemote);
  1356. // We do a "_ModuleChanged" even if the load failed, so we rehup the callstack and stop
  1357. // saying "<Loading...>"
  1358. _ModuleChanged(entry.mModule);
  1359. }
  1360. }
  1361. }
  1362. if (IsMiniDumpDebugger())
  1363. {
  1364. //
  1365. {
  1366. AutoCrit autoCrit(mDebugManager->mCritSect);
  1367. if (mRunState == RunState_Terminating)
  1368. {
  1369. mRunState = RunState_Terminated;
  1370. return false;
  1371. }
  1372. }
  1373. Sleep(20);
  1374. return false;
  1375. }
  1376. if (mIsDebuggerWaiting)
  1377. {
  1378. if ((IsInRunState()) || (mRunState == RunState_Terminating) || (mRunState == RunState_DebugEval))
  1379. ContinueDebugEvent();
  1380. if (mContinueEvent.WaitFor(8))
  1381. {
  1382. BF_ASSERT(!mWantsDebugContinue); // mWantsDebugContinue should already been reset
  1383. BfLogDbg("::ContinueDebugEvent 1 ThreadId:%d\n", mDebuggerWaitingThread->mThreadId);
  1384. BF_ASSERT_REL(mDebuggerWaitingThread->mIsAtBreakpointAddress == 0);
  1385. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, mIsContinuingFromException ? DBG_EXCEPTION_NOT_HANDLED : DBG_CONTINUE);
  1386. mIsContinuingFromException = false;
  1387. mIsDebuggerWaiting = false;
  1388. mDebuggerWaitingThread = NULL;
  1389. }
  1390. else
  1391. return false;
  1392. }
  1393. if (!WaitForDebugEvent(&mDebugEvent, 8))
  1394. return false;
  1395. gDebugUpdateCnt++;
  1396. static const char* eventNames[] = { "DBG_EVENT ?",
  1397. "EXCEPTION_DEBUG_EVENT",
  1398. "CREATE_THREAD_DEBUG_EVENT",
  1399. "CREATE_PROCESS_DEBUG_EVENT",
  1400. "EXIT_THREAD_DEBUG_EVENT",
  1401. "EXIT_PROCESS_DEBUG_EVENT",
  1402. "LOAD_DLL_DEBUG_EVENT",
  1403. "UNLOAD_DLL_DEBUG_EVENT",
  1404. "OUTPUT_DEBUG_STRING_EVENT",
  1405. "RIP_EVENT"};
  1406. BfLogDbg("WaitForDebugEvent %s ThreadId:%d\n", eventNames[mDebugEvent.dwDebugEventCode], mDebugEvent.dwThreadId);
  1407. BP_ZONE(eventNames[mDebugEvent.dwDebugEventCode]);
  1408. AutoCrit autoCrit(mDebugManager->mCritSect);
  1409. mActiveBreakpoint = NULL;
  1410. mIsDebuggerWaiting = true;
  1411. mWantsDebugContinue = true;
  1412. mRequestedStackFrameIdx = 0;
  1413. mBreakStackFrameIdx = 0;
  1414. mShowPCOverride = 0;
  1415. WdThreadInfo* threadInfo = NULL;
  1416. mThreadMap.TryGetValue(mDebugEvent.dwThreadId, &threadInfo);
  1417. mDebuggerWaitingThread = threadInfo;
  1418. mExplicitStopThread = mDebuggerWaitingThread;
  1419. switch (mDebugEvent.dwDebugEventCode)
  1420. {
  1421. case CREATE_PROCESS_DEBUG_EVENT:
  1422. {
  1423. if (threadInfo == NULL)
  1424. {
  1425. BF_ASSERT(mThreadMap.size() == 0);
  1426. WdThreadInfo* newThreadInfo = new WdThreadInfo();
  1427. newThreadInfo->mProcessId = mDebugEvent.dwProcessId;
  1428. newThreadInfo->mThreadId = mDebugEvent.dwThreadId;
  1429. newThreadInfo->mHThread = mDebugEvent.u.CreateProcessInfo.hThread;
  1430. newThreadInfo->mThreadLocalBase = mDebugEvent.u.CreateProcessInfo.lpThreadLocalBase;
  1431. newThreadInfo->mStartAddress = (void*)mDebugEvent.u.CreateProcessInfo.lpStartAddress;
  1432. BF_CONTEXT lcContext;
  1433. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1434. BF_GetThreadContext(newThreadInfo->mHThread, &lcContext);
  1435. newThreadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1436. mThreadMap[mDebugEvent.dwThreadId] = newThreadInfo;
  1437. mDebuggerWaitingThread = newThreadInfo;
  1438. mThreadList.push_back(mDebuggerWaitingThread);
  1439. UpdateThreadDebugRegisters();
  1440. OutputMessage(StrFormat("Creating thread from CREATE_PROCESS_DEBUG_EVENT %d\n", mDebugEvent.dwThreadId));
  1441. threadInfo = mDebuggerWaitingThread;
  1442. mProcessInfo.dwThreadId = threadInfo->mThreadId;
  1443. mProcessInfo.hThread = threadInfo->mHThread;
  1444. mProcessInfo.hProcess = mDebugEvent.u.CreateProcessInfo.hProcess;
  1445. }
  1446. else
  1447. {
  1448. threadInfo->mThreadLocalBase = mDebugEvent.u.CreateProcessInfo.lpThreadLocalBase;
  1449. threadInfo->mStartAddress = (void*)mDebugEvent.u.CreateProcessInfo.lpStartAddress;
  1450. }
  1451. BF_CONTEXT lcContext;
  1452. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1453. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1454. threadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1455. DbgModule* launchBinary = mDebugTarget->Init(mLaunchPath, mTargetPath, (addr_target)(intptr)mDebugEvent.u.CreateProcessInfo.lpBaseOfImage);
  1456. addr_target gotImageBase = (addr_target)(intptr)mDebugEvent.u.CreateProcessInfo.lpBaseOfImage;
  1457. if (launchBinary->mImageBase != gotImageBase)
  1458. {
  1459. BF_FATAL("Image base didn't match");
  1460. }
  1461. launchBinary->mImageBase = gotImageBase;
  1462. launchBinary->mImageSize = (int)launchBinary->GetImageSize();
  1463. launchBinary->mOrigImageData = new DbgModuleMemoryCache(launchBinary->mImageBase, launchBinary->mImageSize);
  1464. if (launchBinary == mDebugTarget->mTargetBinary)
  1465. mDebugTarget->SetupTargetBinary();
  1466. if (mDebugEvent.u.CreateProcessInfo.hFile != NULL)
  1467. CloseHandle(mDebugEvent.u.CreateProcessInfo.hFile);
  1468. mDbgProcessHandle = mDebugEvent.u.CreateProcessInfo.hProcess;
  1469. mDbgThreadHandle = mDebugEvent.u.CreateProcessInfo.hThread;
  1470. mGotStartupEvent = true;
  1471. mDebugManager->mOutMessages.push_back("modulesChanged");
  1472. }
  1473. break;
  1474. case EXIT_PROCESS_DEBUG_EVENT:
  1475. {
  1476. BfLogDbg("EXIT_PROCESS_DEBUG_EVENT\n");
  1477. DWORD exitCode = mDebugEvent.u.ExitProcess.dwExitCode;
  1478. String exitMessage;
  1479. switch (exitCode)
  1480. {
  1481. case STATUS_DLL_NOT_FOUND:
  1482. exitMessage = "STATUS_DLL_NOT_FOUND";
  1483. break;
  1484. case STATUS_DLL_INIT_FAILED:
  1485. exitMessage = "STATUS_DLL_INIT_FAILED";
  1486. break;
  1487. case STATUS_ENTRYPOINT_NOT_FOUND:
  1488. exitMessage = "STATUS_ENTRYPOINT_NOT_FOUND";
  1489. break;
  1490. }
  1491. String exitCodeStr;
  1492. if ((exitCode >= 0x10000000) && (exitCode <= 0xF7000000))
  1493. exitCodeStr = StrFormat("0x%X", exitCode);
  1494. else
  1495. exitCodeStr = StrFormat("%d", exitCode);
  1496. if (!exitMessage.IsEmpty())
  1497. OutputMessage(StrFormat("Process terminated. ExitCode: %s (%s).\n", exitCodeStr.c_str(), exitMessage.c_str()));
  1498. else
  1499. OutputMessage(StrFormat("Process terminated. ExitCode: %s.\n", exitCodeStr.c_str()));
  1500. mRunState = RunState_Terminated;
  1501. mDebugManager->mOutMessages.push_back("modulesChanged");
  1502. }
  1503. break;
  1504. case LOAD_DLL_DEBUG_EVENT:
  1505. {
  1506. WCHAR moduleNameStr[MAX_PATH] = { 0 };
  1507. GetFinalPathNameByHandleW(mDebugEvent.u.LoadDll.hFile, moduleNameStr, MAX_PATH, FILE_NAME_NORMALIZED);
  1508. std::wstring wow64Dir;
  1509. std::wstring systemDir;
  1510. PWSTR wow64DirPtr = NULL;
  1511. SHGetKnownFolderPath(FOLDERID_SystemX86, KF_FLAG_NO_ALIAS, NULL, &wow64DirPtr);
  1512. if (wow64DirPtr != NULL)
  1513. {
  1514. wow64Dir = wow64DirPtr;
  1515. CoTaskMemFree(wow64DirPtr);
  1516. }
  1517. PWSTR systemDirPtr = NULL;
  1518. SHGetKnownFolderPath(FOLDERID_System, KF_FLAG_NO_ALIAS, NULL, &systemDirPtr);
  1519. if (systemDirPtr != NULL)
  1520. {
  1521. systemDir = systemDirPtr;
  1522. CoTaskMemFree(systemDirPtr);
  1523. }
  1524. if ((mDebugEvent.u.LoadDll.lpImageName != 0) && (mDebugEvent.u.LoadDll.fUnicode))
  1525. {
  1526. addr_target strAddr = ReadMemory<addr_target>((addr_target)(intptr)mDebugEvent.u.LoadDll.lpImageName);
  1527. for (int i = 0; i < MAX_PATH - 1; i++)
  1528. {
  1529. WCHAR c = ReadMemory<WCHAR>(strAddr + i*2);
  1530. moduleNameStr[i] = (WCHAR)c;
  1531. if (c == 0)
  1532. break;
  1533. }
  1534. }
  1535. String origModuleName = UTF8Encode(moduleNameStr);
  1536. String moduleName = origModuleName;
  1537. String loadMsg;
  1538. HANDLE altFileHandle = INVALID_HANDLE_VALUE;
  1539. if (moduleName != origModuleName)
  1540. {
  1541. loadMsg = StrFormat("Loading DLL: %s(%s) @ %s", origModuleName.c_str(), moduleName.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.LoadDll.lpBaseOfDll, true).c_str());
  1542. altFileHandle = ::CreateFileW(UTF8Decode(moduleName).c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  1543. }
  1544. else
  1545. {
  1546. loadMsg = StrFormat("Loading DLL: %s @ %s", moduleName.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.LoadDll.lpBaseOfDll, true).c_str());
  1547. }
  1548. BfLogDbg("LOAD_DLL_DEBUG_EVENT %s\n", moduleName.c_str());
  1549. bool skipLoad = false;
  1550. #ifdef BF_DBG_32
  1551. if (((uintptr)mDebugEvent.u.LoadDll.lpBaseOfDll & 0xFFFFFFFF00000000LL) != 0)
  1552. {
  1553. skipLoad = true;
  1554. loadMsg += " - Skipped";
  1555. }
  1556. #endif
  1557. if (!skipLoad)
  1558. {
  1559. FileHandleStream stream;
  1560. stream.mFileHandle = mDebugEvent.u.LoadDll.hFile;
  1561. if (altFileHandle != INVALID_HANDLE_VALUE)
  1562. stream.mFileHandle = altFileHandle;
  1563. if (mDebugTarget->SetupDyn(moduleName, &stream, (intptr)mDebugEvent.u.LoadDll.lpBaseOfDll) == NULL)
  1564. loadMsg += " - Failed to load";
  1565. stream.mFileHandle = 0;
  1566. }
  1567. OutputMessage(loadMsg + "\n");
  1568. if (altFileHandle != INVALID_HANDLE_VALUE)
  1569. ::CloseHandle(altFileHandle);
  1570. ::CloseHandle(mDebugEvent.u.LoadDll.hFile);
  1571. // Try to bind any breakpoints tied to this DLL
  1572. RehupBreakpoints(true);
  1573. mDebugManager->mOutMessages.push_back("modulesChanged");
  1574. }
  1575. break;
  1576. case UNLOAD_DLL_DEBUG_EVENT:
  1577. {
  1578. bool needsBreakpointRehup = false;
  1579. String name = "???";
  1580. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress((addr_target)(intptr)mDebugEvent.u.UnloadDll.lpBaseOfDll);
  1581. if (dbgModule != NULL)
  1582. {
  1583. name = dbgModule->mFilePath;
  1584. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  1585. {
  1586. auto breakpoint = mBreakpoints[i];
  1587. auto checkBreakpoint = breakpoint;
  1588. bool hasAddr = false;
  1589. while (checkBreakpoint != NULL)
  1590. {
  1591. if ((checkBreakpoint->mAddr >= dbgModule->mImageBase) && (checkBreakpoint->mAddr < dbgModule->mImageBase + dbgModule->mImageSize))
  1592. hasAddr = true;
  1593. checkBreakpoint = (WdBreakpoint*)checkBreakpoint->mLinkedSibling;
  1594. }
  1595. if (hasAddr)
  1596. {
  1597. DetachBreakpoint(breakpoint);
  1598. needsBreakpointRehup = true;
  1599. }
  1600. }
  1601. mDebugTarget->UnloadDyn(dbgModule->mImageBase);
  1602. if (needsBreakpointRehup)
  1603. RehupBreakpoints(true);
  1604. mPendingDebugInfoLoad.Remove(dbgModule);
  1605. mPendingDebugInfoRequests.Remove(dbgModule);
  1606. mDebugManager->mOutMessages.push_back("modulesChanged");
  1607. }
  1608. if (!name.empty())
  1609. OutputMessage(StrFormat("Unloading DLL: %s @ %0s\n", name.c_str(), EncodeDataPtr((addr_target)(intptr)mDebugEvent.u.UnloadDll.lpBaseOfDll, true).c_str()));
  1610. BfLogDbg("UNLOAD_DLL_DEBUG_EVENT %s\n", name.c_str());
  1611. }
  1612. break;
  1613. case OUTPUT_DEBUG_STRING_EVENT:
  1614. {
  1615. const int maxChars = 1024 * 1024;
  1616. int len = BF_MIN(maxChars, (int)mDebugEvent.u.DebugString.nDebugStringLength); // 1MB max
  1617. char* message = new char[len + 1];
  1618. message[0] = 0;
  1619. message[len] = 0;
  1620. ReadMemory((addr_target)(intptr)mDebugEvent.u.DebugString.lpDebugStringData, len, message);
  1621. if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId == mDebugEvalThreadInfo.mThreadId))
  1622. mDebugManager->mOutMessages.push_back(String("dbgEvalMsg ") + message);
  1623. else
  1624. mDebugManager->mOutMessages.push_back(String("msg ") + message);
  1625. BfLogDbg("OUTPUT_DEBUG_STRING_EVENT (BreakAddr:%@): %s\n", threadInfo->mIsAtBreakpointAddress, message);
  1626. BF_ASSERT_REL(threadInfo->mIsAtBreakpointAddress == 0);
  1627. delete [] message;
  1628. }
  1629. break;
  1630. case CREATE_THREAD_DEBUG_EVENT:
  1631. {
  1632. WdThreadInfo* threadInfo = new WdThreadInfo();
  1633. threadInfo->mProcessId = mDebugEvent.dwProcessId;
  1634. threadInfo->mThreadId = mDebugEvent.dwThreadId;
  1635. threadInfo->mHThread = mDebugEvent.u.CreateThread.hThread;
  1636. threadInfo->mThreadLocalBase = mDebugEvent.u.CreateThread.lpThreadLocalBase;
  1637. threadInfo->mStartAddress = (void*)mDebugEvent.u.CreateThread.lpStartAddress;
  1638. BF_CONTEXT lcContext;
  1639. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  1640. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1641. threadInfo->mStartSP = BF_CONTEXT_SP(lcContext);
  1642. mThreadMap[mDebugEvent.dwThreadId] = threadInfo;
  1643. mDebuggerWaitingThread = threadInfo;
  1644. mThreadList.push_back(mDebuggerWaitingThread);
  1645. UpdateThreadDebugRegisters();
  1646. OutputMessage(StrFormat("Creating thread %d\n", mDebugEvent.dwThreadId));
  1647. }
  1648. break;
  1649. case EXIT_THREAD_DEBUG_EVENT:
  1650. {
  1651. OutputMessage(StrFormat("Exiting thread %d\n", mDebugEvent.dwThreadId));
  1652. if (mSteppingThread == threadInfo)
  1653. {
  1654. // We were attempting stepping on this thread, but not anymore!
  1655. ClearStep();
  1656. }
  1657. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_CONTINUE);
  1658. mIsDebuggerWaiting = false;
  1659. mWantsDebugContinue = false;
  1660. if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId == mDebugEvalThreadInfo.mThreadId))
  1661. {
  1662. // Thread terminated while evaluating! Is there a more graceful way of handling this?
  1663. CleanupDebugEval(false);
  1664. mRunState = RunState_Running;
  1665. }
  1666. mThreadList.Remove(mDebuggerWaitingThread);
  1667. delete mDebuggerWaitingThread;
  1668. mDebuggerWaitingThread = NULL;
  1669. mThreadMap.Remove(mDebugEvent.dwThreadId);
  1670. return true;
  1671. }
  1672. break;
  1673. case RIP_EVENT:
  1674. OutputMessage("RIP Event\n");
  1675. break;
  1676. case EXCEPTION_DEBUG_EVENT:
  1677. {
  1678. auto exceptionRecord = &mDebugEvent.u.Exception.ExceptionRecord;
  1679. switch (exceptionRecord->ExceptionCode)
  1680. {
  1681. case STATUS_WX86_BREAKPOINT:
  1682. case EXCEPTION_BREAKPOINT:
  1683. {
  1684. if (mRunState == RunState_Terminating)
  1685. {
  1686. BfLogDbg("Ignoring event because of RunState_Terminating\n");
  1687. break;
  1688. }
  1689. mAtBreakThread = threadInfo;
  1690. mActiveThread = mAtBreakThread;
  1691. bool isHighAddr = false;
  1692. #ifdef BF_DBG_32
  1693. if (((uintptr)exceptionRecord->ExceptionAddress & 0xFFFFFFFF00000000) != 0)
  1694. {
  1695. if (mActiveThread == mThreadList.front())
  1696. {
  1697. // Skip the initial Wow64 ntdll.dll!LdrpDoDebuggerBreak
  1698. mRunState = RunState_Running;
  1699. break;
  1700. }
  1701. isHighAddr = true;
  1702. }
  1703. #endif
  1704. addr_target pcAddress = (addr_target)(intptr)exceptionRecord->ExceptionAddress;
  1705. if (isHighAddr)
  1706. pcAddress = (addr_target)-1;
  1707. //mStoppedAtAddress = pcAddress;
  1708. bool isStepOut = false;
  1709. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto))
  1710. {
  1711. isStepOut = mStepBreakpointAddrs.Contains(pcAddress);
  1712. }
  1713. BF_CONTEXT lcContext;
  1714. lcContext.ContextFlags = BF_CONTEXT_ALL;
  1715. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  1716. BfLogDbg("EXCEPTION_BREAKPOINT Thread:%d %p SP:%p\n", mActiveThread->mThreadId, pcAddress, BF_CONTEXT_SP(lcContext));
  1717. uint8 origImageData = 0xCC;
  1718. mDebugTarget->ReadOrigImageData(pcAddress, &origImageData, 1);
  1719. bool wasDebugBreakpoint = origImageData != 0xCC;
  1720. DbgSubprogram* dwSubprogram = NULL;
  1721. DbgLineData* dwLineData = NULL;
  1722. if (!isStepOut)
  1723. {
  1724. dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  1725. if (dwSubprogram == NULL)
  1726. dwSubprogram = mDebugTarget->FindSubProgram(pcAddress, DbgOnDemandKind_LocalOnly);
  1727. }
  1728. bool isLineStart = (dwLineData != NULL) && (dwSubprogram->GetLineAddr(*dwLineData) == pcAddress);
  1729. bool isNonDebuggerBreak = false;
  1730. if (wasDebugBreakpoint)
  1731. {
  1732. // Go ahead and set EIP back one instruction
  1733. BF_CONTEXT_IP(lcContext)--;
  1734. BF_SetThreadContext(threadInfo->mHThread, &lcContext);
  1735. if ((dwSubprogram != NULL) && (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid) &&
  1736. (pcAddress == dwSubprogram->mBlock.mLowPC))
  1737. {
  1738. BfLogDbg("Hit HotReplaceKind_Invalid breakpoint\n");
  1739. mRunState = RunState_Paused;
  1740. mDebugManager->mOutMessages.push_back("error This lambda was replaced by a new version that has incompatible captures. A program restart is required.");
  1741. PhysRemoveBreakpoint(pcAddress);
  1742. break;
  1743. }
  1744. }
  1745. else
  1746. {
  1747. // This was an actual "break" instruction
  1748. BfLogDbg("Non-debugger break\n");
  1749. isNonDebuggerBreak = true;
  1750. auto prevState = mRunState;
  1751. // Make it an "auto" stop, so for example when we have an assert/retry we won't stop inside assembly
  1752. mRequestedStackFrameIdx = -2;
  1753. mRunState = RunState_Paused;
  1754. CheckNonDebuggerBreak();
  1755. if (IsInRunState())
  1756. {
  1757. BF_ASSERT((prevState == RunState_Running) || (prevState == RunState_DebugEval));
  1758. mRunState = prevState;
  1759. break; // Continue as if nothing happened
  1760. }
  1761. if (prevState == RunState_DebugEval)
  1762. mRequestedStackFrameIdx = -1; // Don't show a rolled back stack idx if a debug eval fails
  1763. ClearStep();
  1764. }
  1765. if (threadInfo->mIsBreakRestorePaused)
  1766. {
  1767. // The thread is supposed to be paused, but the IP has been reset
  1768. // so just break here so we'll hit that breakpoint again once we're
  1769. // actually unpaused properly
  1770. BfLogDbg("Ignoring EXCEPTION_BREAKPOINT\n", threadInfo->mThreadId);
  1771. break;
  1772. }
  1773. if ((mRunState == RunState_DebugEval) || (mRunState == RunState_HotStep))
  1774. {
  1775. // If we hit a breakpoint while doing a debug eval, we just remove the breakpoint
  1776. // and expect to reinstate it during a rehup after the evaluation has completed
  1777. WdBreakpoint* breakpoint = (WdBreakpoint*)FindBreakpointAt((uintptr_t) exceptionRecord->ExceptionAddress);
  1778. if (breakpoint != NULL)
  1779. {
  1780. mNeedsRehupBreakpoints = true;
  1781. RemoveBreakpoint(breakpoint->mLineData.GetAddress());
  1782. }
  1783. break;
  1784. }
  1785. bool isDeeper = false;
  1786. int stepBreakAddrIdx = (int)mStepBreakpointAddrs.IndexOf(pcAddress);
  1787. WdBreakpoint* breakpoint = NULL;
  1788. bool ignoreBreakpoint = false;
  1789. if ((mStepType != StepType_None) && (mSteppingThread == mAtBreakThread))
  1790. {
  1791. if (mStepType == StepType_ToTempBreakpoint)
  1792. {
  1793. RemoveTempBreakpoints();
  1794. mRunState = RunState_Paused;
  1795. break;
  1796. }
  1797. if (mContinueFromBreakpointFailed)
  1798. {
  1799. BfLogDbg("Continuing from ContinueFromBreakpointFailed\n");
  1800. SetupStep(mStepType);
  1801. mRunState = RunState_Running;
  1802. break;
  1803. }
  1804. if (!isStepOut)
  1805. breakpoint = (WdBreakpoint*)FindBreakpointAt(pcAddress);
  1806. // Ignore breakpoint if it's on the line we're stepping off of
  1807. if ((breakpoint != NULL) && (breakpoint->mAddr == mStepPC) &&
  1808. (mStepSP == BF_CONTEXT_SP(lcContext)))
  1809. {
  1810. ignoreBreakpoint = true;
  1811. }
  1812. else if ((breakpoint != NULL) && (stepBreakAddrIdx == -1) && (!CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress)))
  1813. {
  1814. ignoreBreakpoint = true;
  1815. }
  1816. if ((stepBreakAddrIdx == -1) && (breakpoint == NULL) && (!isNonDebuggerBreak))
  1817. {
  1818. // If a breakpoint is removed in a prior thread
  1819. BfLogDbg("Ignoring step break (old breakpoint)\n");
  1820. if ((mSteppingThread == mAtBreakThread) && (mStepSwitchedThreads))
  1821. {
  1822. SetupStep(mStepType);
  1823. }
  1824. break;
  1825. }
  1826. if ((stepBreakAddrIdx != -1) && (breakpoint == NULL) && (mSteppingThread != mActiveThread))
  1827. {
  1828. BfLogDbg("Ignoring break (wrong thread)\n");
  1829. ThreadRestorePause(mSteppingThread, mActiveThread);
  1830. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1831. break;
  1832. }
  1833. isDeeper = mStepSP > BF_CONTEXT_SP(lcContext);
  1834. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto))
  1835. {
  1836. isDeeper = mStepSP >= BF_CONTEXT_SP(lcContext);
  1837. BfLogDbg("StepOut Iteration SP:%p StartSP:%p IsDeeper:%d\n", BF_CONTEXT_SP(lcContext), mStepSP, isDeeper);
  1838. }
  1839. if (((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_ThenInto)) && (breakpoint == NULL) && (isDeeper))
  1840. {
  1841. // We're encountered recursion
  1842. // Make sure we don't already have one of these stored
  1843. BF_ASSERT(mStoredReturnValueAddr == 0);
  1844. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1845. break; // Don't fall through, we don't want to set mIsAtBreakpointAddress
  1846. }
  1847. if (isStepOut)
  1848. {
  1849. threadInfo->mIsAtBreakpointAddress = pcAddress;
  1850. if (mStepType == StepType_StepOut_ThenInto)
  1851. {
  1852. dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  1853. if ((dwLineData != NULL) && (pcAddress == dwSubprogram->GetLineAddr(*dwLineData)))
  1854. {
  1855. // Our step out from a filtered function put us at the start of a new line. Stop here
  1856. // <do nothing>
  1857. }
  1858. else
  1859. {
  1860. // .. otherwise keep going until we get to the start of a new line
  1861. SetupStep(StepType_StepInto);
  1862. mRunState = RunState_Running;
  1863. break;
  1864. }
  1865. }
  1866. if (!mStepInAssembly)
  1867. {
  1868. // Keep stepping out until we find a frame that we have source for
  1869. DbgSubprogram* dwSubprogram = NULL;
  1870. DbgLineData* dwLineData = FindLineDataAtAddress(BF_CONTEXT_IP(lcContext), &dwSubprogram);
  1871. if (dwLineData == NULL)
  1872. {
  1873. SetupStep(StepType_StepOut);
  1874. break;
  1875. }
  1876. if ((dwLineData->mColumn == -1) && (!dwSubprogram->HasValidLines()))
  1877. {
  1878. // This is a method we don't actually want to be in, it has no valid lines!
  1879. SetupStep(StepType_StepOut);
  1880. break;
  1881. }
  1882. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  1883. {
  1884. // We've stepped out, but right into the start of an inlined method, so step out of this inlined method now...
  1885. SetupStep(StepType_StepOut);
  1886. break;
  1887. }
  1888. }
  1889. ClearStep();
  1890. mRunState = RunState_Paused;
  1891. threadInfo->mStoppedAtAddress = pcAddress;
  1892. break;
  1893. }
  1894. mRunState = RunState_Paused;
  1895. if (breakpoint != NULL)
  1896. {
  1897. // While stepping we hit a legit breakpoint
  1898. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  1899. // Ignore breakpoint on return statement if we're return-stepping
  1900. mRunState = RunState_Breakpoint;
  1901. }
  1902. if ((mStepType == StepType_StepInto) && (dwSubprogram != NULL))
  1903. {
  1904. // Don't filter out the current subprogram (would break cases where we explicitly stepped into or hit breakpoint in a filtered subprogram)
  1905. bool isInStartSubprogram = (mStepStartPC >= dwSubprogram->mBlock.mLowPC) && (mStepStartPC < dwSubprogram->mBlock.mHighPC);
  1906. if ((!isInStartSubprogram) && (IsStepFiltered(dwSubprogram, dwLineData)))
  1907. {
  1908. BfLogDbg("Hit step filter\n");
  1909. mRunState = RunState_Running;
  1910. SetupStep(StepType_StepOut_ThenInto);
  1911. break;
  1912. }
  1913. }
  1914. if ((mStepType == StepType_StepOver) && (stepBreakAddrIdx == 0) && (mStepBreakpointAddrs[0] != 0) && (mStepBreakpointAddrs.size() > 1))
  1915. {
  1916. // Break was on the 'call' instruction, not the instruction after it -- means recursion
  1917. BfLogDbg("StepOver detected recursing\n");
  1918. mStepIsRecursing = true;
  1919. if (mTempBreakpoint.Remove(mStepBreakpointAddrs[0]))
  1920. {
  1921. RemoveBreakpoint(mStepBreakpointAddrs[0]);
  1922. }
  1923. mStepBreakpointAddrs[0] = 0;
  1924. mRunState = RunState_Running;
  1925. break;
  1926. }
  1927. if ((mStepType == StepType_StepOver) && (stepBreakAddrIdx > 0) && (mStepBreakpointAddrs[0] != 0) && (isDeeper))
  1928. {
  1929. // This is the first time we've hit the target breakpoint.
  1930. if (HasSteppedIntoCall())
  1931. {
  1932. mStepIsRecursing = true;
  1933. RemoveBreakpoint(mStepBreakpointAddrs[0]);
  1934. mStepBreakpointAddrs[0] = 0;
  1935. //mStepBreakpointAddrs.erase(mStepBreakpointAddrs.begin());
  1936. }
  1937. }
  1938. if ((mStepType == StepType_StepOver) && (mStepIsRecursing) && (stepBreakAddrIdx != -1) && (isDeeper))
  1939. {
  1940. // Decrement so the equality test on "step out" marks us as not being deeper when we
  1941. // hit the expected SP
  1942. BfLogDbg("Converting StepOver to StepOut\n");
  1943. mStepSP--;
  1944. mStepType = StepType_StepOut_ThenInto;
  1945. //SetupStep(StepType_StepOut);
  1946. mRunState = RunState_Running;
  1947. break;
  1948. }
  1949. if ((mStepType == StepType_StepOver) && (!ignoreBreakpoint) && (breakpoint == NULL) && (!mStepInAssembly))
  1950. {
  1951. // Test for stepping over inline method
  1952. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  1953. // mTempBreakpoints will have 2 entries if we are on a 'call' line. If we have an inlined call immediately following a call, then we
  1954. // assume we're hitting a return break
  1955. /*if ((dwSubprogram != NULL) && (dwSubprogram->mInlineParent != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC) && (mTempBreakpoint.size() < 2))
  1956. {
  1957. BfLogDbg("Attempting StepOver of inlined method\n");
  1958. SetupStep(StepType_StepOut);
  1959. mRunState = RunState_Running;
  1960. break;
  1961. } */
  1962. //TODO: The previous logic with the "(mTempBreakpoint.size() < 2)" was causing Try!(Method()); stepovers to enter into Try!. What did we mean by
  1963. // "assume we're hitting a return break"?
  1964. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  1965. {
  1966. RemoveTempBreakpoints();
  1967. BfLogDbg("Attempting StepOver of inlined method\n");
  1968. SetupStep(StepType_StepOut);
  1969. mRunState = RunState_Running;
  1970. break;
  1971. }
  1972. }
  1973. if (mStepType == StepType_StepOut_Inline)
  1974. {
  1975. if (mOrigStepType == StepType_StepOver)
  1976. {
  1977. // For the step over, if we are still inside the source line after an inline then step over again...
  1978. DbgSubprogram* origSubprogram = NULL;
  1979. auto origLineData = FindLineDataAtAddress(mStepStartPC, &origSubprogram);
  1980. DbgSubprogram* curSubprogram = NULL;
  1981. auto curLineData = FindLineDataAtAddress(pcAddress, &curSubprogram);
  1982. if ((origLineData != NULL) &&
  1983. ((origLineData == curLineData) ||
  1984. ((origSubprogram == curSubprogram) && (origLineData->mLine == curLineData->mLine))))
  1985. {
  1986. mRunState = RunState_Running;
  1987. SetupStep(StepType_StepOver);
  1988. break;
  1989. }
  1990. }
  1991. ClearStep();
  1992. break;
  1993. }
  1994. if ((mStepType != StepType_None) && (ignoreBreakpoint) && (!mStepInAssembly) && (stepBreakAddrIdx == -1))
  1995. {
  1996. // Ignore breakpoint by just continuing...
  1997. mRunState = RunState_Running;
  1998. break;
  1999. }
  2000. RemoveTempBreakpoints();
  2001. if ((mStepType != StepType_None) && (!mStepInAssembly) && (!isLineStart) && (stepBreakAddrIdx != -1))
  2002. {
  2003. SetupStep(mStepType);
  2004. mRunState = RunState_Running;
  2005. }
  2006. else
  2007. {
  2008. //if (mStepType != StepType_Return)
  2009. if (stepBreakAddrIdx != -1)
  2010. {
  2011. // Even if we've detected we're at a breakpoint, we mark ourselves as just stepping if we also
  2012. // have a step breakpoint here
  2013. StepLineTryPause(pcAddress, true);
  2014. }
  2015. if (mRunState == RunState_Paused)
  2016. ClearStep();
  2017. }
  2018. if (ignoreBreakpoint)
  2019. {
  2020. SetupStep(mStepType);
  2021. mRunState = RunState_Running;
  2022. }
  2023. if ((mRunState == RunState_Paused) && (breakpoint != NULL))
  2024. {
  2025. // Just do the 'check' here so we can do the logging/condition stuff
  2026. CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress);
  2027. }
  2028. }
  2029. else
  2030. {
  2031. breakpoint = (WdBreakpoint*)FindBreakpointAt((uintptr_t)exceptionRecord->ExceptionAddress);
  2032. if ((breakpoint != NULL) && (!CheckConditionalBreakpoint(breakpoint, dwSubprogram, pcAddress)))
  2033. {
  2034. ClearCallStack();
  2035. BfLogDbg("Skipping conditional breakpoint. Setting mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  2036. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  2037. mRunState = RunState_Running;
  2038. break;
  2039. }
  2040. if (breakpoint != NULL)
  2041. {
  2042. BfLogDbg("Breakpoint hit. mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  2043. threadInfo->mIsAtBreakpointAddress = breakpoint->mAddr;
  2044. mRunState = RunState_Breakpoint;
  2045. }
  2046. else if ((stepBreakAddrIdx != -1) || (isNonDebuggerBreak))
  2047. {
  2048. if (mRunState != RunState_DebugEval)
  2049. {
  2050. // Was in mStepBreakpointAddrs list
  2051. if ((isNonDebuggerBreak) || (mStepType == StepType_None) || (mSteppingThread == mAtBreakThread))
  2052. {
  2053. BfLogDbg("Hit mStepBreakpointAddrs breakpoint\n");
  2054. mRunState = RunState_Paused;
  2055. }
  2056. else
  2057. {
  2058. BfLogDbg("Ignored mStepBreakpointAddrs breakpoint (wrong thread)\n");
  2059. mRunState = RunState_Running;
  2060. }
  2061. }
  2062. }
  2063. else
  2064. {
  2065. BfLogDbg("Ignoring break (old or ignored breakpoint)\n");
  2066. mRunState = RunState_Running;
  2067. }
  2068. }
  2069. if ((breakpoint != NULL) && (!ignoreBreakpoint))
  2070. {
  2071. mActiveBreakpoint = breakpoint;
  2072. mBreakStackFrameIdx = -1;
  2073. }
  2074. if ((mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint))
  2075. threadInfo->mStoppedAtAddress = pcAddress;
  2076. }
  2077. break;
  2078. case STATUS_WX86_SINGLE_STEP:
  2079. case EXCEPTION_SINGLE_STEP:
  2080. {
  2081. if (mRunState == RunState_Terminating)
  2082. {
  2083. BfLogDbg("Ignoring event because of RunState_Terminating\n");
  2084. break;
  2085. }
  2086. if ((mStepSwitchedThreads) && (mActiveThread == mSteppingThread) && (mActiveThread->mIsAtBreakpointAddress != NULL))
  2087. {
  2088. ContinueFromBreakpoint();
  2089. break;
  2090. }
  2091. if (mRunState == RunState_HotStep)
  2092. {
  2093. BF_ASSERT(mActiveThread == mDebuggerWaitingThread);
  2094. mRunState = RunState_Paused;
  2095. break;
  2096. }
  2097. mActiveThread = mDebuggerWaitingThread;
  2098. BF_CONTEXT lcContext;
  2099. lcContext.ContextFlags = BF_CONTEXT_ALL;
  2100. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  2101. addr_target pcAddress = BF_CONTEXT_IP(lcContext);
  2102. bool wasUnfilteredStep = mStepType == StepType_StepInto_Unfiltered;
  2103. if (mStepType == StepType_StepInto_UnfilteredSingle)
  2104. {
  2105. wasUnfilteredStep = true;
  2106. mStepType = StepType_StepInto;
  2107. mStepStartPC = pcAddress;
  2108. }
  2109. BfLogDbg("EXCEPTION_SINGLE_STEP Thread:%d PC:%p\n", mActiveThread->mThreadId, exceptionRecord->ExceptionAddress);
  2110. if (lcContext.Dr6 & 0x0F) // Memory breakpoint hit
  2111. {
  2112. WdBreakpoint* foundBreakpoint = NULL;
  2113. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  2114. {
  2115. if ((lcContext.Dr6 & ((intptr_target)1 << memoryWatchSlot)) != 0)
  2116. {
  2117. foundBreakpoint = mMemoryBreakpoints[memoryWatchSlot].mBreakpoint;
  2118. break;
  2119. }
  2120. }
  2121. BF_ASSERT(foundBreakpoint != NULL);
  2122. DbgSubprogram* subprogram = mDebugTarget->FindSubProgram(pcAddress);
  2123. if (CheckConditionalBreakpoint(foundBreakpoint, subprogram, pcAddress))
  2124. {
  2125. if (foundBreakpoint != NULL)
  2126. {
  2127. mDebugManager->mOutMessages.push_back(StrFormat("memoryBreak %s", EncodeDataPtr(foundBreakpoint->mMemoryBreakpointInfo->mMemoryAddress, false).c_str()));
  2128. mRunState = RunState_Paused;
  2129. }
  2130. mActiveBreakpoint = foundBreakpoint;
  2131. mBreakStackFrameIdx = -1;
  2132. RemoveTempBreakpoints();
  2133. BfLogDbg("Memory breakpoint hit: %p\n", foundBreakpoint);
  2134. }
  2135. else
  2136. ClearCallStack();
  2137. break;
  2138. }
  2139. if ((mRunState == RunState_DebugEval) && (mDebugEvalThreadInfo.mThreadId == mDebuggerWaitingThread->mThreadId))
  2140. {
  2141. if ((addr_target)(intptr)exceptionRecord->ExceptionAddress == mDebugEvalSetRegisters.GetPC())
  2142. {
  2143. // This indicates we are returning from kernel mode and our registers are clobbered
  2144. SetRegisters(&mDebugEvalSetRegisters);
  2145. }
  2146. break;
  2147. }
  2148. bool hadBreakpointContinue = true;
  2149. if (threadInfo->mBreakpointAddressContinuing != 0)
  2150. {
  2151. bool wantsBreakpoint = WantsBreakpointAt(threadInfo->mBreakpointAddressContinuing);
  2152. BfLogDbg("Continuing breakpoint at %p WantsReset:%d\n", threadInfo->mBreakpointAddressContinuing, wantsBreakpoint);
  2153. if (wantsBreakpoint)
  2154. {
  2155. PhysSetBreakpoint(threadInfo->mBreakpointAddressContinuing);
  2156. }
  2157. threadInfo->mBreakpointAddressContinuing = NULL;
  2158. hadBreakpointContinue = true;
  2159. ThreadRestoreUnpause();
  2160. }
  2161. if ((mSteppingThread != NULL) && (mSteppingThread != mActiveThread))
  2162. {
  2163. // This SINGLE_STEP happened in the wrong thread - we need the stepping thread to do the stepping!
  2164. // Try again.
  2165. mActiveThread = mSteppingThread;
  2166. SingleStepX86();
  2167. break;
  2168. }
  2169. bool isDeeper = mStepSP > BF_CONTEXT_SP(lcContext);
  2170. if ((mStepSwitchedThreads) && (mStepType == StepType_StepOver) && (isDeeper))
  2171. {
  2172. if (HasSteppedIntoCall())
  2173. {
  2174. // Since we switched threads, we needed to do a hardware step which has placed us inside a
  2175. // call, so we need to step out of that now...
  2176. SetupStep(StepType_StepOut_NoFrame);
  2177. break;
  2178. }
  2179. }
  2180. // If we don't have a mStepBreakpointAddrs set, that means we're stepping through individual instructions --
  2181. // so process the new location here
  2182. if (((mStepType == StepType_StepInto) || (mStepType == StepType_StepInto_Unfiltered) || (mStepType == StepType_StepOver)) && (mStepBreakpointAddrs.size() == 0))
  2183. {
  2184. DbgSubprogram* dwSubprogram = NULL;
  2185. DbgLineData* dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  2186. if ((dwSubprogram != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC) && (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced))
  2187. {
  2188. BfLogDbg("Stepping through hot thunk\n");
  2189. mRunState = RunState_Running;
  2190. SingleStepX86();
  2191. break;
  2192. }
  2193. if ((mStepType == StepType_StepOver) && (!mStepInAssembly))
  2194. {
  2195. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress == dwSubprogram->mBlock.mLowPC))
  2196. {
  2197. BfLogDbg("Attempting StepOver of inlined method - SingleStep\n");
  2198. SetupStep(StepType_StepOut);
  2199. mRunState = RunState_Running;
  2200. break;
  2201. }
  2202. }
  2203. // Column of -1 means "Illegal", keep stepping!
  2204. if ((mStepInAssembly) ||
  2205. ((dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dwLineData->mColumn >= 0) &&
  2206. ((dwSubprogram->GetLineAddr(*dwLineData) == pcAddress) || (mStepStopOnNextInstruction))))
  2207. {
  2208. // Hit a line while stepping, we're done!
  2209. mRunState = RunState_Paused;
  2210. StepLineTryPause(pcAddress, false);
  2211. if (mRunState == RunState_Paused)
  2212. {
  2213. if ((mStepType == StepType_StepInto) && (!wasUnfilteredStep) && (!mStepInAssembly) && (dwSubprogram != NULL))
  2214. {
  2215. // Don't filter out the current subprogram (would break cases where we explicitly stepped into or hit breakpoint in a filtered subprogram)
  2216. bool isInStartSubprogram = (mStepStartPC >= dwSubprogram->mBlock.mLowPC) && (mStepStartPC < dwSubprogram->mBlock.mHighPC);
  2217. if ((!isInStartSubprogram) && (IsStepFiltered(dwSubprogram, dwLineData)))
  2218. {
  2219. BfLogDbg("Hit step filter (2)\n");
  2220. mRunState = RunState_Running;
  2221. SetupStep(StepType_StepOut_ThenInto);
  2222. break;
  2223. }
  2224. }
  2225. ClearStep();
  2226. mCurNoInfoStepTries = 0; // Reset
  2227. }
  2228. else
  2229. SetupStep(mStepType);
  2230. }
  2231. else if (dwSubprogram != NULL)
  2232. {
  2233. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && ((mStepType == StepType_StepInto) || (mStepType == StepType_StepInto_Unfiltered)))
  2234. {
  2235. SingleStepX86();
  2236. }
  2237. else
  2238. {
  2239. // Inside a line's instruction, keep going
  2240. SetupStep(mStepType);
  2241. mCurNoInfoStepTries = 0; // Reset
  2242. }
  2243. }
  2244. else if (mStepType == StepType_StepInto_Unfiltered)
  2245. {
  2246. CPUInst inst;
  2247. if (mDebugTarget->DecodeInstruction(pcAddress, &inst))
  2248. {
  2249. if (inst.IsBranch())
  2250. {
  2251. auto target = inst.GetTarget();
  2252. if (target != 0)
  2253. {
  2254. DbgSubprogram* destSubprogram = mDebugTarget->FindSubProgram(target);
  2255. if ((destSubprogram != NULL) && (target == destSubprogram->mBlock.mLowPC))
  2256. {
  2257. // We're jumping to an actual subprogram, so continue stepping here
  2258. mStepType = StepType_StepInto_UnfilteredSingle;
  2259. SingleStepX86();
  2260. break;
  2261. }
  2262. }
  2263. }
  2264. }
  2265. // We requested to step into this method so stop here even if we don't have source
  2266. mRunState = RunState_Paused;
  2267. }
  2268. else
  2269. {
  2270. // No debug info!
  2271. bool doStepOut = false;
  2272. if (mCurNoInfoStepTries < 16)
  2273. {
  2274. mCurNoInfoStepTries++;
  2275. BfLogDbg("NoInfoStepTries: %d\n", mCurNoInfoStepTries);
  2276. if (!SetupStep(mStepType))
  2277. doStepOut = true;
  2278. }
  2279. else
  2280. doStepOut = true;
  2281. if (doStepOut)
  2282. {
  2283. // Step out of current call.
  2284. mStepSP = 0;
  2285. SetupStep(StepType_StepOut_NoFrame);
  2286. // Aggressive stepout - don't monitor BP
  2287. mStepSP = 0;
  2288. }
  2289. }
  2290. }
  2291. else if (!hadBreakpointContinue)
  2292. {
  2293. BF_DBG_FATAL("EXCEPTION_SINGLE_STEP bad debugger state");
  2294. }
  2295. if (mRunState == RunState_Paused)
  2296. threadInfo->mStoppedAtAddress = pcAddress;
  2297. }
  2298. break;
  2299. default:
  2300. {
  2301. bool isSystemException =
  2302. (exceptionRecord->ExceptionCode >= STATUS_ACCESS_VIOLATION) &&
  2303. (exceptionRecord->ExceptionCode <= STATUS_ASSERTION_FAILURE);
  2304. bool isFirstChance = mDebugEvent.u.Exception.dwFirstChance != 0;
  2305. bool handled = false;
  2306. //TODO: Use a user-defined filter here to determine whether to stop or continue
  2307. if ((!isSystemException) && (isFirstChance))
  2308. {
  2309. if (exceptionRecord->ExceptionCode == 0x406D1388) // Visual C
  2310. {
  2311. if ((int32)exceptionRecord->ExceptionInformation[0] == 0x1000)
  2312. {
  2313. struct THREADNAME_INFO
  2314. {
  2315. DWORD dwType; // Must be 0x1000.
  2316. LPCSTR szName; // Pointer to name (in user addr space).
  2317. DWORD dwThreadID; // Thread ID (-1=caller thread).
  2318. DWORD dwFlags; // Reserved for future use, must be zero.
  2319. };
  2320. THREADNAME_INFO* threadNameInfo = (THREADNAME_INFO*)exceptionRecord->ExceptionInformation;
  2321. DwFormatInfo formatInfo;
  2322. formatInfo.mRawString = true;
  2323. String nameStr = ReadString(DbgType_SChar, (intptr)threadNameInfo->szName, false, 1024, formatInfo, false);
  2324. WdThreadInfo* namingThreadInfo = threadInfo;
  2325. if (threadNameInfo->dwThreadID != (DWORD)-1)
  2326. {
  2327. namingThreadInfo = NULL;
  2328. mThreadMap.TryGetValue(threadNameInfo->dwThreadID, &namingThreadInfo);
  2329. }
  2330. if (namingThreadInfo != NULL)
  2331. {
  2332. namingThreadInfo->mName = nameStr;
  2333. FilterThreadName(namingThreadInfo->mName);
  2334. }
  2335. }
  2336. else if (((int32)exceptionRecord->ExceptionInformation[0] == 0x1001) && ((int32)exceptionRecord->ExceptionInformation[1] == 0x1002))
  2337. {
  2338. struct FailMessage
  2339. {
  2340. addr_target mPtr0; // Unknown
  2341. addr_target mPtr1; // 0
  2342. addr_target mPtr2; // 0
  2343. addr_target mPtr3; // Unknown
  2344. addr_target mErrorStr;
  2345. };
  2346. FailMessage failMessage = ReadMemory<FailMessage>(exceptionRecord->ExceptionInformation[2]);
  2347. DwFormatInfo formatInfo;
  2348. String failStr = ReadString(DbgType_SChar16, failMessage.mErrorStr, false, 8192, formatInfo, false);
  2349. mDebugManager->mOutMessages.push_back(StrFormat("error Run-Time Check Failure %d - %s", exceptionRecord->ExceptionInformation[6], failStr.c_str()));
  2350. mRunState = RunState_Paused;
  2351. mRequestedStackFrameIdx = -2; // -2 = "auto"
  2352. handled = true;
  2353. }
  2354. }
  2355. if (!handled)
  2356. {
  2357. OutputMessage(StrFormat("Skipping first chance exception %08X at address %@ in thread %d\n", exceptionRecord->ExceptionCode, exceptionRecord->ExceptionAddress, threadInfo->mThreadId));
  2358. ::ContinueDebugEvent(mDebuggerWaitingThread->mProcessId, mDebuggerWaitingThread->mThreadId, DBG_EXCEPTION_NOT_HANDLED);
  2359. mIsDebuggerWaiting = false;
  2360. }
  2361. }
  2362. else
  2363. {
  2364. BfLogDbg("EXCEPTION in thread %d at %p\n", threadInfo->mThreadId, exceptionRecord->ExceptionAddress);
  2365. OutputDebugStrF("EXCEPTION\n");
  2366. mActiveThread = threadInfo;
  2367. memcpy(&mCurException, exceptionRecord, sizeof(EXCEPTION_RECORD));
  2368. if (mRunState == RunState_DebugEval)
  2369. {
  2370. if ((intptr)mCurException.ExceptionAddress == 42)
  2371. {
  2372. BfLogDbg("RunState_DebugEval_Done\n");
  2373. OutputDebugStrF(" RunState_DebugEval_Done\n");
  2374. }
  2375. else
  2376. {
  2377. BfLogDbg("Exception at 0x%@ in thread %d, exception code 0x%08X",
  2378. mCurException.ExceptionAddress, mActiveThread->mThreadId, mCurException.ExceptionCode);
  2379. mDebugPendingExpr->mException = StrFormat("Exception at 0x%@ in thread %d, exception code 0x%08X",
  2380. mCurException.ExceptionAddress, mActiveThread->mThreadId, mCurException.ExceptionCode);
  2381. }
  2382. mRunState = RunState_DebugEval_Done;
  2383. mExplicitStopThread = mActiveThread;
  2384. mRequestedStackFrameIdx = mDebugPendingExpr->mCallStackIdx;
  2385. }
  2386. else
  2387. {
  2388. mRunState = RunState_Exception;
  2389. }
  2390. }
  2391. }
  2392. break;
  2393. }
  2394. }
  2395. break;
  2396. }
  2397. if ((mDebugEvalThreadInfo.mThreadId != 0) && (mRunState != RunState_DebugEval) && (mRunState != RunState_DebugEval_Done))
  2398. {
  2399. CleanupDebugEval();
  2400. }
  2401. // Stepping done?
  2402. if (mStepType == StepType_None)
  2403. {
  2404. mLastValidStepIntoPC = 0;
  2405. }
  2406. BF_ASSERT(mDebuggerWaitingThread != NULL);
  2407. return true;
  2408. }
  2409. void WinDebugger::Update()
  2410. {
  2411. AutoCrit autoCrit(mDebugManager->mCritSect);
  2412. // if (mRunState == RunState_DebugEval)
  2413. // ContinueDebugEvent();
  2414. if (mRunState == RunState_DebugEval_Done)
  2415. {
  2416. if (mDebugPendingExpr != NULL)
  2417. {
  2418. mDebugPendingExpr->mIdleTicks++;
  2419. if (mDebugPendingExpr->mIdleTicks >= 2)
  2420. {
  2421. BfLogDbg("Finishing pending expr in thread %d\n", mDebugEvalThreadInfo.mThreadId);
  2422. mRunState = RunState_Paused;
  2423. CleanupDebugEval();
  2424. }
  2425. }
  2426. }
  2427. else if (mDebugPendingExpr != NULL)
  2428. {
  2429. mDebugPendingExpr->mIdleTicks = 0;
  2430. }
  2431. }
  2432. void WinDebugger::ContinueDebugEvent()
  2433. {
  2434. AutoCrit autoCrit(mDebugManager->mCritSect);
  2435. BF_ASSERT(mRunState != RunState_DebugEval_Done);
  2436. if (!mWantsDebugContinue)
  2437. return;
  2438. if (!TryRunContinue())
  2439. return;
  2440. // if ((mRunState == RunState_DebugEval) && (mDebuggerWaitingThread->mThreadId != mDebugEvalThreadInfo.mThreadId))
  2441. // {
  2442. // // Don't process the 'mIsAtBreakpointAddress' stuff
  2443. // mWantsDebugContinue = false;
  2444. // mContinueEvent.Set();
  2445. // return;
  2446. // }
  2447. if ((mDebuggerWaitingThread->mIsAtBreakpointAddress == 0) && (mDebuggerWaitingThread->mStoppedAtAddress != 0))
  2448. {
  2449. auto breakpoint = FindBreakpointAt(mDebuggerWaitingThread->mStoppedAtAddress);
  2450. if (breakpoint != NULL)
  2451. {
  2452. mDebuggerWaitingThread->mIsAtBreakpointAddress = mDebuggerWaitingThread->mStoppedAtAddress;
  2453. }
  2454. }
  2455. if (mDebuggerWaitingThread->mIsAtBreakpointAddress != 0)
  2456. {
  2457. if (!ContinueFromBreakpoint())
  2458. {
  2459. BfLogDbg("ContinueFromBreakpoint failed\n");
  2460. ClearCallStack();
  2461. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  2462. mDebuggerWaitingThread->mIsAtBreakpointAddress = 0;
  2463. mWantsDebugContinue = false;
  2464. mContinueFromBreakpointFailed = true;
  2465. mContinueEvent.Set();
  2466. return;
  2467. }
  2468. }
  2469. if ((mRunState == RunState_Breakpoint) || (mRunState == RunState_Paused))
  2470. {
  2471. ClearCallStack();
  2472. mRunState = RunState_Running;
  2473. }
  2474. mDebuggerWaitingThread->mStoppedAtAddress = 0;
  2475. mWantsDebugContinue = false;
  2476. BF_ASSERT_REL(mDebuggerWaitingThread->mIsAtBreakpointAddress == 0);
  2477. mContinueEvent.Set();
  2478. }
  2479. static BOOL CALLBACK WdEnumWindowsProc(HWND hwnd, LPARAM lParam)
  2480. {
  2481. HWND owner = GetWindow(hwnd, GW_OWNER);
  2482. if (!IsWindowVisible(hwnd))
  2483. return TRUE;
  2484. DWORD processId = 0;
  2485. DWORD threadId = GetWindowThreadProcessId(hwnd, &processId);
  2486. if (processId != ((WinDebugger*)gDebugger)->mProcessInfo.dwProcessId)
  2487. return TRUE;
  2488. SetForegroundWindow(hwnd);
  2489. return TRUE;
  2490. }
  2491. void WinDebugger::ForegroundTarget()
  2492. {
  2493. EnumWindows(WdEnumWindowsProc, 0);
  2494. }
  2495. static int gFindLineDataAt = 0;
  2496. DbgLineData* WinDebugger::FindLineDataAtAddress(addr_target address, DbgSubprogram** outSubProgram, DbgSrcFile** outSrcFile, int* outLineIdx, DbgOnDemandKind onDemandKind)
  2497. {
  2498. gFindLineDataAt++;
  2499. BP_ZONE("WinDebugger::FindLineDataAtAddress");
  2500. auto dwSubprogram = mDebugTarget->FindSubProgram((addr_target)address, onDemandKind);
  2501. if (dwSubprogram == NULL)
  2502. return NULL;
  2503. FixupLineDataForSubprogram(dwSubprogram);
  2504. auto lineData = dwSubprogram->FindClosestLine(address, outSubProgram, outSrcFile, outLineIdx);
  2505. return lineData;
  2506. }
  2507. DbgLineData* WinDebugger::FindLineDataInSubprogram(addr_target address, DbgSubprogram* dwSubprogram)
  2508. {
  2509. auto dwCompileUnit = dwSubprogram->mCompileUnit;
  2510. FixupLineDataForSubprogram(dwSubprogram);
  2511. auto lineData = dwSubprogram->FindClosestLine(address);
  2512. return lineData;
  2513. }
  2514. bool WinDebugger::IsStepFiltered(DbgSubprogram* dbgSubprogram, DbgLineData* dbgLineData)
  2515. {
  2516. if (mIsStepIntoSpecific)
  2517. return false;
  2518. if (dbgSubprogram->mStepFilterVersion != mDebugManager->mStepFilterVersion)
  2519. {
  2520. String filterName;
  2521. CreateFilterName(filterName, dbgSubprogram);
  2522. dbgSubprogram->PopulateSubprogram();
  2523. bool doDefault = false;
  2524. StepFilter* stepFilterPtr;
  2525. if (mDebugManager->mStepFilters.TryGetValue(filterName, &stepFilterPtr))
  2526. {
  2527. switch (stepFilterPtr->mFilterKind)
  2528. {
  2529. case BfStepFilterKind_Default:
  2530. doDefault = true;
  2531. break;
  2532. case BfStepFilterKind_Filtered:
  2533. dbgSubprogram->mIsStepFiltered = true;
  2534. break;
  2535. case BfStepFilterKind_NotFiltered:
  2536. dbgSubprogram->mIsStepFiltered = false;
  2537. break;
  2538. }
  2539. }
  2540. else
  2541. {
  2542. doDefault = true;
  2543. }
  2544. if (doDefault)
  2545. {
  2546. dbgSubprogram->mIsStepFiltered = dbgSubprogram->mIsStepFilteredDefault;
  2547. }
  2548. dbgSubprogram->mStepFilterVersion = mDebugManager->mStepFilterVersion;
  2549. }
  2550. if (!dbgSubprogram->mIsStepFiltered)
  2551. {
  2552. if (dbgLineData != NULL)
  2553. {
  2554. auto dbgSrcFile = dbgSubprogram->GetLineSrcFile(*dbgLineData);
  2555. if (dbgSrcFile->mStepFilterVersion != mDebugManager->mStepFilterVersion)
  2556. {
  2557. dbgSrcFile->mFileExistKind = dbgSubprogram->mCompileUnit->mDbgModule->CheckSourceFileExist(dbgSrcFile->GetLocalPath());
  2558. dbgSrcFile->mStepFilterVersion = mDebugManager->mStepFilterVersion;
  2559. }
  2560. switch (dbgSrcFile->mFileExistKind)
  2561. {
  2562. case DbgFileExistKind_NotFound:
  2563. return true;
  2564. case DbgFileExistKind_HasOldSourceCommand:
  2565. if (mDebugManager->mStepOverExternalFiles)
  2566. return true;
  2567. }
  2568. }
  2569. }
  2570. return dbgSubprogram->mIsStepFiltered;
  2571. }
  2572. void WinDebugger::RemoveTempBreakpoints()
  2573. {
  2574. BfLogDbg("RemoveTempBreakpoints\n");
  2575. for (auto address : mTempBreakpoint)
  2576. {
  2577. RemoveBreakpoint(address);
  2578. // if (FindBreakpointAt(address) == NULL)
  2579. // {
  2580. // RemoveBreakpoint(address);
  2581. // }
  2582. // else
  2583. // {
  2584. // BfLogDbg("Ignoring remove on temp breakpoint %p\n", address);
  2585. // }
  2586. }
  2587. mTempBreakpoint.Clear();
  2588. mStepBreakpointAddrs.Clear();
  2589. }
  2590. void WinDebugger::RehupBreakpoints(bool doFlush)
  2591. {
  2592. BfLogDbg("RehupBreakpoints\n");
  2593. // First pass- detach breakpoints that need to be rebound
  2594. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  2595. {
  2596. auto breakpoint = mBreakpoints[i];
  2597. while (breakpoint != NULL)
  2598. {
  2599. if (((breakpoint->mSrcFile != NULL) && (breakpoint->mSrcFile->mDeferredRefs.size() > 0)) ||
  2600. (!breakpoint->mSymbolName.IsEmpty()))
  2601. {
  2602. // This breakpoint was already bound, but we loaded a debug module that also had this file so rebind it
  2603. DetachBreakpoint(breakpoint);
  2604. }
  2605. breakpoint = (WdBreakpoint*)breakpoint->mLinkedSibling;
  2606. }
  2607. }
  2608. // Second pass- actually set breakpoints
  2609. for (int i = 0; i < (int)mBreakpoints.size(); i++)
  2610. {
  2611. auto breakpoint = mBreakpoints[i];
  2612. while (breakpoint != NULL)
  2613. {
  2614. CheckBreakpoint(breakpoint);
  2615. if (breakpoint->mAddr != 0)
  2616. SetBreakpoint(breakpoint->mAddr, true);
  2617. breakpoint = (WdBreakpoint*)breakpoint->mLinkedSibling;
  2618. }
  2619. }
  2620. mNeedsRehupBreakpoints = false;
  2621. }
  2622. bool WinDebugger::WantsBreakpointAt(addr_target address)
  2623. {
  2624. if (mTempBreakpoint.Contains(address))
  2625. return true;
  2626. for (auto breakpoint : mBreakpoints)
  2627. {
  2628. WdBreakpoint* checkBreakpoint = breakpoint;
  2629. while (checkBreakpoint != NULL)
  2630. {
  2631. if (address == checkBreakpoint->mAddr)
  2632. return true;
  2633. checkBreakpoint = (WdBreakpoint*)checkBreakpoint->mLinkedSibling;
  2634. }
  2635. }
  2636. return false;
  2637. }
  2638. void WinDebugger::CheckBreakpoint(WdBreakpoint* wdBreakpoint, DbgSrcFile* srcFile, int lineNum, int hotIdx)
  2639. {
  2640. BP_ZONE("WinDebugger::CheckBreakpoint:atLoc");
  2641. if (hotIdx == -1)
  2642. {
  2643. BF_ASSERT(wdBreakpoint->mPendingHotBindIdx == -1);
  2644. }
  2645. WdBreakpoint* headBreakpoint = wdBreakpoint;
  2646. headBreakpoint->mPendingHotBindIdx = -1;
  2647. bool foundInSequence = false;
  2648. DbgSubprogram* lastFoundSubprogram = NULL;
  2649. int highestHotIdx = -1;
  2650. bool foundLine = false;
  2651. int bestLineNum = -1;
  2652. int bestLineOffset = 0x7FFFFFFF;
  2653. auto _CheckLineInfo = [&](DbgSubprogram* dbgSubprogram, DbgLineInfo* dbgLineInfo)
  2654. {
  2655. // Scan first so we can determine if we want to do fix up line data or not.
  2656. bool hasNear = false;
  2657. int maxLineDist = 6;
  2658. for (int lineIdx = 0; lineIdx < dbgLineInfo->mLines.mSize; lineIdx++)
  2659. {
  2660. auto lineData = &dbgLineInfo->mLines[lineIdx];
  2661. auto& ctx = dbgLineInfo->mContexts[lineData->mCtxIdx];
  2662. if (ctx.mSrcFile != srcFile)
  2663. continue;
  2664. int lineOffset = lineData->mLine - lineNum;
  2665. if ((lineOffset >= 0) && (lineOffset <= maxLineDist))
  2666. hasNear = true;
  2667. }
  2668. if (!hasNear)
  2669. return;
  2670. FixupLineDataForSubprogram(dbgSubprogram);
  2671. for (int lineIdx = 0; lineIdx < dbgLineInfo->mLines.mSize; lineIdx++)
  2672. {
  2673. //TODO: Do fixup lineData... ?
  2674. auto lineData = &dbgLineInfo->mLines[lineIdx];
  2675. auto& ctx = dbgLineInfo->mContexts[lineData->mCtxIdx];
  2676. if (ctx.mSrcFile != srcFile)
  2677. continue;
  2678. // if (ctx.mInlinee != NULL)
  2679. // {
  2680. // if (lineIdx + 1 < dbgLineInfo->mLines.mSize)
  2681. // {
  2682. // auto nextLineData = &dbgLineInfo->mLines[lineIdx + 1];
  2683. // if (nextLineData->mRelAddress == lineData->mRelAddress)
  2684. // {
  2685. // // Use the later entry (same logic from DisassembleAt)
  2686. // continue;
  2687. // }
  2688. // }
  2689. // }
  2690. if ((lineData->mColumn == -1) && (wdBreakpoint->mInstrOffset == -1))
  2691. continue;
  2692. int lineOffset = lineData->mLine - lineNum;
  2693. if (lineOffset == 0)
  2694. {
  2695. foundLine = true;
  2696. auto address = dbgSubprogram->GetLineAddr(*lineData);
  2697. auto subProgram = mDebugTarget->FindSubProgram(address);
  2698. if (subProgram->mNeedLineDataFixup)
  2699. FixupLineDataForSubprogram(subProgram);
  2700. if (subProgram != NULL)
  2701. highestHotIdx = BF_MAX(highestHotIdx, subProgram->mCompileUnit->mDbgModule->mHotIdx);
  2702. if ((foundInSequence) && (subProgram != lastFoundSubprogram))
  2703. foundInSequence = false;
  2704. if ((subProgram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && (address < subProgram->mBlock.mLowPC + sizeof(HotJumpOp)))
  2705. {
  2706. // If this breakpoint ends up on the hot jmp instruction
  2707. continue;
  2708. }
  2709. if (!foundInSequence)
  2710. {
  2711. lastFoundSubprogram = subProgram;
  2712. if ((subProgram != NULL) && (subProgram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) && (address == subProgram->mBlock.mLowPC))
  2713. {
  2714. // This instruction is actually the hot jump, we don't need a breakpoint here
  2715. foundInSequence = true;
  2716. continue;
  2717. }
  2718. if (wdBreakpoint->mSrcFile != NULL)
  2719. {
  2720. wdBreakpoint = new WdBreakpoint();
  2721. // Insert at head
  2722. wdBreakpoint->mLinkedSibling = headBreakpoint->mLinkedSibling;
  2723. headBreakpoint->mLinkedSibling = wdBreakpoint;
  2724. wdBreakpoint->mRequestedLineNum = headBreakpoint->mRequestedLineNum;
  2725. wdBreakpoint->mLineNum = headBreakpoint->mLineNum;
  2726. wdBreakpoint->mColumn = headBreakpoint->mColumn;
  2727. wdBreakpoint->mInstrOffset = headBreakpoint->mInstrOffset;
  2728. wdBreakpoint->mIsLinkedSibling = true;
  2729. wdBreakpoint->mHead = headBreakpoint;
  2730. }
  2731. if (wdBreakpoint->mInstrOffset > 0)
  2732. {
  2733. for (int instIdx = 0; instIdx < wdBreakpoint->mInstrOffset; instIdx++)
  2734. {
  2735. CPUInst inst;
  2736. if (!mDebugTarget->DecodeInstruction(address, &inst))
  2737. break;
  2738. address += inst.mSize;
  2739. }
  2740. }
  2741. wdBreakpoint->mSrcFile = ctx.mSrcFile;
  2742. wdBreakpoint->mLineData = DbgLineDataEx(lineData, subProgram);
  2743. wdBreakpoint->mBreakpointType = BreakpointType_User;
  2744. wdBreakpoint->mAddr = address;
  2745. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mStoppedAtAddress == address))
  2746. {
  2747. BfLogDbg("CheckBreakpoint setting mIsAtBreakpointAddress = %p\n", address);
  2748. mDebuggerWaitingThread->mIsAtBreakpointAddress = address;
  2749. }
  2750. BfLogDbg("Breakpoint %p found at %s in %s\n", wdBreakpoint, subProgram->mName, GetFileName(subProgram->mCompileUnit->mDbgModule->mFilePath).c_str());
  2751. mBreakpointAddrMap.ForceAdd(address, wdBreakpoint);
  2752. SetBreakpoint(address);
  2753. foundInSequence = true;
  2754. }
  2755. }
  2756. else
  2757. {
  2758. //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
  2759. // multiple places so we need to ensure this will break on them all
  2760. foundInSequence = false;
  2761. }
  2762. if ((lineOffset >= 0) && (lineOffset <= maxLineDist) && (lineOffset <= bestLineOffset))
  2763. {
  2764. if (lineOffset < bestLineOffset)
  2765. {
  2766. bestLineNum = lineData->mLine;
  2767. bestLineOffset = lineOffset;
  2768. }
  2769. }
  2770. }
  2771. };
  2772. for (int pass = 0; pass < 2; pass++)
  2773. {
  2774. if (lineNum == -1)
  2775. break;
  2776. bestLineNum = -1;
  2777. bestLineOffset = 0x7FFFFFFF;
  2778. if (hotIdx >= 0)
  2779. {
  2780. if (hotIdx >= srcFile->mHotReplacedDbgLineInfo.size())
  2781. return;
  2782. auto hotReplacedLineInfo = srcFile->mHotReplacedDbgLineInfo[hotIdx];
  2783. for (auto& hotReplacedEntry : hotReplacedLineInfo->mEntries)
  2784. {
  2785. _CheckLineInfo(hotReplacedEntry.mSubprogram, hotReplacedEntry.mLineInfo);
  2786. }
  2787. }
  2788. else
  2789. {
  2790. for (auto subprogram : srcFile->mLineDataRefs)
  2791. _CheckLineInfo(subprogram, subprogram->mLineInfo);
  2792. }
  2793. if (foundLine)
  2794. break;
  2795. // Don't allow the breakpoint to be inexactly bound -- only match on pass 0
  2796. if (hotIdx != -1)
  2797. break;
  2798. if (bestLineNum == -1)
  2799. break;
  2800. lineNum = bestLineNum;
  2801. wdBreakpoint->mLineNum = bestLineNum;
  2802. }
  2803. int highestCheckHotIdx = highestHotIdx - 1;
  2804. if (hotIdx != -1)
  2805. highestCheckHotIdx = hotIdx - 1;
  2806. for (int hotFileIdx = highestCheckHotIdx; hotFileIdx >= 0; hotFileIdx--)
  2807. {
  2808. auto& hotReplacedDbgLineData = wdBreakpoint->mSrcFile->mHotReplacedDbgLineInfo;
  2809. // Only try to bind to an old hot version if we haven't unloaded the hot module
  2810. if ((hotFileIdx < (int)hotReplacedDbgLineData.size()) && (hotReplacedDbgLineData[hotFileIdx]->mEntries.size() > 0))
  2811. {
  2812. headBreakpoint->mPendingHotBindIdx = hotFileIdx;
  2813. break;
  2814. }
  2815. }
  2816. }
  2817. void WinDebugger::HotBindBreakpoint(Breakpoint* breakpoint, int lineNum, int hotIdx)
  2818. {
  2819. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  2820. CheckBreakpoint(wdBreakpoint, wdBreakpoint->mSrcFile, lineNum, hotIdx);
  2821. }
  2822. void WinDebugger::CheckBreakpoint(WdBreakpoint* wdBreakpoint)
  2823. {
  2824. if (!mGotStartupEvent)
  2825. return;
  2826. if (wdBreakpoint->mThreadId == 0) // Not bound to threadId yet...
  2827. {
  2828. return;
  2829. }
  2830. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  2831. {
  2832. if (wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap != 0)
  2833. return;
  2834. if (mFreeMemoryBreakIndices.size() == 0)
  2835. return;
  2836. if ((IsInRunState()) || (mActiveThread == NULL))
  2837. return;
  2838. int wantBytes[4];
  2839. int wantBindCount = 0;
  2840. int bytesLeft = wdBreakpoint->mMemoryBreakpointInfo->mByteCount;
  2841. addr_target curAddr = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress;
  2842. while (bytesLeft > 0)
  2843. {
  2844. if (wantBindCount >= mFreeMemoryBreakIndices.size())
  2845. return;
  2846. int curByteCount = 1;
  2847. #ifdef BF_DBG_64
  2848. if ((bytesLeft >= 8) && ((curAddr & 7) == 0))
  2849. curByteCount = 8;
  2850. else
  2851. #endif
  2852. if ((bytesLeft >= 4) && ((curAddr & 3) == 0))
  2853. curByteCount = 4;
  2854. else if ((bytesLeft >= 2) && ((curAddr & 1) == 0))
  2855. curByteCount = 2;
  2856. wantBytes[wantBindCount++] = curByteCount;
  2857. bytesLeft -= curByteCount;
  2858. curAddr += curByteCount;
  2859. }
  2860. addr_target curOfs = 0;
  2861. for (int i = 0; i < wantBindCount; i++)
  2862. {
  2863. int memoryBreakIdx = mFreeMemoryBreakIndices.back();
  2864. mFreeMemoryBreakIndices.pop_back();
  2865. mMemoryBreakpoints[memoryBreakIdx].mBreakpoint = wdBreakpoint;
  2866. mMemoryBreakpoints[memoryBreakIdx].mAddress = wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress + curOfs;
  2867. mMemoryBreakpoints[memoryBreakIdx].mByteCount = wantBytes[i];
  2868. mMemoryBreakpoints[memoryBreakIdx].mOfs = curOfs;
  2869. curOfs += wantBytes[i];
  2870. mMemoryBreakpointVersion++;
  2871. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap |= 1<<memoryBreakIdx;
  2872. }
  2873. UpdateThreadDebugRegisters();
  2874. }
  2875. if (wdBreakpoint->mAddr != 0)
  2876. return;
  2877. if (!wdBreakpoint->mSymbolName.IsEmpty())
  2878. {
  2879. auto headBreakpoint = wdBreakpoint->GetHeadBreakpoint();
  2880. String symbolName = wdBreakpoint->mSymbolName;
  2881. bool onlyBindFirst = false;
  2882. if (symbolName.StartsWith("-"))
  2883. {
  2884. symbolName.Remove(0);
  2885. onlyBindFirst = true;
  2886. }
  2887. for (auto dbgModule : mDebugTarget->mDbgModules)
  2888. {
  2889. dbgModule->ParseSymbolData();
  2890. addr_target targetAddr = -1;
  2891. auto entry = dbgModule->mSymbolNameMap.Find(symbolName.c_str());
  2892. if (entry != NULL)
  2893. {
  2894. DbgSymbol* dwSymbol = entry->mValue;
  2895. targetAddr = dwSymbol->mAddress;
  2896. }
  2897. if (targetAddr == -1)
  2898. {
  2899. if (symbolName == ".")
  2900. {
  2901. targetAddr = mDebugTarget->mLaunchBinary->mImageBase + mDebugTarget->mLaunchBinary->mEntryPoint;
  2902. onlyBindFirst = true;
  2903. }
  2904. }
  2905. if (targetAddr != -1)
  2906. {
  2907. if (wdBreakpoint->mAddr == 0)
  2908. {
  2909. wdBreakpoint->mAddr = targetAddr;
  2910. wdBreakpoint->mBreakpointType = BreakpointType_User;
  2911. mBreakpointAddrMap.ForceAdd(wdBreakpoint->mAddr, wdBreakpoint);
  2912. SetBreakpoint(wdBreakpoint->mAddr);
  2913. }
  2914. else
  2915. {
  2916. wdBreakpoint = new WdBreakpoint();
  2917. // Insert at head
  2918. wdBreakpoint->mLinkedSibling = headBreakpoint->mLinkedSibling;
  2919. headBreakpoint->mLinkedSibling = wdBreakpoint;
  2920. wdBreakpoint->mSymbolName = headBreakpoint->mSymbolName;
  2921. wdBreakpoint->mIsLinkedSibling = true;
  2922. wdBreakpoint->mHead = headBreakpoint;
  2923. }
  2924. if (onlyBindFirst)
  2925. break;
  2926. }
  2927. }
  2928. return;
  2929. }
  2930. BP_ZONE("WinDebugger::CheckBreakpoint");
  2931. // Rehup if we load a DLL that also uses this file we bound to (thus the mDeferredRefs check)
  2932. if (wdBreakpoint->mSrcFile == NULL)
  2933. {
  2934. DbgSrcFile* srcFile = mDebugTarget->GetSrcFile(wdBreakpoint->mFilePath);
  2935. if (srcFile == NULL)
  2936. return;
  2937. for (auto& deferredSrcFileRef : srcFile->mDeferredRefs)
  2938. {
  2939. deferredSrcFileRef.mDbgModule->ParseCompileUnit(deferredSrcFileRef.mCompileUnitId);
  2940. }
  2941. srcFile->mDeferredRefs.Clear();
  2942. CheckBreakpoint(wdBreakpoint, srcFile, wdBreakpoint->mRequestedLineNum, -1);
  2943. }
  2944. }
  2945. bool WinDebugger::IsMemoryBreakpointSizeValid(addr_target addr, int size)
  2946. {
  2947. int wantBindCount = 0;
  2948. int bytesLeft = size;
  2949. addr_target curAddr = addr;
  2950. for (int i = 0; i < 4; i++)
  2951. {
  2952. int curByteCount = 1;
  2953. #ifdef BF_DBG_64
  2954. if ((bytesLeft >= 8) && ((curAddr & 7) == 0))
  2955. curByteCount = 8;
  2956. else
  2957. #endif
  2958. if ((bytesLeft >= 4) && ((curAddr & 3) == 0))
  2959. curByteCount = 4;
  2960. else if ((bytesLeft >= 2) && ((curAddr & 1) == 0))
  2961. curByteCount = 2;
  2962. bytesLeft -= curByteCount;
  2963. curAddr += curByteCount;
  2964. if (bytesLeft == 0)
  2965. return true;
  2966. }
  2967. return false;
  2968. }
  2969. bool WinDebugger::HasMemoryBreakpoint(addr_target addr, int size)
  2970. {
  2971. for (int i = 0; i < 4; i++)
  2972. {
  2973. if ((mMemoryBreakpoints[i].mAddress == addr) &&
  2974. (mMemoryBreakpoints[i].mOfs == 0) &&
  2975. (mMemoryBreakpoints[i].mBreakpoint->mMemoryBreakpointInfo->mByteCount == size))
  2976. return true;
  2977. }
  2978. return false;
  2979. }
  2980. Breakpoint* WinDebugger::CreateBreakpoint(const StringImpl& fileName, int lineNum, int wantColumn, int instrOffset)
  2981. {
  2982. AutoCrit autoCrit(mDebugManager->mCritSect);
  2983. BfLogDbg("CreateBreakpoint %s %d %d\n", fileName.c_str(), lineNum, wantColumn);
  2984. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  2985. wdBreakpoint->mFilePath = FixPathAndCase(fileName);
  2986. wdBreakpoint->mRequestedLineNum = lineNum;
  2987. wdBreakpoint->mLineNum = lineNum;
  2988. wdBreakpoint->mColumn = wantColumn;
  2989. wdBreakpoint->mInstrOffset = instrOffset;
  2990. mBreakpoints.push_back(wdBreakpoint);
  2991. BfLogDbg("CreateBreakpoint Created %p\n", wdBreakpoint);
  2992. return wdBreakpoint;
  2993. }
  2994. void WinDebugger::CheckBreakpoint(Breakpoint* checkBreakpoint)
  2995. {
  2996. AutoCrit autoCrit(mDebugManager->mCritSect);
  2997. CheckBreakpoint((WdBreakpoint*)checkBreakpoint);
  2998. }
  2999. Breakpoint* WinDebugger::CreateMemoryBreakpoint(intptr addr, int byteCount)
  3000. {
  3001. AutoCrit autoCrit(mDebugManager->mCritSect);
  3002. BfLogDbg("CreateMemoryBreakpoint %p %d\n", addr, byteCount);
  3003. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  3004. WdMemoryBreakpointInfo* memoryBreakInfo = new WdMemoryBreakpointInfo();
  3005. memoryBreakInfo->mMemoryAddress = addr;
  3006. memoryBreakInfo->mByteCount = byteCount;
  3007. wdBreakpoint->mMemoryBreakpointInfo = memoryBreakInfo;
  3008. mBreakpoints.push_back(wdBreakpoint);
  3009. CheckBreakpoint(wdBreakpoint);
  3010. return wdBreakpoint;
  3011. }
  3012. Breakpoint* WinDebugger::CreateSymbolBreakpoint(const StringImpl& symbolName)
  3013. {
  3014. AutoCrit autoCrit(mDebugManager->mCritSect);
  3015. BfLogDbg("CreateSymbolBreakpoint %s\n", symbolName.c_str());
  3016. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  3017. wdBreakpoint->mSymbolName = symbolName;
  3018. mBreakpoints.push_back(wdBreakpoint);
  3019. CheckBreakpoint(wdBreakpoint);
  3020. return wdBreakpoint;
  3021. }
  3022. Breakpoint* WinDebugger::CreateAddressBreakpoint(intptr inAddress)
  3023. {
  3024. AutoCrit autoCrit(mDebugManager->mCritSect);
  3025. BfLogDbg("CreateAddressBreakpoint %p\n", inAddress);
  3026. addr_target address = (addr_target)inAddress;
  3027. WdBreakpoint* wdBreakpoint = new WdBreakpoint();
  3028. wdBreakpoint->mAddr = address;
  3029. mBreakpointAddrMap.ForceAdd(wdBreakpoint->mAddr, wdBreakpoint);
  3030. SetBreakpoint(address);
  3031. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mStoppedAtAddress == address))
  3032. {
  3033. BfLogDbg("CreateAddressBreakpoint setting mIsAtBreakpointAddress = %p\n", address);
  3034. mDebuggerWaitingThread->mIsAtBreakpointAddress = address;
  3035. }
  3036. mBreakpoints.push_back(wdBreakpoint);
  3037. return wdBreakpoint;
  3038. }
  3039. void WinDebugger::DeleteBreakpoint(Breakpoint* breakpoint)
  3040. {
  3041. AutoCrit autoCrit(mDebugManager->mCritSect);
  3042. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3043. while (wdBreakpoint != NULL)
  3044. {
  3045. BfLogDbg("WinDebugger::DeleteBreakpoint %p Count:%d\n", wdBreakpoint, mBreakpoints.size());
  3046. if (wdBreakpoint == mActiveBreakpoint)
  3047. mActiveBreakpoint = NULL;
  3048. if (wdBreakpoint->mCondition != NULL)
  3049. {
  3050. if (!wdBreakpoint->mIsLinkedSibling)
  3051. delete wdBreakpoint->mCondition;
  3052. }
  3053. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  3054. {
  3055. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  3056. {
  3057. if (mMemoryBreakpoints[memoryWatchSlot].mBreakpoint == wdBreakpoint)
  3058. {
  3059. mFreeMemoryBreakIndices.push_back(memoryWatchSlot);
  3060. mMemoryBreakpoints[memoryWatchSlot] = WdMemoryBreakpointBind();
  3061. mMemoryBreakpointVersion++;
  3062. UpdateThreadDebugRegisters();
  3063. }
  3064. }
  3065. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap = 0;
  3066. }
  3067. if (wdBreakpoint->mAddr != 0)
  3068. {
  3069. mBreakpointAddrMap.Remove(wdBreakpoint->mAddr, wdBreakpoint);
  3070. RemoveBreakpoint(wdBreakpoint->mAddr);
  3071. for (auto thread : mThreadList)
  3072. {
  3073. if (thread->mIsAtBreakpointAddress == wdBreakpoint->mAddr)
  3074. thread->mIsAtBreakpointAddress = NULL;
  3075. if (thread->mBreakpointAddressContinuing == wdBreakpoint->mAddr)
  3076. thread->mBreakpointAddressContinuing = NULL;
  3077. }
  3078. }
  3079. if (!wdBreakpoint->mIsLinkedSibling)
  3080. {
  3081. mBreakpoints.Remove(wdBreakpoint);
  3082. }
  3083. auto nextBreakpoint = (WdBreakpoint*)wdBreakpoint->mLinkedSibling;
  3084. delete wdBreakpoint;
  3085. wdBreakpoint = nextBreakpoint;
  3086. }
  3087. }
  3088. void WinDebugger::DetachBreakpoint(Breakpoint* breakpoint)
  3089. {
  3090. AutoCrit autoCrit(mDebugManager->mCritSect);
  3091. BfLogDbg("WinDebugger::DetachBreakpoint %p\n", breakpoint);
  3092. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3093. if (wdBreakpoint->mAddr != 0)
  3094. {
  3095. mBreakpointAddrMap.Remove(wdBreakpoint->mAddr, wdBreakpoint);
  3096. RemoveBreakpoint(wdBreakpoint->mAddr);
  3097. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mIsAtBreakpointAddress == wdBreakpoint->mAddr))
  3098. mDebuggerWaitingThread->mIsAtBreakpointAddress = NULL;
  3099. if ((mDebuggerWaitingThread != NULL) && (mDebuggerWaitingThread->mBreakpointAddressContinuing == wdBreakpoint->mAddr))
  3100. mDebuggerWaitingThread->mBreakpointAddressContinuing = NULL;
  3101. wdBreakpoint->mLineData = DbgLineDataEx();
  3102. wdBreakpoint->mAddr = 0;
  3103. }
  3104. if (wdBreakpoint->mCondition != NULL)
  3105. {
  3106. delete wdBreakpoint->mCondition->mDbgEvaluationContext;
  3107. wdBreakpoint->mCondition->mDbgEvaluationContext = NULL;
  3108. }
  3109. if (wdBreakpoint->mMemoryBreakpointInfo != NULL)
  3110. {
  3111. for (int memoryWatchSlot = 0; memoryWatchSlot < 4; memoryWatchSlot++)
  3112. {
  3113. if (mMemoryBreakpoints[memoryWatchSlot].mBreakpoint == wdBreakpoint)
  3114. {
  3115. mFreeMemoryBreakIndices.push_back(memoryWatchSlot);
  3116. mMemoryBreakpoints[memoryWatchSlot] = WdMemoryBreakpointBind();
  3117. mMemoryBreakpointVersion++;
  3118. UpdateThreadDebugRegisters();
  3119. }
  3120. }
  3121. wdBreakpoint->mMemoryBreakpointInfo->mMemoryWatchSlotBitmap = 0;
  3122. }
  3123. if (wdBreakpoint->mLinkedSibling != NULL)
  3124. {
  3125. DeleteBreakpoint(wdBreakpoint->mLinkedSibling);
  3126. wdBreakpoint->mLinkedSibling = NULL;
  3127. }
  3128. wdBreakpoint->mSrcFile = NULL;
  3129. wdBreakpoint->mPendingHotBindIdx = -1;
  3130. }
  3131. void WinDebugger::MoveBreakpoint(Breakpoint* breakpoint, int lineNum, int wantColumn, bool rebindNow)
  3132. {
  3133. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3134. AutoCrit autoCrit(mDebugManager->mCritSect);
  3135. DetachBreakpoint(wdBreakpoint);
  3136. //TODO: This doesn't actually rebind correctly while the app is running
  3137. if ((lineNum != -1) && (wantColumn != -1))
  3138. {
  3139. wdBreakpoint->mRequestedLineNum = lineNum;
  3140. wdBreakpoint->mLineNum = lineNum;
  3141. wdBreakpoint->mColumn = wantColumn;
  3142. }
  3143. if (rebindNow)
  3144. CheckBreakpoint(wdBreakpoint);
  3145. }
  3146. void WinDebugger::MoveMemoryBreakpoint(Breakpoint* breakpoint, intptr addr, int byteCount)
  3147. {
  3148. AutoCrit autoCrit(mDebugManager->mCritSect);
  3149. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3150. DetachBreakpoint(wdBreakpoint);
  3151. wdBreakpoint->mMemoryBreakpointInfo->mMemoryAddress = addr;
  3152. wdBreakpoint->mMemoryBreakpointInfo->mByteCount = byteCount;
  3153. CheckBreakpoint(wdBreakpoint);
  3154. }
  3155. void WinDebugger::DisableBreakpoint(Breakpoint* breakpoint)
  3156. {
  3157. AutoCrit autoCrit(mDebugManager->mCritSect);
  3158. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3159. DetachBreakpoint(wdBreakpoint);
  3160. delete wdBreakpoint->mMemoryBreakpointInfo;
  3161. wdBreakpoint->mMemoryBreakpointInfo = NULL;
  3162. }
  3163. void WinDebugger::SetBreakpointCondition(Breakpoint* breakpoint, const StringImpl& conditionExpr)
  3164. {
  3165. AutoCrit autoCrit(mDebugManager->mCritSect);
  3166. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3167. BF_ASSERT(!wdBreakpoint->mIsLinkedSibling);
  3168. if (conditionExpr.empty())
  3169. {
  3170. delete wdBreakpoint->mCondition;
  3171. WdBreakpoint* curBreakpoint = wdBreakpoint;
  3172. wdBreakpoint->mCondition = NULL;
  3173. }
  3174. else
  3175. {
  3176. delete wdBreakpoint->mCondition;
  3177. auto condition = new WdBreakpointCondition();
  3178. condition->mExpr = conditionExpr;
  3179. wdBreakpoint->mCondition = condition;
  3180. }
  3181. }
  3182. void WinDebugger::SetBreakpointLogging(Breakpoint* breakpoint, const StringImpl& logging, bool breakAfterLogging)
  3183. {
  3184. AutoCrit autoCrit(mDebugManager->mCritSect);
  3185. WdBreakpoint* wdBreakpoint = (WdBreakpoint*)breakpoint;
  3186. BF_ASSERT(!wdBreakpoint->mIsLinkedSibling);
  3187. wdBreakpoint->mLogging = logging;
  3188. wdBreakpoint->mBreakAfterLogging = breakAfterLogging;
  3189. }
  3190. bool WinDebugger::CheckConditionalBreakpoint(WdBreakpoint* breakpoint, DbgSubprogram* dbgSubprogram, addr_target pcAddress)
  3191. {
  3192. // What was this assertion for?
  3193. //BF_ASSERT(mCallStack.size() == 0);
  3194. auto headBreakpoint = breakpoint->GetHeadBreakpoint();
  3195. if (headBreakpoint->mThreadId != -1)
  3196. {
  3197. if ((mActiveThread != NULL) && (mActiveThread->mThreadId != headBreakpoint->mThreadId))
  3198. return false;
  3199. }
  3200. auto _SplitExpr = [&](const StringImpl& expr, StringImpl& outExpr, StringImpl& outSubject)
  3201. {
  3202. int crPos = expr.IndexOf('\n');
  3203. if (crPos != -1)
  3204. {
  3205. outExpr += expr.Substring(0, crPos);
  3206. outSubject += expr.Substring(crPos + 1);
  3207. }
  3208. else
  3209. {
  3210. outExpr += expr;
  3211. }
  3212. };
  3213. if (headBreakpoint->mCondition != NULL)
  3214. {
  3215. ClearCallStack();
  3216. auto conditional = headBreakpoint->mCondition;
  3217. if (conditional->mDbgEvaluationContext == NULL)
  3218. {
  3219. CPURegisters registers;
  3220. PopulateRegisters(&registers);
  3221. auto pcAddress = registers.GetPC();
  3222. DbgSubprogram* subprogram = mDebugTarget->FindSubProgram(pcAddress);
  3223. if (subprogram == NULL)
  3224. {
  3225. return false;
  3226. }
  3227. StringT<256> expr;
  3228. StringT<256> subjectExpr;
  3229. if (breakpoint->mMemoryBreakpointInfo != NULL)
  3230. {
  3231. subjectExpr += "*";
  3232. }
  3233. _SplitExpr(conditional->mExpr, expr, subjectExpr);
  3234. DbgLanguage language = DbgLanguage_Unknown;
  3235. if (expr.StartsWith("@Beef:"))
  3236. {
  3237. expr.Remove(0, 6);
  3238. language = DbgLanguage_Beef;
  3239. }
  3240. else if (expr.StartsWith("@C:"))
  3241. {
  3242. expr.Remove(0, 3);
  3243. language = DbgLanguage_C;
  3244. }
  3245. conditional->mDbgEvaluationContext = new DbgEvaluationContext(this, subprogram->mCompileUnit->mDbgModule, expr);
  3246. if (language != DbgLanguage_Unknown)
  3247. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mLanguage = language;
  3248. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mSubjectExpr = subjectExpr;
  3249. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mDbgCompileUnit = subprogram->mCompileUnit;
  3250. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mCallStackIdx = 0;
  3251. conditional->mDbgEvaluationContext->mDbgExprEvaluator->mExpressionFlags = (DwEvalExpressionFlags)(DwEvalExpressionFlag_AllowSideEffects);
  3252. }
  3253. WdStackFrame* wdStackFrame = new WdStackFrame();
  3254. PopulateRegisters(&wdStackFrame->mRegisters);
  3255. mCallStack.Add(wdStackFrame);
  3256. DbgTypedValue result = conditional->mDbgEvaluationContext->EvaluateInContext(DbgTypedValue());
  3257. ClearCallStack();
  3258. if ((result.mType != NULL) && (result.mType->mTypeCode == DbgType_Bitfield))
  3259. result.mType = result.mType->mTypeParam;
  3260. if (conditional->mDbgEvaluationContext->mPassInstance->HasFailed())
  3261. {
  3262. String errorStr = "FAILED";
  3263. for (auto error : conditional->mDbgEvaluationContext->mPassInstance->mErrors)
  3264. {
  3265. if (!error->mIsWarning)
  3266. errorStr = error->mError;
  3267. }
  3268. String condError = StrFormat("error Conditional breakpoint expression '%s' failed: %s", conditional->mExpr.c_str(), errorStr.c_str());
  3269. mDebugManager->mOutMessages.push_back(condError);
  3270. return true;
  3271. }
  3272. else if (conditional->mDbgEvaluationContext->mDbgExprEvaluator->mBlockedSideEffects)
  3273. {
  3274. mDebugManager->mOutMessages.push_back(StrFormat("error Conditional breakpoint expression '%s' contained function calls, which is not allowed", conditional->mExpr.c_str()));
  3275. return true;
  3276. }
  3277. else if ((!result) || (!result.mType->IsBoolean()))
  3278. {
  3279. mDebugManager->mOutMessages.push_back(StrFormat("error Conditional breakpoint expression '%s' must result in a boolean value", conditional->mExpr.c_str()));
  3280. return true;
  3281. }
  3282. else if (!result.mBool)
  3283. return false;
  3284. }
  3285. headBreakpoint->mHitCount++;
  3286. switch (headBreakpoint->mHitCountBreakKind)
  3287. {
  3288. case DbgHitCountBreakKind_Equals:
  3289. if (headBreakpoint->mHitCount != headBreakpoint->mTargetHitCount)
  3290. return false;
  3291. break;
  3292. case DbgHitCountBreakKind_GreaterEquals:
  3293. if (headBreakpoint->mHitCount < headBreakpoint->mTargetHitCount)
  3294. return false;
  3295. break;
  3296. case DbgHitCountBreakKind_Multiple:
  3297. if ((headBreakpoint->mHitCount % headBreakpoint->mTargetHitCount) != 0)
  3298. return false;
  3299. break;
  3300. }
  3301. mActiveBreakpoint = breakpoint;
  3302. mBreakStackFrameIdx = -1;
  3303. if (!headBreakpoint->mLogging.IsEmpty())
  3304. {
  3305. ClearCallStack();
  3306. DwFormatInfo formatInfo;
  3307. formatInfo.mCallStackIdx = 0;
  3308. DbgCompileUnit* dbgCompileUnit = NULL;
  3309. if (dbgSubprogram == NULL)
  3310. dbgSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3311. if (dbgSubprogram != NULL)
  3312. {
  3313. dbgCompileUnit = dbgSubprogram->mCompileUnit;
  3314. formatInfo.mLanguage = dbgSubprogram->GetLanguage();
  3315. }
  3316. auto prevRunState = mRunState;
  3317. mRunState = RunState_Paused; // We need to be paused to avoid certain errors in the eval
  3318. String displayString;
  3319. String expr;
  3320. _SplitExpr(headBreakpoint->mLogging, expr, formatInfo.mSubjectExpr);
  3321. if (expr.StartsWith("@Beef:"))
  3322. {
  3323. expr.Remove(0, 6);
  3324. formatInfo.mLanguage = DbgLanguage_Beef;
  3325. }
  3326. else if (expr.StartsWith("@C:"))
  3327. {
  3328. expr.Remove(0, 3);
  3329. formatInfo.mLanguage = DbgLanguage_C;
  3330. }
  3331. ProcessEvalString(dbgCompileUnit, DbgTypedValue(), expr, displayString, formatInfo, NULL, false);
  3332. mRunState = prevRunState;
  3333. displayString.Insert(0, "log ");
  3334. displayString.Append("\n");
  3335. mDebugManager->mOutMessages.push_back(displayString);
  3336. if (!headBreakpoint->mBreakAfterLogging)
  3337. return false;
  3338. }
  3339. return true;
  3340. }
  3341. void WinDebugger::CleanupDebugEval(bool restoreRegisters)
  3342. {
  3343. BfLogDbg("CleanupDebugEval ThreadId=%d\n", mDebugEvalThreadInfo.mThreadId);
  3344. WdThreadInfo* evalThreadInfo = NULL;
  3345. if (mThreadMap.TryGetValue(mDebugEvalThreadInfo.mThreadId, &evalThreadInfo))
  3346. {
  3347. if ((restoreRegisters) && (!mDbgBreak))
  3348. {
  3349. SetAndRestoreValue<WdThreadInfo*> activeThread(mActiveThread, evalThreadInfo);
  3350. RestoreAllRegisters();
  3351. // if (mRunState == RunState_Running_ToTempBreakpoint)
  3352. // mRunState = RunState_Paused;
  3353. }
  3354. evalThreadInfo->mStartSP = mDebugEvalThreadInfo.mStartSP;
  3355. evalThreadInfo->mStoppedAtAddress = mDebugEvalThreadInfo.mStoppedAtAddress;
  3356. evalThreadInfo->mIsAtBreakpointAddress = mDebugEvalThreadInfo.mIsAtBreakpointAddress;
  3357. evalThreadInfo->mBreakpointAddressContinuing = mDebugEvalThreadInfo.mBreakpointAddressContinuing;
  3358. }
  3359. delete mDebugPendingExpr;
  3360. mDebugPendingExpr = NULL;
  3361. mDebugEvalThreadInfo = WdThreadInfo();
  3362. OutputRawMessage("rehupLoc");
  3363. }
  3364. bool WinDebugger::FixCallStackIdx(int& callStackIdx)
  3365. {
  3366. callStackIdx = BF_MAX(callStackIdx, 0);
  3367. if (mCallStack.IsEmpty())
  3368. UpdateCallStack();
  3369. int stackSize = (int)mCallStack.size();
  3370. while (callStackIdx >= mCallStack.size())
  3371. {
  3372. UpdateCallStack();
  3373. if (stackSize == (int)mCallStack.size())
  3374. break; // Didn't change
  3375. stackSize = (int)mCallStack.size();
  3376. }
  3377. if (callStackIdx >= stackSize)
  3378. {
  3379. callStackIdx = 0;
  3380. return false;
  3381. }
  3382. return true;
  3383. }
  3384. bool WinDebugger::HasLineInfoAt(addr_target address)
  3385. {
  3386. BP_ZONE("WinDebugger::HasLineInfoAt");
  3387. DbgSubprogram* dbgSubprogram = NULL;
  3388. auto dwLineData = FindLineDataAtAddress(address, &dbgSubprogram);
  3389. return (dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dbgSubprogram->GetLineAddr(*dwLineData) == address);
  3390. }
  3391. void WinDebugger::StepLineTryPause(addr_target address, bool requireExactMatch)
  3392. {
  3393. if (mStepInAssembly)
  3394. return;
  3395. if (mStepLineData.mLineData != NULL)
  3396. {
  3397. DbgSubprogram* dbgSubprogram = NULL;
  3398. DbgSrcFile* dbgSrcFile = NULL;
  3399. auto dwLineData = FindLineDataAtAddress(address, &dbgSubprogram, &dbgSrcFile);
  3400. if ((dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && ((!requireExactMatch) || (dbgSubprogram->GetLineAddr(*dwLineData) == address)))
  3401. {
  3402. // "Invalid" line
  3403. if (dwLineData->mColumn == -1)
  3404. {
  3405. SetupStep(mStepType);
  3406. mRunState = RunState_Running;
  3407. return;
  3408. }
  3409. // If we're on the same line but a different column or a <= address then keep it keep looking
  3410. if ((dbgSrcFile == mStepLineData.GetSrcFile()) &&
  3411. ((!requireExactMatch) || (dwLineData != mStepLineData.mLineData) || (address <= mStepStartPC)) &&
  3412. (dwLineData->mLine == mStepLineData.mLineData->mLine))
  3413. {
  3414. SetupStep(mStepType);
  3415. mRunState = RunState_Running;
  3416. return;
  3417. }
  3418. }
  3419. }
  3420. mRunState = RunState_Paused;
  3421. }
  3422. void WinDebugger::BreakAll()
  3423. {
  3424. AutoCrit autoCrit(mDebugManager->mCritSect);
  3425. ::DebugBreakProcess(mProcessInfo.hProcess);
  3426. }
  3427. void WinDebugger::StepInto(bool inAssembly)
  3428. {
  3429. AutoCrit autoCrit(mDebugManager->mCritSect);
  3430. if (!TryRunContinue())
  3431. return;
  3432. BfLogDbg("StepInto\n");
  3433. mCurNoInfoStepTries = 0; // Reset
  3434. mStepInAssembly = inAssembly;
  3435. SetupStep(StepType_StepInto);
  3436. ContinueDebugEvent();
  3437. }
  3438. void WinDebugger::StepIntoSpecific(intptr inAddr)
  3439. {
  3440. addr_target addr = (addr_target)inAddr;
  3441. AutoCrit autoCrit(mDebugManager->mCritSect);
  3442. if (!TryRunContinue())
  3443. return;
  3444. BfLogDbg("StepIntoSpecific %p\n", addr);
  3445. mCurNoInfoStepTries = 0; // Reset
  3446. mStepInAssembly = false;
  3447. SetupStep(StepType_StepInto);
  3448. mIsStepIntoSpecific = true;
  3449. mStepType = StepType_StepInto_Unfiltered;
  3450. if (mStepStartPC != addr)
  3451. {
  3452. RemoveTempBreakpoints();
  3453. SetTempBreakpoint(addr);
  3454. mStepBreakpointAddrs.push_back(addr);
  3455. }
  3456. ContinueDebugEvent();
  3457. }
  3458. void WinDebugger::PushValue(CPURegisters* registers, int64 val)
  3459. {
  3460. addr_target* regSP = registers->GetSPRegisterRef();
  3461. *regSP -= sizeof(addr_target);
  3462. WriteMemory<addr_target>(*regSP, (addr_target)val);
  3463. }
  3464. void WinDebugger::PushValue(CPURegisters* registers, const DbgTypedValue& typedValue)
  3465. {
  3466. addr_target* regSP = registers->GetSPRegisterRef();
  3467. int byteCount = typedValue.mType->GetByteCount();
  3468. if ((byteCount == 8) || (sizeof(addr_target) == 8))
  3469. {
  3470. *regSP -= sizeof(int64);
  3471. addr_target val = typedValue.mInt64;
  3472. if (typedValue.mType->IsCompositeType())
  3473. val = typedValue.mSrcAddress;
  3474. WriteMemory<int64>(*regSP, val);
  3475. }
  3476. else
  3477. {
  3478. *regSP -= sizeof(int32);
  3479. addr_target val = typedValue.mInt32;
  3480. if (typedValue.mType->IsCompositeType())
  3481. val = typedValue.mSrcAddress;
  3482. WriteMemory<int32>(*regSP, val);
  3483. }
  3484. }
  3485. void WinDebugger::SetThisRegister(CPURegisters* registers, addr_target val)
  3486. {
  3487. #if BF_DBG_32
  3488. registers->mIntRegs.ecx = val;
  3489. #else
  3490. registers->mIntRegs.rcx = val;
  3491. #endif
  3492. }
  3493. void WinDebugger::AddParamValue(int paramIdx, bool hadThis, CPURegisters* registers, const DbgTypedValue& typedValue)
  3494. {
  3495. #if BF_DBG_32
  3496. PushValue(registers, typedValue);
  3497. #else
  3498. int regIdx = paramIdx + (hadThis ? 1 : 0);
  3499. if (typedValue.mType->IsFloat())
  3500. {
  3501. PushValue(registers, typedValue);
  3502. if (regIdx < 4)
  3503. {
  3504. if (typedValue.mType->mTypeCode == DbgType_Single)
  3505. {
  3506. registers->mXmmRegsArray[regIdx].f[0] = typedValue.mSingle;
  3507. }
  3508. else
  3509. {
  3510. registers->mXmmDRegsArray[regIdx].d[0] = typedValue.mDouble;
  3511. }
  3512. }
  3513. }
  3514. else
  3515. {
  3516. PushValue(registers, typedValue);
  3517. if (regIdx < 4)
  3518. {
  3519. int64 val;
  3520. if (typedValue.mType->IsCompositeType())
  3521. val = typedValue.mSrcAddress;
  3522. else
  3523. val = typedValue.mPtr;
  3524. if (regIdx == 0)
  3525. registers->mIntRegs.rcx = val;
  3526. else if (regIdx == 1)
  3527. registers->mIntRegs.rdx = val;
  3528. else if (regIdx == 2)
  3529. registers->mIntRegs.r8 = val;
  3530. else if (regIdx == 3)
  3531. registers->mIntRegs.r9 = val;
  3532. }
  3533. }
  3534. #endif
  3535. }
  3536. bool WinDebugger::CheckNeedsSRetArgument(DbgType* retType)
  3537. {
  3538. if (!retType->IsCompositeType())
  3539. return false;
  3540. if (retType->GetByteCount() == 0)
  3541. return false;
  3542. //TODO: Change when we change the calling convention
  3543. if (retType->GetLanguage() == DbgLanguage_Beef)
  3544. return true;
  3545. int retSize = retType->GetByteCount();
  3546. //TODO: Check for 'POD' type?
  3547. if ((retSize == 1) || (retSize == 2) || (retSize == 4) || (retSize == sizeof(addr_target)))
  3548. return false;
  3549. return true;
  3550. }
  3551. DbgTypedValue WinDebugger::ReadReturnValue(CPURegisters* registers, DbgType* type)
  3552. {
  3553. DbgTypedValue retValue;
  3554. if (type->IsFloat())
  3555. {
  3556. retValue.mType = type;
  3557. #if BF_DBG_32
  3558. retValue.mDouble = ConvertFloat80ToDouble(registers->mFpMmRegsArray[0].fp.fp80);
  3559. if (type->mSize == 4)
  3560. retValue.mSingle = (float)retValue.mDouble;
  3561. #else
  3562. if (retValue.mType->mTypeCode == DbgType_Single)
  3563. retValue.mSingle = registers->mXmmRegsArray[0].f[0];
  3564. else
  3565. retValue.mDouble = registers->mXmmDRegsArray[0].d[0];
  3566. #endif
  3567. }
  3568. else if (type->IsCompositeType())
  3569. {
  3570. retValue.mType = type;
  3571. if (CheckNeedsSRetArgument(type))
  3572. {
  3573. #ifdef BF_DBG_32
  3574. retValue.mSrcAddress = mSavedContext.Esp - BF_ALIGN(type->GetByteCount(), 16);
  3575. #else
  3576. retValue.mSrcAddress = mSavedContext.Rsp - BF_ALIGN(type->GetByteCount(), 16);
  3577. #endif
  3578. }
  3579. else
  3580. {
  3581. #ifdef BF_DBG_32
  3582. retValue.mInt32 = mSavedContext.Eax;
  3583. #else
  3584. retValue.mInt64 = mSavedContext.Rax;
  3585. #endif
  3586. }
  3587. }
  3588. else
  3589. {
  3590. #ifdef BF_DBG_32
  3591. retValue.mType = type;
  3592. retValue.mInt32 = registers->mIntRegs.eax;
  3593. if (type->mSize == 8)
  3594. (&retValue.mInt32)[1] = registers->mIntRegs.edx;
  3595. #else
  3596. retValue.mType = type;
  3597. retValue.mInt64 = registers->mIntRegs.rax;
  3598. #endif
  3599. return retValue;
  3600. }
  3601. return retValue;
  3602. }
  3603. bool WinDebugger::SetRegisters(CPURegisters* registers)
  3604. {
  3605. BF_CONTEXT lcContext;
  3606. lcContext.ContextFlags = BF_CONTEXT_CONTROL | BF_CONTEXT_INTEGER | BF_CONTEXT_FLOATING_POINT | BF_CONTEXT_EXTENDED_REGISTERS | BF_CONTEXT_SEGMENTS;
  3607. lcContext.ContextFlags |= BF_CONTEXT_EXCEPTION_REQUEST;
  3608. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  3609. #ifdef BF_DBG_32
  3610. lcContext.Eax = registers->mIntRegs.eax;
  3611. lcContext.Ecx = registers->mIntRegs.ecx;
  3612. lcContext.Edx = registers->mIntRegs.edx;
  3613. lcContext.Ebx = registers->mIntRegs.ebx;
  3614. lcContext.Esp = registers->mIntRegs.esp;
  3615. lcContext.Ebp = registers->mIntRegs.ebp;
  3616. lcContext.Esi = registers->mIntRegs.esi;
  3617. lcContext.Edi = registers->mIntRegs.edi;
  3618. lcContext.Eip = registers->mIntRegs.eip;
  3619. lcContext.EFlags = registers->mIntRegs.efl;
  3620. BF_ASSERT(sizeof(lcContext.FloatSave.RegisterArea) == sizeof(registers->mFpMmRegsArray));
  3621. memcpy(lcContext.FloatSave.RegisterArea, registers->mFpMmRegsArray, sizeof(lcContext.FloatSave.RegisterArea));
  3622. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 32*sizeof(float));
  3623. memcpy(&lcContext.ExtendedRegisters[160], registers->mXmmRegsArray, sizeof(registers->mXmmRegsArray));
  3624. #else
  3625. lcContext.Rax = registers->mIntRegs.rax;
  3626. lcContext.Rcx = registers->mIntRegs.rcx;
  3627. lcContext.Rdx = registers->mIntRegs.rdx;
  3628. lcContext.Rbx = registers->mIntRegs.rbx;
  3629. lcContext.Rsp = registers->mIntRegs.rsp;
  3630. lcContext.Rbp = registers->mIntRegs.rbp;
  3631. lcContext.Rsi = registers->mIntRegs.rsi;
  3632. lcContext.Rdi = registers->mIntRegs.rdi;
  3633. lcContext.Rip = registers->mIntRegs.rip;
  3634. lcContext.EFlags = (DWORD)registers->mIntRegs.efl;
  3635. lcContext.R8 = registers->mIntRegs.r8;
  3636. lcContext.R9 = registers->mIntRegs.r9;
  3637. lcContext.R10 = registers->mIntRegs.r10;
  3638. lcContext.R11 = registers->mIntRegs.r11;
  3639. lcContext.R12 = registers->mIntRegs.r12;
  3640. lcContext.R13 = registers->mIntRegs.r13;
  3641. lcContext.R14 = registers->mIntRegs.r14;
  3642. lcContext.R15 = registers->mIntRegs.r15;
  3643. for (int i = 0; i < 8; i++)
  3644. {
  3645. memcpy(&lcContext.FltSave.FloatRegisters[i], &registers->mFpMmRegsArray[i], 10);
  3646. }
  3647. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 64 * sizeof(float));
  3648. memcpy(BF_CONTEXT_XMMDATA(lcContext), registers->mXmmRegsArray, sizeof(registers->mXmmRegsArray));
  3649. #endif
  3650. //lcContext.ContextFlags |= BF_CONTEXT_EXCEPTION_REQUEST;
  3651. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  3652. return (lcContext.ContextFlags & (BF_CONTEXT_EXCEPTION_ACTIVE | BF_CONTEXT_SERVICE_ACTIVE)) == 0;
  3653. }
  3654. void WinDebugger::SaveAllRegisters()
  3655. {
  3656. BfLogDbg("SaveAllRegisters setting mSavedAtBreakpointAddress = %p\n", mActiveThread->mIsAtBreakpointAddress);
  3657. mSavedAtBreakpointAddress = mActiveThread->mIsAtBreakpointAddress;
  3658. mSavedBreakpointAddressContinuing = mActiveThread->mBreakpointAddressContinuing;
  3659. mSavedContext.ContextFlags = BF_CONTEXT_ALL;
  3660. BF_GetThreadContext(mActiveThread->mHThread, &mSavedContext);
  3661. }
  3662. void WinDebugger::RestoreAllRegisters()
  3663. {
  3664. BfLogDbg("RestoreAllRegisters setting mIsAtBreakpointAddress = %p\n", mSavedAtBreakpointAddress);
  3665. mActiveThread->mIsAtBreakpointAddress = mSavedAtBreakpointAddress;
  3666. mActiveThread->mBreakpointAddressContinuing = mSavedBreakpointAddressContinuing;
  3667. BF_SetThreadContext(mActiveThread->mHThread, &mSavedContext);
  3668. #ifdef BF_DBG_32
  3669. //TODO: Find the test that this was required for...
  3670. // if (mActiveThread->mIsAtBreakpointAddress == mSavedContext.Eip)
  3671. // {
  3672. // if (mRunState == RunState_Running_ToTempBreakpoint)
  3673. // mRunState = RunState_Paused;
  3674. // }
  3675. // else
  3676. // {
  3677. // SetTempBreakpoint(mSavedContext.Eip);
  3678. // mRunState = RunState_Running_ToTempBreakpoint;
  3679. // mStepType = StepType_ToTempBreakpoint;
  3680. // mSteppingThread = mActiveThread;
  3681. // }
  3682. #endif
  3683. }
  3684. void WinDebugger::OutputMessage(const StringImpl& msg)
  3685. {
  3686. if (this == NULL)
  3687. return;
  3688. AutoCrit autoCrit(mDebugManager->mCritSect);
  3689. mDebugManager->mOutMessages.push_back("msg " + msg);
  3690. }
  3691. void WinDebugger::OutputRawMessage(const StringImpl& msg)
  3692. {
  3693. if (this == NULL)
  3694. return;
  3695. AutoCrit autoCrit(mDebugManager->mCritSect);
  3696. mDebugManager->mOutMessages.push_back(msg);
  3697. }
  3698. void WinDebugger::SetRunState(RunState runState)
  3699. {
  3700. mRunState = runState;
  3701. }
  3702. bool WinDebugger::TryRunContinue()
  3703. {
  3704. if (mRunState == RunState_Exception)
  3705. {
  3706. mIsContinuingFromException = true;
  3707. mRunState = RunState_Paused;
  3708. }
  3709. if (((mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint)) && (mNeedsRehupBreakpoints))
  3710. RehupBreakpoints(true);
  3711. return true;
  3712. }
  3713. void WinDebugger::ClearStep()
  3714. {
  3715. BfLogDbg("ClearStep\n");
  3716. RemoveTempBreakpoints();
  3717. mOrigStepType = StepType_None;
  3718. mStepType = StepType_None;
  3719. mStepStartPC = 0;
  3720. mStepSP = 0;
  3721. mStepPC = 0;
  3722. mIsStepIntoSpecific = false;
  3723. mStepIsRecursing = false;
  3724. mStepStopOnNextInstruction = false;
  3725. mStepLineData = DbgLineDataEx();
  3726. }
  3727. bool WinDebugger::SetupStep(StepType stepType)
  3728. {
  3729. BP_ZONE("SetupStep");
  3730. RemoveTempBreakpoints();
  3731. if (mNeedsRehupBreakpoints)
  3732. RehupBreakpoints(true);
  3733. if (mOrigStepType == StepType_None)
  3734. mOrigStepType = stepType;
  3735. mStepType = stepType;
  3736. mSteppingThread = mActiveThread;
  3737. mStepSwitchedThreads = false;
  3738. mContinueFromBreakpointFailed = false;
  3739. CPURegisters registers;
  3740. PopulateRegisters(&registers);
  3741. addr_target pcAddress = registers.GetPC();
  3742. if (mStepLineData.IsNull())
  3743. {
  3744. DbgSubprogram* dbgSubprogram = NULL;
  3745. auto dbgLineData = FindLineDataAtAddress(pcAddress, &dbgSubprogram);
  3746. mStepLineData = DbgLineDataEx(dbgLineData, dbgSubprogram);
  3747. mStepStartPC = registers.GetPC();
  3748. }
  3749. bool isDeeper = mStepSP > registers.GetSP();
  3750. 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);
  3751. mStepSP = registers.GetSP();
  3752. mStepPC = registers.GetPC();
  3753. if ((mStepType == StepType_StepOut) || (mStepType == StepType_StepOut_NoFrame) || (mStepType == StepType_StepOut_ThenInto))
  3754. {
  3755. if (mStepType != StepType_StepOut_NoFrame)
  3756. {
  3757. // Test for stepping out of an inline method
  3758. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3759. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL))
  3760. {
  3761. DbgSubprogram* topSubprogram = dwSubprogram->GetRootInlineParent();
  3762. if ((mOrigStepType == StepType_StepInto) || (mOrigStepType == StepType_StepInto_Unfiltered))
  3763. {
  3764. mStepType = mOrigStepType;
  3765. }
  3766. else
  3767. {
  3768. mStepType = StepType_StepOut_Inline;
  3769. // Set up pcAddress to detect recursion
  3770. //TODO: We can't set a physical breakpoint here because we will immediately hit it when attempting to step over an inlined method.
  3771. // An inlined method can't recurse anyway, but store the pcAddress in mTempBreakpoints because we still check that for recursion
  3772. // SetTempBreakpoint(pcAddress);
  3773. //mTempBreakpoint.push_back(pcAddress);
  3774. mStepBreakpointAddrs.push_back(pcAddress);
  3775. }
  3776. addr_target endAddress = dwSubprogram->mBlock.mHighPC;
  3777. if (dwSubprogram->mHasLineAddrGaps)
  3778. {
  3779. // Keep bumping out the address as long as we can find lines that contain the nextPC
  3780. addr_target nextAddr = pcAddress;
  3781. for (auto& lineInfo : topSubprogram->mLineInfo->mLines)
  3782. {
  3783. auto lineAddr = topSubprogram->GetLineAddr(lineInfo);
  3784. if ((nextAddr >= lineAddr) && (nextAddr < lineAddr + lineInfo.mContribSize))
  3785. {
  3786. auto ctx = topSubprogram->mLineInfo->mContexts[lineInfo.mCtxIdx];
  3787. if (ctx.mInlinee == dwSubprogram)
  3788. {
  3789. nextAddr = lineAddr + lineInfo.mContribSize;
  3790. }
  3791. }
  3792. }
  3793. if (nextAddr != pcAddress)
  3794. endAddress = nextAddr;
  3795. }
  3796. BfLogDbg("Stepping out of inlined method, end address: %p\n", endAddress);
  3797. SetTempBreakpoint(endAddress);
  3798. mStepBreakpointAddrs.push_back(endAddress);
  3799. addr_target decodeAddress = dwSubprogram->mBlock.mLowPC;
  3800. while (decodeAddress < endAddress)
  3801. {
  3802. CPUInst inst;
  3803. if (!mDebugTarget->DecodeInstruction(decodeAddress, &inst))
  3804. break;
  3805. addr_target targetAddress = inst.GetTarget();
  3806. // We need to find a targetAddress
  3807. if ((targetAddress != 0) &&
  3808. !((targetAddress >= dwSubprogram->mBlock.mLowPC) && (targetAddress < dwSubprogram->mBlock.mHighPC)) &&
  3809. ((targetAddress >= topSubprogram->mBlock.mLowPC) && (targetAddress < topSubprogram->mBlock.mHighPC)))
  3810. {
  3811. BfLogDbg("Stepping out of inlined method, branch address: %p\n", targetAddress);
  3812. SetTempBreakpoint(targetAddress);
  3813. mStepBreakpointAddrs.push_back(targetAddress);
  3814. }
  3815. decodeAddress += inst.GetLength();
  3816. }
  3817. return true;
  3818. }
  3819. }
  3820. if ((mStepType != StepType_StepOut_NoFrame) && (RollBackStackFrame(&registers, true)))
  3821. {
  3822. bool isStackAdjust = false;
  3823. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress);
  3824. if (dwSubprogram != NULL)
  3825. {
  3826. if ((strcmp(dwSubprogram->mName, "_chkstk") == 0) ||
  3827. (strcmp(dwSubprogram->mName, "__chkstk") == 0) ||
  3828. (strcmp(dwSubprogram->mName, "_alloca_probe") == 0))
  3829. isStackAdjust = true;
  3830. }
  3831. pcAddress = registers.GetPC();
  3832. if (isStackAdjust)
  3833. {
  3834. // We set it to zero so we never detect an "isDeeper" condition which would skip over the return-location breakpoint
  3835. mStepSP = 0;
  3836. }
  3837. else
  3838. {
  3839. addr_target oldAddress = pcAddress;
  3840. CPUInst inst;
  3841. while (true)
  3842. {
  3843. if (mStepInAssembly)
  3844. break;
  3845. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  3846. break;
  3847. if ((inst.IsBranch()) || (inst.IsCall()) || (inst.IsReturn()))
  3848. break;
  3849. #ifdef BF_DBG_32
  3850. if (!inst.StackAdjust(mStepSP))
  3851. break;
  3852. #endif
  3853. DbgSubprogram* checkSubprogram = NULL;
  3854. auto checkLineData = FindLineDataAtAddress(pcAddress, &checkSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  3855. if (checkLineData == NULL)
  3856. break;
  3857. if (checkSubprogram->GetLineAddr(*checkLineData) == pcAddress)
  3858. break;
  3859. pcAddress += inst.GetLength();
  3860. }
  3861. if (pcAddress != oldAddress)
  3862. {
  3863. BfLogDbg("Adjusting stepout address from %p to %p\n", oldAddress, pcAddress);
  3864. }
  3865. }
  3866. BfLogDbg("SetupStep Stepout SetTempBreakpoint %p\n", pcAddress);
  3867. SetTempBreakpoint(pcAddress);
  3868. mStepBreakpointAddrs.push_back(pcAddress);
  3869. if (mStepType != StepType_StepOut_ThenInto)
  3870. mStepType = StepType_StepOut;
  3871. }
  3872. else
  3873. {
  3874. // Try to handle the case where we just entered this call so the return address is the first entry on the stack
  3875. addr_target* regSP = registers.GetSPRegisterRef();
  3876. pcAddress = ReadMemory<addr_target>(*regSP);
  3877. *regSP += sizeof(addr_target);
  3878. if (mDebugTarget->FindSubProgram(pcAddress) != NULL)
  3879. {
  3880. BfLogDbg("SetupStep Stepout SetTempBreakpoint (2) %p\n", pcAddress);
  3881. SetTempBreakpoint(pcAddress);
  3882. mStepBreakpointAddrs.push_back(pcAddress);
  3883. if (mOrigStepType == StepType_StepInto)
  3884. mStepType = StepType_StepInto;
  3885. else
  3886. mStepType = StepType_StepOver;
  3887. return true;
  3888. }
  3889. else
  3890. {
  3891. // Just do stepovers until we eventually step out
  3892. //BF_DBG_FATAL("StepOut Failed");
  3893. BfLogDbg("StepOut Failed\n");
  3894. if (mLastValidStepIntoPC != 0)
  3895. {
  3896. BfLogDbg("Using mLastValidStepIntoPC: %p\n", mLastValidStepIntoPC);
  3897. if (mOrigStepType == StepType_StepInto)
  3898. mStepType = StepType_StepInto;
  3899. else
  3900. mStepType = StepType_StepOver;
  3901. SetTempBreakpoint(mLastValidStepIntoPC);
  3902. mStepBreakpointAddrs.push_back(0);
  3903. mStepBreakpointAddrs.push_back(mLastValidStepIntoPC);
  3904. mLastValidStepIntoPC = 0;
  3905. return true;
  3906. }
  3907. else
  3908. {
  3909. BfLogDbg("Stopping");
  3910. mStepType = StepType_None;
  3911. mRunState = RunState_Paused;
  3912. return true;
  3913. }
  3914. }
  3915. }
  3916. }
  3917. if ((mStepType != StepType_StepOut) && (mStepType != StepType_StepOut_ThenInto))
  3918. {
  3919. if (mDebuggerWaitingThread != mSteppingThread)
  3920. {
  3921. // We've switched threads, so there's a possible race condition:
  3922. // This new thread may already have an EXCEPTION_BREAKPOINT queued up so the PC is actually
  3923. // located one byte past the BREAK instruction, which is one byte into whatever instruction
  3924. // was previously there. We can't insert normal BREAK instructions because we don't know
  3925. // if the current PC is actually at an instruction start, so we do a single step with a
  3926. // slower stack call check to see if we need to step out after a "step over"
  3927. BfLogDbg("Step - switched threads mIsAtBreakpointAddress:%p\n", mSteppingThread->mIsAtBreakpointAddress);
  3928. mStepSwitchedThreads = true;
  3929. SingleStepX86();
  3930. return true;
  3931. }
  3932. bool breakOnNext = false;
  3933. int instIdx = 0;
  3934. for (instIdx = 0; true; instIdx++)
  3935. {
  3936. bool isAtLine = false;
  3937. DbgSubprogram* dwSubprogram = NULL;
  3938. auto dwLineData = FindLineDataAtAddress(pcAddress, &dwSubprogram, NULL, NULL, DbgOnDemandKind_LocalOnly);
  3939. isAtLine = (instIdx > 0) && (dwLineData != NULL) && (dwLineData->IsStackFrameSetup()) && (dwSubprogram->GetLineAddr(*dwLineData) == pcAddress);
  3940. // "Never step into" line
  3941. if ((dwLineData != NULL) && (dwLineData->mColumn == -2) && (stepType == StepType_StepInto))
  3942. stepType = StepType_StepOver;
  3943. CPUInst inst;
  3944. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  3945. {
  3946. BfLogDbg("Decode failed, set up SingleStepX86 %p\n", pcAddress);
  3947. SingleStepX86();
  3948. mStepStopOnNextInstruction = true;
  3949. return true;
  3950. }
  3951. if (instIdx > 256)
  3952. {
  3953. BfLogDbg("Too many SetupStep iterations");
  3954. breakOnNext = true;
  3955. }
  3956. if ((inst.IsReturn()) && (instIdx == 0) && (!mStepInAssembly))
  3957. {
  3958. // Do actual STEP OUT so we set up proper "stepping over unimportant post-return instructions"
  3959. if (stepType == StepType_StepInto)
  3960. return SetupStep(StepType_StepOut_ThenInto);
  3961. else
  3962. return SetupStep(StepType_StepOut);
  3963. }
  3964. if ((breakOnNext) || (mStepInAssembly) || (isAtLine) || (inst.IsBranch()) || (inst.IsCall()) || (inst.IsReturn()))
  3965. {
  3966. if (((instIdx == 0) || (mStepInAssembly)) && (!breakOnNext))
  3967. {
  3968. if ((stepType == StepType_StepOver) && (inst.IsCall()))
  3969. {
  3970. // Continue - sets a breakpoint on the call line to detect recursion.
  3971. // The next loop through will set a breakpoint on the line after the return
  3972. BfLogDbg("StepHadCall\n");
  3973. breakOnNext = true;
  3974. BfLogDbg("StepHadCall setting mIsAtBreakpointAddress = %p\n", pcAddress);
  3975. mSteppingThread->mIsAtBreakpointAddress = pcAddress;
  3976. SetTempBreakpoint(pcAddress);
  3977. mStepBreakpointAddrs.push_back(pcAddress);
  3978. }
  3979. else
  3980. {
  3981. if (inst.IsCall())
  3982. {
  3983. if ((mLastValidStepIntoPC == 0) || (dwSubprogram != NULL))
  3984. mLastValidStepIntoPC = pcAddress + inst.mSize;
  3985. }
  3986. if ((dwLineData != NULL) && (inst.IsBranch()))
  3987. {
  3988. addr_target targetAddr = inst.GetTarget();
  3989. if (targetAddr < dwSubprogram->GetLineAddr(*dwLineData))
  3990. {
  3991. // Jumping backwards, stop at next instruction
  3992. mStepStopOnNextInstruction = true;
  3993. }
  3994. }
  3995. bool isPrefixOnly = false;
  3996. if ((mStepInAssembly) && (stepType == StepType_StepOver) && (inst.IsRep(isPrefixOnly)))
  3997. {
  3998. if (isPrefixOnly)
  3999. {
  4000. CPUInst nextInst;
  4001. if (mDebugTarget->DecodeInstruction(pcAddress + inst.GetLength(), &nextInst))
  4002. {
  4003. if (nextInst.IsBranch())
  4004. {
  4005. // repne jmp - this appears in __chkstk (for example)
  4006. // We don't have a good way to "step over" this one, so just do a single step
  4007. }
  4008. else
  4009. {
  4010. // Step over the rep + target instruction
  4011. auto doneAddr = pcAddress + inst.GetLength() + nextInst.GetLength();
  4012. BfLogDbg("SetupStep SetTempBreakpoint %p\n", doneAddr);
  4013. SetTempBreakpoint(doneAddr);
  4014. mStepBreakpointAddrs.push_back(doneAddr);
  4015. break;
  4016. }
  4017. }
  4018. }
  4019. else
  4020. {
  4021. // Step over the instruction
  4022. auto doneAddr = pcAddress + inst.GetLength();
  4023. BfLogDbg("SetupStep SetTempBreakpoint %p\n", doneAddr);
  4024. SetTempBreakpoint(doneAddr);
  4025. mStepBreakpointAddrs.push_back(doneAddr);
  4026. break;
  4027. }
  4028. }
  4029. // Just step a single instruction
  4030. BfLogDbg("SetupStep SingleStepX86 %p\n", pcAddress);
  4031. SingleStepX86();
  4032. if (inst.IsReturn())
  4033. mStepStopOnNextInstruction = true;
  4034. break;
  4035. }
  4036. }
  4037. else
  4038. {
  4039. // Move us to this instruction so we can hardware single-step into it
  4040. BfLogDbg("SetupStep SetTempBreakpoint %p\n", pcAddress);
  4041. SetTempBreakpoint(pcAddress);
  4042. mStepBreakpointAddrs.push_back(pcAddress);
  4043. break;
  4044. }
  4045. }
  4046. // Not an interesting instruction - move to next
  4047. pcAddress += inst.mSize;
  4048. if ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL) && (pcAddress >= dwSubprogram->mBlock.mHighPC))
  4049. {
  4050. auto endAddress = dwSubprogram->mBlock.mHighPC;
  4051. BfLogDbg("Stepping past end of inlined method, end address: %p\n", endAddress);
  4052. mStepType = StepType_StepOut_Inline;
  4053. SetTempBreakpoint(endAddress);
  4054. mStepBreakpointAddrs.push_back(endAddress);
  4055. return true;
  4056. }
  4057. }
  4058. if (instIdx > 1)
  4059. BfLogDbg("SetupStep instIdx: %d\n", instIdx);
  4060. }
  4061. return true;
  4062. }
  4063. void WinDebugger::CheckNonDebuggerBreak()
  4064. {
  4065. enum MessageType
  4066. {
  4067. MessageType_None = 0,
  4068. MessageType_Error = 1,
  4069. MessageType_ProfilerCmd = 2
  4070. };
  4071. CPURegisters registers;
  4072. PopulateRegisters(&registers);
  4073. addr_target pcAddress = registers.GetPC();
  4074. addr_target debugMessageDataAddr = (addr_target)-1;
  4075. if (mDebugTarget->mTargetBinary != NULL)
  4076. {
  4077. mDebugTarget->mTargetBinary->ParseSymbolData();
  4078. debugMessageDataAddr = mDebugTarget->FindSymbolAddr("gBfDebugMessageData");
  4079. }
  4080. if (debugMessageDataAddr != (addr_target)-1)
  4081. {
  4082. struct BfDebugMessageData
  4083. {
  4084. int mMessageType; // 0 = none, 1 = error
  4085. int mStackWindbackCount;
  4086. int mBufParamLen;
  4087. addr_target mBufParam;
  4088. addr_target mPCOverride;
  4089. };
  4090. BfDebugMessageData messageData = ReadMemory<BfDebugMessageData>(debugMessageDataAddr);
  4091. WriteMemory<int>(debugMessageDataAddr, 0); // Zero out type so we won't trigger again
  4092. if (messageData.mMessageType != 0)
  4093. {
  4094. llvm::SmallVector<char, 4096> strBuf;
  4095. int strLen = messageData.mBufParamLen;
  4096. strBuf.resize(strLen + 1);
  4097. char* str = &strBuf[0];
  4098. str[strLen] = 0;
  4099. if (ReadMemory(messageData.mBufParam, strLen, str))
  4100. {
  4101. if (messageData.mMessageType == MessageType_Error)
  4102. {
  4103. mRequestedStackFrameIdx = messageData.mStackWindbackCount;
  4104. if (messageData.mPCOverride != 0)
  4105. {
  4106. mShowPCOverride = messageData.mPCOverride;
  4107. mRequestedStackFrameIdx = -2;
  4108. }
  4109. mDebugManager->mOutMessages.push_back(StrFormat("error %s", str));
  4110. }
  4111. else if (messageData.mMessageType == MessageType_ProfilerCmd)
  4112. {
  4113. // It's important to set this here, because we unlock the critSect during StopSampling and we can't have the
  4114. // IDE thinking that we're actually paused when it checks the mRunState
  4115. mRunState = RunState_Running;
  4116. char* cmd = strtok(str, "\t");
  4117. if (strcmp(cmd, "StartSampling") == 0)
  4118. {
  4119. char* sessionIdStr = strtok(NULL, "\t");
  4120. char* threadIdStr = strtok(NULL, "\t");
  4121. char* sampleRateStr = strtok(NULL, "\t");
  4122. char* descStr = strtok(NULL, "\t");
  4123. if (threadIdStr != NULL)
  4124. {
  4125. int threadId = atoi(threadIdStr);
  4126. int sampleRate = atoi(sampleRateStr);
  4127. int sessionId = atoi(sessionIdStr);
  4128. Profiler** profilerPtr;
  4129. if (mPendingProfilerMap.TryAdd(sessionId, NULL, &profilerPtr))
  4130. {
  4131. DbgProfiler* profiler = new DbgProfiler(this);
  4132. if (descStr != NULL)
  4133. profiler->mDescription = descStr;
  4134. if (sampleRate > 0)
  4135. profiler->mSamplesPerSecond = sampleRate;
  4136. profiler->Start();
  4137. *profilerPtr = profiler;
  4138. mDebugManager->mOutMessages.push_back("newProfiler");
  4139. mNewProfilerList.push_back(profiler);
  4140. }
  4141. }
  4142. }
  4143. else if (strcmp(cmd, "StopSampling") == 0)
  4144. {
  4145. char* sessionIdStr = strtok(NULL, "\t");
  4146. if (sessionIdStr != NULL)
  4147. {
  4148. int sessionId = atoi(sessionIdStr);
  4149. Profiler* profiler;
  4150. if (mPendingProfilerMap.Remove(sessionId, &profiler))
  4151. {
  4152. if (profiler->IsSampling())
  4153. {
  4154. // Need to unlock so we don't deadlock
  4155. mDebugManager->mCritSect.Unlock();
  4156. profiler->Stop();
  4157. mDebugManager->mCritSect.Lock();
  4158. }
  4159. }
  4160. }
  4161. }
  4162. else if (strcmp(cmd, "ClearSampling") == 0)
  4163. {
  4164. for (auto& kv : mPendingProfilerMap)
  4165. {
  4166. auto profiler = kv.mValue;
  4167. profiler->Clear();
  4168. }
  4169. }
  4170. else if (strcmp(cmd, "ClearOutput") == 0)
  4171. {
  4172. mDebugManager->mOutMessages.push_back("clearOutput");
  4173. }
  4174. }
  4175. return;
  4176. }
  4177. }
  4178. }
  4179. intptr_target objAddr;
  4180. auto dbgBreakKind = mDebugTarget->GetDbgBreakKind(pcAddress, &registers, &objAddr);
  4181. if (dbgBreakKind == DbgBreakKind_ObjectAccess)
  4182. {
  4183. String errorStr = "error Attempted to access deleted object";
  4184. String objectAddr = EncodeDataPtr((addr_target)objAddr, true);
  4185. errorStr += StrFormat("\x1LEAK\t(System.Object)%s\n (%s)%s\n", objectAddr.c_str(), "System.Object", objectAddr.c_str());
  4186. mDebugManager->mOutMessages.push_back(errorStr);
  4187. return;
  4188. }
  4189. else if (dbgBreakKind == DbgBreakKind_ArithmeticOverflow)
  4190. {
  4191. String errorStr = "error Arithmetic overflow detected";
  4192. mDebugManager->mOutMessages.push_back(errorStr);
  4193. return;
  4194. }
  4195. bool showMainThread = false;
  4196. String symbol;
  4197. addr_target offset;
  4198. DbgModule* dbgModule;
  4199. if (mDebugTarget->FindSymbolAt(pcAddress, &symbol, &offset, &dbgModule))
  4200. {
  4201. if ((symbol == "DbgBreakPoint") || (symbol == "RtlUserThreadStart") || (symbol == "RtlUserThreadStart@8"))
  4202. {
  4203. showMainThread = true;
  4204. }
  4205. }
  4206. #ifdef BF_DBG_32
  4207. else if ((dbgModule != NULL) && (dbgModule->mDisplayName.Equals("kernel32.dll", StringImpl::CompareKind_OrdinalIgnoreCase)))
  4208. {
  4209. showMainThread = true;
  4210. }
  4211. #endif
  4212. if (showMainThread)
  4213. {
  4214. // This is a manual break, show the main thread
  4215. mActiveThread = mThreadList.front();
  4216. if (mDebugPendingExpr != NULL)
  4217. {
  4218. for (auto thread : mThreadList)
  4219. {
  4220. if (thread->mThreadId == mDebugEvalThreadInfo.mThreadId)
  4221. {
  4222. mActiveThread = thread;
  4223. break;
  4224. }
  4225. }
  4226. }
  4227. }
  4228. }
  4229. bool WinDebugger::HasSteppedIntoCall()
  4230. {
  4231. // Some calls (like __chkstk) actually push results to the stack, so we need to check
  4232. // if we're REALLY deeper or not, by rolling back the callstack once
  4233. CPURegisters registers;
  4234. PopulateRegisters(&registers);
  4235. if (RollBackStackFrame(&registers, true))
  4236. {
  4237. // If the previous frames SP is equal or deeper than our step start then we are indeed inside a call!
  4238. if (mStepSP >= registers.GetSP())
  4239. return true;
  4240. }
  4241. return false;
  4242. }
  4243. void WinDebugger::StepOver(bool inAssembly)
  4244. {
  4245. AutoCrit autoCrit(mDebugManager->mCritSect);
  4246. BfLogDbg("StepOver\n");
  4247. if (!TryRunContinue())
  4248. return;
  4249. mCurNoInfoStepTries = 0; // Reset
  4250. mStepInAssembly = inAssembly;
  4251. SetupStep(StepType_StepOver);
  4252. ContinueDebugEvent();
  4253. }
  4254. void WinDebugger::StepOut(bool inAssembly)
  4255. {
  4256. AutoCrit autoCrit(mDebugManager->mCritSect);
  4257. BfLogDbg("StepOut\n");
  4258. if (!TryRunContinue())
  4259. return;
  4260. mCurNoInfoStepTries = 0; // Reset
  4261. mStepInAssembly = inAssembly;
  4262. SetupStep(StepType_StepOut);
  4263. ContinueDebugEvent();
  4264. }
  4265. void WinDebugger::SetNextStatement(bool inAssembly, const StringImpl& fileName, int64 lineNumOrAsmAddr, int wantColumn)
  4266. {
  4267. AutoCrit autoCrit(mDebugManager->mCritSect);
  4268. DbgSubprogram* subProgram = NULL;
  4269. if (!inAssembly)
  4270. {
  4271. if (mCallStack.size() == 0)
  4272. UpdateCallStack();
  4273. if (mCallStack.size() > 0)
  4274. {
  4275. UpdateCallStackMethod(0);
  4276. subProgram = mCallStack[0]->mSubProgram;
  4277. }
  4278. if (subProgram == NULL)
  4279. return;
  4280. }
  4281. DbgSubprogram* rootInlineParent = NULL;
  4282. if (subProgram != NULL)
  4283. rootInlineParent = subProgram->GetRootInlineParent();
  4284. String result;
  4285. if (mDebugTarget == NULL)
  4286. return;
  4287. DbgSrcFile* srcFile = NULL;
  4288. if (!fileName.IsEmpty())
  4289. {
  4290. srcFile = mDebugTarget->GetSrcFile(fileName);
  4291. if (srcFile == NULL)
  4292. return;
  4293. }
  4294. addr_target pcAddress = 0;
  4295. if (inAssembly)
  4296. {
  4297. pcAddress = lineNumOrAsmAddr;
  4298. }
  4299. else
  4300. {
  4301. int lineNum = (int)lineNumOrAsmAddr;
  4302. addr_target bestAddr[2] = { 0, 0 };
  4303. int checkLineNum[2] = { lineNum - 1, lineNum };
  4304. auto _CheckLineInfo = [&](DbgSubprogram* dbgSubprogram, DbgLineInfo* dbgLineInfo)
  4305. {
  4306. for (int iPass = 0; iPass < 2; ++iPass)
  4307. {
  4308. int bestLineOffset = 0x7FFFFFFF;
  4309. for (auto& lineData : dbgLineInfo->mLines)
  4310. {
  4311. auto addr = dbgSubprogram->GetLineAddr(lineData);
  4312. if ((addr < subProgram->mBlock.mLowPC) || (addr >= subProgram->mBlock.mHighPC))
  4313. continue;
  4314. int lineOffset = lineData.mLine - checkLineNum[iPass];
  4315. if ((lineOffset >= 0) && (lineOffset <= 6) && (lineOffset <= bestLineOffset))
  4316. {
  4317. if (lineOffset < bestLineOffset)
  4318. {
  4319. bestLineOffset = lineOffset;
  4320. bestAddr[iPass] = addr;
  4321. }
  4322. }
  4323. }
  4324. }
  4325. };
  4326. for (int checkHotIdx = -1; checkHotIdx < (int)srcFile->mHotReplacedDbgLineInfo.size(); checkHotIdx++)
  4327. {
  4328. if (checkHotIdx >= 0)
  4329. {
  4330. auto hotReplacedLineInfo = srcFile->mHotReplacedDbgLineInfo[checkHotIdx];
  4331. for (auto& hotReplacedEntry : hotReplacedLineInfo->mEntries)
  4332. {
  4333. _CheckLineInfo(hotReplacedEntry.mSubprogram, hotReplacedEntry.mLineInfo);
  4334. }
  4335. }
  4336. else
  4337. {
  4338. for (auto subprogram : srcFile->mLineDataRefs)
  4339. _CheckLineInfo(subprogram, subprogram->mLineInfo);
  4340. }
  4341. if (bestAddr[1] != 0)
  4342. break;
  4343. }
  4344. if (bestAddr[1] != 0)
  4345. {
  4346. const int kMaxAddrDist = 64; // within reasonable range
  4347. if ((bestAddr[0] != 0) && (bestAddr[1] - bestAddr[0] <= kMaxAddrDist))
  4348. {
  4349. addr_target addrStart = bestAddr[0];
  4350. addr_target addrEnd = bestAddr[1];
  4351. addr_target addr = addrStart;
  4352. BF_ASSERT(addrEnd - addr <= kMaxAddrDist);
  4353. addr_target lastOp = 0;
  4354. while (addr < addrEnd)
  4355. {
  4356. CPUInst inst;
  4357. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  4358. break;
  4359. lastOp = addr;
  4360. addr += inst.GetLength();
  4361. }
  4362. }
  4363. pcAddress = (uint64)bestAddr[1];
  4364. }
  4365. }
  4366. if (pcAddress)
  4367. {
  4368. BF_ASSERT(mActiveThread->mBreakpointAddressContinuing == 0);
  4369. mActiveThread->mIsAtBreakpointAddress = 0;
  4370. mActiveThread->mStoppedAtAddress = pcAddress;
  4371. if (mCallStack.size() == 0)
  4372. UpdateCallStack();
  4373. CPURegisters* regs = &mCallStack.front()->mRegisters;
  4374. *regs->GetPCRegisterRef() = pcAddress;
  4375. SetRegisters(regs);
  4376. WdBreakpoint* breakpoint = (WdBreakpoint*)FindBreakpointAt(pcAddress);
  4377. if (breakpoint != NULL)
  4378. {
  4379. BfLogDbg("SetNextStatement setting mIsAtBreakpointAddress = %p\n", breakpoint->mAddr);
  4380. mActiveThread->mIsAtBreakpointAddress = breakpoint->mAddr;
  4381. }
  4382. }
  4383. }
  4384. bool WinDebugger::PopulateRegisters(CPURegisters* registers, BF_CONTEXT& lcContext)
  4385. {
  4386. #ifdef BF_DBG_32
  4387. registers->mIntRegs.eax = lcContext.Eax;
  4388. registers->mIntRegs.ecx = lcContext.Ecx;
  4389. registers->mIntRegs.edx = lcContext.Edx;
  4390. registers->mIntRegs.ebx = lcContext.Ebx;
  4391. registers->mIntRegs.esp = lcContext.Esp;
  4392. registers->mIntRegs.ebp = lcContext.Ebp;
  4393. registers->mIntRegs.esi = lcContext.Esi;
  4394. registers->mIntRegs.edi = lcContext.Edi;
  4395. registers->mIntRegs.eip = lcContext.Eip;
  4396. registers->mIntRegs.efl = lcContext.EFlags;
  4397. BF_ASSERT(sizeof(lcContext.FloatSave.RegisterArea) == sizeof(registers->mFpMmRegsArray));
  4398. memcpy(registers->mFpMmRegsArray, lcContext.FloatSave.RegisterArea, sizeof(lcContext.FloatSave.RegisterArea));
  4399. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 32 * sizeof(float));
  4400. memcpy(registers->mXmmRegsArray, &lcContext.ExtendedRegisters[160], sizeof(registers->mXmmRegsArray));
  4401. #else
  4402. registers->mIntRegs.rax = lcContext.Rax;
  4403. registers->mIntRegs.rcx = lcContext.Rcx;
  4404. registers->mIntRegs.rdx = lcContext.Rdx;
  4405. registers->mIntRegs.rbx = lcContext.Rbx;
  4406. registers->mIntRegs.rsp = lcContext.Rsp;
  4407. registers->mIntRegs.rbp = lcContext.Rbp;
  4408. registers->mIntRegs.rsi = lcContext.Rsi;
  4409. registers->mIntRegs.rdi = lcContext.Rdi;
  4410. registers->mIntRegs.rip = lcContext.Rip;
  4411. registers->mIntRegs.efl = lcContext.EFlags;
  4412. registers->mIntRegs.r8 = lcContext.R8;
  4413. registers->mIntRegs.r9 = lcContext.R9;
  4414. registers->mIntRegs.r10 = lcContext.R10;
  4415. registers->mIntRegs.r11 = lcContext.R11;
  4416. registers->mIntRegs.r12 = lcContext.R12;
  4417. registers->mIntRegs.r13 = lcContext.R13;
  4418. registers->mIntRegs.r14 = lcContext.R14;
  4419. registers->mIntRegs.r15 = lcContext.R15;
  4420. registers->mIntRegs.gs = lcContext.SegGs;
  4421. for (int i = 0; i < 8; i++)
  4422. {
  4423. memcpy(&registers->mFpMmRegsArray[i], &lcContext.FltSave.FloatRegisters[i], 10);
  4424. }
  4425. BF_ASSERT(sizeof(registers->mXmmRegsArray) == 64 * sizeof(float));
  4426. memcpy(registers->mXmmRegsArray, BF_CONTEXT_XMMDATA(lcContext), sizeof(registers->mXmmRegsArray));
  4427. #endif
  4428. return (lcContext.ContextFlags & (BF_CONTEXT_EXCEPTION_ACTIVE | BF_CONTEXT_SERVICE_ACTIVE)) == 0;
  4429. }
  4430. bool WinDebugger::PopulateRegisters(CPURegisters* registers)
  4431. {
  4432. /*static bool sCheckedProcessorFeatures = false;
  4433. static bool sMmxAvailable = false;
  4434. static bool sXmmAvailable = false;
  4435. if (!sCheckedProcessorFeatures)
  4436. {
  4437. //CDH we don't do anything with these yet since we grab BF_CONTEXT_ALL anyway, but could be useful
  4438. sMmxAvailable = ::IsProcessorFeaturePresent(PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  4439. sXmmAvailable = ::IsProcessorFeaturePresent(PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  4440. sCheckedProcessorFeatures = true;
  4441. }*/
  4442. BF_ASSERT(registers != nullptr);
  4443. BF_CONTEXT lcContext;
  4444. lcContext.ContextFlags = BF_CONTEXT_ALL | BF_CONTEXT_EXCEPTION_REQUEST;
  4445. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4446. return PopulateRegisters(registers, lcContext);
  4447. }
  4448. bool WinDebugger::RollBackStackFrame(CPURegisters* registers, bool isStackStart)
  4449. {
  4450. BF_ASSERT(registers != nullptr);
  4451. return mDebugTarget->RollBackStackFrame(registers, NULL, isStackStart);
  4452. }
  4453. bool WinDebugger::SetHotJump(DbgSubprogram* oldSubprogram, addr_target newTarget, int newTargetSize)
  4454. {
  4455. BfLogDbg("SetHotJump %s %p->%p\n", oldSubprogram->mName, oldSubprogram->mBlock.mLowPC, newTarget);
  4456. //AutoCrit autoCrit(mDebugManager->mCritSect);
  4457. BF_ASSERT(mDebugManager->mCritSect.mLockCount == 1);
  4458. addr_target jmpInstStart = oldSubprogram->mBlock.mLowPC;
  4459. addr_target jmpInstEnd = jmpInstStart + sizeof(HotJumpOp);
  4460. if (jmpInstEnd > oldSubprogram->mBlock.mHighPC)
  4461. {
  4462. if ((oldSubprogram->mBlock.mHighPC - oldSubprogram->mBlock.mLowPC == 1) &&
  4463. (newTargetSize == 1))
  4464. return true; // Special case for just stub 'ret' methods
  4465. String err = StrFormat("Failed to hot replace method, method '%s' too small to insert hot thunk", oldSubprogram->ToString().c_str());
  4466. Fail(err);
  4467. return false;
  4468. }
  4469. if (oldSubprogram->mHotReplaceKind != DbgSubprogram::HotReplaceKind_Replaced)
  4470. {
  4471. for (int hotThreadIdx = 0; hotThreadIdx < (int)mHotThreadStates.size(); hotThreadIdx++)
  4472. {
  4473. auto& hotThreadState = mHotThreadStates[hotThreadIdx];
  4474. WdThreadInfo* threadInfo = NULL;
  4475. if (!mThreadMap.TryGetValue((uint32)hotThreadState.mThreadId, &threadInfo))
  4476. continue;
  4477. int tryStart = GetTickCount();
  4478. while ((hotThreadState.mRegisters.GetPC() >= jmpInstStart) && (hotThreadState.mRegisters.GetPC() < jmpInstEnd))
  4479. {
  4480. if (GetTickCount() - tryStart >= 8000)
  4481. {
  4482. Fail("Failed to hot replace method, can't move past prelude");
  4483. return false;
  4484. }
  4485. BfLogDbg("SetHotJump skipping through %p\n", hotThreadState.mRegisters.GetPC());
  4486. bool removedBreakpoint = false;
  4487. mActiveThread = threadInfo;
  4488. if ((mActiveThread->mStoppedAtAddress >= jmpInstStart) && (mActiveThread->mStoppedAtAddress < jmpInstEnd))
  4489. {
  4490. for (addr_target addr = jmpInstStart; addr < jmpInstEnd; addr++)
  4491. {
  4492. if (mPhysBreakpointAddrMap.ContainsKey(addr))
  4493. {
  4494. removedBreakpoint = true;
  4495. RemoveBreakpoint(addr);
  4496. }
  4497. }
  4498. }
  4499. RunState oldRunState = mRunState;
  4500. mRunState = RunState_HotStep;
  4501. if (mWantsDebugContinue)
  4502. {
  4503. mWantsDebugContinue = false;
  4504. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4505. mContinueEvent.Set();
  4506. }
  4507. BF_CONTEXT lcContext;
  4508. lcContext.ContextFlags = BF_CONTEXT_ALL;
  4509. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4510. lcContext.EFlags |= 0x100; // Set trap flag, which raises "single-step" exception
  4511. BF_SetThreadContext(mActiveThread->mHThread, &lcContext);
  4512. ::ResumeThread(mActiveThread->mHThread);
  4513. BfLogDbg("ResumeThread %d\n", mActiveThread->mThreadId);
  4514. while (mRunState != RunState_Terminated)
  4515. {
  4516. mDebugManager->mCritSect.Unlock();
  4517. Sleep(0);
  4518. mDebugManager->mCritSect.Lock();
  4519. if (IsPaused())
  4520. break;
  4521. if (mWantsDebugContinue)
  4522. {
  4523. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4524. mWantsDebugContinue = false;
  4525. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4526. mContinueEvent.Set();
  4527. }
  4528. }
  4529. BF_GetThreadContext(mActiveThread->mHThread, &lcContext);
  4530. ::SuspendThread(mActiveThread->mHThread);
  4531. BfLogDbg("SuspendThread %d\n", mActiveThread->mThreadId);
  4532. mRunState = oldRunState;
  4533. if ((mRunState != RunState_Terminated) && (mRunState != RunState_Terminating))
  4534. {
  4535. if (!IsPaused())
  4536. {
  4537. BF_ASSERT(mWantsDebugContinue);
  4538. mWantsDebugContinue = false;
  4539. BF_ASSERT_REL(mActiveThread->mIsAtBreakpointAddress == 0);
  4540. mContinueEvent.Set();
  4541. }
  4542. }
  4543. PopulateRegisters(&hotThreadState.mRegisters);
  4544. }
  4545. }
  4546. }
  4547. HotJumpOp jumpOp;
  4548. jumpOp.mOpCode = 0xE9;
  4549. jumpOp.mRelTarget = newTarget - oldSubprogram->mBlock.mLowPC - sizeof(HotJumpOp);
  4550. WriteMemory(oldSubprogram->mBlock.mLowPC, jumpOp);
  4551. ::FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)oldSubprogram->mBlock.mLowPC, sizeof(HotJumpOp));
  4552. return true;
  4553. }
  4554. DbgSubprogram* WinDebugger::TryFollowHotJump(DbgSubprogram* subprogram, addr_target addr)
  4555. {
  4556. if (subprogram->mHotReplaceKind != DbgSubprogram::HotReplaceKind_Replaced)
  4557. return subprogram;
  4558. if (addr != subprogram->mBlock.mLowPC)
  4559. return subprogram;
  4560. auto dbgModule = subprogram->mCompileUnit->mDbgModule;
  4561. HotJumpOp jumpOp = ReadMemory<HotJumpOp>(addr);
  4562. if (jumpOp.mOpCode != 0xE9)
  4563. return subprogram;
  4564. addr_target jumpAddr = addr + jumpOp.mRelTarget + sizeof(HotJumpOp);
  4565. auto jumpSubprogram = mDebugTarget->FindSubProgram(jumpAddr);
  4566. if (jumpSubprogram == NULL)
  4567. return subprogram;
  4568. return jumpSubprogram;
  4569. }
  4570. bool WinDebugger::ShouldShowStaticMember(DbgType* dbgType, DbgVariable* member)
  4571. {
  4572. // If locationData is non-null, that means it was added in addition to the static declaration in the CV type info,
  4573. // so only add the names from the type definition
  4574. auto flavor = dbgType->mCompileUnit->mDbgModule->mDbgFlavor;
  4575. return ((((dbgType->IsNamespace()) || (flavor != DbgFlavor_MS)) && ((member->mLocationData != NULL) || member->mIsConst)) ||
  4576. ((flavor == DbgFlavor_MS) && (member->mLocationData == NULL)));
  4577. }
  4578. String WinDebugger::GetMemberList(DbgType* dbgType, const StringImpl& expr, bool isPtr, bool isStatic, bool forceCast, bool isSplat, bool isReadOnly)
  4579. {
  4580. auto dbgModule = dbgType->GetDbgModule();
  4581. dbgType->PopulateType();
  4582. auto language = dbgType->GetLanguage();
  4583. if (!isStatic)
  4584. {
  4585. String retVal;
  4586. bool needsNewline = false;
  4587. bool isBfObject = false;
  4588. if (dbgType->IsBfObjectPtr())
  4589. {
  4590. isBfObject = true;
  4591. dbgType = dbgType->mTypeParam;
  4592. }
  4593. int baseIdx = 0;
  4594. for (auto baseTypeEntry : dbgType->mBaseTypes)
  4595. {
  4596. auto baseType = baseTypeEntry->mBaseType;
  4597. if ((baseType->mSize > 0) || (baseType->mTypeCode != DbgType_Struct) || (strcmp(baseType->mTypeName, "ValueType") != 0))
  4598. {
  4599. String baseTypeStr = baseType->ToStringRaw(language);
  4600. if (baseIdx > 0)
  4601. retVal += "\n";
  4602. if (isSplat)
  4603. retVal += "[base]\t((" + baseTypeStr + ")" + expr + "), nv";
  4604. else if (dbgType->WantsRefThis())
  4605. retVal += "[base]\t((" + baseTypeStr + ")this), nd, na, nv, this=" + expr;
  4606. else
  4607. retVal += "[base]\t((" + baseTypeStr + "*)this), nd, na, nv, this=" + expr;
  4608. if (isReadOnly)
  4609. retVal += ", ne";
  4610. }
  4611. needsNewline = true;
  4612. baseIdx++;
  4613. }
  4614. String thisExpr = expr;
  4615. String castString;
  4616. if (dbgType->IsBfObject())
  4617. {
  4618. auto ptrType = dbgType->GetDbgModule()->GetPointerType(dbgType);
  4619. castString = ptrType->ToStringRaw(language);
  4620. }
  4621. else
  4622. castString = dbgType->ToStringRaw(language);
  4623. bool hadStatics = false;
  4624. for (auto member : dbgType->mMemberList)
  4625. {
  4626. if (member->mMemberOffset < 0)
  4627. continue;
  4628. if (member->mIsStatic)
  4629. {
  4630. if (ShouldShowStaticMember(dbgType, member))
  4631. hadStatics = true;
  4632. }
  4633. else
  4634. {
  4635. bool ignoreMember = false;
  4636. if (member->mName != NULL)
  4637. {
  4638. if ((member->mName[0] == '?') ||
  4639. (member->mName[0] == '$') ||
  4640. (strncmp(member->mName, "_vptr$", 6) == 0))
  4641. ignoreMember = true;
  4642. }
  4643. if (!ignoreMember)
  4644. {
  4645. if (needsNewline)
  4646. retVal += "\n";
  4647. if (member->mName == NULL)
  4648. {
  4649. retVal += GetMemberList(member->mType, expr, isPtr, isStatic, forceCast, isSplat, isReadOnly);
  4650. }
  4651. else
  4652. {
  4653. retVal += String(member->mName);
  4654. if (isSplat)
  4655. {
  4656. retVal += "\t(" + thisExpr + ")." + String(member->mName);
  4657. // We don't want to rely on this being enforced here. For one, ref types shouldn't get ", ne" added,
  4658. // and this doesn't solve the issue of attempting to assign via the Immediate window
  4659. /*if (isReadOnly)
  4660. retVal += ", ne";*/
  4661. }
  4662. else
  4663. {
  4664. if (forceCast)
  4665. retVal += "\t((" + castString + ")this)." + String(member->mName);
  4666. else if ((member->mName[0] >= '0') && (member->mName[0] <= '9')) // Numbered tuple member?
  4667. retVal += "\tthis." + String(member->mName);
  4668. else
  4669. retVal += "\t" + String(member->mName);
  4670. retVal += ", this=" + thisExpr;
  4671. // if (isReadOnly)
  4672. // retVal += ", ne";
  4673. }
  4674. }
  4675. needsNewline = true;
  4676. }
  4677. }
  4678. }
  4679. if (hadStatics)
  4680. {
  4681. if (needsNewline)
  4682. retVal += "\n";
  4683. retVal += "Static values\t" + castString;
  4684. }
  4685. return retVal;
  4686. }
  4687. else
  4688. {
  4689. if (dbgType->IsBfObjectPtr())
  4690. dbgType = dbgType->mTypeParam;
  4691. String retVal;
  4692. String memberPrefix = expr;
  4693. bool needsNewline = false;
  4694. bool hadStatics = false;
  4695. for (auto member : dbgType->mMemberList)
  4696. {
  4697. if (member->mIsStatic)
  4698. {
  4699. if (ShouldShowStaticMember(dbgType, member))
  4700. {
  4701. if (needsNewline)
  4702. retVal += "\n";
  4703. retVal += String(member->mName) + "\t" + memberPrefix + "." + String(member->mName);
  4704. needsNewline = true;
  4705. }
  4706. }
  4707. }
  4708. return retVal;
  4709. }
  4710. return "";
  4711. }
  4712. bool WinDebugger::ParseFormatInfo(DbgModule* dbgModule, const StringImpl& formatInfoStr, DwFormatInfo* formatInfo, BfPassInstance* bfPassInstance, int* assignExprOffset, String* assignExprString, String* errorString, DbgTypedValue contextTypedValue)
  4713. {
  4714. String formatFlags = formatInfoStr;
  4715. if (assignExprOffset != NULL)
  4716. *assignExprOffset = -1;
  4717. while (formatFlags.length() > 0)
  4718. {
  4719. formatFlags = Trim(formatFlags);
  4720. if (formatFlags.IsEmpty())
  4721. break;
  4722. if (formatFlags[0] != ',')
  4723. {
  4724. return false;
  4725. }
  4726. else
  4727. {
  4728. int nextComma = formatFlags.IndexOf(',', 1);
  4729. int quotePos = formatFlags.IndexOf('"', 1);
  4730. if ((quotePos != -1) && (quotePos < nextComma))
  4731. {
  4732. int nextQuotePos = formatFlags.IndexOf('"', quotePos + 1);
  4733. if (nextQuotePos != -1)
  4734. nextComma = formatFlags.IndexOf(',', nextQuotePos + 1);
  4735. }
  4736. if (nextComma == -1)
  4737. nextComma = formatFlags.length();
  4738. String formatCmd = formatFlags.Substring(1, nextComma - 1);
  4739. formatCmd = Trim(formatCmd);
  4740. bool hadError = false;
  4741. if (strncmp(formatCmd.c_str(), "this=", 5) == 0)
  4742. {
  4743. formatCmd = formatFlags.Substring(1);
  4744. formatCmd = Trim(formatCmd);
  4745. String thisExpr = formatCmd.Substring(5);
  4746. if (thisExpr.empty())
  4747. break;
  4748. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, thisExpr, formatInfo);
  4749. formatInfo->mExplicitThis = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4750. if (dbgEvaluationContext.HadError())
  4751. {
  4752. if (errorString != NULL)
  4753. *errorString = dbgEvaluationContext.GetErrorStr();
  4754. return false;
  4755. }
  4756. formatFlags = thisExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4757. continue;
  4758. }
  4759. else if (strncmp(formatCmd.c_str(), "count=", 6) == 0)
  4760. {
  4761. formatCmd = formatFlags.Substring(1);
  4762. formatCmd = Trim(formatCmd);
  4763. String countExpr = formatCmd.Substring(6);
  4764. if (countExpr.empty())
  4765. break;
  4766. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4767. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4768. if ((countValue) && (countValue.mType->IsInteger()))
  4769. formatInfo->mOverrideCount = (intptr)countValue.GetInt64();
  4770. if (dbgEvaluationContext.HadError())
  4771. {
  4772. if (errorString != NULL)
  4773. *errorString = dbgEvaluationContext.GetErrorStr();
  4774. return false;
  4775. }
  4776. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4777. continue;
  4778. }
  4779. else if (strncmp(formatCmd.c_str(), "maxcount=", 9) == 0)
  4780. {
  4781. formatCmd = formatFlags.Substring(1);
  4782. formatCmd = Trim(formatCmd);
  4783. String countExpr = formatCmd.Substring(9);
  4784. if (countExpr.empty())
  4785. break;
  4786. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4787. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4788. if ((countValue) && (countValue.mType->IsInteger()))
  4789. formatInfo->mMaxCount = (intptr)countValue.GetInt64();
  4790. if (dbgEvaluationContext.HadError())
  4791. {
  4792. if (errorString != NULL)
  4793. *errorString = dbgEvaluationContext.GetErrorStr();
  4794. return false;
  4795. }
  4796. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4797. continue;
  4798. }
  4799. else if (strncmp(formatCmd.c_str(), "arraysize=", 10) == 0)
  4800. {
  4801. formatCmd = formatFlags.Substring(1);
  4802. formatCmd = Trim(formatCmd);
  4803. String countExpr = formatCmd.Substring(10);
  4804. if (countExpr.empty())
  4805. break;
  4806. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4807. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4808. if ((countValue) && (countValue.mType->IsInteger()))
  4809. formatInfo->mArrayLength = (intptr)countValue.GetInt64();
  4810. if (dbgEvaluationContext.HadError())
  4811. {
  4812. if (errorString != NULL)
  4813. *errorString = dbgEvaluationContext.GetErrorStr();
  4814. return false;
  4815. }
  4816. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4817. continue;
  4818. }
  4819. else if (strncmp(formatCmd.c_str(), "assign=", 7) == 0)
  4820. {
  4821. formatCmd = formatFlags.Substring(1);
  4822. formatCmd = Trim(formatCmd);
  4823. String assignExpr = formatCmd.Substring(7);
  4824. if (assignExpr.empty())
  4825. break;
  4826. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, assignExpr, formatInfo);
  4827. if (dbgEvaluationContext.HadError())
  4828. {
  4829. if (errorString != NULL)
  4830. *errorString = dbgEvaluationContext.GetErrorStr();
  4831. return false;
  4832. }
  4833. if (assignExprOffset != NULL)
  4834. {
  4835. //TODO: Keep track of the offset directly, this is a hack
  4836. *assignExprOffset = (int)formatInfoStr.IndexOf("assign=") + 7;
  4837. }
  4838. if (assignExprString != NULL)
  4839. *assignExprString = dbgEvaluationContext.mExprNode->ToString();
  4840. formatFlags = assignExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4841. continue;
  4842. }
  4843. else if (strncmp(formatCmd.c_str(), "refid=", 6) == 0)
  4844. {
  4845. formatInfo->mReferenceId = formatCmd.Substring(6);
  4846. if ((formatInfo->mReferenceId.mLength >= 2) && (formatInfo->mReferenceId[0] == '\"'))
  4847. formatInfo->mReferenceId = formatInfo->mReferenceId.Substring(1, formatInfo->mReferenceId.length() - 2);
  4848. }
  4849. else if (strncmp(formatCmd.c_str(), "action=", 7) == 0)
  4850. {
  4851. formatInfo->mAction = formatCmd.Substring(7);
  4852. if ((formatInfo->mAction.mLength >= 2) && (formatInfo->mAction[0] == '\"'))
  4853. formatInfo->mAction = formatInfo->mReferenceId.Substring(1, formatInfo->mReferenceId.length() - 2);
  4854. }
  4855. else if (strncmp(formatCmd.c_str(), "_=", 2) == 0)
  4856. {
  4857. formatInfo->mSubjectExpr = formatCmd.Substring(2);
  4858. if ((formatInfo->mSubjectExpr.mLength >= 2) && (formatInfo->mSubjectExpr[0] == '\"'))
  4859. formatInfo->mSubjectExpr = formatInfo->mSubjectExpr.Substring(1, formatInfo->mSubjectExpr.length() - 2);
  4860. }
  4861. else if (strncmp(formatCmd.c_str(), "expectedType=", 13) == 0)
  4862. {
  4863. formatInfo->mExpectedType = formatCmd.Substring(13);
  4864. if ((formatInfo->mExpectedType.mLength >= 2) && (formatInfo->mExpectedType[0] == '\"'))
  4865. formatInfo->mExpectedType = formatInfo->mExpectedType.Substring(1, formatInfo->mExpectedType.length() - 2);
  4866. }
  4867. else if (strncmp(formatCmd.c_str(), "namespaceSearch=", 16) == 0)
  4868. {
  4869. formatInfo->mNamespaceSearch = formatCmd.Substring(16);
  4870. if ((formatInfo->mNamespaceSearch.mLength >= 2) && (formatInfo->mNamespaceSearch[0] == '\"'))
  4871. formatInfo->mNamespaceSearch = formatInfo->mNamespaceSearch.Substring(1, formatInfo->mNamespaceSearch.length() - 2);
  4872. }
  4873. else if (formatCmd == "d")
  4874. {
  4875. formatInfo->mDisplayType = DwDisplayType_Decimal;
  4876. }
  4877. else if (formatCmd == "x")
  4878. {
  4879. formatInfo->mDisplayType = DwDisplayType_HexLower;
  4880. }
  4881. else if (formatCmd == "X")
  4882. {
  4883. formatInfo->mDisplayType = DwDisplayType_HexUpper;
  4884. }
  4885. else if (formatCmd == "s")
  4886. {
  4887. formatInfo->mHidePointers = true;
  4888. formatInfo->mDisplayType = DwDisplayType_Ascii;
  4889. }
  4890. else if (formatCmd == "s8")
  4891. {
  4892. formatInfo->mHidePointers = true;
  4893. formatInfo->mDisplayType = DwDisplayType_Utf8;
  4894. }
  4895. else if (formatCmd == "s16")
  4896. {
  4897. formatInfo->mHidePointers = true;
  4898. formatInfo->mDisplayType = DwDisplayType_Utf16;
  4899. }
  4900. else if (formatCmd == "s32")
  4901. {
  4902. formatInfo->mHidePointers = true;
  4903. formatInfo->mDisplayType = DwDisplayType_Utf32;
  4904. }
  4905. else if (formatCmd == "nd")
  4906. {
  4907. formatInfo->mIgnoreDerivedClassInfo = true;
  4908. }
  4909. else if (formatCmd == "na")
  4910. {
  4911. formatInfo->mHidePointers = true;
  4912. }
  4913. else if (formatCmd == "nm")
  4914. {
  4915. formatInfo->mNoMembers = true;
  4916. }
  4917. else if (formatCmd == "ne")
  4918. {
  4919. formatInfo->mNoEdit = true;
  4920. }
  4921. else if (formatCmd == "nv")
  4922. {
  4923. formatInfo->mNoVisualizers = true;
  4924. }
  4925. else if (formatCmd == "rawStr")
  4926. {
  4927. formatInfo->mRawString = true;
  4928. }
  4929. else if (((!formatCmd.IsEmpty()) && ((formatCmd[0] >= '0') && (formatCmd[0] <= '9'))) ||
  4930. (formatCmd.StartsWith("(")))
  4931. {
  4932. String countExpr = formatCmd;
  4933. if (countExpr.empty())
  4934. break;
  4935. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, countExpr, formatInfo);
  4936. DbgTypedValue countValue = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4937. if ((countValue) && (countValue.mType->IsInteger()))
  4938. formatInfo->mArrayLength = (intptr)countValue.GetInt64();
  4939. if (dbgEvaluationContext.HadError())
  4940. {
  4941. if (errorString != NULL)
  4942. *errorString = dbgEvaluationContext.GetErrorStr();
  4943. return false;
  4944. }
  4945. formatFlags = countExpr.Substring(dbgEvaluationContext.mExprNode->GetSrcEnd());
  4946. continue;
  4947. }
  4948. else
  4949. hadError = true;
  4950. if (hadError)
  4951. {
  4952. if (errorString != NULL)
  4953. *errorString = "Invalid format flags";
  4954. return false;
  4955. }
  4956. formatFlags = formatFlags.Substring(nextComma);
  4957. }
  4958. }
  4959. return true;
  4960. }
  4961. String WinDebugger::MaybeQuoteFormatInfoParam(const StringImpl& str)
  4962. {
  4963. bool needsQuote = false;
  4964. for (int i = 0; i < (int)str.length(); i++)
  4965. {
  4966. char c = str[i];
  4967. if (c == ',')
  4968. needsQuote = true;
  4969. }
  4970. if (!needsQuote)
  4971. return str;
  4972. String qStr = "\"";
  4973. qStr += str;
  4974. qStr += "\"";
  4975. return qStr;
  4976. }
  4977. DbgTypedValue WinDebugger::EvaluateInContext(DbgCompileUnit* dbgCompileUnit, const DbgTypedValue& contextTypedValue, const StringImpl& subExpr, DwFormatInfo* formatInfo, String* outReferenceId, String* outErrors)
  4978. {
  4979. DbgEvaluationContext dbgEvaluationContext(this, dbgCompileUnit->mDbgModule, subExpr, formatInfo, contextTypedValue);
  4980. dbgEvaluationContext.mDbgExprEvaluator->mDbgCompileUnit = dbgCompileUnit;
  4981. if (formatInfo != NULL)
  4982. {
  4983. dbgEvaluationContext.mDbgExprEvaluator->mLanguage = formatInfo->mLanguage;
  4984. dbgEvaluationContext.mDbgExprEvaluator->mSubjectExpr = formatInfo->mSubjectExpr;
  4985. }
  4986. dbgEvaluationContext.mDbgExprEvaluator->mReferenceId = outReferenceId;
  4987. auto result = dbgEvaluationContext.EvaluateInContext(contextTypedValue);
  4988. if ((formatInfo != NULL) && (dbgEvaluationContext.mDbgExprEvaluator->mCountResultOverride != -1))
  4989. formatInfo->mOverrideCount = dbgEvaluationContext.mDbgExprEvaluator->mCountResultOverride;
  4990. if (dbgEvaluationContext.mPassInstance->HasFailed())
  4991. {
  4992. if (outErrors != NULL)
  4993. {
  4994. int errIdx = 0;
  4995. for (auto err : dbgEvaluationContext.mPassInstance->mErrors)
  4996. {
  4997. if (errIdx > 0)
  4998. (*outErrors) += "\n";
  4999. (*outErrors) += err->mError;
  5000. errIdx++;
  5001. }
  5002. }
  5003. return DbgTypedValue();
  5004. }
  5005. return result;
  5006. }
  5007. void WinDebugger::DbgVisFailed(DebugVisualizerEntry* debugVis, const StringImpl& evalString, const StringImpl& errors)
  5008. {
  5009. bool onlyMemError = errors.StartsWith("Failed to read") && !errors.Contains('\n');
  5010. if ((!debugVis->mShowedError) && (!onlyMemError))
  5011. {
  5012. debugVis->mShowedError = true;
  5013. String errStr = StrFormat("DbgVis '%s' failed while evaluating condition '%s'\n", debugVis->mName.c_str(), evalString.c_str());
  5014. String spacedErrors = errors;
  5015. spacedErrors.Insert(0, " ");
  5016. spacedErrors.Replace("\n", "\n ");
  5017. errStr += spacedErrors;
  5018. OutputMessage(errStr);
  5019. }
  5020. }
  5021. bool WinDebugger::EvalCondition(DebugVisualizerEntry* debugVis, DbgCompileUnit* dbgCompileUnit, DbgTypedValue typedVal, DwFormatInfo& formatInfo, const StringImpl& condition, const Array<String>& dbgVisWildcardCaptures, String& errorStr)
  5022. {
  5023. DwFormatInfo displayStrFormatInfo = formatInfo;
  5024. displayStrFormatInfo.mHidePointers = false;
  5025. displayStrFormatInfo.mRawString = false;
  5026. String errors;
  5027. const String conditionStr = mDebugManager->mDebugVisualizers->DoStringReplace(condition, dbgVisWildcardCaptures);
  5028. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, typedVal, conditionStr, &displayStrFormatInfo, NULL, &errors);
  5029. if ((!evalResult) || (!evalResult.mType->IsBoolean()))
  5030. {
  5031. if (formatInfo.mRawString)
  5032. return false;
  5033. errorStr += "<DbgVis Failed>";
  5034. DbgVisFailed(debugVis, conditionStr, errors);
  5035. return false;
  5036. }
  5037. return evalResult.mBool;
  5038. }
  5039. String WinDebugger::GetArrayItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgType* valueType, DbgTypedValue& curNode, int& count, String* outContinuationData)
  5040. {
  5041. DbgEvaluationContext conditionEvaluationContext(this, dbgCompileUnit, debugVis->mCondition);
  5042. String addrs;
  5043. bool checkLeft = true;
  5044. int usedCount = 0;
  5045. while (usedCount < count)
  5046. {
  5047. DbgTypedValue condVal = conditionEvaluationContext.EvaluateInContext(curNode);
  5048. if (!condVal)
  5049. break;
  5050. if (condVal.mBool)
  5051. {
  5052. auto val = curNode;
  5053. if (valueType == NULL)
  5054. {
  5055. String typeAddr = val.mType->ToStringRaw();
  5056. // RPad
  5057. typeAddr.Append(' ', sizeof(addr_target) * 2 - typeAddr.length());
  5058. addrs += typeAddr;
  5059. }
  5060. String addr = EncodeDataPtr(val.mPtr, false);
  5061. addrs += addr;
  5062. usedCount++;
  5063. }
  5064. curNode.mPtr += curNode.mType->mTypeParam->GetStride();
  5065. }
  5066. count = usedCount;
  5067. if (outContinuationData != NULL)
  5068. {
  5069. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(valueType, false) +
  5070. EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  5071. }
  5072. return addrs;
  5073. }
  5074. String WinDebugger::GetLinkedListItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, addr_target endNodePtr, DbgType* valueType, DbgTypedValue& curNode, int& count, String* outContinuationData)
  5075. {
  5076. DbgEvaluationContext nextEvaluationContext(this, dbgCompileUnit, debugVis->mNextPointer);
  5077. DbgEvaluationContext valueEvaluationContext(this, dbgCompileUnit, debugVis->mValuePointer);
  5078. String addrs;
  5079. bool checkLeft = true;
  5080. int mapIdx;
  5081. for (mapIdx = 0; mapIdx < count; mapIdx++)
  5082. {
  5083. if (curNode.mPtr == endNodePtr)
  5084. break;
  5085. DbgTypedValue val = valueEvaluationContext.EvaluateInContext(curNode);
  5086. if (!val)
  5087. break;
  5088. if (val.mPtr == 0)
  5089. break;
  5090. if (valueType == NULL)
  5091. {
  5092. String typeAddr = val.mType->ToStringRaw();
  5093. // RPad
  5094. typeAddr.Append(' ', sizeof(addr_target)*2 - typeAddr.length());
  5095. addrs += typeAddr;
  5096. }
  5097. String addr = EncodeDataPtr(val.mPtr, false);
  5098. addrs += addr;
  5099. curNode = nextEvaluationContext.EvaluateInContext(curNode);
  5100. }
  5101. count = mapIdx;
  5102. if (outContinuationData != NULL)
  5103. {
  5104. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(endNodePtr, false) + EncodeDataPtr(valueType, false) +
  5105. EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  5106. }
  5107. return addrs;
  5108. }
  5109. String WinDebugger::GetDictionaryItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgTypedValue dictValue, int bucketIdx, int nodeIdx, int& count, String* outContinuationData)
  5110. {
  5111. //DbgEvaluationContext bucketsEvaluationContext(this, dbgModule, debugVis->mBuckets);
  5112. DbgEvaluationContext nextEvaluationContext(this, dbgCompileUnit->mDbgModule, debugVis->mNextPointer);
  5113. DbgTypedValue bucketsPtr = EvaluateInContext(dbgCompileUnit, dictValue, debugVis->mBuckets);
  5114. DbgTypedValue entriesPtr = EvaluateInContext(dbgCompileUnit, dictValue, debugVis->mEntries);
  5115. if ((!bucketsPtr) || (!entriesPtr))
  5116. {
  5117. count = -1;
  5118. return "";
  5119. }
  5120. int entrySize = entriesPtr.mType->mTypeParam->GetStride();
  5121. int bucketIdxSize = bucketsPtr.mType->mTypeParam->GetStride();
  5122. String addrs;
  5123. bool checkLeft = true;
  5124. int encodeCount = 0;
  5125. while (encodeCount < count)
  5126. {
  5127. if (nodeIdx != -1)
  5128. {
  5129. DbgTypedValue entryValue;
  5130. entryValue.mSrcAddress = entriesPtr.mPtr + (nodeIdx * entrySize);
  5131. entryValue.mType = entriesPtr.mType->mTypeParam;
  5132. addrs += EncodeDataPtr(entryValue.mSrcAddress, false);
  5133. DbgTypedValue nextValue = nextEvaluationContext.EvaluateInContext(entryValue);
  5134. if ((!nextValue) || (!nextValue.mType->IsInteger()))
  5135. {
  5136. break;
  5137. }
  5138. nodeIdx = (int)nextValue.GetInt64();
  5139. encodeCount++;
  5140. }
  5141. else
  5142. {
  5143. if (bucketIdxSize == 4)
  5144. nodeIdx = ReadMemory<int>(bucketsPtr.mPtr + bucketIdx * sizeof(int32));
  5145. else
  5146. nodeIdx = (int)ReadMemory<int64>(bucketsPtr.mPtr + bucketIdx * sizeof(int64));
  5147. bucketIdx++;
  5148. }
  5149. }
  5150. count = encodeCount;
  5151. //count = mapIdx;
  5152. if (outContinuationData != NULL)
  5153. {
  5154. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(dictValue.mType, false) + EncodeDataPtr(dictValue.mSrcAddress, false) +
  5155. EncodeDataPtr((addr_target)bucketIdx, false) + EncodeDataPtr((addr_target)nodeIdx, false);
  5156. }
  5157. return addrs;
  5158. }
  5159. String WinDebugger::GetTreeItems(DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, Array<addr_target>& parentList, DbgType*& valueType, DbgTypedValue& curNode, int count, String* outContinuationData)
  5160. {
  5161. DbgEvaluationContext leftEvaluationContext(this, dbgCompileUnit, debugVis->mLeftPointer);
  5162. DbgEvaluationContext rightEvaluationContext(this, dbgCompileUnit, debugVis->mRightPointer);
  5163. DbgEvaluationContext valueEvaluationContext(this, dbgCompileUnit, debugVis->mValuePointer);
  5164. DbgEvaluationContext conditionEvaluationContext(this, dbgCompileUnit, debugVis->mCondition);
  5165. String addrs;
  5166. bool checkLeft = true;
  5167. if ((curNode.mPtr & 2) != 0) // Flag from continuation
  5168. {
  5169. checkLeft = false;
  5170. curNode.mPtr &= (addr_target)~2;
  5171. }
  5172. HashSet<intptr> seenAddrs;
  5173. for (int mapIdx = 0; mapIdx < count; mapIdx++)
  5174. {
  5175. DbgTypedValue readNode;
  5176. while (true)
  5177. {
  5178. bool checkNode = (curNode.mPtr & 1) == 0;
  5179. readNode = curNode;
  5180. readNode.mPtr &= (addr_target)~1;
  5181. if (checkLeft)
  5182. {
  5183. DbgTypedValue leftValue = leftEvaluationContext.EvaluateInContext(readNode);
  5184. bool isEmpty = leftValue.mPtr == NULL;
  5185. if ((leftValue) && (conditionEvaluationContext.HasExpression()))
  5186. {
  5187. auto condValue = conditionEvaluationContext.EvaluateInContext(leftValue);
  5188. if (condValue)
  5189. isEmpty = !condValue.mBool;
  5190. }
  5191. if (isEmpty)
  5192. {
  5193. checkLeft = false;
  5194. break; // Handle node
  5195. }
  5196. parentList.push_back(curNode.mPtr);
  5197. curNode = leftValue;
  5198. }
  5199. else if (checkNode)
  5200. {
  5201. break; // Handle node
  5202. }
  5203. else
  5204. {
  5205. DbgTypedValue rightValue = rightEvaluationContext.EvaluateInContext(readNode);
  5206. bool isEmpty = rightValue.mPtr == NULL;
  5207. if ((rightValue) && (conditionEvaluationContext.HasExpression()))
  5208. {
  5209. auto condValue = conditionEvaluationContext.EvaluateInContext(rightValue);
  5210. if (condValue)
  5211. isEmpty = !condValue.mBool;
  5212. }
  5213. if (!isEmpty)
  5214. {
  5215. curNode = rightValue;
  5216. checkLeft = true;
  5217. }
  5218. else
  5219. {
  5220. if (parentList.size() == 0)
  5221. {
  5222. // Failed
  5223. break;
  5224. }
  5225. curNode.mPtr = parentList.back();
  5226. parentList.pop_back();
  5227. continue; // Don't check against seenAddrs
  5228. }
  5229. }
  5230. if (!seenAddrs.Add(curNode.mPtr))
  5231. {
  5232. // Failed!
  5233. return "";
  5234. }
  5235. }
  5236. DbgTypedValue val = valueEvaluationContext.EvaluateInContext(readNode);
  5237. if (valueType == NULL)
  5238. valueType = val.mType;
  5239. String addr = EncodeDataPtr(val.mPtr, false);
  5240. addrs += addr;
  5241. curNode.mPtr |= 1; // Node handled
  5242. }
  5243. if (!checkLeft)
  5244. curNode.mPtr |= 2;
  5245. if (outContinuationData != NULL)
  5246. {
  5247. *outContinuationData += EncodeDataPtr(debugVis, false) + EncodeDataPtr(valueType, false) + EncodeDataPtr(curNode.mType, false) + EncodeDataPtr(curNode.mPtr, false);
  5248. for (auto parent : parentList)
  5249. *outContinuationData += EncodeDataPtr(parent, false);
  5250. }
  5251. return addrs;
  5252. }
  5253. String WinDebugger::GetCollectionContinuation(const StringImpl& continuationData, int callStackIdx, int count)
  5254. {
  5255. DbgCompileUnit* dbgCompileUnit = GetCallStackCompileUnit(callStackIdx);;
  5256. if (!IsPaused())
  5257. return "";
  5258. const char* dataPtr = continuationData.c_str();
  5259. DebugVisualizerEntry* debugVis = (DebugVisualizerEntry*)DecodeLocalDataPtr(dataPtr);
  5260. if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_TreeItems)
  5261. {
  5262. DbgType* valueType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5263. DbgTypedValue curNode;
  5264. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5265. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5266. Array<addr_target> parentList;
  5267. String newContinuationData;
  5268. while (*dataPtr != 0)
  5269. parentList.push_back(DecodeTargetDataPtr(dataPtr));
  5270. String retVal = GetTreeItems(dbgCompileUnit, debugVis, parentList, valueType, curNode, count, &newContinuationData);
  5271. retVal += "\n" + newContinuationData;
  5272. return retVal;
  5273. }
  5274. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_LinkedList)
  5275. {
  5276. addr_target endNodePtr = DecodeTargetDataPtr(dataPtr);
  5277. DbgType* valueType = (DbgType*) DecodeLocalDataPtr(dataPtr);
  5278. DbgTypedValue curNode;
  5279. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5280. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5281. String newContinuationData;
  5282. if (count < 0)
  5283. count = 3;
  5284. String retVal = GetLinkedListItems(dbgCompileUnit, debugVis, endNodePtr, valueType, curNode, count, &newContinuationData);
  5285. retVal += "\n" + newContinuationData;
  5286. return retVal;
  5287. }
  5288. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Array)
  5289. {
  5290. DbgType* valueType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5291. DbgTypedValue curNode;
  5292. curNode.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5293. curNode.mPtr = DecodeTargetDataPtr(dataPtr);
  5294. String newContinuationData;
  5295. if (count < 0)
  5296. count = 3;
  5297. String retVal = GetArrayItems(dbgCompileUnit, debugVis, valueType, curNode, count, &newContinuationData);
  5298. retVal += "\n" + newContinuationData;
  5299. return retVal;
  5300. }
  5301. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Dictionary)
  5302. {
  5303. DbgTypedValue dictValue;
  5304. dictValue.mType = (DbgType*)DecodeLocalDataPtr(dataPtr);
  5305. dictValue.mSrcAddress = DecodeTargetDataPtr(dataPtr);
  5306. int bucketIdx = (int)DecodeTargetDataPtr(dataPtr);
  5307. int nodeIdx = (int)DecodeTargetDataPtr(dataPtr);
  5308. String newContinuationData;
  5309. String retVal = GetDictionaryItems(dbgCompileUnit, debugVis, dictValue, bucketIdx, nodeIdx, count, &newContinuationData);
  5310. retVal += "\n" + newContinuationData;
  5311. return retVal;
  5312. }
  5313. return "";
  5314. }
  5315. template <typename T>
  5316. static String IntTypeToString(T val, const StringImpl& name, DwDisplayInfo* displayInfo, DwFormatInfo& formatInfo)
  5317. {
  5318. auto intDisplayType = displayInfo->mIntDisplayType;
  5319. if (formatInfo.mDisplayType == DwDisplayType_Decimal)
  5320. intDisplayType = DwIntDisplayType_Decimal;
  5321. else if (formatInfo.mDisplayType == DwDisplayType_HexUpper)
  5322. intDisplayType = DwIntDisplayType_HexadecimalUpper;
  5323. else if (formatInfo.mDisplayType == DwDisplayType_HexLower)
  5324. intDisplayType = DwIntDisplayType_HexadecimalLower;
  5325. if (intDisplayType == DwIntDisplayType_Binary)
  5326. {
  5327. String binary;
  5328. for (int i = 0; i < sizeof(T) * 8; i++)
  5329. {
  5330. if ((i != 0) && (i % 4 == 0))
  5331. binary = "'" + binary;
  5332. if ((i != 0) && (i % 16 == 0))
  5333. binary = "'" + binary;
  5334. binary = ((val & ((T)1 << i)) ? "1" : "0") + binary;
  5335. }
  5336. return StrFormat("0b'%s\n%s", binary.c_str(), name.c_str());
  5337. }
  5338. if (intDisplayType == DwIntDisplayType_Octal)
  5339. {
  5340. String format;
  5341. if (sizeof(T) == 8)
  5342. {
  5343. format = StrFormat("0o%%lo\n%s", name.c_str());
  5344. }
  5345. else
  5346. format = StrFormat("0o%%0%do\n%s", sizeof(val) * 2, name.c_str());
  5347. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5348. }
  5349. if (intDisplayType == DwIntDisplayType_HexadecimalUpper)
  5350. {
  5351. String format;
  5352. if (sizeof(T) == 8)
  5353. {
  5354. format = StrFormat("0x%%l@\n%s", name.c_str());
  5355. }
  5356. else
  5357. format = StrFormat("0x%%0%dX\n%s", sizeof(val) * 2, name.c_str());
  5358. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5359. }
  5360. //TODO: Implement HexadecimalLower
  5361. if (intDisplayType == DwIntDisplayType_HexadecimalLower)
  5362. {
  5363. String format;
  5364. if (sizeof(T) == 8)
  5365. {
  5366. format = StrFormat("0x%%l@\n%s", name.c_str());
  5367. }
  5368. else
  5369. format = StrFormat("0x%%0%dX\n%s", sizeof(val) * 2, name.c_str());
  5370. return StrFormat(format.c_str(), (std::make_unsigned<T>::type)(val));
  5371. }
  5372. if (std::is_unsigned<T>::value)
  5373. {
  5374. if (sizeof(T) == 8)
  5375. {
  5376. if (val > 0x7FFFFFFFF)
  5377. return StrFormat("%llu\n%s\n:editVal\t%lluUL", val, name.c_str(), val);
  5378. else
  5379. return StrFormat("%llu\n%s", val, name.c_str());
  5380. }
  5381. else
  5382. return StrFormat("%u\n%s", val, name.c_str());
  5383. }
  5384. else
  5385. {
  5386. if (sizeof(T) == 8)
  5387. {
  5388. if ((val > 0x7FFFFFFFF) || (val < -0x80000000LL))
  5389. return StrFormat("%lld\n%s\n:editVal\t%lldL", val, name.c_str(), val);
  5390. else
  5391. return StrFormat("%lld\n%s", val, name.c_str(), val);
  5392. }
  5393. else
  5394. return StrFormat("%d\n%s", val, name.c_str());
  5395. }
  5396. }
  5397. DwDisplayInfo* WinDebugger::GetDisplayInfo(const StringImpl& referenceId)
  5398. {
  5399. DwDisplayInfo* displayInfo = &mDebugManager->mDefaultDisplayInfo;
  5400. if (!referenceId.empty())
  5401. {
  5402. if (!mDebugManager->mDisplayInfos.TryGetValue(referenceId, &displayInfo))
  5403. {
  5404. int dollarIdx = referenceId.LastIndexOf('$');
  5405. if ((dollarIdx > 0) && (referenceId[dollarIdx - 1] == ']'))
  5406. {
  5407. // Try getting series displayinfo
  5408. mDebugManager->mDisplayInfos.TryGetValueWith(StringView(referenceId, 0, dollarIdx), &displayInfo);
  5409. }
  5410. }
  5411. }
  5412. return displayInfo;
  5413. }
  5414. static String WrapWithModifiers(const StringImpl& origName, DbgType* dbgType, DbgLanguage language)
  5415. {
  5416. if (language == DbgLanguage_Unknown)
  5417. language = dbgType->GetLanguage();
  5418. String name = origName;
  5419. while (true)
  5420. {
  5421. if (dbgType->mTypeCode == DbgType_Const)
  5422. {
  5423. if (language == DbgLanguage_Beef)
  5424. name = "readonly " + name;
  5425. else
  5426. name = "const " + name;
  5427. dbgType = dbgType->mTypeParam;
  5428. }
  5429. else if (dbgType->mTypeCode == DbgType_Volatile)
  5430. {
  5431. name = "volatile " + name;
  5432. dbgType = dbgType->mTypeParam;
  5433. }
  5434. else if (dbgType->mTypeCode == DbgType_TypeDef)
  5435. {
  5436. dbgType = dbgType->mTypeParam;
  5437. }
  5438. else if (dbgType->mTypeCode == DbgType_Ref)
  5439. {
  5440. if (language == DbgLanguage_Beef)
  5441. name = "ref " + name;
  5442. else
  5443. name = name + "&";
  5444. dbgType = dbgType->mTypeParam;
  5445. }
  5446. else if (dbgType->mTypeCode == DbgType_Bitfield)
  5447. {
  5448. return dbgType->ToString(language);
  5449. }
  5450. else
  5451. return name;
  5452. }
  5453. }
  5454. DebugVisualizerEntry* WinDebugger::FindVisualizerForType(DbgType* dbgType, Array<String>* wildcardCaptures)
  5455. {
  5456. auto entry = mDebugManager->mDebugVisualizers->FindEntryForType(dbgType->ToString(DbgLanguage_Unknown, true), dbgType->mCompileUnit->mDbgModule->mDbgFlavor, wildcardCaptures);
  5457. if (entry == NULL)
  5458. {
  5459. dbgType = dbgType->GetPrimaryType();
  5460. dbgType->PopulateType();
  5461. for (auto baseTypeEntry : dbgType->mBaseTypes)
  5462. {
  5463. entry = FindVisualizerForType(baseTypeEntry->mBaseType, wildcardCaptures);
  5464. if (entry != NULL)
  5465. break;
  5466. }
  5467. }
  5468. return entry;
  5469. }
  5470. #define GET_FROM(ptr, T) *((T*)(ptr += sizeof(T)) - 1)
  5471. String WinDebugger::ReadString(DbgTypeCode charType, intptr addr, bool isLocalAddr, intptr maxLength, DwFormatInfo& formatInfo, bool wantStringView)
  5472. {
  5473. int origMaxLength = maxLength;
  5474. if (addr == 0)
  5475. return "";
  5476. BP_ZONE("WinDebugger::ReadString");
  5477. String retVal = "\"";
  5478. bool wasTerminated = false;
  5479. String valString;
  5480. intptr maxShowSize = 255;
  5481. if (maxLength == -1)
  5482. maxLength = formatInfo.mOverrideCount;
  5483. else if (formatInfo.mOverrideCount != -1)
  5484. maxLength = BF_MIN(formatInfo.mOverrideCount, maxLength);
  5485. if (formatInfo.mMaxCount != -1)
  5486. maxLength = BF_MIN(formatInfo.mMaxCount, maxLength);
  5487. if (maxLength == -1)
  5488. maxLength = 8 * 1024 * 1024; // Is 8MB crazy?
  5489. if ((!formatInfo.mRawString) && (!wantStringView))
  5490. maxLength = BF_MIN(maxLength, maxShowSize);
  5491. if (wantStringView)
  5492. {
  5493. // Limit the original string view to 1MB, reevaluate on "More"
  5494. maxLength = BF_MIN(maxLength, 1024 * 1024);
  5495. }
  5496. //EnableMemCache();
  5497. bool readFailed = false;
  5498. intptr strPtr = addr;
  5499. int charLen = 1;
  5500. if ((charType == DbgType_SChar16) || (charType == DbgType_UChar16))
  5501. charLen = 2;
  5502. else if ((charType == DbgType_SChar32) || (charType == DbgType_UChar32))
  5503. charLen = 4;
  5504. bool isUTF8 = formatInfo.mDisplayType == DwDisplayType_Utf8;
  5505. int readSize = BF_MIN(1024, maxLength * charLen);
  5506. uint8 buf[1024];
  5507. uint8* bufPtr = NULL;
  5508. uint8* bufEnd = NULL;
  5509. bool hasHighAscii = false;
  5510. int i;
  5511. for (i = 0; i < maxLength; i++)
  5512. {
  5513. if (bufPtr >= bufEnd)
  5514. {
  5515. while (true)
  5516. {
  5517. if (readSize < charLen)
  5518. {
  5519. readFailed = true;
  5520. break;
  5521. }
  5522. if (ReadMemory(strPtr, readSize, buf, isLocalAddr))
  5523. break;
  5524. readSize /= 2;
  5525. }
  5526. if (readFailed)
  5527. break;
  5528. bufPtr = buf;
  5529. bufEnd = buf + readSize;
  5530. }
  5531. switch (charLen)
  5532. {
  5533. case 1:
  5534. {
  5535. char c = GET_FROM(bufPtr, char);
  5536. if ((c != 0) || (formatInfo.mOverrideCount != -1))
  5537. {
  5538. if ((uint8)c >= 0x80)
  5539. hasHighAscii = true;
  5540. valString.Append(c);
  5541. }
  5542. else
  5543. wasTerminated = true;
  5544. }
  5545. break;
  5546. case 2:
  5547. {
  5548. uint16 c16 = GET_FROM(bufPtr, uint16);
  5549. if ((c16 != 0) || (formatInfo.mOverrideCount != -1))
  5550. {
  5551. char str[8];
  5552. u8_toutf8(str, 8, c16);
  5553. valString += str;
  5554. }
  5555. else
  5556. wasTerminated = true;
  5557. }
  5558. break;
  5559. case 4:
  5560. {
  5561. uint32 c32 = GET_FROM(bufPtr, uint32);
  5562. if ((c32 != 0) || (formatInfo.mOverrideCount != -1))
  5563. {
  5564. char str[8];
  5565. u8_toutf8(str, 8, c32);
  5566. valString += str;
  5567. }
  5568. else
  5569. wasTerminated = true;
  5570. }
  5571. break;
  5572. }
  5573. if ((wasTerminated) && (formatInfo.mOverrideCount != -1))
  5574. {
  5575. valString += '\x00';
  5576. wasTerminated = false;
  5577. }
  5578. if ((wasTerminated) || (readFailed))
  5579. {
  5580. break;
  5581. }
  5582. strPtr += charLen;
  5583. }
  5584. //DisableMemCache();
  5585. if (formatInfo.mOverrideCount != -1)
  5586. {
  5587. if (i == formatInfo.mOverrideCount)
  5588. wasTerminated = true;
  5589. }
  5590. if (strPtr == addr + origMaxLength)
  5591. wasTerminated = true;
  5592. if (valString.length() == formatInfo.mOverrideCount)
  5593. wasTerminated = true;
  5594. // if (formatInfo.mDisplayType == DwDisplayType_Ascii)
  5595. // {
  5596. // // Our encoding for retVal is already assumed to be UTF8, so the special case here actually Ascii
  5597. // valString = UTF8Encode(ToWString(valString));
  5598. // }
  5599. if ((formatInfo.mRawString) || (wantStringView))
  5600. {
  5601. if ((formatInfo.mDisplayType == DwDisplayType_Utf8) || (!hasHighAscii))
  5602. return valString;
  5603. String utf8Str;
  5604. for (int i = 0; i < (int)valString.length(); i++)
  5605. {
  5606. char c = valString[i];
  5607. if ((uint8)c >= 0x80)
  5608. {
  5609. utf8Str += (char)(0xC0 | (((uint8)c & 0xFF) >> 6));
  5610. utf8Str += (char)(0x80 | ((uint8)c & 0x3F));
  5611. }
  5612. else
  5613. utf8Str += c;
  5614. }
  5615. return utf8Str;
  5616. }
  5617. if ((readFailed) && (valString.IsEmpty()))
  5618. return "< Failed to read string >";
  5619. retVal += SlashString(valString, true, true, formatInfo.mLanguage == DbgLanguage_Beef);
  5620. // We could go over 'maxShowSize' if we have a lot of slashed chars. An uninitialized string can be filled with '\xcc' chars
  5621. if ((!formatInfo.mRawString) && (!wantStringView) && ((int)retVal.length() > maxShowSize))
  5622. {
  5623. retVal = retVal.Substring(0, maxShowSize);
  5624. wasTerminated = false;
  5625. }
  5626. if (wasTerminated)
  5627. retVal += "\"";
  5628. else
  5629. retVal += "...";
  5630. return retVal;
  5631. }
  5632. void WinDebugger::ProcessEvalString(DbgCompileUnit* dbgCompileUnit, DbgTypedValue useTypedValue, String& evalStr, String& displayString, DwFormatInfo& formatInfo, DebugVisualizerEntry* debugVis, bool limitLength)
  5633. {
  5634. for (int i = 0; i < (int)evalStr.length(); i++)
  5635. {
  5636. char c = evalStr[i];
  5637. char nextC = 0;
  5638. if (i < (int)evalStr.length() - 1)
  5639. nextC = evalStr[i + 1];
  5640. if ((c == '{') && (nextC != '{'))
  5641. {
  5642. // Evaluate
  5643. int endIdx = i;
  5644. for (; endIdx < (int)evalStr.length(); endIdx++)
  5645. {
  5646. //TODO: Do better parsing - this paren could be inside a string, for example
  5647. if (evalStr[endIdx] == '}')
  5648. break;
  5649. }
  5650. DwFormatInfo displayStrFormatInfo = formatInfo;
  5651. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + (int)displayString.length();
  5652. displayStrFormatInfo.mHidePointers = false;
  5653. if ((limitLength) && (displayStrFormatInfo.mTotalSummaryLength > 255))
  5654. {
  5655. displayString += "...";
  5656. }
  5657. else
  5658. {
  5659. String evalString = evalStr.Substring(i + 1, endIdx - i - 1);
  5660. String errors;
  5661. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, useTypedValue, evalString, &displayStrFormatInfo, NULL, &errors);
  5662. if (evalResult)
  5663. {
  5664. if (displayStrFormatInfo.mNoEdit)
  5665. formatInfo.mNoEdit = true;
  5666. String result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  5667. if ((formatInfo.mRawString) && (limitLength))
  5668. {
  5669. displayString = result;
  5670. return;
  5671. }
  5672. int crPos = result.IndexOf('\n');
  5673. if (crPos != -1)
  5674. displayString += result.Substring(0, crPos);
  5675. else
  5676. displayString += result;
  5677. }
  5678. else if (debugVis != NULL)
  5679. {
  5680. displayString += "<DbgVis Failed>";
  5681. DbgVisFailed(debugVis, evalString, errors);
  5682. }
  5683. else
  5684. {
  5685. displayString += "<Eval Failed>";
  5686. }
  5687. }
  5688. i = endIdx;
  5689. continue;
  5690. }
  5691. else if ((c == '{') && (nextC == '{'))
  5692. {
  5693. // Skip next paren
  5694. i++;
  5695. }
  5696. else if ((c == '}') && (nextC == '}'))
  5697. {
  5698. // Skip next paren
  5699. i++;
  5700. }
  5701. displayString += c;
  5702. }
  5703. }
  5704. static bool IsNormalChar(uint32 c)
  5705. {
  5706. return (c < 0x80);
  5707. }
  5708. String WinDebugger::DbgTypedValueToString(const DbgTypedValue& origTypedValue, const StringImpl& expr, DwFormatInfo& formatInfo, DbgExprEvaluator* optEvaluator, bool fullPrecision)
  5709. {
  5710. BP_ZONE("WinDebugger::DbgTypedValueToString");
  5711. DbgTypedValue typedValue = origTypedValue;
  5712. auto dbgCompileUnit = typedValue.mType->mCompileUnit;
  5713. auto dbgModule = typedValue.mType->GetDbgModule();
  5714. auto language = origTypedValue.mType->GetLanguage();
  5715. if (language == DbgLanguage_Unknown)
  5716. language = formatInfo.mLanguage;
  5717. formatInfo.mLanguage = language;
  5718. bool isBeef = language == DbgLanguage_Beef;
  5719. char str[32];
  5720. bool readFailed = false;
  5721. bool isCompositeType = false;
  5722. bool isSizedArray = false;
  5723. bool isEnum = false;
  5724. int64 enumVal = 0;
  5725. String result;
  5726. String stringViewData;
  5727. DwDisplayInfo* displayInfo = GetDisplayInfo(formatInfo.mReferenceId);
  5728. bool wantStringView = (displayInfo->mFormatStr == "str") && (formatInfo.mAllowStringView);
  5729. DbgType* origValueType = typedValue.mType;
  5730. bool origHadRef = false;
  5731. DbgType* dwValueType = typedValue.mType->RemoveModifiers(&origHadRef);
  5732. if (dwValueType == NULL)
  5733. dwValueType = dbgModule->GetPrimitiveType(DbgType_Void, language);
  5734. else
  5735. dwValueType = dwValueType->GetPrimaryType();
  5736. if (dwValueType->mTypeCode == DbgType_TypeDef)
  5737. {
  5738. DbgTypedValue realTypedVal = typedValue;
  5739. realTypedVal.mType = dwValueType->mTypeParam;
  5740. return DbgTypedValueToString(realTypedVal, expr, formatInfo, optEvaluator);
  5741. }
  5742. if (formatInfo.mRawString)
  5743. {
  5744. if ((dwValueType->mTypeCode != DbgType_Struct) && (dwValueType->mTypeCode != DbgType_Class) && (dwValueType->mTypeCode != DbgType_Ptr) && (dwValueType->mTypeCode != DbgType_SizedArray))
  5745. return "";
  5746. }
  5747. auto _ShowArraySummary = [&](String& retVal, addr_target ptrVal, int64 arraySize, DbgType* innerType)
  5748. {
  5749. String displayString;
  5750. displayString += "{";
  5751. for (int idx = 0; idx < arraySize; idx++)
  5752. {
  5753. if (formatInfo.mTotalSummaryLength + retVal.length() + displayString.length() > 255)
  5754. {
  5755. displayString += "...";
  5756. break;
  5757. }
  5758. if ((idx != 0) && (!displayString.EndsWith('{')))
  5759. displayString += ", ";
  5760. DwFormatInfo displayStrFormatInfo = formatInfo;
  5761. displayStrFormatInfo.mExpandItemDepth = 1;
  5762. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + retVal.length() + displayString.length();
  5763. displayStrFormatInfo.mHidePointers = false;
  5764. displayStrFormatInfo.mArrayLength = -1;
  5765. // Why did we have this "na" on here? It made "void*[3]" type things show up as "{,,}"
  5766. //String evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + StrFormat(")[%d], na", idx);
  5767. String evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + StrFormat(")[%lld]", idx);
  5768. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, typedValue, evalStr, &displayStrFormatInfo);
  5769. String result;
  5770. if (evalResult)
  5771. {
  5772. result = DbgTypedValueToString(evalResult, evalStr, displayStrFormatInfo, NULL);
  5773. int crPos = result.IndexOf('\n');
  5774. if (crPos != -1)
  5775. result.RemoveToEnd(crPos);
  5776. }
  5777. else
  5778. result = "???";
  5779. displayString += result;
  5780. }
  5781. displayString += "}";
  5782. retVal += displayString;
  5783. };
  5784. if (formatInfo.mArrayLength != -1)
  5785. {
  5786. if (formatInfo.mRawString)
  5787. return "";
  5788. if (dwValueType->IsPointer())
  5789. {
  5790. String retVal;
  5791. addr_target ptrVal = (addr_target)typedValue.mPtr;
  5792. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  5793. {
  5794. retVal = EncodeDataPtr(ptrVal, true) + " ";
  5795. retVal += dwValueType->mTypeParam->ToString(language);
  5796. retVal += StrFormat("[%lld] ", (int64)formatInfo.mArrayLength);
  5797. }
  5798. _ShowArraySummary(retVal, ptrVal, formatInfo.mArrayLength, dwValueType->mTypeParam);
  5799. String idxStr = "[{0}]";
  5800. DbgType* innerType = dwValueType->mTypeParam;
  5801. retVal += "\n" + dwValueType->ToString(language);
  5802. String evalStr = "*((" + typedValue.mType->ToStringRaw(language) + ")" + EncodeDataPtr(ptrVal, true) + " + {0})";
  5803. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, (int)BF_MAX(formatInfo.mArrayLength, 0), 10000) +
  5804. "\t" + idxStr + "\t" + evalStr;
  5805. return retVal;
  5806. }
  5807. else
  5808. {
  5809. DwFormatInfo newFormatInfo = formatInfo;
  5810. newFormatInfo.mArrayLength = -1;
  5811. String retVal = DbgTypedValueToString(typedValue, expr, newFormatInfo, optEvaluator);
  5812. int crPos = (int)retVal.IndexOf('\n');
  5813. if (crPos != -1)
  5814. retVal = "!Array length flag not valid with this type" + retVal.Substring(crPos);
  5815. return retVal;
  5816. }
  5817. }
  5818. switch (dwValueType->mTypeCode)
  5819. {
  5820. case DbgType_Void:
  5821. return "\nvoid";
  5822. case DbgType_Bool:
  5823. {
  5824. if (typedValue.mUInt8 == 0)
  5825. return "false\n" + WrapWithModifiers("bool", origValueType, language);
  5826. else if (typedValue.mUInt8 == 1)
  5827. return "true\n" + WrapWithModifiers("bool", origValueType, language);
  5828. else
  5829. return StrFormat("true (%d)\n", typedValue.mUInt8) + WrapWithModifiers("bool", origValueType, language);
  5830. }
  5831. break;
  5832. case DbgType_UChar:
  5833. if (language != DbgLanguage_Beef)
  5834. return IntTypeToString<uint8>(typedValue.mUInt8, WrapWithModifiers("uint8_t", origValueType, language), displayInfo, formatInfo);
  5835. case DbgType_SChar:
  5836. {
  5837. if (typedValue.mInt8 != 0)
  5838. {
  5839. char str[2] = {(char)typedValue.mInt8};
  5840. result = SlashString(str, formatInfo.mDisplayType == DwDisplayType_Utf8, true);
  5841. if (!IsNormalChar(typedValue.mUInt8))
  5842. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt8);
  5843. else
  5844. result = StrFormat("'%s'\n", result.c_str());
  5845. }
  5846. else
  5847. result = "'\\0'\n";
  5848. return result + WrapWithModifiers("char", origValueType, language);
  5849. }
  5850. break;
  5851. case DbgType_UChar16:
  5852. if (language != DbgLanguage_Beef)
  5853. return IntTypeToString<int16>(typedValue.mUInt8, WrapWithModifiers("uint16_t", origValueType, language), displayInfo, formatInfo);
  5854. case DbgType_SChar16:
  5855. {
  5856. if (typedValue.mInt16 != 0)
  5857. {
  5858. u8_toutf8(str, 8, typedValue.mUInt32);
  5859. result = SlashString(str, true, true);
  5860. if (!IsNormalChar(typedValue.mUInt32))
  5861. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt16);
  5862. else
  5863. result = StrFormat("'%s'\n", result.c_str());
  5864. }
  5865. else
  5866. result = "'\\0'\n";
  5867. return result + WrapWithModifiers(isBeef ? "char16" : "int16_t", origValueType, language);
  5868. }
  5869. break;
  5870. case DbgType_UChar32:
  5871. case DbgType_SChar32:
  5872. {
  5873. if (typedValue.mInt32 != 0)
  5874. {
  5875. u8_toutf8(str, 8, typedValue.mUInt32);
  5876. result = SlashString(str, true, true);
  5877. if (!IsNormalChar(typedValue.mUInt32))
  5878. result = StrFormat("'%s' (0x%02X)\n", result.c_str(), typedValue.mUInt32);
  5879. else
  5880. result = StrFormat("'%s'\n", result.c_str());
  5881. }
  5882. else
  5883. result = "'\\0'\n";
  5884. return result + WrapWithModifiers(isBeef ? "char32" : "int32_t", origValueType, language);
  5885. }
  5886. break;
  5887. case DbgType_i8:
  5888. return IntTypeToString<int8>(typedValue.mInt8, WrapWithModifiers(isBeef ? "int8" : "int8_t", origValueType, language), displayInfo, formatInfo);
  5889. case DbgType_u8:
  5890. return IntTypeToString<uint8>(typedValue.mUInt8, WrapWithModifiers(isBeef ? "uint8" : "uint8_t", origValueType, language), displayInfo, formatInfo);
  5891. case DbgType_i16:
  5892. return IntTypeToString<int16>(typedValue.mInt16, WrapWithModifiers(isBeef ? "int16" : "int16_t", origValueType, language), displayInfo, formatInfo);
  5893. case DbgType_u16:
  5894. return IntTypeToString<uint16>(typedValue.mUInt16, WrapWithModifiers(isBeef ? "uint16" : "uint16_t", origValueType, language), displayInfo, formatInfo);
  5895. case DbgType_i32:
  5896. return IntTypeToString<int32>(typedValue.mInt32, WrapWithModifiers(isBeef ? "int32" : "int32_t", origValueType, language), displayInfo, formatInfo);
  5897. case DbgType_u32:
  5898. return IntTypeToString<uint32>(typedValue.mUInt32, WrapWithModifiers(isBeef ? "uint32" : "uint32_t", origValueType, language), displayInfo, formatInfo);
  5899. case DbgType_i64:
  5900. return IntTypeToString<int64>(typedValue.mInt64, WrapWithModifiers(isBeef ? "int64" : "int64_t", origValueType, language), displayInfo, formatInfo);
  5901. case DbgType_u64:
  5902. return IntTypeToString<uint64>(typedValue.mUInt64, WrapWithModifiers(isBeef ? "uint64" : "uint64_t", origValueType, language), displayInfo, formatInfo);
  5903. case DbgType_RegGroup:
  5904. {
  5905. if ((typedValue.mRegNum >= CPUReg_M128_XMMREG_FIRST) && (typedValue.mRegNum <= CPUReg_M128_XMMREG_LAST))
  5906. {
  5907. int callStackIdx = formatInfo.mCallStackIdx;
  5908. FixCallStackIdx(callStackIdx);
  5909. UpdateRegisterUsage(callStackIdx);
  5910. WdStackFrame* wdStackFrame = mCallStack[callStackIdx];
  5911. RegForm regForm = RegForm_Unknown;
  5912. if (typedValue.mRegNum < (int)wdStackFrame->mRegForms.size())
  5913. regForm = wdStackFrame->mRegForms[typedValue.mRegNum];
  5914. int xmmMajor = typedValue.mRegNum - CPUReg_M128_XMMREG_FIRST;
  5915. String headerStr;
  5916. String xmmType = "__m128";
  5917. int xmmCount = 4;
  5918. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2) ||
  5919. (regForm == RegForm_Long) || (regForm == RegForm_Long2) ||
  5920. (regForm == RegForm_ULong) || (regForm == RegForm_ULong2))
  5921. xmmCount = 2;
  5922. //TODO: add byte, short, int, etc...
  5923. if (optEvaluator)
  5924. {
  5925. DwMmDisplayType mmDwMmDisplayType = displayInfo->mMmDisplayType;
  5926. if (mmDwMmDisplayType == DwMmDisplayType_Default)
  5927. {
  5928. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2))
  5929. mmDwMmDisplayType = DwMmDisplayType_Double;
  5930. else if (regForm == RegForm_Int4)
  5931. mmDwMmDisplayType = DwMmDisplayType_Int32;
  5932. }
  5933. if (mmDwMmDisplayType == DwMmDisplayType_Double)
  5934. {
  5935. xmmType = "__m128d";
  5936. xmmCount = 2;
  5937. double xmmRegVals[2];
  5938. CPURegisters* regs = optEvaluator->GetRegisters();
  5939. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5940. {
  5941. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5942. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_Double);
  5943. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5944. xmmRegVals[xmmMinor] = xmmReg.mDouble;
  5945. }
  5946. headerStr = StrFormat("(%f, %f)", xmmRegVals[0], xmmRegVals[1]);
  5947. }
  5948. else if (mmDwMmDisplayType == DwMmDisplayType_UInt8)
  5949. {
  5950. int xmmRegVals[4];
  5951. xmmCount = 16;
  5952. CPURegisters* regs = optEvaluator->GetRegisters();
  5953. for (int xmmMinor = 0; xmmMinor < BF_ARRAY_COUNT(xmmRegVals); ++xmmMinor)
  5954. {
  5955. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5956. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i32);
  5957. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5958. xmmRegVals[xmmMinor] = xmmReg.mInt32;
  5959. }
  5960. headerStr = StrFormat("(%d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d)",
  5961. xmmRegVals[0] & 0xFF, (xmmRegVals[0] >> 8) & 0xFF, (xmmRegVals[0] >> 16) & 0xFF, (xmmRegVals[0] >> 24) & 0xFF,
  5962. xmmRegVals[1] & 0xFF, (xmmRegVals[1] >> 8) & 0xFF, (xmmRegVals[1] >> 16) & 0xFF, (xmmRegVals[1] >> 24) & 0xFF,
  5963. xmmRegVals[2] & 0xFF, (xmmRegVals[2] >> 8) & 0xFF, (xmmRegVals[2] >> 16) & 0xFF, (xmmRegVals[2] >> 24) & 0xFF,
  5964. xmmRegVals[3] & 0xFF, (xmmRegVals[3] >> 8) & 0xFF, (xmmRegVals[3] >> 16) & 0xFF, (xmmRegVals[3] >> 24) & 0xFF);
  5965. }
  5966. else if (mmDwMmDisplayType == DwMmDisplayType_Int16)
  5967. {
  5968. int xmmRegVals[4];
  5969. xmmCount = 8;
  5970. CPURegisters* regs = optEvaluator->GetRegisters();
  5971. for (int xmmMinor = 0; xmmMinor < BF_ARRAY_COUNT(xmmRegVals); ++xmmMinor)
  5972. {
  5973. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5974. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i32);
  5975. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5976. xmmRegVals[xmmMinor] = xmmReg.mInt32;
  5977. }
  5978. headerStr = StrFormat("(%d, %d, %d, %d, %d, %d, %d, %d)",
  5979. xmmRegVals[0] & 0xFFFF, (xmmRegVals[0] >> 16) & 0xFFFF,
  5980. xmmRegVals[1] & 0xFFFF, (xmmRegVals[1] >> 16) & 0xFFFF,
  5981. xmmRegVals[2] & 0xFFFF, (xmmRegVals[2] >> 16) & 0xFFFF,
  5982. xmmRegVals[3] & 0xFFFF, (xmmRegVals[3] >> 16) & 0xFFFF);
  5983. }
  5984. else if (mmDwMmDisplayType == DwMmDisplayType_Int32)
  5985. {
  5986. int xmmRegVals[4];
  5987. xmmCount = 4;
  5988. CPURegisters* regs = optEvaluator->GetRegisters();
  5989. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  5990. {
  5991. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  5992. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i32);
  5993. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  5994. xmmRegVals[xmmMinor] = xmmReg.mInt32;
  5995. }
  5996. headerStr = StrFormat("(%d, %d, %d, %d)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  5997. }
  5998. else if (mmDwMmDisplayType == DwMmDisplayType_Int64)
  5999. {
  6000. int64 xmmRegVals[2];
  6001. xmmCount = 2;
  6002. CPURegisters* regs = optEvaluator->GetRegisters();
  6003. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  6004. {
  6005. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  6006. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_i64);
  6007. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  6008. xmmRegVals[xmmMinor] = xmmReg.mInt64;
  6009. }
  6010. headerStr = StrFormat("(%lld, %lld)", xmmRegVals[0], xmmRegVals[1]);
  6011. }
  6012. else // float
  6013. {
  6014. float xmmRegVals[4];
  6015. xmmCount = 4;
  6016. CPURegisters* regs = optEvaluator->GetRegisters();
  6017. for (int xmmMinor = 0; xmmMinor < xmmCount; ++xmmMinor)
  6018. {
  6019. DbgTypedValue xmmReg = GetRegister(StrFormat("xmm%d_%d", xmmMajor, xmmMinor), language, regs, &wdStackFrame->mRegForms);
  6020. BF_ASSERT(xmmReg.mType->mTypeCode == DbgType_Single);
  6021. BF_ASSERT(xmmReg.mRegNum == CPUReg_XMMREG_FIRST + (xmmMajor * 4) + xmmMinor);
  6022. xmmRegVals[xmmMinor] = xmmReg.mSingle;
  6023. }
  6024. headerStr = StrFormat("(%f, %f, %f, %f)", xmmRegVals[0], xmmRegVals[1], xmmRegVals[2], xmmRegVals[3]);
  6025. }
  6026. }
  6027. else
  6028. {
  6029. headerStr = StrFormat("XMM%d", xmmMajor);
  6030. }
  6031. result = headerStr + "\n" + xmmType;
  6032. for (int i = 0; i < xmmCount; i++)
  6033. {
  6034. if (xmmCount == 16)
  6035. result += WrapWithModifiers(StrFormat("\n[%d]\t(uint8)($xmm%d_%d >> %d)", i, xmmMajor, i / 4, (i % 4)*8), origValueType, language);
  6036. else if (xmmCount == 8)
  6037. result += WrapWithModifiers(StrFormat("\n[%d]\t(int16)($xmm%d_%d >> %d)", i, xmmMajor, i / 2, (i % 2)*8), origValueType, language);
  6038. else
  6039. result += WrapWithModifiers(StrFormat("\n[%d]\t$xmm%d_%d", i, xmmMajor, i), origValueType, language);
  6040. }
  6041. return result;
  6042. }
  6043. else
  6044. {
  6045. switch (typedValue.mRegNum)
  6046. {
  6047. case CPUReg_CAT_ALLREGS:
  6048. {
  6049. return "ALLREGS\n__allregs\niregs\t$iregs\nflags\t$flags\nfpregs\t$fpregs\nmmregs\t$mmregs\nxmmregs\t$xmmregs";
  6050. }
  6051. break;
  6052. case CPUReg_CAT_IREGS:
  6053. {
  6054. #ifdef BF_DBG_32
  6055. String headerStr;
  6056. if (optEvaluator)
  6057. {
  6058. CPURegisters* regs = optEvaluator->GetRegisters();
  6059. 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)",
  6060. (uint32)regs->mIntRegs.eax, (uint32)regs->mIntRegs.ebx, (uint32)regs->mIntRegs.ecx, (uint32)regs->mIntRegs.edx,
  6061. (uint32)regs->mIntRegs.esi, (uint32)regs->mIntRegs.edi, (uint32)regs->mIntRegs.esp, (uint32)regs->mIntRegs.ebp,
  6062. (uint32)regs->mIntRegs.eip, (uint32)regs->mIntRegs.efl);
  6063. }
  6064. else
  6065. {
  6066. headerStr = "IREGS";
  6067. }
  6068. 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());
  6069. #else
  6070. String headerStr;
  6071. if (optEvaluator)
  6072. {
  6073. CPURegisters* regs = optEvaluator->GetRegisters();
  6074. 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)",
  6075. (uint64)regs->mIntRegs.rax, (uint64)regs->mIntRegs.rbx, (uint64)regs->mIntRegs.rcx, (uint64)regs->mIntRegs.rdx,
  6076. (uint64)regs->mIntRegs.rsi, (uint64)regs->mIntRegs.rdi, (uint64)regs->mIntRegs.rsp, (uint64)regs->mIntRegs.rbp,
  6077. (uint64)regs->mIntRegs.rip,
  6078. (uint64)regs->mIntRegs.r8, (uint64)regs->mIntRegs.r9, (uint64)regs->mIntRegs.r10, (uint64)regs->mIntRegs.r11,
  6079. (uint64)regs->mIntRegs.r12, (uint64)regs->mIntRegs.r13, (uint64)regs->mIntRegs.r14, (uint64)regs->mIntRegs.r15,
  6080. (uint32)regs->mIntRegs.efl);
  6081. }
  6082. else
  6083. {
  6084. headerStr = "IREGS";
  6085. }
  6086. 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());
  6087. #endif
  6088. }
  6089. break;
  6090. case CPUReg_CAT_FPREGS:
  6091. {
  6092. String headerStr;
  6093. if (optEvaluator)
  6094. {
  6095. CPURegisters* regs = optEvaluator->GetRegisters();
  6096. headerStr = "(";
  6097. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6098. {
  6099. if (i)
  6100. headerStr += ", ";
  6101. double val = ConvertFloat80ToDouble(regs->mFpMmRegsArray[i].fp.fp80);
  6102. headerStr += StrFormat("%f", val);
  6103. }
  6104. headerStr += ")";
  6105. }
  6106. else
  6107. {
  6108. headerStr = "FPREGS";
  6109. }
  6110. result = StrFormat("%s\n__fpregs", headerStr.c_str());
  6111. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6112. result += StrFormat("\n[%d]\t$st%d", i, i);
  6113. return result;
  6114. }
  6115. break;
  6116. case CPUReg_CAT_MMREGS:
  6117. {
  6118. String headerStr;
  6119. if (optEvaluator)
  6120. {
  6121. CPURegisters* regs = optEvaluator->GetRegisters();
  6122. headerStr = "(";
  6123. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6124. {
  6125. if (i)
  6126. headerStr += ", ";
  6127. uint64 val = regs->mFpMmRegsArray[i].mm;
  6128. headerStr += StrFormat("0x%016llx", val);
  6129. }
  6130. headerStr += ")";
  6131. }
  6132. else
  6133. {
  6134. headerStr = "MMREGS";
  6135. }
  6136. result = StrFormat("%s\n__mmregs", headerStr.c_str());
  6137. for (int i = 0; i < CPURegisters::kNumFpMmRegs; ++i)
  6138. result += StrFormat("\n[%d]\t$mm%d", i, i);
  6139. return result;
  6140. }
  6141. break;
  6142. case CPUReg_CAT_XMMREGS:
  6143. {
  6144. String headerStr = StrFormat("XMMREGS[%d]", CPURegisters::kNumXmmRegs); // these are too big to put a useful header for the entire category
  6145. result = StrFormat("%s\n__xmmregs", headerStr.c_str());
  6146. for (int i = 0; i < CPURegisters::kNumXmmRegs; ++i)
  6147. result += StrFormat("\n[%d]\t$xmm%d", i, i);
  6148. return result;
  6149. }
  6150. break;
  6151. case CPUReg_CAT_FLAGS:
  6152. {
  6153. String headerStr;
  6154. if (optEvaluator)
  6155. {
  6156. CPURegisters* regs = optEvaluator->GetRegisters();
  6157. #ifdef BF_DBG_32
  6158. #define FLAGVAR(abbr, name) int flag##abbr = ((regs->mIntRegs.efl & ((uint64)1 << CPURegisters::GetFlagBitForRegister(X86Reg_FLAG_##abbr##_##name))) != 0) ? 1 : 0
  6159. FLAGVAR(CF, CARRY);
  6160. FLAGVAR(PF, PARITY);
  6161. FLAGVAR(AF, ADJUST);
  6162. FLAGVAR(ZF, ZERO);
  6163. FLAGVAR(SF, SIGN);
  6164. FLAGVAR(IF, INTERRUPT);
  6165. FLAGVAR(DF, DIRECTION);
  6166. FLAGVAR(OF, OVERFLOW);
  6167. #undef FLAGVAR
  6168. #else
  6169. #define FLAGVAR(abbr, name) int flag##abbr = ((regs->mIntRegs.efl & ((uint64)1 << CPURegisters::GetFlagBitForRegister(X64Reg_FLAG_##abbr##_##name))) != 0) ? 1 : 0
  6170. FLAGVAR(CF, CARRY);
  6171. FLAGVAR(PF, PARITY);
  6172. FLAGVAR(AF, ADJUST);
  6173. FLAGVAR(ZF, ZERO);
  6174. FLAGVAR(SF, SIGN);
  6175. FLAGVAR(IF, INTERRUPT);
  6176. FLAGVAR(DF, DIRECTION);
  6177. FLAGVAR(OF, OVERFLOW);
  6178. #undef FLAGVAR
  6179. #endif
  6180. headerStr = StrFormat("(CF=%d, PF=%d, AF=%d, ZF=%d, SF=%d, IF=%d, DF=%d, OF=%d)",
  6181. flagCF, flagPF, flagAF, flagZF, flagSF, flagIF, flagDF, flagOF);
  6182. }
  6183. else
  6184. {
  6185. headerStr = "FLAGS";
  6186. }
  6187. 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",
  6188. headerStr.c_str());
  6189. }
  6190. break;
  6191. default:
  6192. BF_ASSERT(false && "unknown category register");
  6193. return "UNKNOWNCATEGORY\n__unknown\n";
  6194. }
  6195. }
  6196. }
  6197. break;
  6198. case DbgType_Single:
  6199. {
  6200. DwFloatDisplayType floatDisplayType = displayInfo->mFloatDisplayType;
  6201. if (floatDisplayType == DwFloatDisplayType_Default)
  6202. floatDisplayType = DwFloatDisplayType_Minimal;
  6203. if (floatDisplayType == DwFloatDisplayType_Minimal)
  6204. ExactMinimalFloatToStr(typedValue.mSingle, str);
  6205. else if (floatDisplayType == DwFloatDisplayType_Full)
  6206. sprintf(str, "%1.9g", typedValue.mSingle);
  6207. else if (floatDisplayType == DwFloatDisplayType_HexUpper)
  6208. sprintf(str, "0x%04X", typedValue.mUInt32);
  6209. else //if (floatDisplayType == DwFloatDisplayType_HexLower)
  6210. sprintf(str, "0x%04x", typedValue.mUInt32);
  6211. return StrFormat("%s\n%s", str, WrapWithModifiers("float", origValueType, language).c_str());
  6212. }
  6213. case DbgType_Double:
  6214. {
  6215. DwFloatDisplayType floatDisplayType = displayInfo->mFloatDisplayType;
  6216. if (floatDisplayType == DwFloatDisplayType_Default)
  6217. floatDisplayType = DwFloatDisplayType_Minimal;
  6218. if (floatDisplayType == DwFloatDisplayType_Minimal)
  6219. ExactMinimalDoubleToStr(typedValue.mDouble, str);
  6220. else if (floatDisplayType == DwFloatDisplayType_Full)
  6221. sprintf(str, "%1.17g", typedValue.mDouble);
  6222. else if (floatDisplayType == DwFloatDisplayType_HexUpper)
  6223. sprintf(str, "0x%08llX", typedValue.mUInt64);
  6224. else //if (floatDisplayType == DwFloatDisplayType_HexLower)
  6225. sprintf(str, "0x%08llx", typedValue.mUInt64);
  6226. return StrFormat("%s\n%s", str, WrapWithModifiers("double", origValueType, language).c_str());
  6227. }
  6228. case DbgType_Subroutine:
  6229. if (typedValue.mCharPtr != NULL)
  6230. return StrFormat("%s\nfunc", typedValue.mCharPtr);
  6231. else
  6232. return "\nfunc";
  6233. case DbgType_RawText:
  6234. return StrFormat("%s\nrawtext", typedValue.mCharPtr);
  6235. case DbgType_Ptr:
  6236. {
  6237. addr_target ptrVal = (addr_target)typedValue.mPtr;
  6238. String retVal;
  6239. DbgType* innerType = dwValueType->mTypeParam;
  6240. if (innerType == NULL)
  6241. return EncodeDataPtr(ptrVal, true) + "\nvoid*";
  6242. bool isChar = false;
  6243. DbgType* unmodInnerType = innerType->RemoveModifiers();
  6244. if (unmodInnerType != NULL)
  6245. {
  6246. if (language == DbgLanguage_Beef)
  6247. {
  6248. if ((unmodInnerType->mTypeCode == DbgType_UChar) ||
  6249. (unmodInnerType->mTypeCode == DbgType_UChar16) ||
  6250. (unmodInnerType->mTypeCode == DbgType_UChar32))
  6251. isChar = true;
  6252. }
  6253. else
  6254. {
  6255. if ((unmodInnerType->mTypeCode == DbgType_SChar) ||
  6256. (unmodInnerType->mTypeCode == DbgType_SChar16) ||
  6257. (unmodInnerType->mTypeCode == DbgType_SChar32))
  6258. isChar = true;
  6259. }
  6260. }
  6261. if ((isChar) && (formatInfo.mArrayLength == -1))
  6262. {
  6263. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6264. retVal = EncodeDataPtr(ptrVal, true);
  6265. int strLen = formatInfo.mOverrideCount;
  6266. if (typedValue.mIsLiteral)
  6267. {
  6268. if (strLen == -1)
  6269. strLen = 0x7FFFFFFF;
  6270. if (typedValue.mDataLen > 0)
  6271. strLen = BF_MIN(strLen, typedValue.mDataLen);
  6272. else
  6273. strLen = BF_MIN(strLen, strlen(typedValue.mCharPtr));
  6274. }
  6275. SetAndRestoreValue<intptr> prevOverrideLen(formatInfo.mOverrideCount, strLen);
  6276. String strResult = ReadString(unmodInnerType->mTypeCode, typedValue.mLocalIntPtr, typedValue.mIsLiteral, strLen, formatInfo, wantStringView);
  6277. if (formatInfo.mRawString)
  6278. return strResult;
  6279. if (!strResult.IsEmpty())
  6280. {
  6281. if (!retVal.IsEmpty())
  6282. retVal += " ";
  6283. if (!wantStringView)
  6284. retVal += strResult;
  6285. }
  6286. retVal += "\n" + origValueType->ToString(language);
  6287. retVal += "\n:stringView";
  6288. if (wantStringView)
  6289. {
  6290. retVal += "\t";
  6291. retVal += SlashString(strResult, false, false, true);
  6292. }
  6293. return retVal;
  6294. }
  6295. else if ((unmodInnerType != NULL) &&
  6296. ((unmodInnerType->mTypeCode == DbgType_Class) || (unmodInnerType->mTypeCode == DbgType_Struct) || (unmodInnerType->mTypeCode == DbgType_Union)))
  6297. {
  6298. isCompositeType = true;
  6299. }
  6300. else if ((unmodInnerType != NULL) && (unmodInnerType->mTypeCode == DbgType_SizedArray))
  6301. {
  6302. isSizedArray = true;
  6303. }
  6304. else if (unmodInnerType->mTypeCode == DbgType_Subroutine)
  6305. {
  6306. if (formatInfo.mRawString)
  6307. return "";
  6308. addr_target funcPtr = (addr_target)typedValue.mPtr;
  6309. String retVal;
  6310. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6311. retVal = EncodeDataPtr(funcPtr, true);
  6312. String symbolName;
  6313. addr_target offset;
  6314. DbgModule* dwarf;
  6315. static String demangledName;
  6316. auto subProgram = mDebugTarget->FindSubProgram(funcPtr);
  6317. if (subProgram != NULL)
  6318. {
  6319. demangledName = subProgram->ToString();
  6320. }
  6321. else if (mDebugTarget->FindSymbolAt(funcPtr, &symbolName, &offset, &dwarf))
  6322. {
  6323. demangledName = BfDemangler::Demangle(symbolName, language);
  6324. if (offset != 0)
  6325. demangledName += StrFormat("+%d", offset);
  6326. }
  6327. else
  6328. {
  6329. auto dbgModule = mDebugTarget->FindDbgModuleForAddress(funcPtr);
  6330. if (dbgModule != NULL)
  6331. demangledName += dbgModule->GetLinkedModule()->mDisplayName + "!";
  6332. demangledName += StrFormat("0x%@", funcPtr);
  6333. }
  6334. retVal += " {";
  6335. retVal += demangledName;
  6336. retVal += "}";
  6337. retVal += "\n" + origValueType->ToString(language);
  6338. return retVal;
  6339. }
  6340. else if (unmodInnerType->mTypeCode == DbgType_Void)
  6341. {
  6342. if (formatInfo.mRawString)
  6343. return "";
  6344. addr_target ptr = (addr_target)typedValue.mPtr;
  6345. String symbolName;
  6346. addr_target offset;
  6347. DbgModule* dwarf;
  6348. String demangledName;
  6349. retVal += demangledName = StrFormat("0x%@", ptr);
  6350. if (mDebugTarget->FindSymbolAt(ptr, &symbolName, &offset, &dwarf))
  6351. {
  6352. if (offset == 0)
  6353. {
  6354. retVal += " {";
  6355. retVal += BfDemangler::Demangle(symbolName, language);
  6356. retVal += "}";
  6357. }
  6358. }
  6359. retVal += "\n" + origValueType->ToString(language);
  6360. return retVal;
  6361. }
  6362. else
  6363. {
  6364. if (formatInfo.mRawString)
  6365. return "";
  6366. addr_target ptrVal = (addr_target)typedValue.mPtr;
  6367. String retVal;
  6368. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6369. retVal = EncodeDataPtr(ptrVal, true);
  6370. if (ptrVal != 0)
  6371. {
  6372. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, NULL, -1, -1);
  6373. DbgTypedValue innerTypedVal = dbgExprEvaluator.ReadTypedValue(NULL, innerType, typedValue.mPtr, DbgAddrType_Target);
  6374. if (innerTypedVal)
  6375. {
  6376. DwFormatInfo defaultFormatInfo;
  6377. defaultFormatInfo.mLanguage = formatInfo.mLanguage;
  6378. defaultFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + 2; // Take into accout the necessary {}'s
  6379. defaultFormatInfo.mExpandItemDepth++;
  6380. String innerStr = DbgTypedValueToString(innerTypedVal, "", defaultFormatInfo, &dbgExprEvaluator);
  6381. int crIdx = innerStr.IndexOf('\n');
  6382. if (crIdx != -1)
  6383. {
  6384. String innerDataStr = innerStr.Substring(0, crIdx);
  6385. if (!innerDataStr.empty())
  6386. {
  6387. if (!retVal.empty())
  6388. retVal += " ";
  6389. retVal += "{" + innerDataStr + "}";
  6390. }
  6391. }
  6392. else
  6393. {
  6394. retVal += "{ ??? }";
  6395. }
  6396. }
  6397. }
  6398. retVal += "\n" + origValueType->ToString(language);
  6399. innerType->PopulateType();
  6400. if ((ptrVal != 0) &&
  6401. ((!innerType->mMemberList.IsEmpty()) || (innerType->mSize > 0) || (innerType->mTypeParam != NULL)))
  6402. {
  6403. String ptrDataStr = StrFormat("(%s)", dwValueType->ToStringRaw(language).c_str()) + EncodeDataPtr(typedValue.mPtr, true);
  6404. retVal += "\n*\t";
  6405. // Why did we have this? It messed up a pointer to sized array
  6406. /*if (language == DbgLanguage_Beef)
  6407. retVal += "this";
  6408. else*/
  6409. retVal += "*this";
  6410. if (!formatInfo.mReferenceId.empty())
  6411. retVal += ", refid=" + MaybeQuoteFormatInfoParam(formatInfo.mReferenceId);
  6412. retVal += ", this=" + ptrDataStr;
  6413. }
  6414. return retVal;
  6415. }
  6416. break;
  6417. }
  6418. case DbgType_Union:
  6419. case DbgType_Class:
  6420. case DbgType_Struct:
  6421. isCompositeType = true;
  6422. break;
  6423. case DbgType_Enum:
  6424. enumVal = typedValue.GetInt64();
  6425. isEnum = true;
  6426. break;
  6427. case DbgType_SizedArray:
  6428. {
  6429. isSizedArray = true;
  6430. }
  6431. break;
  6432. default:
  6433. break;
  6434. }
  6435. if (isSizedArray)
  6436. {
  6437. String retVal;
  6438. addr_target ptrVal = 0;
  6439. DbgType* arrayType = dwValueType;
  6440. DbgType* innerType = dwValueType->mTypeParam;
  6441. if (dwValueType->mTypeCode == DbgType_SizedArray)
  6442. {
  6443. ptrVal = (addr_target)typedValue.mSrcAddress;
  6444. }
  6445. else
  6446. {
  6447. BF_ASSERT(dwValueType->mTypeCode == DbgType_Ptr);
  6448. arrayType = innerType;
  6449. innerType = arrayType->mTypeParam;
  6450. ptrVal = typedValue.mPtr;
  6451. if ((!typedValue.mIsLiteral) && (!formatInfo.mHidePointers))
  6452. retVal = EncodeDataPtr(ptrVal, true) + " ";
  6453. }
  6454. if (ptrVal == 0)
  6455. ptrVal = typedValue.mPtr;
  6456. intptr arraySize = 0;
  6457. intptr innerSize = innerType->GetStride();
  6458. if (innerSize > 0)
  6459. arraySize = arrayType->GetStride() / innerSize;
  6460. else
  6461. {
  6462. // Failure!
  6463. }
  6464. String idxStr = "[{0}]";
  6465. if (innerType->IsChar(language))
  6466. {
  6467. String strVal = ReadString(innerType->mTypeCode, typedValue.mSrcAddress, false, arraySize, formatInfo, false);
  6468. if (formatInfo.mRawString)
  6469. return strVal;
  6470. retVal += strVal;
  6471. }
  6472. else
  6473. {
  6474. if (formatInfo.mRawString)
  6475. return "";
  6476. _ShowArraySummary(retVal, ptrVal, arraySize, innerType);
  6477. }
  6478. retVal += "\n" + origValueType->ToString(language);
  6479. String referenceId = dwValueType->ToString(language);
  6480. String evalStr;
  6481. // Why did we have the "na"? Do we not want to show addresses for all members?
  6482. evalStr = "((" + innerType->ToStringRaw(language) + "*)" + EncodeDataPtr(ptrVal, true) + ")[{0}], refid=" + MaybeQuoteFormatInfoParam(referenceId + ".[]");
  6483. if (typedValue.mIsReadOnly)
  6484. evalStr += ", ne";
  6485. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, (int)BF_MAX(arraySize, 0), 10000) +
  6486. "\t" + idxStr + "\t" + evalStr;
  6487. return retVal;
  6488. }
  6489. dwValueType->PopulateType();
  6490. if (isEnum)
  6491. {
  6492. String retVal;
  6493. int64 bitsLeft = enumVal;
  6494. int valueCount = 0;
  6495. String editVal;
  6496. dwValueType = dwValueType->GetPrimaryType();
  6497. dwValueType->PopulateType();
  6498. while ((bitsLeft != 0) || (valueCount == 0))
  6499. {
  6500. DbgVariable* bestMatch = NULL;
  6501. for (auto member : dwValueType->mMemberList)
  6502. {
  6503. if (member->mConstValue == bitsLeft)
  6504. {
  6505. bestMatch = member;
  6506. break;
  6507. }
  6508. }
  6509. if (bestMatch == NULL)
  6510. {
  6511. for (auto member : dwValueType->mMemberList)
  6512. {
  6513. if ((member->mConstValue != 0) &&
  6514. ((member->mConstValue & bitsLeft) == member->mConstValue))
  6515. {
  6516. bestMatch = member;
  6517. break;
  6518. }
  6519. }
  6520. }
  6521. if (bestMatch == NULL)
  6522. break;
  6523. if (valueCount > 0)
  6524. {
  6525. retVal += " | ";
  6526. if (language == DbgLanguage_C)
  6527. editVal += " | ";
  6528. }
  6529. if (language == DbgLanguage_Beef)
  6530. retVal += ".";
  6531. retVal += bestMatch->mName;
  6532. if (language == DbgLanguage_C)
  6533. {
  6534. if (dwValueType->mParent != NULL)
  6535. {
  6536. editVal += dwValueType->mParent->ToString(language);
  6537. editVal += "::";
  6538. }
  6539. editVal += bestMatch->mName;
  6540. }
  6541. valueCount++;
  6542. bitsLeft &= ~bestMatch->mConstValue;
  6543. }
  6544. if ((valueCount == 0) || (bitsLeft != 0))
  6545. {
  6546. if (valueCount > 0)
  6547. retVal += " | ";
  6548. retVal += StrFormat("%lld", bitsLeft);
  6549. if (language == DbgLanguage_C)
  6550. {
  6551. if (valueCount > 0)
  6552. editVal += " | ";
  6553. editVal += StrFormat("%lld", bitsLeft);
  6554. }
  6555. }
  6556. retVal += "\n" + origValueType->ToString();
  6557. if (language == DbgLanguage_C)
  6558. {
  6559. retVal += "\n:editVal\t";
  6560. retVal += editVal;
  6561. }
  6562. retVal += "\n:canEdit";
  6563. return retVal;
  6564. }
  6565. else if (isCompositeType)
  6566. {
  6567. addr_target ptrVal;
  6568. if (dwValueType->IsPointer())
  6569. ptrVal = (addr_target)typedValue.mPtr;
  6570. else
  6571. ptrVal = (addr_target)typedValue.mSrcAddress;
  6572. String retVal;
  6573. if ((!typedValue.mIsLiteral) && (dwValueType->IsPointer()) &&
  6574. ((!formatInfo.mHidePointers) || (ptrVal == 0)))
  6575. retVal = EncodeDataPtr(ptrVal, true);
  6576. DbgType* innerType = dwValueType;
  6577. bool wasPtr = false;
  6578. if (innerType->mTypeCode == DbgType_Ptr)
  6579. {
  6580. wasPtr = true;
  6581. innerType = dwValueType->mTypeParam;
  6582. innerType = innerType->RemoveModifiers();
  6583. }
  6584. innerType = innerType->GetPrimaryType();
  6585. addr_target dataPtr = wasPtr ? typedValue.mPtr : typedValue.mSrcAddress;
  6586. DbgType* actualType = NULL;
  6587. bool useActualRawType = false;
  6588. bool isBfObject = innerType->IsBfObject();
  6589. bool hasCPPVTable = false;
  6590. if (!isBfObject)
  6591. hasCPPVTable = innerType->HasCPPVTable();
  6592. int bfObjectFlags = 0;
  6593. addr_target classVDataPtr = 0;
  6594. bool isAppendBfObject = false;
  6595. bool isStackBfObject = false;
  6596. bool isDeletedBfObject = false;
  6597. bool isCompositeWithoutAddress = false;
  6598. if (innerType->IsBfPayloadEnum())
  6599. {
  6600. if (formatInfo.mRawString)
  6601. return "";
  6602. auto tagMember = innerType->mMemberList.mTail;
  6603. int tagIdx = 0;
  6604. if (dataPtr == -1)
  6605. {
  6606. DbgEvaluationContext dbgEvaluationContext(this, dbgModule, "(int)" + expr, &formatInfo);
  6607. auto dscValue = dbgEvaluationContext.EvaluateInContext(DbgTypedValue());
  6608. tagIdx = dscValue.mInt32;
  6609. }
  6610. else if (!ReadMemory((intptr)ptrVal + tagMember->mMemberOffset, tagMember->mType->mSize, (void*)&tagIdx))
  6611. {
  6612. return StrFormat("!Failed to read from 0x%@", ptrVal);
  6613. }
  6614. char findStr[16];
  6615. findStr[0] = '_';
  6616. itoa(tagIdx, findStr + 1, 10);
  6617. int len = strlen(findStr);
  6618. findStr[len] = '_';
  6619. len++;
  6620. if (!retVal.empty())
  6621. retVal += " ";
  6622. int startIdx = 0;
  6623. for (auto member : innerType->mMemberList)
  6624. {
  6625. if (strncmp(member->mName, findStr, len) == 0)
  6626. {
  6627. retVal += ".";
  6628. retVal += member->mName + len;
  6629. String tupleExpr;
  6630. DbgTypedValue tupleVal;
  6631. if (dataPtr == -1)
  6632. {
  6633. tupleVal.mSrcAddress = -1;
  6634. tupleVal.mType = member->mType;
  6635. //tupleExpr = "$" + expr + "$u";
  6636. tupleVal.mVariable = typedValue.mVariable;
  6637. tupleExpr = "(" + member->mType->ToStringRaw() + ")(" + expr + ")";
  6638. }
  6639. else
  6640. {
  6641. tupleVal.mType = member->mType;
  6642. tupleVal.mSrcAddress = ptrVal;
  6643. }
  6644. DwFormatInfo displayStrFormatInfo = formatInfo;
  6645. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + (int)retVal.length();
  6646. displayStrFormatInfo.mExpandItemDepth++;
  6647. displayStrFormatInfo.mHidePointers = false;
  6648. retVal += DbgTypedValueToString(tupleVal, tupleExpr, displayStrFormatInfo, NULL);
  6649. int idx = (int)retVal.IndexOf('\n');
  6650. if (idx != -1)
  6651. {
  6652. if ((idx > 2) && (strncmp(retVal.c_str() + idx - 2, "()", 2) == 0))
  6653. {
  6654. // Take off a terminating "()" on the value, if there is one
  6655. retVal.Remove(idx - 2, 2);
  6656. }
  6657. String typeName = innerType->ToString(DbgLanguage_Unknown, true);
  6658. typeName += " ";
  6659. retVal.Insert(idx + 1, typeName);
  6660. }
  6661. return retVal;
  6662. }
  6663. }
  6664. }
  6665. if (isBfObject)
  6666. {
  6667. classVDataPtr = ReadMemory<addr_target>(ptrVal);
  6668. mDebugTarget->GetCompilerSettings();
  6669. if (mDebugTarget->mBfObjectHasFlags)
  6670. {
  6671. bfObjectFlags = ((int)classVDataPtr) & 0xFF;
  6672. if ((bfObjectFlags & BfObjectFlag_Deleted) != 0)
  6673. isDeletedBfObject = true;
  6674. if ((bfObjectFlags & BfObjectFlag_AppendAlloc) != 0)
  6675. isAppendBfObject = true;
  6676. if ((bfObjectFlags & (BfObjectFlag_StackAlloc | BfObjectFlag_Allocated)) == BfObjectFlag_StackAlloc)
  6677. isStackBfObject = true;
  6678. classVDataPtr &= ~0xFF;
  6679. }
  6680. }
  6681. if (!formatInfo.mIgnoreDerivedClassInfo)
  6682. {
  6683. if (isBfObject)
  6684. {
  6685. dbgModule->ParseSymbolData();
  6686. String symbolName;
  6687. addr_target symOffset;
  6688. if ((mDebugTarget->FindSymbolAt(classVDataPtr, &symbolName, &symOffset)) && (symOffset < 0x100))
  6689. {
  6690. String mangledClassName;
  6691. const char* symEnd = "sBfClassVData";
  6692. int symEndLen = strlen(symEnd);
  6693. if (((int)symbolName.length() > symEndLen) && (strstr(symbolName.c_str(), symEnd) != NULL))
  6694. mangledClassName = symbolName;
  6695. // If we have flags then we may be pointing past the _typeData, actually. We could fix this by masking out
  6696. // the flags area, but we need to be sure we are running a build that supports flags
  6697. symEnd = "sBfTypeData";
  6698. symEndLen = strlen(symEnd);
  6699. if (((int) symbolName.length() > symEndLen) && (strstr(symbolName.c_str(), symEnd) != NULL))
  6700. mangledClassName = symbolName;
  6701. if (mangledClassName.length() > 0)
  6702. {
  6703. String className = BfDemangler::Demangle(mangledClassName, innerType->GetLanguage(), BfDemangler::Flag_RawDemangle);
  6704. for (int i = 0; i < className.length() - 3; i++)
  6705. {
  6706. if ((className[i] == 'b') &&
  6707. (className[i + 1] == 'f') &&
  6708. (className[i + 2] == '.'))
  6709. {
  6710. bool matches;
  6711. if (i == 0)
  6712. matches = true;
  6713. else
  6714. {
  6715. char prevC = className[i - 1];
  6716. if ((prevC == ' ') ||
  6717. (prevC == ',') ||
  6718. (prevC == '<'))
  6719. {
  6720. matches = true;
  6721. }
  6722. }
  6723. if (matches)
  6724. className.Remove(i, 3);
  6725. }
  6726. }
  6727. int lastDot = (int)className.LastIndexOf('.');
  6728. if (lastDot > 0)
  6729. className = className.Substring(0, lastDot);
  6730. const char* arrPrefix = "System.Array1<";
  6731. if (strncmp(className.c_str(), arrPrefix, strlen(arrPrefix)) == 0)
  6732. {
  6733. className = className.Substring(strlen(arrPrefix), className.length() - strlen(arrPrefix) - 1);
  6734. className += "[]";
  6735. }
  6736. auto typeEntry = dbgModule->GetLinkedModule()->mTypeMap.Find(className.c_str(), DbgLanguage_BeefUnfixed);
  6737. if (typeEntry != NULL)
  6738. {
  6739. actualType = typeEntry->mValue;
  6740. if (!actualType->IsBfObject())
  6741. {
  6742. if (actualType->mTypeCode == DbgType_Ptr)
  6743. {
  6744. actualType = actualType->mTypeParam;
  6745. }
  6746. }
  6747. }
  6748. }
  6749. }
  6750. }
  6751. else if (hasCPPVTable)
  6752. {
  6753. dbgModule->ParseSymbolData();
  6754. addr_target classVDataPtr = ReadMemory<addr_target>(ptrVal);
  6755. String symbolName;
  6756. addr_target offset = 0;
  6757. if (mDebugTarget->FindSymbolAt(classVDataPtr, &symbolName, &offset, NULL))
  6758. {
  6759. // On GNU, vtable indices can "go negative" for things like RTTI and virtual inheritance, so
  6760. // we can't rely on an exact vtable address lookup
  6761. if (offset < 0x200)
  6762. {
  6763. DbgLanguage lang = innerType->GetLanguage();
  6764. const char* symStart = (innerType->mCompileUnit->mDbgModule->mDbgFlavor == DbgFlavor_GNU) ? "_ZTV" : "??_7";
  6765. if (strncmp(symbolName.c_str(), symStart, strlen(symStart)) == 0)
  6766. {
  6767. //String mangledClassName = symbolName.Substring(1);
  6768. String className = BfDemangler::Demangle(symbolName, lang);
  6769. int vtableNameIdx = (int)className.IndexOf("::`vftable'");
  6770. if (vtableNameIdx != -1)
  6771. className = className.Substring(0, vtableNameIdx);
  6772. auto typeEntry = dbgModule->mTypeMap.Find(className.c_str(), DbgLanguage_C);
  6773. if (typeEntry != NULL)
  6774. {
  6775. actualType = typeEntry->mValue;
  6776. if ((int)className.IndexOf('<') != -1)
  6777. useActualRawType = true;
  6778. int thisOffset = 0;
  6779. if (!DbgExprEvaluator::TypeIsSubTypeOf(actualType, innerType, &thisOffset))
  6780. {
  6781. // This catches virtual inheritance cases where we can't downcast
  6782. actualType = NULL;
  6783. }
  6784. }
  6785. }
  6786. }
  6787. }
  6788. }
  6789. }
  6790. DbgType* displayType = origValueType;
  6791. String displayString;
  6792. bool wantsCustomExpandedItems = false;
  6793. DebugVisualizerEntry* debugVis = NULL;
  6794. Array<String> dbgVisWildcardCaptures;
  6795. DbgType* dwUseType = (actualType != NULL) ? actualType : innerType;
  6796. //auto ptrDataType = dwValueType;
  6797. //TODO: Changed this from the above to account for COFF types where 'this' is always a fwd reference, does this cause any issues?
  6798. auto ptrDataType = innerType;
  6799. String ptrDataStr;
  6800. if (/*(!innerType->IsBfObject()) &&*/ (!ptrDataType->IsPointer()))
  6801. {
  6802. if ((dataPtr != 0) || (ptrDataType->GetByteCount() > sizeof(addr_target)))
  6803. {
  6804. bool wantsRefThis = ptrDataType->WantsRefThis();
  6805. ptrDataType = ptrDataType->GetDbgModule()->GetPointerType(ptrDataType);
  6806. if (wantsRefThis)
  6807. ptrDataStr += "*";
  6808. }
  6809. else
  6810. {
  6811. // Data is inline - must be int-sized or less
  6812. isCompositeWithoutAddress = true;
  6813. dataPtr = typedValue.mPtr;
  6814. }
  6815. }
  6816. String ptrDataTypeStr = ptrDataType->ToStringRaw();
  6817. ptrDataStr += StrFormat("(%s)", ptrDataTypeStr.c_str()) + EncodeDataPtr(dataPtr, true);
  6818. DbgType* dwUsePtrType = dwUseType;
  6819. String ptrUseDataStr;
  6820. if (!dwUsePtrType->IsPointer())
  6821. {
  6822. bool wantsRefThis = dwUsePtrType->WantsRefThis();
  6823. dwUsePtrType = dwUsePtrType->GetDbgModule()->GetPointerType(dwUsePtrType);
  6824. if (wantsRefThis)
  6825. ptrUseDataStr += "*";
  6826. }
  6827. String ptrUseDataTypeStr = dwUsePtrType->ToStringRaw();
  6828. ptrUseDataStr += StrFormat("(%s)", ptrUseDataTypeStr.c_str()) + EncodeDataPtr(dataPtr, true);
  6829. if ((origTypedValue.mSrcAddress == -1) && (origTypedValue.mVariable != NULL))
  6830. {
  6831. ptrDataStr = origTypedValue.mVariable->mName;
  6832. if (!origTypedValue.mType->RemoveModifiers()->Equals(origTypedValue.mVariable->mType->RemoveModifiers()))
  6833. {
  6834. //ptrDataStr = StrFormat("(%s)%s", origTypedValue.mType->ToString().c_str(), origTypedValue.mVariable->mName);
  6835. ptrDataStr = expr;
  6836. }
  6837. ptrUseDataStr = ptrDataStr;
  6838. }
  6839. bool isNull = wasPtr && (dataPtr == 0);
  6840. bool isBadSrc = !wasPtr && (dataPtr == 0) && (!dwValueType->IsValuelessType());
  6841. if ((ptrVal == 0) && (dwValueType->IsTypedPrimitive()))
  6842. {
  6843. DbgTypedValue rawVal;
  6844. rawVal.mInt64 = origTypedValue.mInt64;
  6845. rawVal.mType = dwValueType->GetRootBaseType();
  6846. ptrDataStr = "(" + dwUseType->ToStringRaw() + ")";
  6847. ptrDataStr += DbgTypedValueToString(rawVal, expr, formatInfo, optEvaluator, fullPrecision);
  6848. int editValIdx = ptrDataStr.IndexOf(":editVal");
  6849. if (editValIdx != -1)
  6850. ptrDataStr.Remove(0, editValIdx + 9);
  6851. int crPos = (int)ptrDataStr.IndexOf('\n');
  6852. if (crPos != -1)
  6853. ptrDataStr.RemoveToEnd(crPos);
  6854. ptrUseDataStr = ptrDataStr;
  6855. if ((origTypedValue.mRegNum != -1) && (!expr.IsEmpty()) && (!formatInfo.mExplicitThis))
  6856. {
  6857. // There's no address, use direct local identifier
  6858. ptrDataStr = expr;
  6859. ptrUseDataStr = expr;
  6860. }
  6861. // This keeps 'function' types from showing null as "<null parent>"
  6862. isBadSrc = false;
  6863. }
  6864. else if ((ptrVal == 0) && (dwValueType->IsCompositeType()))
  6865. {
  6866. }
  6867. DbgTypedValue useTypedValue = typedValue;
  6868. if ((origHadRef) || ((typedValue.mType->HasPointer()) && (!dwUseType->HasPointer())))
  6869. {
  6870. useTypedValue.mSrcAddress = useTypedValue.mPtr;
  6871. useTypedValue.mPtr = 0;
  6872. if (dwUseType->IsTypedPrimitive())
  6873. {
  6874. int byteCount = dwUseType->GetByteCount();
  6875. if (byteCount <= sizeof(intptr))
  6876. {
  6877. ReadMemory(useTypedValue.mSrcAddress, byteCount, &useTypedValue.mPtr);
  6878. }
  6879. }
  6880. }
  6881. useTypedValue.mType = dwUseType;
  6882. if ((!formatInfo.mNoVisualizers) && (!isNull) && (!isBadSrc))
  6883. {
  6884. if (language == DbgLanguage_Beef)
  6885. dwUseType->FixName();
  6886. debugVis = FindVisualizerForType(dwUseType, &dbgVisWildcardCaptures);
  6887. }
  6888. bool hadCustomDisplayString = false;
  6889. if (debugVis != NULL)
  6890. {
  6891. auto& displayStringList = (formatInfo.mRawString || wantStringView) ? debugVis->mStringViews : debugVis->mDisplayStrings;
  6892. for (auto displayEntry : displayStringList)
  6893. {
  6894. if (!displayEntry->mCondition.empty())
  6895. {
  6896. if (!EvalCondition(debugVis, dbgCompileUnit, useTypedValue, formatInfo, displayEntry->mCondition, dbgVisWildcardCaptures, displayString))
  6897. continue;
  6898. }
  6899. hadCustomDisplayString = true;
  6900. String displayStr = mDebugManager->mDebugVisualizers->DoStringReplace(displayEntry->mString, dbgVisWildcardCaptures);
  6901. if (displayString.length() > 0)
  6902. displayString += " ";
  6903. if (wantStringView)
  6904. {
  6905. DwFormatInfo strFormatInfo = formatInfo;
  6906. strFormatInfo.mRawString = true;
  6907. ProcessEvalString(dbgCompileUnit, useTypedValue, displayStr, stringViewData, strFormatInfo, debugVis, true);
  6908. }
  6909. else
  6910. ProcessEvalString(dbgCompileUnit, useTypedValue, displayStr, displayString, formatInfo, debugVis, true);
  6911. if (formatInfo.mRawString)
  6912. return displayString;
  6913. break;
  6914. }
  6915. if ((!debugVis->mExpandItems.empty()) || (debugVis->mCollectionType != DebugVisualizerEntry::CollectionType_None))
  6916. {
  6917. wantsCustomExpandedItems = true;
  6918. }
  6919. }
  6920. if (formatInfo.mRawString)
  6921. return "";
  6922. bool isTuple = (dwUseType->mName != NULL) && (dwUseType->mName[0] == '(') && (language == DbgLanguage_Beef);
  6923. if (isBadSrc)
  6924. {
  6925. displayString += "<null parent>";
  6926. }
  6927. else if ((!isNull) && (!formatInfo.mNoVisualizers) && (!hadCustomDisplayString))
  6928. {
  6929. // Create our own custom display
  6930. String firstRet;
  6931. String bigRet = isTuple ? "(" : "{ ";
  6932. int memberIdx = 0;
  6933. DbgType* summaryType = dwUseType;
  6934. bool summaryDone = false;
  6935. bool truncatedMemberList = false;
  6936. DbgTypedValue summaryTypedValue = useTypedValue;
  6937. String summaryDataStr = ptrDataStr;
  6938. String splatStr;
  6939. if (dataPtr == -1)
  6940. splatStr = expr;
  6941. while (summaryType != NULL)
  6942. {
  6943. summaryType->PopulateType();
  6944. if ((summaryType->IsTypedPrimitive()) &&
  6945. ((summaryType->mBaseTypes.IsEmpty()) || (!summaryType->mBaseTypes.front()->mBaseType->IsTypedPrimitive())))
  6946. {
  6947. if (formatInfo.mTotalSummaryLength + (int)displayString.length() > 255)
  6948. {
  6949. truncatedMemberList = true;
  6950. summaryDone = true;
  6951. bigRet += "...";
  6952. }
  6953. else
  6954. {
  6955. DwFormatInfo displayStrFormatInfo = formatInfo;
  6956. displayStrFormatInfo.mExpandItemDepth = 1;
  6957. displayStrFormatInfo.mTotalSummaryLength += (int)displayString.length();
  6958. displayStrFormatInfo.mHidePointers = false;
  6959. DbgType* primType = summaryType->mTypeParam;
  6960. String result;
  6961. if (primType->IsInteger())
  6962. formatInfo.mTypeKindFlags = (DbgTypeKindFlags)(formatInfo.mTypeKindFlags | DbgTypeKindFlag_Int);
  6963. if ((dataPtr != 0) && (dataPtr != -1))
  6964. {
  6965. String evalString = "(" + primType->ToString() + ")" + ptrDataStr;
  6966. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, origTypedValue, evalString, &displayStrFormatInfo);
  6967. if (evalResult)
  6968. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  6969. }
  6970. else
  6971. {
  6972. DbgTypedValue evalResult = origTypedValue;
  6973. evalResult.mType = primType;
  6974. String evalString = "(" + primType->ToString() + ")" + expr;
  6975. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  6976. }
  6977. if (formatInfo.mRawString)
  6978. return result;
  6979. int crPos = result.IndexOf('\n');
  6980. if (crPos != -1)
  6981. result.RemoveToEnd(crPos);
  6982. if (memberIdx == 0)
  6983. firstRet = result;
  6984. bigRet += result;
  6985. memberIdx++;
  6986. }
  6987. }
  6988. for (auto member : summaryType->mMemberList)
  6989. {
  6990. if (!member->mIsStatic)
  6991. {
  6992. if (formatInfo.mTotalSummaryLength + retVal.length() + bigRet.length() > 255)
  6993. {
  6994. truncatedMemberList = true;
  6995. summaryDone = true;
  6996. bigRet += "...";
  6997. break;
  6998. }
  6999. if (member->mName != NULL)
  7000. {
  7001. if (member->mName[0] == '$')
  7002. continue;
  7003. if (!isdigit(*member->mName))
  7004. {
  7005. if (memberIdx != 0)
  7006. bigRet += isTuple ? ", " : " ";
  7007. if ((!isTuple) || (member->mName[0] != '_'))
  7008. {
  7009. bigRet += String(member->mName);
  7010. bigRet += isTuple ? ":" : "=";
  7011. }
  7012. }
  7013. else
  7014. {
  7015. if (memberIdx != 0)
  7016. bigRet += ", ";
  7017. }
  7018. DwFormatInfo displayStrFormatInfo = formatInfo;
  7019. displayStrFormatInfo.mExpandItemDepth = 1;
  7020. displayStrFormatInfo.mHidePointers = false;
  7021. displayStrFormatInfo.mTotalSummaryLength = formatInfo.mTotalSummaryLength + retVal.length() + bigRet.length();
  7022. String evalString;
  7023. if (dataPtr != -1)
  7024. {
  7025. if ((member->mName[0] >= '0') && (member->mName[0] <= '9'))
  7026. evalString += "this.";
  7027. evalString += String(member->mName); // +", this=" + summaryDataStr;
  7028. }
  7029. else
  7030. {
  7031. evalString = "(";
  7032. evalString += splatStr;
  7033. evalString += ").";
  7034. evalString += member->mName;
  7035. }
  7036. String referenceId;
  7037. String result;
  7038. if (!member->mType->IsValuelessType())
  7039. {
  7040. DbgTypedValue evalResult = EvaluateInContext(dbgCompileUnit, summaryTypedValue, evalString, &displayStrFormatInfo, &referenceId);
  7041. if (evalResult)
  7042. {
  7043. displayStrFormatInfo.mReferenceId = referenceId;
  7044. result = DbgTypedValueToString(evalResult, evalString, displayStrFormatInfo, NULL);
  7045. int crPos = result.IndexOf('\n');
  7046. if (crPos != -1)
  7047. result.RemoveToEnd(crPos);
  7048. }
  7049. else
  7050. result = "???";
  7051. }
  7052. if (member->mType->IsInteger())
  7053. formatInfo.mTypeKindFlags = (DbgTypeKindFlags)(formatInfo.mTypeKindFlags | DbgTypeKindFlag_Int);
  7054. if (formatInfo.mRawString)
  7055. return result;
  7056. if (memberIdx == 0)
  7057. firstRet = result;
  7058. bigRet += result;
  7059. //formatInfo.mEmbeddedDisplayCount = displayStrFormatInfo.mEmbeddedDisplayCount;
  7060. memberIdx++;
  7061. }
  7062. else
  7063. {
  7064. //TODO: Handle C++ unions?
  7065. }
  7066. }
  7067. }
  7068. if (truncatedMemberList)
  7069. break;
  7070. // Find first base class with members
  7071. DbgType* nextSummaryType = NULL;
  7072. for (auto checkBase : summaryType->mBaseTypes)
  7073. {
  7074. auto checkBaseType = checkBase->mBaseType;
  7075. checkBaseType = checkBaseType->GetPrimaryType();
  7076. checkBaseType->PopulateType();
  7077. if ((checkBaseType->GetByteCount() > 0) || (checkBaseType->IsPrimitiveType()))
  7078. {
  7079. if (!splatStr.empty())
  7080. {
  7081. splatStr = "(" + checkBaseType->ToString() + ")" + splatStr;
  7082. }
  7083. else
  7084. {
  7085. summaryTypedValue.mType = checkBaseType;
  7086. }
  7087. nextSummaryType = checkBaseType;
  7088. break;
  7089. }
  7090. }
  7091. summaryType = nextSummaryType;
  7092. if (summaryType == NULL)
  7093. break;
  7094. // Don't add the Object members
  7095. if ((summaryType->GetBaseType() == NULL) && (summaryType->IsBfObject()))
  7096. break;
  7097. // If we don't have many members then find a base class with some members to show
  7098. if ((memberIdx != 0) && (displayString.length() >= 255))
  7099. {
  7100. truncatedMemberList = true;
  7101. bigRet += "...";
  7102. break;
  7103. }
  7104. }
  7105. bigRet += isTuple ? ")" : " }";
  7106. if (displayString.length() > 0)
  7107. displayString += " ";
  7108. if ((memberIdx == 1) && (!truncatedMemberList) && (firstRet.IndexOf('{') == -1) && (!isTuple))
  7109. displayString += "{ " + firstRet + " }";
  7110. else
  7111. displayString += bigRet;
  7112. }
  7113. DbgType* memberListType = actualType;
  7114. bool memberListForceCast = false;
  7115. if (actualType != NULL)
  7116. {
  7117. String valTypeName = displayType->ToString();
  7118. String actualTypeName = actualType->ToString(DbgLanguage_Unknown, true);
  7119. String actualUseTypeName = actualTypeName;
  7120. if ((int)actualTypeName.IndexOf('^') != -1)
  7121. useActualRawType = true;
  7122. if (useActualRawType)
  7123. actualUseTypeName = actualType->ToStringRaw();
  7124. if (displayString.empty())
  7125. {
  7126. // Nothing to display
  7127. }
  7128. else
  7129. {
  7130. if (!retVal.empty())
  7131. retVal += " ";
  7132. retVal += displayString;
  7133. }
  7134. retVal += "\n" + valTypeName;
  7135. if ((innerType->IsBaseBfObject()) || (innerType->IsInterface()))
  7136. {
  7137. if (actualType != innerType)
  7138. {
  7139. retVal += " {" + actualTypeName + "}";
  7140. memberListForceCast = true;
  7141. }
  7142. }
  7143. else
  7144. {
  7145. if (actualType != innerType)
  7146. {
  7147. retVal += " {" + actualTypeName + "}";
  7148. retVal += "\n";
  7149. if (!wantsCustomExpandedItems)
  7150. {
  7151. retVal += "[" + actualTypeName + "]\t((" + actualUseTypeName;
  7152. if (!actualType->IsBfObject())
  7153. retVal += "*";
  7154. retVal += ")this), nd, na, nv, this=" + ptrDataStr;
  7155. memberListType = innerType;
  7156. }
  7157. }
  7158. }
  7159. }
  7160. else
  7161. {
  7162. if ((formatInfo.mHidePointers) && (formatInfo.mIgnoreDerivedClassInfo))
  7163. {
  7164. displayType = innerType;
  7165. if (displayString.empty())
  7166. retVal += displayType->ToString(DbgLanguage_Unknown, true);
  7167. }
  7168. if (!displayString.empty())
  7169. {
  7170. if (!retVal.empty())
  7171. retVal += " ";
  7172. retVal += displayString;
  7173. }
  7174. else
  7175. {
  7176. if (formatInfo.mRawString)
  7177. return "";
  7178. }
  7179. retVal += "\n" + displayType->ToString(DbgLanguage_Unknown, true);
  7180. memberListType = innerType;
  7181. }
  7182. if ((isBfObject) && (mDebugTarget->mBfObjectHasFlags) && (!formatInfo.mNoVisualizers) && (!formatInfo.mRawString))
  7183. {
  7184. int stackTraceLen = 1;
  7185. addr_target stackTraceAddr = ptrVal + sizeof(addr_target);
  7186. if ((bfObjectFlags & BfObjectFlag_AllocInfo) != 0)
  7187. {
  7188. addr_target objectSize = ReadMemory<addr_target>(ptrVal + sizeof(addr_target));
  7189. addr_target largeAllocInfo = ReadMemory<addr_target>(ptrVal + objectSize);
  7190. stackTraceLen = largeAllocInfo & 0xFFFF;
  7191. stackTraceAddr = ptrVal + objectSize + sizeof(addr_target);
  7192. }
  7193. else if ((bfObjectFlags & BfObjectFlag_AllocInfo_Short) != 0)
  7194. {
  7195. addr_target dbgAllocInfo = ReadMemory<addr_target>(ptrVal + sizeof(addr_target));
  7196. stackTraceLen = dbgAllocInfo & 0xFF;
  7197. stackTraceAddr = ptrVal + (dbgAllocInfo >> 16);
  7198. }
  7199. retVal += StrFormat("\n[AllocStackTrace]\t(System.CallStackList)%s, count=%d, na", EncodeDataPtr(stackTraceAddr, true).c_str(), stackTraceLen);
  7200. }
  7201. retVal += StrFormat("\n:language\t%d", language);
  7202. if (formatInfo.mNoMembers)
  7203. {
  7204. //
  7205. }
  7206. else if (wantsCustomExpandedItems)
  7207. {
  7208. HandleCustomExpandedItems(retVal, dbgCompileUnit, debugVis, dwUseType, dwValueType, ptrUseDataStr, ptrDataStr, useTypedValue, dbgVisWildcardCaptures, formatInfo);
  7209. }
  7210. else if ((!isNull) && (!isBadSrc))
  7211. {
  7212. if (dataPtr == -1)
  7213. {
  7214. //String splatName = ((origTypedValue.mSrcAddress == -1) && (origTypedValue.mVariable != NULL)) ? origTypedValue.mVariable->mName : expr;
  7215. String splatName = expr;
  7216. retVal += "\n" + GetMemberList(memberListType, splatName, wasPtr, false, false, true, origTypedValue.mIsReadOnly);
  7217. }
  7218. else
  7219. {
  7220. retVal += "\n" + GetMemberList(memberListType, ptrDataStr, wasPtr, false, memberListForceCast, isCompositeWithoutAddress, origTypedValue.mIsReadOnly);
  7221. }
  7222. }
  7223. if (formatInfo.mExpandItemDepth > 0)
  7224. return retVal;
  7225. if (isAppendBfObject)
  7226. retVal += "\n:appendAlloc";
  7227. if (isStackBfObject)
  7228. retVal += "\n:stack";
  7229. if (isDeletedBfObject)
  7230. retVal += "\n:deleted";
  7231. if (!formatInfo.mAction.IsEmpty())
  7232. {
  7233. retVal += "\n:action\t";
  7234. retVal += formatInfo.mAction;
  7235. }
  7236. else if ((debugVis != NULL) && (!debugVis->mAction.empty()))
  7237. {
  7238. String rawActionStr = mDebugManager->mDebugVisualizers->DoStringReplace(debugVis->mAction, dbgVisWildcardCaptures);
  7239. String actionStr;
  7240. ProcessEvalString(dbgCompileUnit, useTypedValue, rawActionStr, actionStr, formatInfo, debugVis, true);
  7241. retVal += "\n:action\t" + actionStr;
  7242. }
  7243. if ((!typedValue.mIsLiteral) && (dwValueType->IsPointer()))
  7244. {
  7245. retVal += "\n:editVal\t" + EncodeDataPtr(ptrVal, true);
  7246. }
  7247. if (((debugVis != NULL) && (!debugVis->mStringViews.IsEmpty())) || (wantStringView))
  7248. retVal += "\n:stringView";
  7249. if (wantStringView)
  7250. {
  7251. retVal += "\t";
  7252. retVal += SlashString(stringViewData, false, false, true);
  7253. }
  7254. return retVal;
  7255. }
  7256. return "Unknown Type\n" + origValueType->ToString();
  7257. }
  7258. void WinDebugger::HandleCustomExpandedItems(String& retVal, DbgCompileUnit* dbgCompileUnit, DebugVisualizerEntry* debugVis, DbgType* dwUseType, DbgType* dwValueType, String& ptrUseDataStr, String& ptrDataStr, DbgTypedValue useTypedValue, Array<String>& dbgVisWildcardCaptures, DwFormatInfo& formatInfo)
  7259. {
  7260. auto debugVisualizers = mDebugManager->mDebugVisualizers;
  7261. auto dbgModule = dbgCompileUnit->mDbgModule;
  7262. if (formatInfo.mExpandItemDepth > 10) // Avoid crashing on circular ExpandItems
  7263. return;
  7264. auto language = formatInfo.mLanguage;
  7265. bool isReadOnly = false;
  7266. if (useTypedValue.mIsReadOnly)
  7267. isReadOnly = true;
  7268. for (auto entry : debugVis->mExpandItems)
  7269. {
  7270. if (!entry->mCondition.empty())
  7271. {
  7272. String error;
  7273. if (!EvalCondition(debugVis, dbgCompileUnit, useTypedValue, formatInfo, entry->mCondition, dbgVisWildcardCaptures, error))
  7274. {
  7275. if (!error.empty())
  7276. retVal += "\n" + entry->mName + "\t@!<DbgVis Failed>@!";
  7277. continue;
  7278. }
  7279. }
  7280. String replacedStr = debugVisualizers->DoStringReplace(entry->mValue, dbgVisWildcardCaptures);
  7281. retVal += "\n" + entry->mName + "\t" + replacedStr + ", this=(" + ptrUseDataStr + ")";
  7282. }
  7283. String referenceId = dwUseType->ToString();
  7284. if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_ExpandedItem)
  7285. {
  7286. DbgTypedValue itemValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7287. if (itemValue)
  7288. {
  7289. DwFormatInfo itemFormatInfo = formatInfo;
  7290. itemFormatInfo.mExpandItemDepth++;
  7291. String itemRetVal = DbgTypedValueToString(itemValue, "", itemFormatInfo, NULL);
  7292. int crIdx = (int)itemRetVal.IndexOf('\n');
  7293. if (crIdx != -1)
  7294. {
  7295. crIdx = (int)itemRetVal.IndexOf('\n', crIdx + 1);
  7296. if (crIdx != -1)
  7297. retVal += itemRetVal.Substring(crIdx);
  7298. }
  7299. }
  7300. }
  7301. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Array)
  7302. {
  7303. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7304. Array<int> lowerDimSizes;
  7305. for (auto lowerDim : debugVis->mLowerDimSizes)
  7306. {
  7307. DbgTypedValue lowerDimValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(lowerDim, dbgVisWildcardCaptures), &formatInfo);
  7308. int dimSize = 0;
  7309. if ((lowerDimValue) && (lowerDimValue.mType->IsInteger()))
  7310. dimSize = (int)lowerDimValue.GetInt64();
  7311. dimSize = BF_MAX(dimSize, 1);
  7312. lowerDimSizes.push_back(dimSize);
  7313. }
  7314. if ((sizeValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7315. {
  7316. if (!debugVis->mCondition.IsEmpty())
  7317. {
  7318. int size = (int)sizeValue.GetInt64();
  7319. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7320. DbgTypedValue curNode = headPointer;
  7321. Array<addr_target> parentList;
  7322. String continuationData;
  7323. int totalSize = 2;
  7324. auto valueType = headPointer.mType;
  7325. String addrs = GetArrayItems(dbgCompileUnit, debugVis, valueType, headPointer, totalSize, &continuationData);
  7326. String firstAddr;
  7327. String secondAddr;
  7328. bool hasSecondAddr = valueType == NULL;
  7329. if (addrs.length() > 0)
  7330. {
  7331. const char* addrsPtr = addrs.c_str();
  7332. firstAddr = addrs.Substring(0, sizeof(addr_target) * 2);
  7333. if (hasSecondAddr)
  7334. secondAddr = addrs.Substring(sizeof(addr_target) * 2, sizeof(addr_target) * 2);
  7335. }
  7336. String evalStr;
  7337. if (valueType != NULL)
  7338. {
  7339. evalStr = "(" + valueType->ToStringRaw();
  7340. if (!valueType->IsPointer())
  7341. evalStr += "*";
  7342. evalStr += ")0x{1}";
  7343. }
  7344. else
  7345. {
  7346. evalStr += "({1})0x{2}";
  7347. }
  7348. if (!debugVis->mShowElementAddrs)
  7349. evalStr.Insert(0, "*");
  7350. if (addrs.length() > 0)
  7351. {
  7352. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7353. if (isReadOnly)
  7354. evalStr += ", ne";
  7355. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, BF_MAX(size, 0), 10000) +
  7356. "\t[{0}]\t" + evalStr + "\t" + firstAddr;
  7357. if (hasSecondAddr)
  7358. retVal += "\t" + secondAddr;
  7359. if (size != 0)
  7360. {
  7361. retVal += "\n:addrs\t" + addrs;
  7362. if (valueType == NULL)
  7363. retVal += "\n:addrsEntrySize\t2";
  7364. if (continuationData.length() > 0)
  7365. retVal += "\n:continuation\t" + continuationData;
  7366. }
  7367. }
  7368. }
  7369. else if (lowerDimSizes.size() == 1)
  7370. {
  7371. int dimSize1 = lowerDimSizes[0];
  7372. String evalStr = "(" + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7373. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7374. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7375. if (isReadOnly)
  7376. evalStr += ", ne";
  7377. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, sizeValue.GetInt64() / dimSize1, 50000) +
  7378. "\t[{0}]\t" + evalStr;
  7379. }
  7380. else if (lowerDimSizes.size() == 2)
  7381. {
  7382. int dimSize1 = lowerDimSizes[0];
  7383. int dimSize2 = lowerDimSizes[1];
  7384. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7385. if ((headPointer.mType != NULL) && (headPointer.mType->IsPointer()))
  7386. {
  7387. String evalStr = StrFormat("((%s[%d]*)", headPointer.mType->mTypeParam->ToStringRaw(language).c_str(), dimSize2) + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7388. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7389. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7390. if (isReadOnly)
  7391. evalStr += ", ne";
  7392. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, sizeValue.GetInt64() / dimSize1 / dimSize2, 50000) +
  7393. "\t[{0}]\t" + evalStr;
  7394. }
  7395. }
  7396. else if (lowerDimSizes.size() == 3)
  7397. {
  7398. int dimSize1 = lowerDimSizes[0];
  7399. int dimSize2 = lowerDimSizes[1];
  7400. int dimSize3 = lowerDimSizes[2];
  7401. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures), &formatInfo);
  7402. if ((headPointer.mType != NULL) && (headPointer.mType->IsPointer()))
  7403. {
  7404. String evalStr = StrFormat("((%s[%d][%d]*)", headPointer.mType->mTypeParam->ToStringRaw(language).c_str(), dimSize2, dimSize3) + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) +
  7405. StrFormat(" + {0} * %d), arraysize=%d, na, this=", dimSize1, dimSize1) + ptrUseDataStr;
  7406. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7407. if (isReadOnly)
  7408. evalStr += ", ne";
  7409. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, sizeValue.GetInt64() / dimSize1 / dimSize2 / dimSize3, 50000) +
  7410. "\t[{0}]\t" + evalStr;
  7411. }
  7412. }
  7413. else
  7414. {
  7415. String evalStr = "*(" + debugVisualizers->DoStringReplace(debugVis->mValuePointer, dbgVisWildcardCaptures) + " + {0}), this=" + ptrUseDataStr;
  7416. evalStr += ", refid=\"" + referenceId + ".[]${0}\"";
  7417. if (isReadOnly)
  7418. evalStr += ", ne";
  7419. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, sizeValue.GetInt64(), 50000) +
  7420. "\t[{0}]\t" + evalStr;
  7421. }
  7422. }
  7423. }
  7424. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_IndexItems)
  7425. {
  7426. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7427. if ((sizeValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7428. {
  7429. String evalStr = debugVis->mValuePointer + ", this=" + ptrUseDataStr;
  7430. evalStr.Replace("$i", "{0}");
  7431. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7432. if (isReadOnly)
  7433. evalStr += ", ne";
  7434. retVal += "\n:repeat" + StrFormat("\t%d\t%lld\t%d", 0, sizeValue.GetInt64(), 50000) +
  7435. "\t[{0}]\t" + evalStr;
  7436. }
  7437. }
  7438. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_LinkedList)
  7439. {
  7440. DbgType* valueType = NULL;
  7441. if (!debugVis->mValueType.empty())
  7442. {
  7443. valueType = dbgModule->FindType(debugVisualizers->DoStringReplace(debugVis->mValueType, dbgVisWildcardCaptures), dwValueType);
  7444. if (valueType != NULL)
  7445. valueType = valueType->ResolveTypeDef();
  7446. }
  7447. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mHeadPointer, dbgVisWildcardCaptures), &formatInfo);
  7448. if (headPointer)
  7449. {
  7450. DbgTypedValue endPointer;
  7451. if (!debugVis->mEndPointer.empty())
  7452. endPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mEndPointer, dbgVisWildcardCaptures), &formatInfo);
  7453. DbgTypedValue nextPointer = EvaluateInContext(dbgCompileUnit, headPointer, debugVisualizers->DoStringReplace(debugVis->mNextPointer, dbgVisWildcardCaptures), &formatInfo);
  7454. int size = -1;
  7455. if (!debugVis->mSize.empty())
  7456. {
  7457. auto sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7458. if (sizeValue)
  7459. size = (int)sizeValue.GetInt64();
  7460. }
  7461. DbgTypedValue curNode = headPointer;
  7462. Array<addr_target> parentList;
  7463. String continuationData;
  7464. int totalSize = 2;
  7465. String addrs = GetLinkedListItems(dbgCompileUnit, debugVis, endPointer.mPtr, valueType, curNode, totalSize, &continuationData);
  7466. String firstAddr;
  7467. String secondAddr;
  7468. bool hasSecondAddr = valueType == NULL;
  7469. if (addrs.length() > 0)
  7470. {
  7471. const char* addrsPtr = addrs.c_str();
  7472. firstAddr = addrs.Substring(0, sizeof(addr_target)*2);
  7473. if (hasSecondAddr)
  7474. secondAddr = addrs.Substring(sizeof(addr_target)*2, sizeof(addr_target)*2);
  7475. }
  7476. String evalStr;
  7477. if (valueType != NULL)
  7478. {
  7479. evalStr = "(" + valueType->ToStringRaw();
  7480. if (!valueType->IsPointer())
  7481. evalStr += "*";
  7482. evalStr += ")0x{1}";
  7483. }
  7484. else
  7485. {
  7486. evalStr += "({1})0x{2}";
  7487. }
  7488. if (!debugVis->mShowElementAddrs)
  7489. evalStr.Insert(0, "*");
  7490. if (addrs.length() > 0)
  7491. {
  7492. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7493. if (isReadOnly)
  7494. evalStr += ", ne";
  7495. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, size, 10000) +
  7496. "\t[{0}]\t" + evalStr + "\t" + firstAddr;
  7497. if (hasSecondAddr)
  7498. retVal += "\t" + secondAddr;
  7499. if (size != 0)
  7500. {
  7501. retVal += "\n:addrs\t" + addrs;
  7502. if (valueType == NULL)
  7503. retVal += "\n:addrsEntrySize\t2";
  7504. if (continuationData.length() > 0)
  7505. retVal += "\n:continuation\t" + continuationData;
  7506. }
  7507. }
  7508. }
  7509. }
  7510. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_TreeItems)
  7511. {
  7512. DbgType* valueType = NULL;
  7513. if (!debugVis->mValueType.empty())
  7514. {
  7515. valueType = dbgModule->FindType(debugVisualizers->DoStringReplace(debugVis->mValueType, dbgVisWildcardCaptures), dwValueType);
  7516. if (valueType != NULL)
  7517. valueType = valueType->ResolveTypeDef();
  7518. }
  7519. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7520. DbgTypedValue headPointer = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mHeadPointer, dbgVisWildcardCaptures), &formatInfo);
  7521. if (sizeValue)
  7522. sizeValue.mType = sizeValue.mType->RemoveModifiers();
  7523. if ((sizeValue) && (headPointer) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7524. {
  7525. DbgTypedValue curNode = headPointer;
  7526. Array<addr_target> parentList;
  7527. String continuationData;
  7528. int getItemCount = (int)BF_MIN(sizeValue.GetInt64(), 32LL);
  7529. String addrs = GetTreeItems(dbgCompileUnit, debugVis, parentList, valueType, curNode, getItemCount, &continuationData);
  7530. addr_target firstAddr = 0;
  7531. addr_target secondAddr = 0;
  7532. bool hasSecondAddr = valueType == NULL;
  7533. if (addrs.length() > 0)
  7534. {
  7535. const char* addrsPtr = addrs.c_str();
  7536. firstAddr = DecodeTargetDataPtr(addrsPtr);
  7537. if (hasSecondAddr)
  7538. secondAddr = DecodeTargetDataPtr(addrsPtr);
  7539. }
  7540. String evalStr;
  7541. if (valueType != NULL)
  7542. {
  7543. evalStr = "*(" + valueType->ToStringRaw();
  7544. if (!valueType->IsPointer())
  7545. evalStr += "*";
  7546. evalStr += ")0x{1}";
  7547. }
  7548. else
  7549. {
  7550. evalStr += "*(_T_{1}*)0x{2}";
  7551. }
  7552. int size = (int)sizeValue.GetInt64();
  7553. if (addrs.length() == 0)
  7554. {
  7555. evalStr = ""; // Failed
  7556. }
  7557. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7558. if (isReadOnly)
  7559. evalStr += ", ne";
  7560. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, size, 10000) +
  7561. "\t[{0}]\t" + evalStr + "\t" + EncodeDataPtr(firstAddr, false);
  7562. if (hasSecondAddr)
  7563. retVal += "\t" + EncodeDataPtr(secondAddr, false);
  7564. if (addrs.length() > 0)
  7565. {
  7566. retVal += "\n:addrs\t" + addrs;
  7567. if (continuationData.length() > 0)
  7568. retVal += "\n:continuation\t" + continuationData;
  7569. }
  7570. }
  7571. }
  7572. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_Dictionary)
  7573. {
  7574. DbgTypedValue sizeValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mSize, dbgVisWildcardCaptures), &formatInfo);
  7575. DbgTypedValue entriesPtrValue = EvaluateInContext(dbgCompileUnit, useTypedValue, debugVisualizers->DoStringReplace(debugVis->mEntries, dbgVisWildcardCaptures), &formatInfo);
  7576. if (sizeValue)
  7577. sizeValue.mType = sizeValue.mType->RemoveModifiers();
  7578. if ((sizeValue) && (entriesPtrValue) && (sizeValue.mType->IsInteger()) && (sizeValue.GetInt64() > 0))
  7579. {
  7580. String continuationData;
  7581. DbgType* valueType = entriesPtrValue.mType;
  7582. int getItemCount = (int)std::min(sizeValue.GetInt64(), 2LL);
  7583. DbgType* useTypedValType = useTypedValue.mType;
  7584. addr_target useTypedValPtr = useTypedValue.mPtr;
  7585. addr_target useTypedValAddr = useTypedValue.mSrcAddress;
  7586. String addrs = GetDictionaryItems(dbgCompileUnit, debugVis, useTypedValue, 0, -1, getItemCount, &continuationData);
  7587. addr_target firstAddr = 0;
  7588. if (addrs.length() > 0)
  7589. {
  7590. const char* addrsPtr = addrs.c_str();
  7591. firstAddr = DecodeTargetDataPtr(addrsPtr);
  7592. }
  7593. String evalStr = "((" + valueType->ToStringRaw() + ")0x{1}), na";
  7594. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7595. if (isReadOnly)
  7596. evalStr += ", ne";
  7597. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, (int)sizeValue.GetInt64(), 10000) +
  7598. "\t[{0}]\t" + evalStr + "\t" + EncodeDataPtr(firstAddr, false);
  7599. if (addrs.length() > 0)
  7600. {
  7601. retVal += "\n:addrs\t" + addrs;
  7602. if (continuationData.length() > 0)
  7603. retVal += "\n:continuation\t" + continuationData;
  7604. }
  7605. }
  7606. }
  7607. else if (debugVis->mCollectionType == DebugVisualizerEntry::CollectionType_CallStackList)
  7608. {
  7609. int size = 0;
  7610. String addrs;
  7611. String firstVal;
  7612. auto ptr = useTypedValue.mPtr;
  7613. for (int i = 0; i < formatInfo.mOverrideCount; i++)
  7614. {
  7615. auto funcAddr = ReadMemory<addr_target>(ptr + i * sizeof(addr_target));
  7616. auto srcFuncAddr = funcAddr;
  7617. addrs += EncodeDataPtr(funcAddr - 1, false);
  7618. if (i == 0)
  7619. firstVal = addrs;
  7620. addrs += EncodeDataPtr((addr_target)0, false);
  7621. size++;
  7622. int inlineIdx = 0;
  7623. auto subProgram = mDebugTarget->FindSubProgram(funcAddr - 1, DbgOnDemandKind_LocalOnly);
  7624. while (subProgram != NULL)
  7625. {
  7626. if (subProgram->mInlineeInfo == NULL)
  7627. break;
  7628. auto prevFuncAddr = subProgram->mBlock.mLowPC;
  7629. subProgram = subProgram->mInlineeInfo->mInlineParent;
  7630. addrs += EncodeDataPtr(subProgram->mBlock.mLowPC + 1, false);
  7631. addrs += EncodeDataPtr(prevFuncAddr, false);
  7632. size++;
  7633. inlineIdx++;
  7634. }
  7635. }
  7636. String evalStr = "(System.CallStackAddr)0x{1}";
  7637. evalStr += ", refid=\"" + referenceId + ".[]\"";
  7638. evalStr += ", ne";
  7639. retVal += "\n:repeat" + StrFormat("\t%d\t%d\t%d", 0, size, 10000) +
  7640. "\t[{0}]\t" + evalStr + ", action=ShowCodeAddr {1} {2}\t" + firstVal + "\t" + EncodeDataPtr((addr_target)0, false);
  7641. retVal += "\n:addrs\t" + addrs;
  7642. retVal += "\n:addrsEntrySize\t2";
  7643. return;
  7644. }
  7645. if (formatInfo.mExpandItemDepth == 0)
  7646. {
  7647. //retVal += "\n[Raw View]\tthis, this=" + ptrDataStr + ", nv";
  7648. retVal += "\n[Raw View]\t" + ptrDataStr + ", nv";
  7649. }
  7650. }
  7651. bool WinDebugger::IsPaused()
  7652. {
  7653. return (mRunState == RunState_Paused) || (mRunState == RunState_Breakpoint) || (mRunState == RunState_Exception) || (mRunState == RunState_DebugEval_Done);
  7654. }
  7655. DbgTypedValue WinDebugger::GetRegister(const StringImpl& regName, DbgLanguage language, CPURegisters* registers, Array<RegForm>* regForms)
  7656. {
  7657. int regNum = -1;
  7658. String lwrRegName(regName);
  7659. _strlwr((char*)lwrRegName.c_str());
  7660. // int regs
  7661. #ifdef BF_DBG_32
  7662. DbgTypeCode regType = DbgType_i32;
  7663. if (lwrRegName == "eax")
  7664. regNum = X86Reg_EAX;
  7665. else if (lwrRegName == "ecx")
  7666. regNum = X86Reg_ECX;
  7667. else if (lwrRegName == "edx")
  7668. regNum = X86Reg_EDX;
  7669. else if (lwrRegName == "ebx")
  7670. regNum = X86Reg_EBX;
  7671. else if (lwrRegName == "esp")
  7672. regNum = X86Reg_ESP;
  7673. else if (lwrRegName == "ebp")
  7674. regNum = X86Reg_EBP;
  7675. else if (lwrRegName == "esi")
  7676. regNum = X86Reg_ESI;
  7677. else if (lwrRegName == "edi")
  7678. regNum = X86Reg_EDI;
  7679. else if (lwrRegName == "eip")
  7680. regNum = X86Reg_EIP;
  7681. else if (lwrRegName == "efl")
  7682. regNum = X86Reg_EFL;
  7683. #else
  7684. DbgTypeCode regType = DbgType_i64;
  7685. if (lwrRegName == "rax")
  7686. regNum = X64Reg_RAX;
  7687. else if (lwrRegName == "rcx")
  7688. regNum = X64Reg_RCX;
  7689. else if (lwrRegName == "rdx")
  7690. regNum = X64Reg_RDX;
  7691. else if (lwrRegName == "rbx")
  7692. regNum = X64Reg_RBX;
  7693. else if (lwrRegName == "rsp")
  7694. regNum = X64Reg_RSP;
  7695. else if (lwrRegName == "rbp")
  7696. regNum = X64Reg_RBP;
  7697. else if (lwrRegName == "rsi")
  7698. regNum = X64Reg_RSI;
  7699. else if (lwrRegName == "rdi")
  7700. regNum = X64Reg_RDI;
  7701. else if (lwrRegName == "rip")
  7702. regNum = X64Reg_RIP;
  7703. else if (lwrRegName == "r8")
  7704. regNum = X64Reg_R8;
  7705. else if (lwrRegName == "r9")
  7706. regNum = X64Reg_R9;
  7707. else if (lwrRegName == "r10")
  7708. regNum = X64Reg_R10;
  7709. else if (lwrRegName == "r11")
  7710. regNum = X64Reg_R11;
  7711. else if (lwrRegName == "r12")
  7712. regNum = X64Reg_R12;
  7713. else if (lwrRegName == "r13")
  7714. regNum = X64Reg_R13;
  7715. else if (lwrRegName == "r14")
  7716. regNum = X64Reg_R14;
  7717. else if (lwrRegName == "r15")
  7718. regNum = X64Reg_R15;
  7719. else
  7720. {
  7721. regType = DbgType_i32;
  7722. if (lwrRegName == "eax")
  7723. regNum = X64Reg_RAX;
  7724. else if (lwrRegName == "ecx")
  7725. regNum = X64Reg_RCX;
  7726. else if (lwrRegName == "edx")
  7727. regNum = X64Reg_RDX;
  7728. else if (lwrRegName == "ebx")
  7729. regNum = X64Reg_RBX;
  7730. else if (lwrRegName == "efl")
  7731. regNum = X64Reg_EFL;
  7732. else if (lwrRegName == "esi")
  7733. regNum = X64Reg_RSI;
  7734. else if (lwrRegName == "edi")
  7735. regNum = X64Reg_RDI;
  7736. else if (lwrRegName == "r8d")
  7737. regNum = X64Reg_R8;
  7738. else if (lwrRegName == "r9d")
  7739. regNum = X64Reg_R9;
  7740. else if (lwrRegName == "r10d")
  7741. regNum = X64Reg_R10;
  7742. else if (lwrRegName == "r11d")
  7743. regNum = X64Reg_R11;
  7744. else if (lwrRegName == "r12d")
  7745. regNum = X64Reg_R12;
  7746. else if (lwrRegName == "r13d")
  7747. regNum = X64Reg_R13;
  7748. else if (lwrRegName == "r14d")
  7749. regNum = X64Reg_R14;
  7750. else if (lwrRegName == "r15d")
  7751. regNum = X64Reg_R15;
  7752. else
  7753. {
  7754. regType = DbgType_i16;
  7755. if (lwrRegName == "ax")
  7756. regNum = X64Reg_RAX;
  7757. else if (lwrRegName == "cx")
  7758. regNum = X64Reg_RCX;
  7759. else if (lwrRegName == "dx")
  7760. regNum = X64Reg_RDX;
  7761. else if (lwrRegName == "bx")
  7762. regNum = X64Reg_RBX;
  7763. else if (lwrRegName == "si")
  7764. regNum = X64Reg_RSI;
  7765. else if (lwrRegName == "di")
  7766. regNum = X64Reg_RDI;
  7767. else if (lwrRegName == "r8w")
  7768. regNum = X64Reg_R8;
  7769. else if (lwrRegName == "r9w")
  7770. regNum = X64Reg_R9;
  7771. else if (lwrRegName == "r10w")
  7772. regNum = X64Reg_R10;
  7773. else if (lwrRegName == "r11w")
  7774. regNum = X64Reg_R11;
  7775. else if (lwrRegName == "r12w")
  7776. regNum = X64Reg_R12;
  7777. else if (lwrRegName == "r13w")
  7778. regNum = X64Reg_R13;
  7779. else if (lwrRegName == "r14w")
  7780. regNum = X64Reg_R14;
  7781. else if (lwrRegName == "r15w")
  7782. regNum = X64Reg_R15;
  7783. else
  7784. {
  7785. regType = DbgType_i8;
  7786. if (lwrRegName == "al")
  7787. regNum = X64Reg_RAX;
  7788. else if (lwrRegName == "cl")
  7789. regNum = X64Reg_RCX;
  7790. else if (lwrRegName == "dl")
  7791. regNum = X64Reg_RDX;
  7792. else if (lwrRegName == "bl")
  7793. regNum = X64Reg_RBX;
  7794. else if (lwrRegName == "sil")
  7795. regNum = X64Reg_RSI;
  7796. else if (lwrRegName == "dil")
  7797. regNum = X64Reg_RDI;
  7798. else if (lwrRegName == "r8b")
  7799. regNum = X64Reg_R8;
  7800. else if (lwrRegName == "r9b")
  7801. regNum = X64Reg_R9;
  7802. else if (lwrRegName == "r10b")
  7803. regNum = X64Reg_R10;
  7804. else if (lwrRegName == "r11b")
  7805. regNum = X64Reg_R11;
  7806. else if (lwrRegName == "r12b")
  7807. regNum = X64Reg_R12;
  7808. else if (lwrRegName == "r13b")
  7809. regNum = X64Reg_R13;
  7810. else if (lwrRegName == "r14b")
  7811. regNum = X64Reg_R14;
  7812. else if (lwrRegName == "r15b")
  7813. regNum = X64Reg_R15;
  7814. }
  7815. }
  7816. }
  7817. #endif
  7818. auto dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  7819. if (regNum != -1)
  7820. {
  7821. DbgTypedValue typedVal;
  7822. typedVal.mType = dbgModule->GetPrimitiveType(regType, language);
  7823. typedVal.mInt64 = registers->mIntRegsArray[regNum];
  7824. typedVal.mRegNum = regNum;
  7825. return typedVal;
  7826. }
  7827. // st regs
  7828. if ((lwrRegName.length() == 3) && (lwrRegName[0] == 's') && (lwrRegName[1] == 't') && (lwrRegName[2] >= '0') && (lwrRegName[2] <= '7'))
  7829. {
  7830. regNum = CPUReg_FPSTREG_FIRST + (lwrRegName[2] - '0');
  7831. }
  7832. if (regNum != -1)
  7833. {
  7834. DbgTypedValue typedVal;
  7835. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Double, language);
  7836. typedVal.mDouble = ConvertFloat80ToDouble(registers->mFpMmRegsArray[regNum - CPUReg_FPSTREG_FIRST].fp.fp80);
  7837. typedVal.mRegNum = regNum;
  7838. return typedVal;
  7839. }
  7840. // mm regs
  7841. if ((lwrRegName.length() == 3) && (lwrRegName[0] == 'm') && (lwrRegName[1] == 'm') && (lwrRegName[2] >= '0') && (lwrRegName[2] <= '7'))
  7842. {
  7843. regNum = CPUReg_MMREG_FIRST + (lwrRegName[2] - '0');
  7844. }
  7845. if (regNum != -1)
  7846. {
  7847. DbgTypedValue typedVal;
  7848. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_i64, language);
  7849. typedVal.mInt64 = registers->mFpMmRegsArray[regNum - CPUReg_MMREG_FIRST].mm;
  7850. typedVal.mRegNum = regNum;
  7851. return typedVal;
  7852. }
  7853. // xmm regs
  7854. #ifdef BF_DBG_32
  7855. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '7') &&
  7856. (lwrRegName[4] == '_') && (lwrRegName[5] >= '0') && (lwrRegName[5] <= '3'))
  7857. {
  7858. regNum = CPUReg_XMMREG_FIRST + ((lwrRegName[3] - '0') * 4) + (lwrRegName[5] - '0');
  7859. }
  7860. #else
  7861. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '9') &&
  7862. (lwrRegName[4] == '_') && (lwrRegName[5] >= '0') && (lwrRegName[5] <= '3'))
  7863. {
  7864. regNum = CPUReg_XMMREG_FIRST + ((lwrRegName[3] - '0') * 4) + (lwrRegName[5] - '0');
  7865. }
  7866. if ((lwrRegName.length() == 7) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] == '1') && (lwrRegName[4] >= '0') && (lwrRegName[4] <= '9') &&
  7867. (lwrRegName[5] == '_') && (lwrRegName[6] >= '0') && (lwrRegName[6] <= '3'))
  7868. {
  7869. regNum = CPUReg_XMMREG_FIRST + ((10 + (lwrRegName[4] - '0')) * 4) + (lwrRegName[6] - '0');
  7870. }
  7871. #endif
  7872. if (regNum != -1)
  7873. {
  7874. int xmmMajor = (regNum - CPUReg_XMMREG_FIRST) >> 2;
  7875. int xmmMinor = (regNum - CPUReg_XMMREG_FIRST) & 3;
  7876. DwMmDisplayType mmDisplayType = GetDisplayInfo(StrFormat("$XMM%d", xmmMajor))->mMmDisplayType;
  7877. RegForm regForm = RegForm_Unknown;
  7878. if (regForms != NULL)
  7879. {
  7880. int regFormIdx = CPUReg_M128_XMMREG_FIRST + xmmMajor;
  7881. if (regFormIdx < (int)regForms->size())
  7882. regForm = (*regForms)[regFormIdx];
  7883. }
  7884. if (mmDisplayType == DwMmDisplayType_Default)
  7885. {
  7886. if ((regForm == RegForm_Double) || (regForm == RegForm_Double2))
  7887. mmDisplayType = DwMmDisplayType_Double;
  7888. else if (regForm == RegForm_Int4)
  7889. mmDisplayType = DwMmDisplayType_Int32;
  7890. }
  7891. //TODO: Add int types
  7892. if (mmDisplayType == DwMmDisplayType_Double)
  7893. {
  7894. DbgTypedValue typedVal;
  7895. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Double, language);
  7896. typedVal.mDouble = registers->mXmmDRegsArray[xmmMajor].d[xmmMinor];
  7897. typedVal.mRegNum = regNum;
  7898. return typedVal;
  7899. }
  7900. else if ((mmDisplayType == DwMmDisplayType_UInt8) || (mmDisplayType == DwMmDisplayType_Int16) || (mmDisplayType == DwMmDisplayType_Int32))
  7901. {
  7902. DbgTypedValue typedVal;
  7903. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_i32, language);
  7904. typedVal.mInt32 = registers->mXmmI32RegsARray[xmmMajor].i[xmmMinor];
  7905. typedVal.mRegNum = regNum;
  7906. return typedVal;
  7907. }
  7908. else if (mmDisplayType == DwMmDisplayType_Int64)
  7909. {
  7910. DbgTypedValue typedVal;
  7911. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_i64, language);
  7912. typedVal.mInt64 = registers->mXmmI64RegsARray[xmmMajor].i[xmmMinor];
  7913. typedVal.mRegNum = regNum;
  7914. return typedVal;
  7915. }
  7916. DbgTypedValue typedVal;
  7917. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Single, language);
  7918. typedVal.mSingle = registers->mXmmRegsArray[xmmMajor].f[xmmMinor];
  7919. typedVal.mRegNum = regNum;
  7920. return typedVal;
  7921. }
  7922. #ifdef BF_DBG_32
  7923. if ((lwrRegName.length() == 4) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '7'))
  7924. {
  7925. regNum = CPUReg_M128_XMMREG_FIRST + (lwrRegName[3] - '0');
  7926. }
  7927. #else
  7928. if ((lwrRegName.length() == 4) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] >= '0') && (lwrRegName[3] <= '9'))
  7929. {
  7930. regNum = CPUReg_M128_XMMREG_FIRST + (lwrRegName[3] - '0');
  7931. }
  7932. if ((lwrRegName.length() == 5) && (lwrRegName[0] == 'x') && (lwrRegName[1] == 'm') && (lwrRegName[2] == 'm') && (lwrRegName[3] == '1') && (lwrRegName[4] >= '0') && (lwrRegName[4] <= '5'))
  7933. {
  7934. regNum = CPUReg_M128_XMMREG_FIRST + 10 + (lwrRegName[4] - '0');
  7935. }
  7936. #endif
  7937. if (regNum != -1)
  7938. {
  7939. DbgTypedValue typedVal;
  7940. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_RegGroup, language);
  7941. 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)
  7942. typedVal.mRegNum = regNum;
  7943. return typedVal;
  7944. }
  7945. // flags
  7946. if ((lwrRegName.length() == 6) && (lwrRegName[0] == 'f') && (lwrRegName[1] == 'l') && (lwrRegName[2] == 'a') && (lwrRegName[3] == 'g') && (lwrRegName[5] == 'f'))
  7947. {
  7948. switch(lwrRegName[4])
  7949. {
  7950. case 'c': regNum = CPUReg_FLAG_CF_CARRY; break;
  7951. case 'p': regNum = CPUReg_FLAG_PF_PARITY; break;
  7952. case 'a': regNum = CPUReg_FLAG_AF_ADJUST; break;
  7953. case 'z': regNum = CPUReg_FLAG_ZF_ZERO; break;
  7954. case 's': regNum = CPUReg_FLAG_SF_SIGN; break;
  7955. case 'i': regNum = CPUReg_FLAG_IF_INTERRUPT; break;
  7956. case 'd': regNum = CPUReg_FLAG_DF_DIRECTION; break;
  7957. case 'o': regNum = CPUReg_FLAG_OF_OVERFLOW; break;
  7958. default: break;
  7959. }
  7960. }
  7961. if (regNum != -1)
  7962. {
  7963. int flagBit = CPURegisters::GetFlagBitForRegister(regNum);
  7964. BF_ASSERT(flagBit >= 0);
  7965. DbgTypedValue typedVal;
  7966. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_Bool, language);
  7967. typedVal.mBool = (registers->mIntRegs.efl & ((uint64)1 << flagBit)) != 0;
  7968. typedVal.mRegNum = regNum;
  7969. return typedVal;
  7970. }
  7971. // categories
  7972. if (lwrRegName == "allregs")
  7973. regNum = CPUReg_CAT_ALLREGS;
  7974. else if (lwrRegName == "iregs")
  7975. regNum = CPUReg_CAT_IREGS;
  7976. else if (lwrRegName == "fpregs")
  7977. regNum = CPUReg_CAT_FPREGS;
  7978. else if (lwrRegName == "mmregs")
  7979. regNum = CPUReg_CAT_MMREGS;
  7980. else if (lwrRegName == "xmmregs")
  7981. regNum = CPUReg_CAT_XMMREGS;
  7982. else if (lwrRegName == "flags")
  7983. regNum = CPUReg_CAT_FLAGS;
  7984. if (regNum != -1)
  7985. {
  7986. DbgTypedValue typedVal;
  7987. typedVal.mType = dbgModule->GetPrimitiveType(DbgType_RegGroup, language);
  7988. 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)
  7989. typedVal.mRegNum = regNum;
  7990. return typedVal;
  7991. }
  7992. return DbgTypedValue();
  7993. }
  7994. DbgModule* WinDebugger::GetCallStackDbgModule(int callStackIdx)
  7995. {
  7996. if ((mRunState == RunState_NotStarted) || (!IsPaused()))
  7997. return mEmptyDebugTarget->GetMainDbgModule();
  7998. if (callStackIdx == -1)
  7999. return mDebugTarget->GetMainDbgModule();
  8000. FixCallStackIdx(callStackIdx);
  8001. if (callStackIdx >= mCallStack.size())
  8002. return mDebugTarget->GetMainDbgModule();
  8003. UpdateCallStackMethod(callStackIdx);
  8004. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  8005. if (subProgram != NULL)
  8006. return subProgram->mCompileUnit->mDbgModule;
  8007. auto dbgModule = mDebugTarget->FindDbgModuleForAddress(mCallStack[callStackIdx]->mRegisters.GetPC());
  8008. if (dbgModule != NULL)
  8009. return dbgModule;
  8010. return mDebugTarget->GetMainDbgModule();
  8011. }
  8012. DbgSubprogram* WinDebugger::GetCallStackSubprogram(int callStackIdx)
  8013. {
  8014. if ((IsInRunState()) || (mRunState == RunState_NotStarted) || (callStackIdx == -1))
  8015. return NULL;
  8016. if (callStackIdx >= (int)mCallStack.size())
  8017. UpdateCallStack();
  8018. if (mCallStack.IsEmpty())
  8019. return NULL;
  8020. if (callStackIdx >= (int)mCallStack.size())
  8021. callStackIdx = 0;
  8022. UpdateCallStackMethod(callStackIdx);
  8023. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  8024. return subProgram;
  8025. }
  8026. DbgCompileUnit* WinDebugger::GetCallStackCompileUnit(int callStackIdx)
  8027. {
  8028. if ((IsInRunState()) || (mRunState == RunState_NotStarted) || (callStackIdx == -1))
  8029. return NULL;
  8030. if (callStackIdx >= (int)mCallStack.size())
  8031. UpdateCallStack();
  8032. if (mCallStack.IsEmpty())
  8033. return NULL;
  8034. if (callStackIdx >= (int)mCallStack.size())
  8035. callStackIdx = 0;
  8036. UpdateCallStackMethod(callStackIdx);
  8037. auto subProgram = mCallStack[callStackIdx]->mSubProgram;
  8038. if (subProgram == NULL)
  8039. return NULL;
  8040. return subProgram->mCompileUnit;
  8041. }
  8042. String WinDebugger::EvaluateContinue(DbgPendingExpr* pendingExpr, BfPassInstance& bfPassInstance)
  8043. {
  8044. DbgModule* dbgModule = NULL;
  8045. DbgCompileUnit* dbgCompileUnit = NULL;
  8046. if (pendingExpr->mThreadId == -1)
  8047. {
  8048. if ((pendingExpr->mFormatInfo.mLanguage == DbgLanguage_Beef) && (mDebugTarget != NULL) && (mDebugTarget->mTargetBinary != NULL))
  8049. dbgModule = mDebugTarget->mTargetBinary;
  8050. else
  8051. dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  8052. }
  8053. else
  8054. {
  8055. dbgModule = GetCallStackDbgModule(pendingExpr->mCallStackIdx);
  8056. if ((dbgModule != NULL) &&(!dbgModule->mDebugTarget->mIsEmpty))
  8057. dbgCompileUnit = GetCallStackCompileUnit(pendingExpr->mCallStackIdx);
  8058. }
  8059. if (dbgModule == NULL)
  8060. dbgModule = mEmptyDebugTarget->GetMainDbgModule();
  8061. if (!pendingExpr->mException.empty())
  8062. {
  8063. RestoreAllRegisters();
  8064. return "!" + pendingExpr->mException;
  8065. }
  8066. DwAutoComplete autoComplete;
  8067. if (bfPassInstance.HasFailed())
  8068. {
  8069. // Don't allow pending calls if we've already failed in the calling Evaluate()
  8070. pendingExpr->mExpressionFlags = (DwEvalExpressionFlags)(pendingExpr->mExpressionFlags & ~DwEvalExpressionFlag_AllowCalls);
  8071. }
  8072. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, pendingExpr->mCallStackIdx, pendingExpr->mCursorPos);
  8073. if (!pendingExpr->mFormatInfo.mStackSearchStr.IsEmpty())
  8074. {
  8075. dbgExprEvaluator.mStackSearch = new DbgStackSearch();
  8076. dbgExprEvaluator.mStackSearch->mSearchStr = pendingExpr->mFormatInfo.mStackSearchStr;
  8077. }
  8078. dbgExprEvaluator.mLanguage = pendingExpr->mFormatInfo.mLanguage;
  8079. dbgExprEvaluator.mReferenceId = &pendingExpr->mReferenceId;
  8080. dbgExprEvaluator.mExpressionFlags = pendingExpr->mExpressionFlags;
  8081. dbgExprEvaluator.mExplicitThis = pendingExpr->mFormatInfo.mExplicitThis;
  8082. dbgExprEvaluator.mSubjectExpr = pendingExpr->mFormatInfo.mSubjectExpr;
  8083. dbgExprEvaluator.mNamespaceSearchStr = pendingExpr->mFormatInfo.mNamespaceSearch;
  8084. dbgExprEvaluator.mExpectingTypeName = pendingExpr->mFormatInfo.mExpectedType;
  8085. dbgExprEvaluator.mCallResults = &pendingExpr->mCallResults;
  8086. if ((pendingExpr->mExpressionFlags & DwEvalExpressionFlag_ValidateOnly) != 0)
  8087. {
  8088. dbgExprEvaluator.mValidateOnly = true;
  8089. }
  8090. if (pendingExpr->mCursorPos != -1)
  8091. {
  8092. dbgExprEvaluator.mAutoComplete = &autoComplete;
  8093. }
  8094. dbgExprEvaluator.mDbgCompileUnit = dbgCompileUnit;
  8095. DbgTypedValue exprResult;
  8096. if (pendingExpr->mExplitType != NULL)
  8097. {
  8098. exprResult.mHasNoValue = true;
  8099. exprResult.mType = pendingExpr->mExplitType;
  8100. }
  8101. else if (pendingExpr->mExprNode != NULL)
  8102. {
  8103. exprResult = dbgExprEvaluator.Resolve(pendingExpr->mExprNode);
  8104. }
  8105. if (dbgExprEvaluator.mCreatedPendingCall)
  8106. {
  8107. BF_ASSERT(mRunState == RunState_DebugEval);
  8108. //ContinueDebugEvent();
  8109. return "!pending";
  8110. }
  8111. if (dbgExprEvaluator.mCountResultOverride != -1)
  8112. pendingExpr->mFormatInfo.mOverrideCount = dbgExprEvaluator.mCountResultOverride;
  8113. String val;
  8114. if (bfPassInstance.HasFailed())
  8115. {
  8116. BfLogDbgExpr("Evaluate Failed: %s\n", bfPassInstance.mErrors[0]->mError.c_str());
  8117. val = StrFormat("!%d\t%d\t%s", bfPassInstance.mErrors[0]->GetSrcStart(), bfPassInstance.mErrors[0]->GetSrcLength(), bfPassInstance.mErrors[0]->mError.c_str());
  8118. }
  8119. else if (dbgExprEvaluator.mBlockedSideEffects)
  8120. {
  8121. BfLogDbgExpr("Evaluate blocked side effects\n");
  8122. val = "!sideeffects";
  8123. }
  8124. else if (!exprResult)
  8125. {
  8126. if (exprResult.mType != NULL)
  8127. {
  8128. BfLogDbgExpr("Evaluate success\n");
  8129. String typeName = exprResult.mType->ToString();
  8130. DbgType* rawType = exprResult.mType;
  8131. if (rawType->IsBfObjectPtr())
  8132. rawType = rawType->mTypeParam;
  8133. String typeNameRaw = rawType->ToStringRaw();
  8134. val = typeName + "\n" + typeName;
  8135. val += "\n" + GetMemberList(exprResult.mType, typeNameRaw, false, true, false, false, exprResult.mIsReadOnly);
  8136. if (exprResult.mType->mTypeCode == DbgType_Namespace)
  8137. {
  8138. val += "\n:type\tnamespace";
  8139. }
  8140. else
  8141. {
  8142. auto type = exprResult.mType;
  8143. if (type->IsPointer())
  8144. type = type->mTypeParam;
  8145. if (type->IsBfObject())
  8146. val += "\n:type\tclass";
  8147. else
  8148. val += "\n:type\tvaluetype";
  8149. }
  8150. if (!pendingExpr->mReferenceId.empty())
  8151. val += "\n:referenceId\t" + pendingExpr->mReferenceId;
  8152. }
  8153. else
  8154. val = "!";
  8155. }
  8156. else if ((pendingExpr->mExpressionFlags & (DwEvalExpressionFlag_MemoryAddress)) != 0)
  8157. {
  8158. DbgType* resultType = exprResult.mType->RemoveModifiers();
  8159. if ((resultType->IsInteger()) || (resultType->IsPointerOrRef()))
  8160. {
  8161. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", 0);
  8162. }
  8163. else
  8164. {
  8165. if (exprResult.mSrcAddress != 0)
  8166. val = StrFormat("!Type '%s' is invalid. A pointer or address value is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  8167. else
  8168. val = StrFormat("!Type '%s' is invalid. A pointer or address value is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  8169. }
  8170. }
  8171. else if ((pendingExpr->mExpressionFlags & (DwEvalExpressionFlag_MemoryWatch)) != 0)
  8172. {
  8173. DbgType* resultType = exprResult.mType->RemoveModifiers();
  8174. bool isMemoryWatch = (pendingExpr->mExpressionFlags & DwEvalExpressionFlag_MemoryWatch) != 0;
  8175. if (!resultType->IsPointerOrRef())
  8176. {
  8177. if (exprResult.mSrcAddress != 0)
  8178. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  8179. else
  8180. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  8181. }
  8182. else
  8183. {
  8184. auto innerType = resultType->mTypeParam;
  8185. int byteCount = innerType->GetByteCount();
  8186. if (pendingExpr->mFormatInfo.mArrayLength != -1)
  8187. byteCount *= pendingExpr->mFormatInfo.mArrayLength;
  8188. if (byteCount == 0)
  8189. {
  8190. 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());
  8191. }
  8192. #ifdef BF_DBG_32
  8193. else if ((isMemoryWatch) && (!IsMemoryBreakpointSizeValid(exprResult.mPtr, byteCount)))
  8194. {
  8195. if (innerType->mSize > 16)
  8196. 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);
  8197. else if (!IsMemoryBreakpointSizeValid(0, byteCount))
  8198. 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);
  8199. else
  8200. 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);
  8201. }
  8202. #else
  8203. else if ((isMemoryWatch) && (!IsMemoryBreakpointSizeValid(exprResult.mPtr, byteCount)))
  8204. {
  8205. if (innerType->mSize > 32)
  8206. 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);
  8207. else if (!IsMemoryBreakpointSizeValid(0, byteCount))
  8208. 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);
  8209. else
  8210. 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);
  8211. }
  8212. #endif
  8213. else
  8214. {
  8215. auto language = dbgExprEvaluator.GetLanguage();
  8216. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", byteCount) + "\n" + StrFormat("%d\t", language) + innerType->ToStringRaw(language);
  8217. }
  8218. }
  8219. }
  8220. else
  8221. {
  8222. if (pendingExpr->mFormatInfo.mNoEdit)
  8223. exprResult.mIsReadOnly = true;
  8224. if (!pendingExpr->mReferenceId.empty())
  8225. pendingExpr->mFormatInfo.mReferenceId = pendingExpr->mReferenceId;
  8226. val = DbgTypedValueToString(exprResult, pendingExpr->mExprNode->ToString(), pendingExpr->mFormatInfo, &dbgExprEvaluator, (pendingExpr->mExpressionFlags & DwEvalExpressionFlag_FullPrecision) != 0);
  8227. if ((!val.empty()) && (val[0] == '!'))
  8228. return val;
  8229. if (pendingExpr->mFormatInfo.mRawString)
  8230. return val;
  8231. if (exprResult.mIsLiteral)
  8232. val += "\n:literal";
  8233. if (bfPassInstance.HasMessages())
  8234. {
  8235. for (auto error : bfPassInstance.mErrors)
  8236. {
  8237. if (error->mIsWarning)
  8238. {
  8239. val += "\n:warn\t";
  8240. val += error->mError;
  8241. }
  8242. }
  8243. }
  8244. if (!pendingExpr->mFormatInfo.mReferenceId.empty())
  8245. val += "\n:referenceId\t" + pendingExpr->mFormatInfo.mReferenceId;
  8246. auto breakAddress = exprResult.mSrcAddress;
  8247. int breakSize = exprResult.mType->GetByteCount();
  8248. if (exprResult.mType->IsRef())
  8249. breakSize = exprResult.mType->mTypeParam->GetByteCount();
  8250. if ((breakAddress != 0) && (HasMemoryBreakpoint(breakAddress, breakSize)))
  8251. val += StrFormat("\n:break\t%@", breakAddress);
  8252. auto checkType = exprResult.mType->RemoveModifiers();
  8253. if (checkType->IsBfObjectPtr())
  8254. val += "\n:type\tobject";
  8255. else if ((checkType->IsPointer()) || (checkType->mTypeCode == DbgType_Subroutine))
  8256. val += "\n:type\tpointer";
  8257. else if (checkType->IsInteger())
  8258. val += "\n:type\tint";
  8259. else if (checkType->IsFloat())
  8260. val += "\n:type\tfloat";
  8261. else if ((exprResult.mRegNum >= X64Reg_M128_XMM0) && (exprResult.mRegNum <= X64Reg_M128_XMM15))
  8262. val += "\n:type\tmm128";
  8263. else
  8264. val += "\n:type\tvaluetype";
  8265. if ((pendingExpr->mFormatInfo.mTypeKindFlags & DbgTypeKindFlag_Int) != 0)
  8266. val += "\n:type\tint";
  8267. if (dbgExprEvaluator.mHadSideEffects)
  8268. val += "\n:sideeffects";
  8269. if ((dbgExprEvaluator.mStackSearch != NULL) && (dbgExprEvaluator.mStackSearch->mStartingStackIdx != dbgExprEvaluator.mCallStackIdx))
  8270. val += StrFormat("\n:stackIdx\t%d", dbgExprEvaluator.mCallStackIdx);
  8271. auto underlyingType = exprResult.mType->RemoveModifiers();
  8272. bool canEdit = true;
  8273. if (pendingExpr->mFormatInfo.mLanguage == DbgLanguage_Beef)
  8274. {
  8275. if (exprResult.mType->IsConst())
  8276. canEdit = false;
  8277. }
  8278. if (pendingExpr->mFormatInfo.mNoEdit)
  8279. canEdit = false;
  8280. if (exprResult.mIsReadOnly)
  8281. canEdit = false;
  8282. const char* langStr = (pendingExpr->mFormatInfo.mLanguage == DbgLanguage_Beef) ? "@Beef:" : "@C:";
  8283. if (exprResult.mSrcAddress != 0)
  8284. {
  8285. val += StrFormat("\n:addrValueExpr\t%s(%s*)", langStr, exprResult.mType->ToString(pendingExpr->mFormatInfo.mLanguage).c_str());
  8286. val += EncodeDataPtr(exprResult.mSrcAddress, true);
  8287. }
  8288. if (exprResult.mType->IsPointerOrRef())
  8289. {
  8290. auto underlyingType = exprResult.mType->mTypeParam;
  8291. if (underlyingType != NULL)
  8292. {
  8293. val += StrFormat("\n:pointeeExpr\t%s(%s%s)", langStr, underlyingType->ToString(pendingExpr->mFormatInfo.mLanguage).c_str(),
  8294. underlyingType->IsBfObject() ? "" : "*");
  8295. val += EncodeDataPtr(exprResult.mPtr, true);
  8296. }
  8297. }
  8298. if (val[0] == '!')
  8299. {
  8300. // Already has an error embedded, can't edit
  8301. }
  8302. else if ((exprResult.mSrcAddress != 0) && (underlyingType->mTypeCode >= DbgType_i8) && (underlyingType->mTypeCode <= DbgType_Ptr) &&
  8303. (underlyingType->mTypeCode != DbgType_Class) && (underlyingType->mTypeCode != DbgType_Struct))
  8304. {
  8305. if (canEdit)
  8306. val += "\n:canEdit";
  8307. if (exprResult.mType->mTypeCode == DbgType_Ptr)
  8308. {
  8309. val += "\n:editVal\t" + EncodeDataPtr(exprResult.mPtr, true);
  8310. }
  8311. }
  8312. else if ((underlyingType->IsStruct()) && (exprResult.mSrcAddress != 0) && (underlyingType->IsTypedPrimitive()))
  8313. {
  8314. auto primType = underlyingType->GetRootBaseType();
  8315. DbgTypedValue primVal = dbgExprEvaluator.ReadTypedValue(NULL, primType, exprResult.mSrcAddress, DbgAddrType_Target);
  8316. String primResult = DbgTypedValueToString(primVal, "", pendingExpr->mFormatInfo, NULL);
  8317. int crPos = (int)primResult.IndexOf('\n');
  8318. if (crPos != -1)
  8319. primResult.RemoveToEnd(crPos);
  8320. if (canEdit)
  8321. val += "\n:canEdit";
  8322. val += "\n:editVal\t" + primResult;
  8323. }
  8324. else if (exprResult.mRegNum >= 0)
  8325. {
  8326. bool isPseudoReg = ( ((exprResult.mRegNum >= X86Reg_M128_XMMREG_FIRST) && (exprResult.mRegNum <= X86Reg_M128_XMMREG_LAST))
  8327. || ((exprResult.mRegNum >= X86Reg_CAT_FIRST) && (exprResult.mRegNum <= X86Reg_CAT_LAST)) );
  8328. if (!isPseudoReg)
  8329. {
  8330. if (canEdit)
  8331. val += "\n:canEdit";
  8332. }
  8333. }
  8334. }
  8335. if (pendingExpr->mFormatInfo.mRawString)
  8336. return "";
  8337. if (val[0] != '!')
  8338. {
  8339. if (pendingExpr->mUsedSpecifiedLock)
  8340. val += "\n:usedLock";
  8341. if (pendingExpr->mStackIdxOverride != -1)
  8342. val += StrFormat("\n:stackIdx\t%d", pendingExpr->mStackIdxOverride);
  8343. }
  8344. if (pendingExpr->mCursorPos != -1)
  8345. val += GetAutocompleteOutput(autoComplete);
  8346. return val;
  8347. }
  8348. String WinDebugger::EvaluateContinue()
  8349. {
  8350. BP_ZONE("WinDebugger::EvaluateContinue");
  8351. AutoCrit autoCrit(mDebugManager->mCritSect);
  8352. if (mDebugPendingExpr == NULL)
  8353. return "!Evaluation canceled";
  8354. if (!IsPaused())
  8355. return "!Not paused";
  8356. if (mRunState == RunState_DebugEval_Done)
  8357. mRunState = RunState_Paused;
  8358. BfPassInstance bfPassInstance(mBfSystem);
  8359. String result = EvaluateContinue(mDebugPendingExpr, bfPassInstance);
  8360. if (result != "!pending")
  8361. {
  8362. BfLogDbg("EvaluateContinue finishing pending expr in thread %d\n", mDebugEvalThreadInfo.mThreadId);
  8363. CleanupDebugEval();
  8364. }
  8365. return result;
  8366. }
  8367. void WinDebugger::EvaluateContinueKeep()
  8368. {
  8369. if (mDebugPendingExpr != NULL)
  8370. mDebugPendingExpr->mIdleTicks = 0;
  8371. }
  8372. static void PdbTestFile(WinDebugger* debugger, const StringImpl& path)
  8373. {
  8374. if (!path.EndsWith(".PDB", StringImpl::CompareKind_OrdinalIgnoreCase))
  8375. return;
  8376. OutputDebugStrF("Testing %s\n", path.c_str());
  8377. COFF coffFile(debugger->mDebugTarget);
  8378. uint8 wantGuid[16] = { 0 };
  8379. if (!coffFile.TryLoadPDB(path, wantGuid, -1))
  8380. return;
  8381. if (!coffFile.mIs64Bit)
  8382. return;
  8383. coffFile.ParseTypeData();
  8384. coffFile.ParseSymbolData();
  8385. coffFile.ParseGlobalsData();
  8386. for (int i = 0; i < coffFile.mTypes.mSize; i++)
  8387. coffFile.mTypes[i]->PopulateType();
  8388. for (int i = 0; i < coffFile.mCvModuleInfo.mSize; i++)
  8389. coffFile.ParseCompileUnit(i);
  8390. }
  8391. static void PdbTest(WinDebugger* debugger, const StringImpl& path)
  8392. {
  8393. for (auto& fileEntry : FileEnumerator(path, FileEnumerator::Flags_Files))
  8394. {
  8395. String filePath = fileEntry.GetFilePath();
  8396. PdbTestFile(debugger, filePath);
  8397. }
  8398. for (auto& fileEntry : FileEnumerator(path, FileEnumerator::Flags_Directories))
  8399. {
  8400. String childPath = fileEntry.GetFilePath();
  8401. String dirName;
  8402. dirName = GetFileName(childPath);
  8403. PdbTest(debugger, childPath);
  8404. }
  8405. }
  8406. String WinDebugger::Evaluate(const StringImpl& expr, DwFormatInfo formatInfo, int callStackIdx, int cursorPos, int language, DwEvalExpressionFlags expressionFlags)
  8407. {
  8408. BP_ZONE_F("WinDebugger::Evaluate %s", BP_DYN_STR(expr.c_str()));
  8409. AutoCrit autoCrit(mDebugManager->mCritSect);
  8410. if ((expressionFlags & DwEvalExpressionFlag_Symbol) != 0)
  8411. {
  8412. DwAutoComplete autoComplete;
  8413. String retVal;
  8414. retVal += GetAutocompleteOutput(autoComplete);
  8415. return retVal;
  8416. }
  8417. UpdateCallStackMethod(callStackIdx);
  8418. BfLogDbgExpr("Evaluate %s in thread %d\n", expr.c_str(), (mActiveThread != NULL) ? mActiveThread->mThreadId : 0);
  8419. if (language != -1)
  8420. formatInfo.mLanguage = (DbgLanguage)language;
  8421. auto activeThread = mActiveThread;
  8422. if ((!IsPaused()) && (mRunState != RunState_NotStarted) && (mRunState != RunState_DebugEval))
  8423. {
  8424. activeThread = NULL;
  8425. callStackIdx = -1;
  8426. }
  8427. if (mDebugPendingExpr != NULL)
  8428. {
  8429. // We already have a pending call
  8430. expressionFlags = (DwEvalExpressionFlags)(expressionFlags & ~DwEvalExpressionFlag_AllowCalls);
  8431. }
  8432. if ((expressionFlags & DwEvalExpressionFlag_RawStr) != 0)
  8433. {
  8434. formatInfo.mRawString = true;
  8435. }
  8436. if ((expressionFlags & DwEvalExpressionFlag_AllowStringView) != 0)
  8437. {
  8438. formatInfo.mAllowStringView = true;
  8439. }
  8440. auto terminatedExpr = expr + ";";
  8441. auto prevActiveThread = mActiveThread;
  8442. bool restoreActiveThread = false;
  8443. defer(
  8444. {
  8445. if (restoreActiveThread)
  8446. SetActiveThread(prevActiveThread->mThreadId);
  8447. });
  8448. bool usedSpecifiedLock = false;
  8449. int stackIdxOverride = -1;
  8450. if (terminatedExpr.StartsWith('{'))
  8451. {
  8452. String locString;
  8453. int closeIdx = terminatedExpr.IndexOf('}');
  8454. if (closeIdx != -1)
  8455. locString = terminatedExpr.Substring(1, closeIdx - 1);
  8456. for (int i = 0; i <= closeIdx; i++)
  8457. terminatedExpr[i] = ' ';
  8458. locString.Trim();
  8459. if (locString.StartsWith("Thread:", StringImpl::CompareKind_OrdinalIgnoreCase))
  8460. {
  8461. bool foundLockMatch = true;
  8462. locString.Remove(0, 7);
  8463. char* endPtr = NULL;
  8464. int64 threadId = (int64)strtoll(locString.c_str(), &endPtr, 10);
  8465. if (endPtr != NULL)
  8466. {
  8467. locString.Remove(0, endPtr - locString.c_str());
  8468. locString.Trim();
  8469. if (locString.StartsWith("SP:", StringImpl::CompareKind_OrdinalIgnoreCase))
  8470. {
  8471. locString.Remove(0, 3);
  8472. char* endPtr = NULL;
  8473. uint64 sp = (uint64)strtoll(locString.c_str(), &endPtr, 16);
  8474. if (endPtr != NULL)
  8475. {
  8476. locString.Remove(0, endPtr - locString.c_str());
  8477. locString.Trim();
  8478. if (locString.StartsWith("Func:", StringImpl::CompareKind_OrdinalIgnoreCase))
  8479. {
  8480. locString.Remove(0, 5);
  8481. char* endPtr = NULL;
  8482. int64 funcAddr = (int64)strtoll(locString.c_str(), &endPtr, 16);
  8483. if (endPtr != NULL)
  8484. {
  8485. // Actually do it
  8486. if ((mActiveThread != NULL) && (mActiveThread->mThreadId != threadId))
  8487. restoreActiveThread = true;
  8488. if ((mActiveThread == NULL) || (mActiveThread->mThreadId != threadId))
  8489. SetActiveThread(threadId);
  8490. if ((mActiveThread != NULL) && (mActiveThread->mThreadId == threadId))
  8491. {
  8492. int foundStackIdx = -1;
  8493. int checkStackIdx = 0;
  8494. while (true)
  8495. {
  8496. if (checkStackIdx >= mCallStack.mSize)
  8497. UpdateCallStack();
  8498. if (checkStackIdx >= mCallStack.mSize)
  8499. break;
  8500. auto stackFrame = mCallStack[checkStackIdx];
  8501. if (stackFrame->mRegisters.GetSP() == sp)
  8502. {
  8503. foundStackIdx = checkStackIdx;
  8504. break;
  8505. }
  8506. if (stackFrame->mRegisters.GetSP() > sp)
  8507. {
  8508. foundStackIdx = checkStackIdx - 1;
  8509. break;
  8510. }
  8511. checkStackIdx++;
  8512. }
  8513. if (foundStackIdx != -1)
  8514. {
  8515. UpdateCallStackMethod(foundStackIdx);
  8516. auto stackFrame = mCallStack[foundStackIdx];
  8517. if ((stackFrame->mSubProgram != NULL) && ((int64)stackFrame->mSubProgram->mBlock.mLowPC == funcAddr))
  8518. {
  8519. if ((callStackIdx != foundStackIdx) || (mActiveThread != prevActiveThread))
  8520. usedSpecifiedLock = true;
  8521. callStackIdx = foundStackIdx;
  8522. foundLockMatch = true;
  8523. }
  8524. }
  8525. }
  8526. }
  8527. }
  8528. }
  8529. }
  8530. }
  8531. if (!foundLockMatch)
  8532. return "!Locked stack frame not found";
  8533. bool doClear = false;
  8534. for (int i = closeIdx; i < terminatedExpr.mLength; i++)
  8535. {
  8536. char c = terminatedExpr[i];
  8537. if (doClear)
  8538. {
  8539. terminatedExpr[i] = ' ';
  8540. if (c == '}')
  8541. break;
  8542. }
  8543. else
  8544. {
  8545. if (c == '{')
  8546. {
  8547. int endIdx = terminatedExpr.IndexOf('}');
  8548. if (endIdx == -1)
  8549. break;
  8550. terminatedExpr[i] = ' ';
  8551. doClear = true;
  8552. }
  8553. else if (!::isspace((uint8)c))
  8554. break;
  8555. }
  8556. }
  8557. }
  8558. else if (!locString.IsEmpty())
  8559. {
  8560. const char* checkPtr = locString.c_str();
  8561. if ((*checkPtr == '^') || (*checkPtr == '@'))
  8562. checkPtr++;
  8563. char* endPtr = NULL;
  8564. int useCallStackIdx = strtol(checkPtr, &endPtr, 10);
  8565. if (endPtr == locString.c_str() + locString.length())
  8566. {
  8567. if (locString[0] == '@')
  8568. callStackIdx = useCallStackIdx;
  8569. else
  8570. callStackIdx += useCallStackIdx;
  8571. stackIdxOverride = callStackIdx;
  8572. }
  8573. else
  8574. {
  8575. formatInfo.mStackSearchStr = locString;
  8576. }
  8577. }
  8578. }
  8579. auto dbgModule = GetCallStackDbgModule(callStackIdx);
  8580. auto dbgSubprogram = GetCallStackSubprogram(callStackIdx);
  8581. DbgCompileUnit* dbgCompileUnit = NULL;
  8582. if (dbgSubprogram != NULL)
  8583. dbgCompileUnit = dbgSubprogram->mCompileUnit;
  8584. if ((expr.length() > 0) && (expr[0] == '!'))
  8585. {
  8586. if (expr.StartsWith("!step "))
  8587. {
  8588. expressionFlags = (DwEvalExpressionFlags)(expressionFlags | DwEvalExpressionFlag_StepIntoCalls);
  8589. for (int i = 0; i < 5; i++)
  8590. terminatedExpr[i] = ' ';
  8591. }
  8592. else
  8593. {
  8594. String cmd = expr;
  8595. int commaPos = (int)cmd.IndexOf(',');
  8596. if (commaPos != -1)
  8597. cmd.RemoveToEnd(commaPos);
  8598. if (cmd == "!info")
  8599. {
  8600. OutputMessage(StrFormat("Module: %s\n", dbgModule->mDisplayName.c_str()));
  8601. if (dbgSubprogram == NULL)
  8602. {
  8603. //
  8604. }
  8605. else if (dbgSubprogram->mLinkName != NULL)
  8606. {
  8607. OutputMessage(StrFormat("Link Name: %s\n", dbgSubprogram->mLinkName));
  8608. }
  8609. else
  8610. {
  8611. String outSymbol;
  8612. if (mDebugTarget->FindSymbolAt(dbgSubprogram->mBlock.mLowPC, &outSymbol))
  8613. {
  8614. OutputMessage(StrFormat("Link Name: %s\n", outSymbol.c_str()));
  8615. }
  8616. }
  8617. return "";
  8618. }
  8619. else if (cmd == "!dbg")
  8620. {
  8621. mDbgBreak = true;
  8622. return "";
  8623. }
  8624. else if (cmd == "!pdbtest")
  8625. {
  8626. PdbTest(this, "c:\\");
  8627. }
  8628. else if (cmd.StartsWith("!pdbtest "))
  8629. PdbTestFile(this, cmd.Substring(9));
  8630. }
  8631. }
  8632. bool valIsAddr = false;
  8633. BfParser* parser = new BfParser(mBfSystem);
  8634. parser->mCompatMode = true;
  8635. BfPassInstance bfPassInstance(mBfSystem);
  8636. if ((terminatedExpr.length() > 2) && (terminatedExpr[0] == '@'))
  8637. {
  8638. if (terminatedExpr[1] == '!') // Return string as error
  8639. {
  8640. int errorEnd = (int)terminatedExpr.IndexOf("@!", 2);
  8641. if (errorEnd != -1)
  8642. return terminatedExpr.Substring(1, errorEnd - 1);
  8643. else
  8644. return terminatedExpr.Substring(1);
  8645. }
  8646. else if (terminatedExpr[1] == '>') // Return string as text
  8647. {
  8648. int errorEnd = (int)terminatedExpr.IndexOf("@>", 2);
  8649. if (errorEnd != -1)
  8650. return terminatedExpr.Substring(2, errorEnd - 1);
  8651. else
  8652. return terminatedExpr.Substring(2);
  8653. }
  8654. else // Look for "@:" or "@Beef:" style
  8655. {
  8656. int colonIdx = terminatedExpr.IndexOf(':');
  8657. if (colonIdx > 0)
  8658. {
  8659. bool isValid = true;
  8660. DbgLanguage language = DbgLanguage_Unknown;
  8661. String lang = terminatedExpr.Substring(1, colonIdx - 1);
  8662. lang = ToUpper(lang);
  8663. if ((lang == "") || (lang == "BEEF"))
  8664. {
  8665. language = DbgLanguage_Beef;
  8666. }
  8667. else if (lang == "C")
  8668. {
  8669. language = DbgLanguage_C;
  8670. }
  8671. if (language != DbgLanguage_Unknown)
  8672. {
  8673. for (int i = 0; i < colonIdx + 1; i++)
  8674. terminatedExpr[i] = ' ';
  8675. DbgLanguage curLanguage = DbgLanguage_Unknown;
  8676. if (dbgSubprogram != NULL)
  8677. curLanguage = dbgSubprogram->GetLanguage();
  8678. if (language != curLanguage)
  8679. {
  8680. dbgModule = mDebugTarget->mTargetBinary;
  8681. dbgSubprogram = NULL;
  8682. formatInfo.mLanguage = language;
  8683. callStackIdx = -1;
  8684. }
  8685. }
  8686. }
  8687. }
  8688. }
  8689. parser->SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  8690. parser->Parse(&bfPassInstance);
  8691. BfReducer bfReducer;
  8692. bfReducer.mAlloc = parser->mAlloc;
  8693. bfReducer.mSystem = mBfSystem;
  8694. bfReducer.mPassInstance = &bfPassInstance;
  8695. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser->mRootNode);
  8696. bfReducer.mVisitorPos.MoveNext();
  8697. bfReducer.mCompatMode = parser->mCompatMode;
  8698. bfReducer.mSource = parser;
  8699. auto exprNode = bfReducer.CreateExpression(parser->mRootNode->mChildArr.GetAs<BfAstNode*>(0));
  8700. parser->Close();
  8701. formatInfo.mCallStackIdx = callStackIdx;
  8702. if ((formatInfo.mLanguage == DbgLanguage_Unknown) && (dbgSubprogram != NULL))
  8703. formatInfo.mLanguage = dbgSubprogram->GetLanguage();
  8704. DbgPendingExpr* pendingExpr = new DbgPendingExpr();
  8705. if (activeThread != NULL)
  8706. pendingExpr->mThreadId = activeThread->mThreadId;
  8707. pendingExpr->mParser = parser;
  8708. pendingExpr->mCallStackIdx = callStackIdx;
  8709. pendingExpr->mCursorPos = cursorPos;
  8710. pendingExpr->mExpressionFlags = expressionFlags;
  8711. pendingExpr->mExprNode = exprNode;
  8712. DbgType* explicitType = NULL;
  8713. String formatFlags;
  8714. String assignExpr;
  8715. int assignExprOffset = -1;
  8716. if ((exprNode != NULL) && (exprNode->GetSrcEnd() < (int)expr.length()))
  8717. {
  8718. int formatOffset = exprNode->GetSrcEnd();
  8719. while (formatOffset < (int)expr.length())
  8720. {
  8721. char c = expr[formatOffset];
  8722. if (c == ' ')
  8723. formatOffset++;
  8724. else
  8725. break;
  8726. }
  8727. formatFlags = Trim(expr.Substring(formatOffset));
  8728. bool isComplexType = false;
  8729. for (char c : formatFlags)
  8730. if (c == '>')
  8731. isComplexType = true;
  8732. if (isComplexType)
  8733. {
  8734. explicitType = dbgModule->FindType(expr);
  8735. }
  8736. if ((explicitType == NULL) && (formatFlags.length() > 0))
  8737. {
  8738. String errorString = "Invalid expression";
  8739. if (!ParseFormatInfo(dbgModule, formatFlags, &formatInfo, &bfPassInstance, &assignExprOffset, &assignExpr, &errorString))
  8740. {
  8741. if (formatInfo.mRawString)
  8742. return "";
  8743. bfPassInstance.FailAt(errorString, parser->mSourceData, exprNode->GetSrcEnd(), (int) expr.length() - exprNode->GetSrcEnd());
  8744. formatFlags = "";
  8745. }
  8746. if (assignExprOffset != -1)
  8747. assignExprOffset += formatOffset;
  8748. }
  8749. }
  8750. if (assignExpr.length() > 0)
  8751. {
  8752. String newEvalStr = exprNode->ToString() + " = ";
  8753. int errorOffset = (int)newEvalStr.length();
  8754. newEvalStr += assignExpr;
  8755. String result = Evaluate(newEvalStr, formatInfo, callStackIdx, cursorPos, language, expressionFlags);
  8756. if (result[0] == '!')
  8757. {
  8758. int tabPos = (int)result.IndexOf('\t');
  8759. if (tabPos > 0)
  8760. {
  8761. int errorStart = atoi(result.Substring(1, tabPos - 1).c_str());
  8762. if (errorStart >= errorOffset)
  8763. {
  8764. result = StrFormat("!%d", errorStart - errorOffset + assignExprOffset) + result.Substring(tabPos);
  8765. }
  8766. }
  8767. }
  8768. return result;
  8769. }
  8770. pendingExpr->mUsedSpecifiedLock = usedSpecifiedLock;
  8771. pendingExpr->mStackIdxOverride = stackIdxOverride;
  8772. pendingExpr->mExplitType = explicitType;
  8773. pendingExpr->mFormatInfo = formatInfo;
  8774. String result = EvaluateContinue(pendingExpr, bfPassInstance);
  8775. if (result == "!pending")
  8776. {
  8777. BF_ASSERT(mDebugPendingExpr == NULL);
  8778. if (mDebugPendingExpr != NULL)
  8779. {
  8780. return "!retry"; // We already have a pending
  8781. }
  8782. mDebugPendingExpr = pendingExpr;
  8783. mDebugEvalThreadInfo = *mActiveThread;
  8784. mActiveThread->mIsAtBreakpointAddress = 0;
  8785. mActiveThread->mStoppedAtAddress = 0;
  8786. mActiveThread->mBreakpointAddressContinuing = 0;
  8787. }
  8788. else
  8789. delete pendingExpr;
  8790. return result;
  8791. }
  8792. String WinDebugger::Evaluate(const StringImpl& expr, int callStackIdx, int cursorPos, int language, DwEvalExpressionFlags expressionFlags)
  8793. {
  8794. DwFormatInfo formatInfo;
  8795. return Evaluate(expr, formatInfo, callStackIdx, cursorPos, language, expressionFlags);
  8796. }
  8797. static void ConvertDoubleToFloat80(double d, byte fp80[10])
  8798. {
  8799. uint64 di = *reinterpret_cast<uint64*>(&d);
  8800. uint64 m = di & (((uint64)1 << 52) - 1);
  8801. uint64 e = (di >> 52) & 0x7ff;
  8802. memset(fp80, 0, 10);
  8803. // sign bit is directly transferred
  8804. if (di & ((uint64)1 << 63))
  8805. fp80[9] |= 0x80;
  8806. if (!e && !m)
  8807. return; // zero
  8808. fp80[7] |= 0x80; // leading integer bit in mantissa (always 1 in normalized numbers)
  8809. if (e == 0x7ff)
  8810. {
  8811. fp80[9] |= 0x7f;
  8812. fp80[8] = 0xff;
  8813. if (m == 0)
  8814. return; // inf
  8815. fp80[7] |= 0x3f; // any nonzero value will be a NaN (SNaN or QNaN)
  8816. if (m & ((uint64)1 << 51))
  8817. fp80[7] |= 0x40; // QNaN
  8818. return;
  8819. }
  8820. int useExponent = (int)e - 1023;
  8821. if (!e)
  8822. {
  8823. // denormal; can renormalize though since fp80 supports lower exponents
  8824. BF_ASSERT(m != 0); // we should have trapped zero above
  8825. while (!(m & ((uint64)1 << 51)))
  8826. {
  8827. m <<= 1;
  8828. --useExponent;
  8829. }
  8830. // finally we have our leading 1 bit; strip that off and we have a normalized number again
  8831. m <<= 1;
  8832. --useExponent;
  8833. m &= (((uint64)1 << 52) - 1);
  8834. }
  8835. useExponent += 16383;
  8836. BF_ASSERT((useExponent > 0) && (useExponent < 0x7fff));
  8837. *reinterpret_cast<uint16*>(&fp80[8]) |= (uint16)useExponent;
  8838. *reinterpret_cast<uint64*>(&fp80[0]) |= (m << 11);
  8839. }
  8840. bool WinDebugger::AssignToReg(int callStackIdx, DbgTypedValue regVal, DbgTypedValue value, String& outError)
  8841. {
  8842. BF_ASSERT(regVal.mRegNum >= 0);
  8843. if (mCallStack.size() == 0)
  8844. {
  8845. outError = "No call stack";
  8846. return false;
  8847. }
  8848. if (callStackIdx >= (int)mCallStack.size())
  8849. {
  8850. outError = "Invalid call stack index";
  8851. return false;
  8852. }
  8853. auto registers = &mCallStack[callStackIdx]->mRegisters;
  8854. void* regPtr = NULL;
  8855. #ifdef BF_DBG_32
  8856. if ((regVal.mRegNum >= X86Reg_INTREG_FIRST) && (regVal.mRegNum <= X86Reg_INTREG_LAST))
  8857. {
  8858. BF_ASSERT(regVal.mType->mSize == sizeof(int32));
  8859. registers->mIntRegsArray[regVal.mRegNum - X86Reg_INTREG_FIRST] = (uint64)value.mUInt32; // don't sign-extend
  8860. }
  8861. else if ((regVal.mRegNum >= X86Reg_FPSTREG_FIRST) && (regVal.mRegNum <= X86Reg_FPSTREG_LAST))
  8862. {
  8863. BF_ASSERT(regVal.mType->mSize == sizeof(float) || regVal.mType->mSize == sizeof(double));
  8864. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X86Reg_FPSTREG_FIRST];
  8865. double d;
  8866. if (regVal.mType->mSize == sizeof(float))
  8867. d = (double)value.mSingle;
  8868. else
  8869. d = value.mDouble;
  8870. ConvertDoubleToFloat80(d, reg->fp.fp80);
  8871. }
  8872. else if ((regVal.mRegNum >= X86Reg_MMREG_FIRST) && (regVal.mRegNum <= X86Reg_MMREG_LAST))
  8873. {
  8874. BF_ASSERT(regVal.mType->mSize == sizeof(int32) || regVal.mType->mSize == sizeof(int64));
  8875. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X86Reg_MMREG_FIRST];
  8876. if (regVal.mType->mSize == sizeof(int32))
  8877. reg->mm = (uint64)value.mUInt32; // don't sign-extend
  8878. else if (regVal.mType->mSize == sizeof(int64))
  8879. reg->mm = value.mInt64;
  8880. // 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
  8881. reg->fp.fp80[8] = reg->fp.fp80[9] = 0xFF;
  8882. }
  8883. else if ((regVal.mRegNum >= X86Reg_XMMREG_FIRST) && (regVal.mRegNum <= X86Reg_XMMREG_LAST))
  8884. {
  8885. int xmmMajor = (regVal.mRegNum - X86Reg_XMMREG_FIRST) >> 2;
  8886. int xmmMinor = (regVal.mRegNum - X86Reg_XMMREG_FIRST) & 3;
  8887. registers->mXmmRegsArray[xmmMajor].f[xmmMinor] = value.mSingle;
  8888. }
  8889. else if ((regVal.mRegNum >= X86Reg_M128_XMMREG_FIRST) && (regVal.mRegNum <= X86Reg_M128_XMMREG_LAST))
  8890. {
  8891. outError = "Cannot write directly to 128-bit XMM register, please use inner float components";
  8892. return false;
  8893. }
  8894. else if ((regVal.mRegNum >= X86Reg_FLAG_FIRST) && (regVal.mRegNum <= X86Reg_FLAG_LAST))
  8895. {
  8896. int flagBit = CPURegisters::GetFlagBitForRegister(regVal.mRegNum);
  8897. if (flagBit >= 0)
  8898. {
  8899. if (value.mBool)
  8900. registers->mIntRegs.efl |= ((uint64)1 << flagBit);
  8901. else
  8902. registers->mIntRegs.efl &= ~((uint64)1 << flagBit);
  8903. }
  8904. else
  8905. {
  8906. outError = "Unrecognized flag";
  8907. return false;
  8908. }
  8909. }
  8910. else if ((regVal.mRegNum >= X86Reg_CAT_FIRST) && (regVal.mRegNum <= X86Reg_CAT_LAST))
  8911. {
  8912. outError = "Cannot write directly to register categories, please use inner float components";
  8913. return false;
  8914. }
  8915. #else
  8916. if ((regVal.mRegNum >= X64Reg_INTREG_FIRST) && (regVal.mRegNum <= X64Reg_INTREG_LAST))
  8917. {
  8918. //BF_ASSERT(regVal.mType->mSize == sizeof(addr_target));
  8919. registers->mIntRegsArray[regVal.mRegNum - X64Reg_INTREG_FIRST] = value.GetInt64(); // don't sign-extend
  8920. regPtr = &registers->mIntRegsArray[regVal.mRegNum - X64Reg_INTREG_FIRST];
  8921. }
  8922. else if ((regVal.mRegNum >= X64Reg_FPSTREG_FIRST) && (regVal.mRegNum <= X64Reg_FPSTREG_LAST))
  8923. {
  8924. BF_ASSERT(regVal.mType->mSize == sizeof(float) || regVal.mType->mSize == sizeof(double));
  8925. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X64Reg_FPSTREG_FIRST];
  8926. double d;
  8927. if (regVal.mType->mSize == sizeof(float))
  8928. d = (double)value.mSingle;
  8929. else
  8930. d = value.mDouble;
  8931. ConvertDoubleToFloat80(d, reg->fp.fp80);
  8932. regPtr = reg;
  8933. }
  8934. else if ((regVal.mRegNum >= X64Reg_MMREG_FIRST) && (regVal.mRegNum <= X64Reg_MMREG_LAST))
  8935. {
  8936. BF_ASSERT(regVal.mType->mSize == sizeof(int32) || regVal.mType->mSize == sizeof(int64));
  8937. CPURegisters::FpMmReg* reg = &registers->mFpMmRegsArray[regVal.mRegNum - X64Reg_MMREG_FIRST];
  8938. if (regVal.mType->mSize == sizeof(int32))
  8939. reg->mm = (uint64)value.mUInt32; // don't sign-extend
  8940. else if (regVal.mType->mSize == sizeof(int64))
  8941. reg->mm = value.mInt64;
  8942. // 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
  8943. reg->fp.fp80[8] = reg->fp.fp80[9] = 0xFF;
  8944. regPtr = reg;
  8945. }
  8946. else if ((regVal.mRegNum >= X64Reg_XMMREG_FIRST) && (regVal.mRegNum <= X64Reg_XMMREG_LAST))
  8947. {
  8948. int xmmMajor = (regVal.mRegNum - X64Reg_XMMREG_FIRST) >> 2;
  8949. int xmmMinor = (regVal.mRegNum - X64Reg_XMMREG_FIRST) & 3;
  8950. if (value.mType->GetByteCount() == 4)
  8951. registers->mXmmRegsArray[xmmMajor].f[xmmMinor] = value.mSingle;
  8952. else if (value.mType->GetByteCount() == 8)
  8953. registers->mXmmDRegsArray[xmmMajor].d[xmmMinor] = value.mDouble;
  8954. else
  8955. BF_FATAL("Invalid XMM set value type");
  8956. regPtr = &registers->mXmmRegsArray[xmmMajor];
  8957. }
  8958. else if ((regVal.mRegNum >= X64Reg_M128_XMMREG_FIRST) && (regVal.mRegNum <= X64Reg_M128_XMMREG_LAST))
  8959. {
  8960. outError = "Cannot write directly to 128-bit XMM register, please use inner float components";
  8961. return false;
  8962. }
  8963. else if ((regVal.mRegNum >= X64Reg_FLAG_FIRST) && (regVal.mRegNum <= X64Reg_FLAG_LAST))
  8964. {
  8965. int flagBit = CPURegisters::GetFlagBitForRegister(regVal.mRegNum);
  8966. if (flagBit >= 0)
  8967. {
  8968. if (value.mBool)
  8969. registers->mIntRegs.efl |= ((uint64)1 << flagBit);
  8970. else
  8971. registers->mIntRegs.efl &= ~((uint64)1 << flagBit);
  8972. regPtr = &registers->mIntRegs.efl;
  8973. }
  8974. else
  8975. {
  8976. outError = "Unrecognized flag";
  8977. return false;
  8978. }
  8979. }
  8980. else if ((regVal.mRegNum >= X64Reg_CAT_FIRST) && (regVal.mRegNum <= X64Reg_CAT_LAST))
  8981. {
  8982. outError = "Cannot write directly to register categories, please use inner float components";
  8983. return false;
  8984. }
  8985. else
  8986. BF_FATAL("Not implemented");
  8987. #endif
  8988. if (callStackIdx == 0)
  8989. {
  8990. SetRegisters(&mCallStack[0]->mRegisters);
  8991. return true;
  8992. }
  8993. else
  8994. {
  8995. bool wasSaved = false;
  8996. for (int calleeStackIdx = callStackIdx - 1; calleeStackIdx >= 0; calleeStackIdx--)
  8997. {
  8998. auto calleeRegisters = &mCallStack[calleeStackIdx]->mRegisters;
  8999. if (!mDebugTarget->PropogateRegisterUpCallStack(registers, calleeRegisters, regPtr, wasSaved))
  9000. {
  9001. outError = "Failed to set register";
  9002. return false;
  9003. }
  9004. if (wasSaved)
  9005. return true;
  9006. }
  9007. // This register wasn't saved, so commit it to the callstack top
  9008. return AssignToReg(0, regVal, value, outError);
  9009. }
  9010. }
  9011. String WinDebugger::GetAutocompleteOutput(DwAutoComplete& autoComplete)
  9012. {
  9013. String val = "\n:autocomplete\n";
  9014. if (autoComplete.mInsertStartIdx != -1)
  9015. {
  9016. val += StrFormat("insertRange\t%d %d\n", autoComplete.mInsertStartIdx, autoComplete.mInsertEndIdx);
  9017. }
  9018. Array<AutoCompleteEntry*> entries;
  9019. for (auto& entry : autoComplete.mEntriesSet)
  9020. {
  9021. entries.Add(&entry);
  9022. }
  9023. std::sort(entries.begin(), entries.end(), [](AutoCompleteEntry* lhs, AutoCompleteEntry* rhs)
  9024. {
  9025. return stricmp(lhs->mDisplay, rhs->mDisplay) < 0;
  9026. });
  9027. for (auto entry : entries)
  9028. {
  9029. val += String(entry->mEntryType);
  9030. val += "\t";
  9031. val += String(entry->mDisplay);
  9032. val += "\n";
  9033. }
  9034. /*if (autoComplete.mEntries.size() != 0)
  9035. {
  9036. for (auto& entry : autoComplete.mEntries)
  9037. {
  9038. val += String(entry.mEntryType) + "\t" + String(entry.mDisplay) + "\n";
  9039. }
  9040. }*/
  9041. return val;
  9042. }
  9043. String WinDebugger::EvaluateToAddress(const StringImpl& expr, int callStackIdx, int cursorPos)
  9044. {
  9045. AutoCrit autoCrit(mDebugManager->mCritSect);
  9046. if (IsInRunState())
  9047. return "!Target not paused";
  9048. auto dbgModule = GetCallStackDbgModule(callStackIdx);
  9049. auto dbgCompileUnit = GetCallStackCompileUnit(callStackIdx);
  9050. BfParser parser(mBfSystem);
  9051. parser.mCompatMode = true;
  9052. BfPassInstance bfPassInstance(mBfSystem);
  9053. auto terminatedExpr = expr + ";";
  9054. parser.SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  9055. parser.Parse(&bfPassInstance);
  9056. BfReducer bfReducer;
  9057. bfReducer.mAlloc = parser.mAlloc;
  9058. bfReducer.mSystem = mBfSystem;
  9059. bfReducer.mPassInstance = &bfPassInstance;
  9060. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser.mRootNode);
  9061. bfReducer.mVisitorPos.MoveNext();
  9062. bfReducer.mSource = &parser;
  9063. auto exprNode = bfReducer.CreateExpression(parser.mRootNode->GetFirst());
  9064. parser.Close();
  9065. DwAutoComplete autoComplete;
  9066. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, callStackIdx, cursorPos);
  9067. if (cursorPos != -1)
  9068. dbgExprEvaluator.mAutoComplete = &autoComplete;
  9069. dbgExprEvaluator.mDbgCompileUnit = dbgCompileUnit;
  9070. DwFormatInfo formatInfo;
  9071. formatInfo.mCallStackIdx = callStackIdx;
  9072. DbgTypedValue exprResult;
  9073. if (exprNode != NULL)
  9074. exprResult = dbgExprEvaluator.Resolve(exprNode);
  9075. DbgType* resultType = exprResult.mType->RemoveModifiers();
  9076. String val;
  9077. if (bfPassInstance.HasFailed())
  9078. {
  9079. val = StrFormat("!%d\t%d\t%s", bfPassInstance.mErrors[0]->mSrcStart, bfPassInstance.mErrors[0]->GetSrcLength(), bfPassInstance.mErrors[0]->mError.c_str());
  9080. }
  9081. else if (exprResult.mType == NULL)
  9082. {
  9083. val = "!Invalid expression";
  9084. }
  9085. else if (!resultType->IsPointerOrRef())
  9086. {
  9087. if (exprResult.mSrcAddress != 0)
  9088. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. Try using the '&' address-of operator.", exprResult.mType->ToString().c_str());
  9089. else
  9090. val = StrFormat("!Type '%s' is invalid. A sized pointer type is expected. An explicit cast may be required.", exprResult.mType->ToString().c_str());
  9091. }
  9092. else
  9093. {
  9094. auto innerType = resultType->mTypeParam;
  9095. int byteCount = innerType->GetByteCount();
  9096. if (byteCount == 0)
  9097. {
  9098. 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());
  9099. }
  9100. #ifdef BF_DBG_32
  9101. else if ((byteCount != 1) && (byteCount != 2) && (byteCount != 4))
  9102. {
  9103. 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);
  9104. }
  9105. #else
  9106. else if ((byteCount != 1) && (byteCount != 2) && (byteCount != 4) && (byteCount != 8))
  9107. {
  9108. 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);
  9109. }
  9110. #endif
  9111. else
  9112. {
  9113. val = EncodeDataPtr(exprResult.mPtr, false) + "\n" + StrFormat("%d", byteCount);
  9114. }
  9115. }
  9116. if (cursorPos != -1)
  9117. val += GetAutocompleteOutput(autoComplete);
  9118. return val;
  9119. }
  9120. // This is currently only used for autocomplete during conditional breakpoint expression entry.
  9121. // If we want to use it for more than that then remove DwEvalExpressionFlags_ValidateOnly
  9122. String WinDebugger::EvaluateAtAddress(const StringImpl& expr, intptr atAddr, int cursorPos)
  9123. {
  9124. AutoCrit autoCrit(mDebugManager->mCritSect);
  9125. if (IsInRunState())
  9126. return "!Target not paused";
  9127. if (!IsPaused())
  9128. return "!Target not running";
  9129. WdStackFrame stackFrame;
  9130. memset(&stackFrame.mRegisters, 0, sizeof(stackFrame.mRegisters));
  9131. stackFrame.mHasGottenSubProgram = true;
  9132. *stackFrame.mRegisters.GetPCRegisterRef() = (intptr_target)atAddr;
  9133. stackFrame.mSubProgram = mDebugTarget->FindSubProgram((addr_target)atAddr);
  9134. if (stackFrame.mSubProgram == NULL)
  9135. return "!Invalid address";
  9136. mCallStack.push_back(&stackFrame);
  9137. int callStackIdx = (int)mCallStack.size() - 1;
  9138. String val = Evaluate(expr, callStackIdx, cursorPos, -1, DwEvalExpressionFlag_ValidateOnly);
  9139. mCallStack.pop_back();
  9140. return val;
  9141. }
  9142. String WinDebugger::GetAutoExpressions(int callStackIdx, uint64 memoryRangeStart, uint64 memoryRangeLen)
  9143. {
  9144. BP_ZONE("WinDebugger::GetAutoExpressions");
  9145. AutoCrit autoCrit(mDebugManager->mCritSect);
  9146. if (IsInRunState())
  9147. return "!Not paused";
  9148. if (!IsPaused())
  9149. return "!Not running";
  9150. if (!FixCallStackIdx(callStackIdx))
  9151. return "";
  9152. CPUStackFrame* stackFrame = (callStackIdx >= 0) ? mCallStack[callStackIdx] : mCallStack.front();
  9153. String result;
  9154. DbgAutoValueMapType dwarfAutos;
  9155. mDebugTarget->GetAutoValueNames(dwarfAutos, stackFrame, memoryRangeStart, memoryRangeLen);
  9156. for (auto const &a : dwarfAutos)
  9157. {
  9158. std::pair<uint64, uint64> varRange = a.mValue;
  9159. if (varRange.first != 0)
  9160. result += StrFormat("&%s\t%llu\t%llu\n", a.mKey.c_str(), varRange.second, varRange.first);
  9161. else
  9162. result += StrFormat("?%s\t%llu\n", a.mKey.c_str(), varRange.second);
  9163. }
  9164. #ifdef BF_DBG_64
  9165. // add int regs
  9166. const char* regStrs[] = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "rip", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", 0 };
  9167. #else
  9168. // add int regs
  9169. const char* regStrs[] = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "eip", 0 };
  9170. #endif
  9171. for (const char** p = regStrs; *p; ++p)
  9172. result += StrFormat("$%s\t%d\n", *p, sizeof(addr_target));
  9173. if (callStackIdx < (int)mCallStack.size() - 2)
  9174. {
  9175. WdStackFrame* prevStackFrame = mCallStack[callStackIdx + 1];
  9176. // Inlined methods have no stack frame
  9177. int stackSize = prevStackFrame->mRegisters.GetSP() - stackFrame->mRegisters.GetSP();
  9178. result += StrFormat("&$StackFrame\t%llu\t%llu\n", stackSize, stackFrame->mRegisters.GetSP());
  9179. }
  9180. return result;
  9181. }
  9182. String WinDebugger::GetAutoLocals(int stackFrameIdx, bool showRegs)
  9183. {
  9184. BP_ZONE("WinDebugger::GetAutoExpressions");
  9185. AutoCrit autoCrit(mDebugManager->mCritSect);
  9186. if (IsInRunState())
  9187. return "";
  9188. if (!IsPaused())
  9189. return "";
  9190. if (mCallStack.size() == 0)
  9191. UpdateCallStack();
  9192. String result;
  9193. Array<String> localList;
  9194. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9195. UpdateCallStackMethod(actualStackFrameIdx);
  9196. if (actualStackFrameIdx >= mCallStack.size())
  9197. return "";
  9198. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9199. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  9200. if (dwSubprogram == NULL)
  9201. return "";
  9202. auto langage = dwSubprogram->GetLanguage();
  9203. DbgLineData* dwLineData = FindLineDataInSubprogram(wdStackFrame->GetSourcePC(), dwSubprogram);
  9204. if (dwLineData == NULL)
  9205. return "";
  9206. dwSubprogram->PopulateSubprogram();
  9207. mDebugTarget->GetAutoLocalsInBlock(localList, dwSubprogram, &dwSubprogram->mBlock, wdStackFrame, dwLineData);
  9208. String lastLocal;
  9209. for (auto local : localList)
  9210. {
  9211. if (langage == DbgLanguage_C)
  9212. {
  9213. if ((local == "this") && (strncmp(dwSubprogram->mName, "<lambda_", 8) == 0))
  9214. {
  9215. // Use explicit "$this" so we can see the actual capture
  9216. result += "$this\n";
  9217. continue;
  9218. }
  9219. }
  9220. bool wasAlias = false;
  9221. for (int i = 0; i < (int)local.length() - 1; i++)
  9222. {
  9223. if ((local[i] == '$') && (local[i + 1] == 'a'))
  9224. {
  9225. // Alias
  9226. wasAlias = true;
  9227. String localName = local.Substring(0, i) + "\n";
  9228. if (localName != lastLocal)
  9229. {
  9230. result += localName;
  9231. lastLocal = localName;
  9232. }
  9233. break;
  9234. }
  9235. }
  9236. if (!wasAlias)
  9237. result += local + "\n";
  9238. }
  9239. if (showRegs)
  9240. {
  9241. result += "$FLAGS\n";
  9242. UpdateRegisterUsage(stackFrameIdx);
  9243. for (int regIdx = 0; regIdx < (int)wdStackFrame->mRegForms.size(); regIdx++)
  9244. {
  9245. if (wdStackFrame->mRegForms[regIdx] != RegForm_Invalid)
  9246. result += "$" + String(CPURegisters::GetRegisterName(regIdx)) + "\n";
  9247. }
  9248. }
  9249. return result;
  9250. }
  9251. String WinDebugger::CompactChildExpression(const StringImpl& expr, const StringImpl& parentExpr, int callStackIdx)
  9252. {
  9253. DbgCompileUnit* compileUnit = GetCallStackCompileUnit(callStackIdx);
  9254. DbgModule* dbgModule = GetCallStackDbgModule(callStackIdx);
  9255. if (dbgModule == NULL)
  9256. return "!failed";
  9257. DbgLanguage language = DbgLanguage_Unknown;
  9258. if (compileUnit != NULL)
  9259. language = compileUnit->mLanguage;
  9260. BfPassInstance bfPassInstance(mBfSystem);
  9261. BfParser parser(mBfSystem);
  9262. parser.mCompatMode = language != DbgLanguage_Beef;
  9263. auto terminatedExpr = expr + ";";
  9264. parser.SetSource(terminatedExpr.c_str(), terminatedExpr.length());
  9265. parser.Parse(&bfPassInstance);
  9266. auto terminatedParentExpr = parentExpr + ";";
  9267. String parentPrefix;
  9268. if (terminatedParentExpr.StartsWith('{'))
  9269. {
  9270. int prefixEnd = terminatedParentExpr.IndexOf('}');
  9271. parentPrefix = terminatedParentExpr.Substring(0, prefixEnd + 1);
  9272. terminatedParentExpr.Remove(0, prefixEnd + 1);
  9273. }
  9274. BfParser parentParser(mBfSystem);
  9275. parentParser.mCompatMode = language != DbgLanguage_Beef;
  9276. parentParser.SetSource(terminatedParentExpr.c_str(), terminatedParentExpr.length());
  9277. parentParser.Parse(&bfPassInstance);
  9278. BfReducer bfReducer;
  9279. bfReducer.mCompatMode = true;
  9280. bfReducer.mAlloc = parser.mAlloc;
  9281. bfReducer.mSystem = mBfSystem;
  9282. bfReducer.mPassInstance = &bfPassInstance;
  9283. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parser.mRootNode);
  9284. bfReducer.mVisitorPos.MoveNext();
  9285. bfReducer.mSource = &parser;
  9286. auto exprNode = bfReducer.CreateExpression(parser.mRootNode->GetFirst());
  9287. bfReducer.mAlloc = parentParser.mAlloc;
  9288. bfReducer.mVisitorPos = BfReducer::BfVisitorPos(parentParser.mRootNode);
  9289. bfReducer.mVisitorPos.MoveNext();
  9290. auto parentExprNode = bfReducer.CreateExpression(parentParser.mRootNode->GetFirst());
  9291. parser.Close();
  9292. if ((exprNode == NULL) || (parentExprNode == NULL))
  9293. return "!failed";
  9294. DbgExprEvaluator dbgExprEvaluator(this, dbgModule, &bfPassInstance, callStackIdx, -1);
  9295. DwFormatInfo formatInfo;
  9296. formatInfo.mCallStackIdx = callStackIdx;
  9297. formatInfo.mLanguage = language;
  9298. String formatFlags;
  9299. String assignExpr;
  9300. if ((exprNode != NULL) && (exprNode->GetSrcEnd() < (int) expr.length()))
  9301. {
  9302. formatFlags = Trim(expr.Substring(exprNode->GetSrcEnd()));
  9303. if (formatFlags.length() > 0)
  9304. {
  9305. String errorString = "Invalid expression";
  9306. if (!ParseFormatInfo(dbgModule, formatFlags, &formatInfo, &bfPassInstance, NULL, &assignExpr, &errorString))
  9307. {
  9308. bfPassInstance.FailAt(errorString, parser.mSourceData, exprNode->GetSrcEnd(), (int) expr.length() - exprNode->GetSrcEnd());
  9309. formatFlags = "";
  9310. }
  9311. }
  9312. }
  9313. dbgExprEvaluator.mExplicitThis = formatInfo.mExplicitThis;
  9314. dbgExprEvaluator.mExplicitThisExpr = parentExprNode;
  9315. DbgTypedValue exprResult = dbgExprEvaluator.Resolve(exprNode);
  9316. BfAstNode* headNode = dbgExprEvaluator.FinalizeExplicitThisReferences(exprNode);
  9317. BfPrinter printer(parser.mRootNode, NULL, NULL);
  9318. printer.mIgnoreTrivia = true;
  9319. printer.mReformatting = true;
  9320. printer.VisitChild(headNode);
  9321. String result;
  9322. result += parentPrefix;
  9323. result += printer.mOutString;
  9324. if (formatInfo.mNoVisualizers)
  9325. result += ", nv";
  9326. if (formatInfo.mNoMembers)
  9327. result += ", nm";
  9328. if (formatInfo.mNoEdit)
  9329. result += ", ne";
  9330. if (formatInfo.mIgnoreDerivedClassInfo)
  9331. result += ", nd";
  9332. if (formatInfo.mDisplayType == DwDisplayType_Ascii)
  9333. result += ", s";
  9334. if (formatInfo.mDisplayType == DwDisplayType_Utf8)
  9335. result += ", s8";
  9336. if (formatInfo.mDisplayType == DwDisplayType_Utf16)
  9337. result += ", s16";
  9338. if (formatInfo.mDisplayType == DwDisplayType_Utf32)
  9339. result += ", s32";
  9340. return result;
  9341. }
  9342. String WinDebugger::GetProcessInfo()
  9343. {
  9344. AutoCrit autoCrit(mDebugManager->mCritSect);
  9345. if ((mActiveThread == NULL) && (!mIsRunning))
  9346. return "";
  9347. SYSTEM_INFO sysinfo = { 0 };
  9348. GetSystemInfo(&sysinfo);
  9349. FILETIME creationTime = { 0 };
  9350. FILETIME exitTime = { 0 };
  9351. FILETIME kernelTime = { 0 };
  9352. FILETIME userTime = { 0 };
  9353. ::GetProcessTimes(mProcessInfo.hProcess, &creationTime, &exitTime, &kernelTime, &userTime);
  9354. String retStr;
  9355. PROCESS_MEMORY_COUNTERS memInfo = { 0 };
  9356. ::GetProcessMemoryInfo(mProcessInfo.hProcess, &memInfo, sizeof(PROCESS_MEMORY_COUNTERS));
  9357. FILETIME currentTime = { 0 };
  9358. ::GetSystemTimeAsFileTime(&currentTime);
  9359. retStr += StrFormat("VirtualMemory\t%lld\n", memInfo.PagefileUsage);
  9360. retStr += StrFormat("WorkingMemory\t%lld\n", memInfo.WorkingSetSize);
  9361. retStr += StrFormat("RunningTime\t%lld\n", *(int64*)&currentTime - *(int64*)&creationTime);
  9362. retStr += StrFormat("KernelTime\t%lld\n", *(int64*)&kernelTime / sysinfo.dwNumberOfProcessors);
  9363. retStr += StrFormat("UserTime\t%lld\n", *(int64*)&userTime / sysinfo.dwNumberOfProcessors);
  9364. return retStr;
  9365. }
  9366. String WinDebugger::GetThreadInfo()
  9367. {
  9368. AutoCrit autoCrit(mDebugManager->mCritSect);
  9369. String retStr;
  9370. if ((mActiveThread == NULL) && (!mIsRunning))
  9371. {
  9372. retStr = "";
  9373. }
  9374. else
  9375. {
  9376. if (mActiveThread != NULL)
  9377. retStr = StrFormat("%d", mActiveThread->mThreadId);
  9378. for (auto threadInfo : mThreadList)
  9379. {
  9380. SetAndRestoreValue<WdThreadInfo*> prevThread(mActiveThread, threadInfo);
  9381. retStr += "\n";
  9382. for (int pass = 0; pass < 2; pass++)
  9383. {
  9384. CPURegisters registers;
  9385. PopulateRegisters(&registers);
  9386. String locString = EncodeDataPtr((addr_target)registers.GetPC(), true);
  9387. TryGetThreadName(threadInfo);
  9388. bool hadThreadName = true;
  9389. String threadName = threadInfo->mName;
  9390. if (threadName.IsEmpty())
  9391. {
  9392. hadThreadName = false;
  9393. if (threadInfo->mThreadId == mProcessInfo.dwThreadId)
  9394. threadName = "Main Thread";
  9395. else
  9396. threadName = "Worker Thread";
  9397. }
  9398. bool isInvalid = false;
  9399. addr_target appendAddr = 0;
  9400. for (int stackIdx = 0; true; stackIdx++)
  9401. {
  9402. auto subProgram = mDebugTarget->FindSubProgram(registers.GetPC(), DbgOnDemandKind_LocalOnly);
  9403. if (subProgram != NULL)
  9404. {
  9405. if (subProgram->mLineInfo != NULL)
  9406. {
  9407. DbgModule* module = subProgram->mCompileUnit->mDbgModule;
  9408. DbgModule* linkedModule = module->GetLinkedModule();
  9409. if (linkedModule->mDisplayName.length() > 0)
  9410. {
  9411. locString = linkedModule->mDisplayName + "!" + subProgram->ToString();
  9412. if (!hadThreadName)
  9413. threadName = module->mDisplayName + " thread";
  9414. }
  9415. else
  9416. {
  9417. locString = subProgram->ToString();
  9418. }
  9419. appendAddr = 0;
  9420. break;
  9421. }
  9422. }
  9423. DbgModule* module = mDebugTarget->FindDbgModuleForAddress(registers.GetPC());
  9424. if (module == NULL)
  9425. {
  9426. isInvalid = true;
  9427. break;
  9428. }
  9429. DbgModule* linkedModule = module->GetLinkedModule();
  9430. appendAddr = (addr_target)registers.GetPC();
  9431. locString = linkedModule->mDisplayName + "!" + EncodeDataPtr((addr_target)registers.GetPC(), true);
  9432. if (!hadThreadName)
  9433. threadName = linkedModule->mDisplayName + " thread";
  9434. if ((mActiveThread == mExplicitStopThread) && (mActiveBreakpoint != NULL))
  9435. {
  9436. if ((subProgram == NULL) ||
  9437. (mActiveBreakpoint->mAddr < subProgram->mBlock.mLowPC) ||
  9438. (mActiveBreakpoint->mAddr >= subProgram->mBlock.mHighPC))
  9439. break;
  9440. }
  9441. if (pass == 1) // Just take the first item
  9442. break;
  9443. if (stackIdx == 128)
  9444. break; // Too many!
  9445. addr_target returnAddr;
  9446. if (!mDebugTarget->RollBackStackFrame(&registers, &returnAddr, true))
  9447. {
  9448. isInvalid = true;
  9449. break;
  9450. }
  9451. }
  9452. if ((isInvalid) && (pass == 0))
  9453. continue;
  9454. if (appendAddr != 0)
  9455. {
  9456. String symbolName;
  9457. addr_target offset;
  9458. DbgModule* dwarf;
  9459. if (mDebugTarget->FindSymbolAt(appendAddr, &symbolName, &offset, &dwarf))
  9460. {
  9461. DbgModule* linkedModule = dwarf->GetLinkedModule();
  9462. String demangledName = BfDemangler::Demangle(symbolName, DbgLanguage_Unknown);
  9463. if (!linkedModule->mDisplayName.empty())
  9464. {
  9465. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  9466. }
  9467. locString = demangledName + StrFormat("+0x%X", offset);
  9468. }
  9469. }
  9470. retStr += StrFormat("%d\t%s\t%s", threadInfo->mThreadId, threadName.c_str(), locString.c_str());
  9471. String attrs;
  9472. if (threadInfo->mFrozen)
  9473. {
  9474. attrs += "Fr";
  9475. }
  9476. if (!attrs.IsEmpty())
  9477. {
  9478. retStr += "\t";
  9479. retStr += attrs;
  9480. }
  9481. break;
  9482. }
  9483. }
  9484. }
  9485. return retStr;
  9486. }
  9487. void WinDebugger::SetActiveThread(int threadId)
  9488. {
  9489. AutoCrit autoCrit(mDebugManager->mCritSect);
  9490. if ((mActiveThread != NULL) && (mActiveThread->mThreadId == threadId))
  9491. return;
  9492. auto prevThread = mActiveThread;
  9493. if (mThreadMap.TryGetValue(threadId, &mActiveThread))
  9494. {
  9495. BfLogDbg("SetActiveThread %d\n", threadId);
  9496. if (prevThread != NULL)
  9497. {
  9498. Array<WdStackFrame*>* prevFrameArray = NULL;
  9499. mSavedCallStacks.TryAdd(prevThread, NULL, &prevFrameArray);
  9500. for (auto frameInfo : *prevFrameArray)
  9501. delete frameInfo;
  9502. *prevFrameArray = mCallStack;
  9503. mCallStack.Clear();
  9504. }
  9505. DoClearCallStack(false);
  9506. Array<WdStackFrame*>* newFrameArray = NULL;
  9507. if (mSavedCallStacks.TryGetValue(mActiveThread, &newFrameArray))
  9508. {
  9509. mCallStack = *newFrameArray;
  9510. newFrameArray->Clear();
  9511. }
  9512. }
  9513. else
  9514. {
  9515. BfLogDbg("SetActiveThread %d FAILED\n", threadId);
  9516. }
  9517. }
  9518. int WinDebugger::GetActiveThread()
  9519. {
  9520. AutoCrit autoCrit(mDebugManager->mCritSect);
  9521. if (mActiveThread == NULL)
  9522. return -1;
  9523. return mActiveThread->mThreadId;
  9524. }
  9525. void WinDebugger::FreezeThread(int threadId)
  9526. {
  9527. AutoCrit autoCrit(mDebugManager->mCritSect);
  9528. BF_ASSERT(!IsInRunState());
  9529. auto thread = mThreadMap[threadId];
  9530. if (!thread->mFrozen)
  9531. {
  9532. thread->mFrozen = true;
  9533. ::SuspendThread(thread->mHThread);
  9534. BfLogDbg("SuspendThread %d from FreezeThread\n", thread->mThreadId);
  9535. }
  9536. }
  9537. void WinDebugger::ThawThread(int threadId)
  9538. {
  9539. AutoCrit autoCrit(mDebugManager->mCritSect);
  9540. BF_ASSERT(!IsInRunState());
  9541. auto thread = mThreadMap[threadId];
  9542. if (thread->mFrozen)
  9543. {
  9544. thread->mFrozen = false;
  9545. ::ResumeThread(thread->mHThread);
  9546. BfLogDbg("ResumeThread %d from ThawThread\n", thread->mThreadId);
  9547. }
  9548. }
  9549. bool WinDebugger::IsActiveThreadWaiting()
  9550. {
  9551. AutoCrit autoCrit(mDebugManager->mCritSect);
  9552. return mActiveThread == mDebuggerWaitingThread;
  9553. }
  9554. void WinDebugger::DoClearCallStack(bool clearSavedStacks)
  9555. {
  9556. AutoCrit autoCrit(mDebugManager->mCritSect);
  9557. BfLogDbg("ClearCallstack\n");
  9558. BF_ASSERT(mRunState != RunState_DebugEval);
  9559. for (auto wdStackFrame : mCallStack)
  9560. delete wdStackFrame;
  9561. if (clearSavedStacks)
  9562. {
  9563. for (auto& kv : mSavedCallStacks)
  9564. {
  9565. for (auto wdStackFrame : kv.mValue)
  9566. delete wdStackFrame;
  9567. }
  9568. mSavedCallStacks.Clear();
  9569. }
  9570. mCallStack.Clear();
  9571. mIsPartialCallStack = true;
  9572. }
  9573. void WinDebugger::ClearCallStack()
  9574. {
  9575. DoClearCallStack(true);
  9576. }
  9577. void WinDebugger::UpdateCallStack(bool slowEarlyOut)
  9578. {
  9579. AutoCrit autoCrit(mDebugManager->mCritSect);
  9580. if (!mIsPartialCallStack)
  9581. return;
  9582. BF_ASSERT(!IsInRunState());
  9583. uint32 tickStart = BFTickCount();
  9584. CPURegisters registers;
  9585. if (mCallStack.size() > 0)
  9586. {
  9587. WdStackFrame* wdStackFrame = mCallStack.back();
  9588. if (wdStackFrame->mIsEnd)
  9589. {
  9590. return;
  9591. }
  9592. memcpy(&registers, &wdStackFrame->mRegisters, sizeof(registers));
  9593. bool regsRolledBack = RollBackStackFrame(&registers, mCallStack.size() == 1);
  9594. // If we can't roll them back then mIsEnd should have been set for the previous frame
  9595. BF_ASSERT(regsRolledBack);
  9596. }
  9597. else
  9598. {
  9599. BF_ASSERT(mIsPartialCallStack);
  9600. mCallStack.Reserve(1024);
  9601. PopulateRegisters(&registers);
  9602. BfLogDbg("UpdateCallStack starting. Thread=%d PC=0x%p\n", mActiveThread->mThreadId, registers.GetPC());
  9603. }
  9604. bool isPartial = false;
  9605. // Incrementally fill callstack structure to avoid stepping slowdown during deep nesting
  9606. for (int fillIdx = 0; fillIdx < (slowEarlyOut ? 10000 : 100000); fillIdx++)
  9607. {
  9608. WdStackFrame* wdStackFrame = new WdStackFrame();
  9609. memcpy(&wdStackFrame->mRegisters, &registers, sizeof(registers));
  9610. wdStackFrame->mIsStart = mCallStack.size() == 0;
  9611. wdStackFrame->mIsEnd = false;
  9612. bool rollbackSuccess = false;
  9613. for (int tryCount = 0; tryCount < 16; tryCount++)
  9614. {
  9615. if (!RollBackStackFrame(&registers, wdStackFrame->mIsStart))
  9616. {
  9617. break;
  9618. }
  9619. if (registers.GetPC() > 0xFFFF)
  9620. {
  9621. rollbackSuccess = true;
  9622. break;
  9623. }
  9624. if (mCallStack.size() > 0)
  9625. break; // Only retry for the first frame
  9626. }
  9627. if (!rollbackSuccess)
  9628. wdStackFrame->mIsEnd = true;
  9629. if (registers.GetSP() <= wdStackFrame->mRegisters.GetSP())
  9630. {
  9631. // SP went the wrong direction, stop rolling back
  9632. wdStackFrame->mIsEnd = true;
  9633. }
  9634. mCallStack.push_back(wdStackFrame);
  9635. if (IsMiniDumpDebugger())
  9636. {
  9637. // Make sure to queue up any debug stuff we need
  9638. UpdateCallStackMethod((int)mCallStack.size() - 1);
  9639. }
  9640. if (wdStackFrame->mIsEnd)
  9641. break;
  9642. // Time-limit callstack generation. Most useful for debug mode.
  9643. if ((slowEarlyOut) && ((fillIdx % 100) == 0))
  9644. {
  9645. uint32 tickEnd = BFTickCount();
  9646. if (tickEnd - tickStart >= 10)
  9647. {
  9648. isPartial = true;
  9649. break;
  9650. }
  9651. }
  9652. }
  9653. if (!isPartial)
  9654. mIsPartialCallStack = false;
  9655. }
  9656. int WinDebugger::GetCallStackCount()
  9657. {
  9658. AutoCrit autoCrit(mDebugManager->mCritSect);
  9659. return (int)mCallStack.size();
  9660. }
  9661. int WinDebugger::GetRequestedStackFrameIdx()
  9662. {
  9663. AutoCrit autoCrit(mDebugManager->mCritSect);
  9664. if ((mActiveThread == mExplicitStopThread) && (mRequestedStackFrameIdx >= -1))
  9665. {
  9666. if (mActiveBreakpoint != NULL)
  9667. mRequestedStackFrameIdx = GetBreakStackFrameIdx();
  9668. if (mRequestedStackFrameIdx == -1)
  9669. mRequestedStackFrameIdx = 0;
  9670. return mRequestedStackFrameIdx;
  9671. }
  9672. int newCallStackIdx = 0;
  9673. while (true)
  9674. {
  9675. if (newCallStackIdx >= (int)mCallStack.size() - 1)
  9676. UpdateCallStack();
  9677. if (newCallStackIdx >= (int)mCallStack.size() - 1)
  9678. break;
  9679. intptr addr;
  9680. String file;
  9681. int hotIdx;
  9682. int defLineStart;
  9683. int defLineEnd;
  9684. int line;
  9685. int column;
  9686. int language;
  9687. int stackSize;
  9688. int8 flags;
  9689. GetStackFrameInfo(newCallStackIdx, &addr, &file, &hotIdx, &defLineStart, &defLineEnd, &line, &column, &language, &stackSize, &flags);
  9690. if (!file.empty())
  9691. return newCallStackIdx;
  9692. newCallStackIdx++;
  9693. }
  9694. return 0;
  9695. }
  9696. int WinDebugger::GetBreakStackFrameIdx()
  9697. {
  9698. AutoCrit autoCrit(mDebugManager->mCritSect);
  9699. if ((mActiveBreakpoint == NULL) || (mRunState != RunState_Breakpoint))
  9700. return -1;
  9701. if ((mBreakStackFrameIdx != -1) || (mActiveThread != mExplicitStopThread))
  9702. return mBreakStackFrameIdx;
  9703. mBreakStackFrameIdx = 0;
  9704. BF_ASSERT(mActiveBreakpoint != NULL);
  9705. if (mCallStack.IsEmpty())
  9706. UpdateCallStack();
  9707. if (!mCallStack.IsEmpty())
  9708. {
  9709. UpdateCallStackMethod(0);
  9710. for (int stackIdx = 0; stackIdx < (int)mCallStack.size(); stackIdx++)
  9711. {
  9712. auto callStackEntry = mCallStack[stackIdx];
  9713. if (callStackEntry->mSubProgram == NULL)
  9714. break;
  9715. if ((mActiveBreakpoint->mAddr < callStackEntry->mSubProgram->mBlock.mLowPC) ||
  9716. (mActiveBreakpoint->mAddr >= callStackEntry->mSubProgram->mBlock.mHighPC))
  9717. break;
  9718. DbgSubprogram* specificSubprogram = callStackEntry->mSubProgram;
  9719. auto dwLineData = callStackEntry->mSubProgram->FindClosestLine(mActiveBreakpoint->mAddr, &specificSubprogram);
  9720. if (dwLineData == NULL)
  9721. break;
  9722. if (mActiveBreakpoint->mLineData == dwLineData)
  9723. {
  9724. mBreakStackFrameIdx = stackIdx;
  9725. break;
  9726. }
  9727. }
  9728. }
  9729. return mBreakStackFrameIdx;
  9730. }
  9731. static const char* SafeString(const char* str)
  9732. {
  9733. if (str == NULL)
  9734. return "???";
  9735. return str;
  9736. }
  9737. void WinDebugger::UpdateRegisterUsage(int stackFrameIdx)
  9738. {
  9739. WdStackFrame* wdStackFrame = mCallStack[stackFrameIdx];
  9740. if (wdStackFrame->mRegForms.size() != 0)
  9741. return;
  9742. auto dwSubprogram = wdStackFrame->mSubProgram;
  9743. if (dwSubprogram == NULL)
  9744. return;
  9745. addr_target addr = dwSubprogram->mBlock.mLowPC;
  9746. const uint8* baseOp = nullptr;
  9747. while (addr < dwSubprogram->mBlock.mHighPC)
  9748. {
  9749. CPUInst inst;
  9750. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  9751. break;
  9752. bool overrideForm = inst.mAddress <= (addr_target)wdStackFrame->mRegisters.GetPC();
  9753. inst.MarkRegsUsed(wdStackFrame->mRegForms, overrideForm);
  9754. addr += inst.GetLength();
  9755. }
  9756. }
  9757. // It's safe to pass an invalid idx in here
  9758. void WinDebugger::UpdateCallStackMethod(int stackFrameIdx)
  9759. {
  9760. if (mCallStack.empty())
  9761. return;
  9762. int startIdx = std::min(stackFrameIdx, (int)mCallStack.size() - 1);
  9763. while (startIdx >= 0)
  9764. {
  9765. WdStackFrame* wdStackFrame = mCallStack[startIdx];
  9766. if (wdStackFrame->mHasGottenSubProgram)
  9767. break;
  9768. startIdx--;
  9769. }
  9770. startIdx++;
  9771. for (int checkFrameIdx = startIdx; checkFrameIdx <= stackFrameIdx; checkFrameIdx++)
  9772. {
  9773. //BF_ASSERT(checkFrameIdx < mCallStack.size());
  9774. if (checkFrameIdx >= mCallStack.size())
  9775. break;
  9776. WdStackFrame* wdStackFrame = mCallStack[checkFrameIdx];
  9777. wdStackFrame->mHasGottenSubProgram = true;
  9778. addr_target pcAddress = (addr_target)wdStackFrame->GetSourcePC();
  9779. DbgSubprogram* dwSubprogram = mDebugTarget->FindSubProgram(pcAddress, DbgOnDemandKind_LocalOnly);
  9780. wdStackFrame->mHasGottenSubProgram = true;
  9781. wdStackFrame->mSubProgram = dwSubprogram;
  9782. if ((dwSubprogram == NULL) && (IsMiniDumpDebugger()))
  9783. {
  9784. // FindSymbolAt will queue up debug info if necessary...
  9785. String symbolName;
  9786. addr_target offset;
  9787. DbgModule* dbgModule;
  9788. mDebugTarget->FindSymbolAt(pcAddress, &symbolName, &offset, &dbgModule);
  9789. }
  9790. auto prevStackFrame = wdStackFrame;
  9791. // Insert inlines
  9792. int insertIdx = checkFrameIdx + 1;
  9793. while ((dwSubprogram != NULL) && (dwSubprogram->mInlineeInfo != NULL))
  9794. {
  9795. WdStackFrame* inlineStackFrame = new WdStackFrame();
  9796. *inlineStackFrame = *wdStackFrame;
  9797. inlineStackFrame->mInInlineMethod = true;
  9798. wdStackFrame->mInInlineCall = true;
  9799. inlineStackFrame->mSubProgram = dwSubprogram->mInlineeInfo->mInlineParent;
  9800. mCallStack.Insert(insertIdx, inlineStackFrame);
  9801. dwSubprogram = dwSubprogram->mInlineeInfo->mInlineParent;
  9802. insertIdx++;
  9803. checkFrameIdx++;
  9804. prevStackFrame = inlineStackFrame;
  9805. }
  9806. }
  9807. }
  9808. void WinDebugger::GetCodeAddrInfo(intptr addr, intptr inlineCallAddr, String* outFile, int* outHotIdx, int* outDefLineStart, int* outDefLineEnd, int* outLine, int* outColumn)
  9809. {
  9810. AutoCrit autoCrit(mDebugManager->mCritSect);
  9811. DbgSubprogram* subProgram = NULL;
  9812. DbgLineData* callingLineData = FindLineDataAtAddress((addr_target)addr, &subProgram);
  9813. if (inlineCallAddr != 0)
  9814. {
  9815. auto inlinedSubProgram = mDebugTarget->FindSubProgram(inlineCallAddr);
  9816. if (inlinedSubProgram != 0)
  9817. {
  9818. FixupLineDataForSubprogram(inlinedSubProgram->mInlineeInfo->mRootInliner);
  9819. DbgSubprogram* parentSubprogram = inlinedSubProgram->mInlineeInfo->mInlineParent; // Require it be in the inline parent
  9820. auto foundLine = parentSubprogram->FindClosestLine(inlinedSubProgram->mBlock.mLowPC, &parentSubprogram);
  9821. if (foundLine != NULL)
  9822. {
  9823. auto srcFile = parentSubprogram->GetLineSrcFile(*foundLine);
  9824. *outFile = srcFile->GetLocalPath();
  9825. *outLine = foundLine->mLine;
  9826. }
  9827. *outHotIdx = inlinedSubProgram->mCompileUnit->mDbgModule->mHotIdx;
  9828. *outColumn = -1;
  9829. DbgSubprogram* callingSubProgram = NULL;
  9830. DbgLineData* callingLineData = FindLineDataAtAddress(inlinedSubProgram->mBlock.mLowPC - 1, &callingSubProgram);
  9831. if ((callingLineData != NULL) && (callingSubProgram == subProgram))
  9832. {
  9833. auto callingSrcFile = callingSubProgram->GetLineSrcFile(*callingLineData);
  9834. auto srcFile = callingSrcFile;
  9835. *outFile = srcFile->GetLocalPath();
  9836. if (*outLine == callingLineData->mLine)
  9837. *outColumn = callingLineData->mColumn;
  9838. }
  9839. return;
  9840. }
  9841. }
  9842. if (subProgram != NULL)
  9843. {
  9844. if ((subProgram->mInlineeInfo != NULL) && ((addr_target)addr >= subProgram->mBlock.mHighPC))
  9845. callingLineData = &subProgram->mInlineeInfo->mLastLineData;
  9846. *outHotIdx = subProgram->mCompileUnit->mDbgModule->mHotIdx;
  9847. *outFile = subProgram->GetLineSrcFile(*callingLineData)->GetLocalPath();
  9848. *outLine = callingLineData->mLine;
  9849. *outColumn = callingLineData->mColumn;
  9850. FixupLineDataForSubprogram(subProgram);
  9851. DbgLineData* dwStartLineData = NULL;
  9852. DbgLineData* dwEndLineData = NULL;
  9853. if (subProgram->mLineInfo != NULL)
  9854. {
  9855. if (subProgram->mLineInfo->mLines.size() > 0)
  9856. {
  9857. dwStartLineData = &subProgram->mLineInfo->mLines[0];
  9858. dwEndLineData = &subProgram->mLineInfo->mLines.back();
  9859. }
  9860. }
  9861. else
  9862. {
  9863. if (subProgram->mInlineeInfo != NULL)
  9864. {
  9865. dwStartLineData = &subProgram->mInlineeInfo->mFirstLineData;
  9866. dwEndLineData = &subProgram->mInlineeInfo->mLastLineData;
  9867. }
  9868. }
  9869. if (dwEndLineData != NULL)
  9870. {
  9871. *outDefLineStart = dwStartLineData->mLine;
  9872. *outDefLineEnd = dwEndLineData->mLine;
  9873. }
  9874. }
  9875. }
  9876. void WinDebugger::GetStackAllocInfo(intptr addr, int* outThreadId, int* outStackIdx)
  9877. {
  9878. AutoCrit autoCrit(mDebugManager->mCritSect);
  9879. *outThreadId = 0;
  9880. if (outStackIdx != NULL)
  9881. *outStackIdx = -1;
  9882. if (!IsPaused())
  9883. return;
  9884. for (auto thread : mThreadList)
  9885. {
  9886. NT_TIB64 tib = { 0 };
  9887. if (!ReadMemory((intptr)thread->mThreadLocalBase, sizeof(tib), &tib))
  9888. continue;
  9889. MEMORY_BASIC_INFORMATION stackInfo = { 0 };
  9890. if (VirtualQueryEx(mProcessInfo.hProcess, (void*)(tib.StackBase - 1), &stackInfo, sizeof(MEMORY_BASIC_INFORMATION)) == 0)
  9891. continue;
  9892. if ((addr >= (intptr)stackInfo.AllocationBase) && (addr < (intptr)tib.StackBase))
  9893. {
  9894. *outThreadId = thread->mThreadId;
  9895. if (outStackIdx == NULL)
  9896. return;
  9897. if (mActiveThread == thread)
  9898. {
  9899. UpdateCallStack(false);
  9900. for (int callStackIdx = 0; callStackIdx < (int)mCallStack.size(); callStackIdx++)
  9901. {
  9902. UpdateCallStackMethod(callStackIdx);
  9903. auto stackFrame = mCallStack[callStackIdx];
  9904. if (addr >= (intptr)stackFrame->mRegisters.GetSP())
  9905. {
  9906. *outStackIdx = callStackIdx;
  9907. }
  9908. }
  9909. }
  9910. return;
  9911. }
  9912. }
  9913. }
  9914. String WinDebugger::GetStackFrameInfo(int stackFrameIdx, intptr* addr, String* outFile, int* outHotIdx, int* outDefLineStart, int* outDefLineEnd,
  9915. int* outLine, int* outColumn, int* outLanguage, int* outStackSize, int8* outFlags)
  9916. {
  9917. enum FrameFlags
  9918. {
  9919. FrameFlags_Optimized = 1,
  9920. FrameFlags_HasPendingDebugInfo = 2,
  9921. FrameFlags_CanGetOldSource = 4,
  9922. FrameFlags_WasHotReplaced = 8,
  9923. FrameFlags_HadError = 0x10
  9924. };
  9925. AutoCrit autoCrit(mDebugManager->mCritSect);
  9926. if (mCallStack.size() == 0)
  9927. UpdateCallStack();
  9928. *addr = 0;
  9929. *outFile = "";
  9930. *outHotIdx = 0;
  9931. *outDefLineStart = -1;
  9932. *outDefLineEnd = -1;
  9933. *outLine = -1;
  9934. *outColumn = 0;
  9935. *outLanguage = 0;
  9936. *outStackSize = 0;
  9937. *outFlags = 0;
  9938. UpdateCallStackMethod(stackFrameIdx);
  9939. if (stackFrameIdx >= mCallStack.size())
  9940. {
  9941. return "";
  9942. }
  9943. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  9944. UpdateCallStackMethod(actualStackFrameIdx);
  9945. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  9946. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  9947. if (stackFrameIdx == -1)
  9948. pcAddress = mShowPCOverride;
  9949. *addr = pcAddress;
  9950. if (actualStackFrameIdx < (int)mCallStack.size() - 2)
  9951. {
  9952. WdStackFrame* prevStackFrame = mCallStack[actualStackFrameIdx + 1];
  9953. // Inlined methods have no stack frame
  9954. *outStackSize = prevStackFrame->mRegisters.GetSP() - wdStackFrame->mRegisters.GetSP();
  9955. }
  9956. const auto& _CheckHashSrcFile = [&](String& outStr, DbgModule* dbgModule, DbgSrcFile* srcFile)
  9957. {
  9958. if (srcFile->mHashKind != DbgHashKind_None)
  9959. {
  9960. outStr += "#";
  9961. srcFile->GetHash(outStr);
  9962. }
  9963. };
  9964. auto _SetFlags = [&](DbgSubprogram* dwSubprogram)
  9965. {
  9966. DbgModule* dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  9967. if (dwSubprogram->mIsOptimized)
  9968. *outFlags |= FrameFlags_Optimized;
  9969. if (dbgModule->HasPendingDebugInfo())
  9970. *outFlags |= FrameFlags_HasPendingDebugInfo;
  9971. if (dbgModule->CanGetOldSource())
  9972. *outFlags |= FrameFlags_CanGetOldSource;
  9973. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) || (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid))
  9974. *outFlags |= FrameFlags_WasHotReplaced;
  9975. };
  9976. auto _FixFilePath = [&](DbgModule* dbgModule)
  9977. {
  9978. if (outFile == NULL)
  9979. return;
  9980. if (outFile->StartsWith("$Emit"))
  9981. {
  9982. int dollarPos = outFile->IndexOf('$', 1);
  9983. if (dollarPos == -1)
  9984. return;
  9985. outFile->Insert(dollarPos, StrFormat("%d", dbgModule->mId));
  9986. }
  9987. };
  9988. if (wdStackFrame->mInInlineMethod)
  9989. {
  9990. WdStackFrame* nextStackFrame = mCallStack[actualStackFrameIdx - 1];
  9991. auto subProgram = nextStackFrame->mSubProgram;
  9992. _SetFlags(subProgram);
  9993. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  9994. DbgSubprogram* parentSubprogram = subProgram->mInlineeInfo->mInlineParent; // Require it be in the inline parent
  9995. auto foundLine = parentSubprogram->FindClosestLine(subProgram->mBlock.mLowPC, &parentSubprogram);
  9996. if (foundLine != NULL)
  9997. {
  9998. auto srcFile = parentSubprogram->GetLineSrcFile(*foundLine);
  9999. *outFile = srcFile->GetLocalPath();
  10000. _CheckHashSrcFile(*outFile, subProgram->mCompileUnit->mDbgModule, srcFile);
  10001. *outLine = foundLine->mLine;
  10002. }
  10003. *outLanguage = subProgram->GetLanguage();
  10004. *outHotIdx = subProgram->mCompileUnit->mDbgModule->mHotIdx;
  10005. *outColumn = -1;
  10006. DbgSubprogram* callingSubProgram = NULL;
  10007. DbgLineData* callingLineData = FindLineDataAtAddress(nextStackFrame->mSubProgram->mBlock.mLowPC - 1, &callingSubProgram);
  10008. if ((callingLineData != NULL) && (callingSubProgram == wdStackFrame->mSubProgram))
  10009. {
  10010. auto callingSrcFile = callingSubProgram->GetLineSrcFile(*callingLineData);
  10011. *outLanguage = callingSubProgram->mCompileUnit->mLanguage;
  10012. auto srcFile = callingSrcFile;
  10013. *outFile = srcFile->GetLocalPath();
  10014. _CheckHashSrcFile(*outFile, subProgram->mCompileUnit->mDbgModule, srcFile);
  10015. if (*outLine == callingLineData->mLine)
  10016. *outColumn = callingLineData->mColumn;
  10017. }
  10018. String name = wdStackFrame->mSubProgram->ToString();
  10019. DbgModule* dbgModule = wdStackFrame->mSubProgram->mCompileUnit->mDbgModule;
  10020. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  10021. if (!linkedModule->mDisplayName.empty())
  10022. name = linkedModule->mDisplayName + "!" + name;
  10023. _FixFilePath(dbgModule);
  10024. return name;
  10025. }
  10026. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  10027. if (dwSubprogram != NULL)
  10028. {
  10029. String demangledName;
  10030. if ((dwSubprogram->mName != NULL) && (strncmp(dwSubprogram->mName, ":Sep@", 5) == 0))
  10031. {
  10032. char* p;
  10033. auto addr = strtoll(dwSubprogram->mName + 5, &p, 16);
  10034. if (addr != 0)
  10035. {
  10036. auto parentSubprogram = mDebugTarget->FindSubProgram(addr);
  10037. if (parentSubprogram != NULL)
  10038. demangledName = parentSubprogram->ToString();
  10039. }
  10040. }
  10041. if (demangledName.IsEmpty())
  10042. {
  10043. dwSubprogram->ToString(demangledName, true);
  10044. }
  10045. DbgSrcFile* dwSrcFile = NULL;
  10046. DbgLineData* dwLineData = NULL;
  10047. FixupLineDataForSubprogram(dwSubprogram);
  10048. addr_target findAddress = wdStackFrame->GetSourcePC();
  10049. DbgSubprogram* specificSubprogram = dwSubprogram;
  10050. dwLineData = dwSubprogram->FindClosestLine(findAddress, &specificSubprogram);
  10051. if ((dwLineData == NULL) && (dwSubprogram->mInlineeInfo != NULL) && (findAddress >= dwSubprogram->mBlock.mHighPC))
  10052. dwLineData = &dwSubprogram->mInlineeInfo->mLastLineData;
  10053. if (dwLineData != NULL)
  10054. dwSrcFile = dwSubprogram->GetLineSrcFile(*dwLineData);
  10055. DbgLineData* dwStartLineData = NULL;
  10056. DbgLineData* dwEndLineData = NULL;
  10057. if (dwSubprogram->mLineInfo != NULL)
  10058. {
  10059. if (dwSubprogram->mLineInfo->mLines.size() > 0)
  10060. {
  10061. dwStartLineData = &dwSubprogram->mLineInfo->mLines[0];
  10062. dwEndLineData = &dwSubprogram->mLineInfo->mLines.back();
  10063. }
  10064. }
  10065. else
  10066. {
  10067. if (dwSubprogram->mInlineeInfo != NULL)
  10068. {
  10069. dwStartLineData = &dwSubprogram->mInlineeInfo->mFirstLineData;
  10070. dwEndLineData = &dwSubprogram->mInlineeInfo->mLastLineData;
  10071. }
  10072. }
  10073. DbgModule* dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  10074. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  10075. if (!linkedModule->mDisplayName.empty())
  10076. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  10077. if ((dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Replaced) || (dwSubprogram->mHotReplaceKind == DbgSubprogram::HotReplaceKind_Invalid))
  10078. demangledName = "#" + demangledName;
  10079. _SetFlags(dwSubprogram);
  10080. if ((dwLineData != NULL) && (dwSrcFile != NULL))
  10081. {
  10082. *outFile = dwSrcFile->GetLocalPath();
  10083. _CheckHashSrcFile(*outFile, dbgModule, dwSrcFile);
  10084. *outHotIdx = dbgModule->mHotIdx;
  10085. *outLine = dwLineData->mLine;
  10086. *outColumn = dwLineData->mColumn;
  10087. *outLanguage = (int)dwSubprogram->mCompileUnit->mLanguage;
  10088. if (dwEndLineData != NULL)
  10089. {
  10090. *outDefLineStart = dwStartLineData->mLine;
  10091. *outDefLineEnd = dwEndLineData->mLine;
  10092. }
  10093. _FixFilePath(dbgModule);
  10094. return demangledName;
  10095. }
  10096. else
  10097. {
  10098. _FixFilePath(dbgModule);
  10099. return demangledName + StrFormat("+0x%X", pcAddress - dwSubprogram->mBlock.mLowPC);
  10100. }
  10101. }
  10102. else
  10103. {
  10104. String symbolName;
  10105. addr_target offset;
  10106. DbgModule* dbgModule = NULL;
  10107. if (mDebugTarget->FindSymbolAt(pcAddress, &symbolName, &offset, &dbgModule))
  10108. {
  10109. if (dbgModule->HasPendingDebugInfo())
  10110. {
  10111. *outFlags |= FrameFlags_HasPendingDebugInfo;
  10112. if (mPendingDebugInfoLoad.ContainsKey(dbgModule))
  10113. {
  10114. String outName = EncodeDataPtr(pcAddress, true);
  10115. if ((dbgModule != NULL) && (!dbgModule->mDisplayName.empty()))
  10116. outName = dbgModule->mDisplayName + "!<Loading...>" + outName;
  10117. return outName;
  10118. }
  10119. }
  10120. DbgModule* linkedModule = dbgModule->GetLinkedModule();
  10121. String demangledName = BfDemangler::Demangle(symbolName, DbgLanguage_Unknown);
  10122. if (!linkedModule->mDisplayName.empty())
  10123. demangledName = linkedModule->mDisplayName + "!" + demangledName;
  10124. _FixFilePath(dbgModule);
  10125. return demangledName + StrFormat("+0x%X", offset);
  10126. }
  10127. }
  10128. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress(pcAddress);
  10129. DbgModule* linkedModule = NULL;
  10130. if (dbgModule != NULL)
  10131. {
  10132. linkedModule = dbgModule->GetLinkedModule();
  10133. if (dbgModule->HasPendingDebugInfo())
  10134. *outFlags |= FrameFlags_HasPendingDebugInfo;
  10135. }
  10136. String outName = EncodeDataPtr(pcAddress, true);
  10137. if ((linkedModule != NULL) && (!linkedModule->mDisplayName.empty()))
  10138. outName = linkedModule->mDisplayName + "!" + outName;
  10139. _FixFilePath(dbgModule);
  10140. return outName;
  10141. }
  10142. String WinDebugger::GetStackFrameId(int stackFrameIdx)
  10143. {
  10144. AutoCrit autoCrit(mDebugManager->mCritSect);
  10145. if (!FixCallStackIdx(stackFrameIdx))
  10146. return "";
  10147. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  10148. UpdateCallStackMethod(actualStackFrameIdx);
  10149. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  10150. intptr addr = 0;
  10151. if (wdStackFrame->mSubProgram != NULL)
  10152. addr = wdStackFrame->mSubProgram->mBlock.mLowPC;
  10153. else
  10154. addr = wdStackFrame->mRegisters.GetPC();
  10155. String str = StrFormat("Thread:%d SP:%llX Func:%llX", mActiveThread->mThreadId, wdStackFrame->mRegisters.GetSP(), addr);
  10156. return str;
  10157. }
  10158. String WinDebugger::Callstack_GetStackFrameOldFileInfo(int stackFrameIdx)
  10159. {
  10160. AutoCrit autoCrit(mDebugManager->mCritSect);
  10161. if (!FixCallStackIdx(stackFrameIdx))
  10162. return "";
  10163. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  10164. UpdateCallStackMethod(actualStackFrameIdx);
  10165. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  10166. DbgModule* dbgModule = NULL;
  10167. DbgSrcFile* dbgSrcFile = NULL;
  10168. if (wdStackFrame->mInInlineMethod)
  10169. {
  10170. WdStackFrame* nextStackFrame = mCallStack[actualStackFrameIdx - 1];
  10171. auto subProgram = nextStackFrame->mSubProgram;
  10172. dbgModule = subProgram->mCompileUnit->mDbgModule;
  10173. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  10174. DbgSubprogram* parentSubprogram = subProgram->mInlineeInfo->mInlineParent; // Require it be in the inline parent
  10175. auto foundLine = parentSubprogram->FindClosestLine(subProgram->mBlock.mLowPC, &parentSubprogram);
  10176. if (foundLine != NULL)
  10177. dbgSrcFile = parentSubprogram->GetLineSrcFile(*foundLine);
  10178. DbgSubprogram* callingSubProgram = NULL;
  10179. DbgLineData* callingLineData = FindLineDataAtAddress(nextStackFrame->mSubProgram->mBlock.mLowPC - 1, &callingSubProgram);
  10180. if ((callingLineData != NULL) && (callingSubProgram == wdStackFrame->mSubProgram))
  10181. dbgSrcFile = callingSubProgram->GetLineSrcFile(*callingLineData);
  10182. }
  10183. else
  10184. {
  10185. DbgSubprogram* dwSubprogram = wdStackFrame->mSubProgram;
  10186. if (dwSubprogram != NULL)
  10187. {
  10188. FixupLineDataForSubprogram(dwSubprogram);
  10189. addr_target findAddress = wdStackFrame->GetSourcePC();
  10190. DbgSubprogram* dbgSubprogram = NULL;
  10191. DbgLineData* dwLineData = dwSubprogram->FindClosestLine(findAddress, &dbgSubprogram, &dbgSrcFile);
  10192. dbgModule = dwSubprogram->mCompileUnit->mDbgModule;
  10193. }
  10194. }
  10195. if (dbgSrcFile != NULL)
  10196. {
  10197. // Note: we must use mFilePath here, make sure we don't use GetLocalPath()
  10198. return dbgModule->GetOldSourceCommand(dbgSrcFile->mFilePath);
  10199. }
  10200. return "";
  10201. }
  10202. int WinDebugger::GetJmpState(int stackFrameIdx)
  10203. {
  10204. AutoCrit autoCrit(mDebugManager->mCritSect);
  10205. if (!FixCallStackIdx(stackFrameIdx))
  10206. return -1;
  10207. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  10208. UpdateCallStackMethod(actualStackFrameIdx);
  10209. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  10210. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  10211. CPUInst inst;
  10212. if (!mDebugTarget->DecodeInstruction(pcAddress, &inst))
  10213. return -1;
  10214. return inst.GetJmpState(wdStackFrame->mRegisters.mIntRegs.efl);
  10215. }
  10216. intptr WinDebugger::GetStackFrameCalleeAddr(int stackFrameIdx)
  10217. {
  10218. AutoCrit autoCrit(mDebugManager->mCritSect);
  10219. if (!FixCallStackIdx(stackFrameIdx))
  10220. return -1;
  10221. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  10222. UpdateCallStackMethod(actualStackFrameIdx);
  10223. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  10224. addr_target pcAddress = (addr_target)wdStackFrame->mRegisters.GetPC();
  10225. if (stackFrameIdx == -1)
  10226. pcAddress = mShowPCOverride;
  10227. if (wdStackFrame->mInInlineMethod)
  10228. {
  10229. WdStackFrame* inlineStackFrame = mCallStack[actualStackFrameIdx - 1];
  10230. return inlineStackFrame->mSubProgram->mBlock.mLowPC - 1;
  10231. }
  10232. return pcAddress - 1;
  10233. }
  10234. String WinDebugger::GetStackMethodOwner(int stackFrameIdx, int& language)
  10235. {
  10236. AutoCrit autoCrit(mDebugManager->mCritSect);
  10237. if (!FixCallStackIdx(stackFrameIdx))
  10238. return "";
  10239. int actualStackFrameIdx = BF_MAX(0, stackFrameIdx);
  10240. if (actualStackFrameIdx >= (int)mCallStack.size())
  10241. actualStackFrameIdx = 0;
  10242. UpdateCallStackMethod(actualStackFrameIdx);
  10243. WdStackFrame* wdStackFrame = mCallStack[actualStackFrameIdx];
  10244. if (wdStackFrame->mSubProgram == NULL)
  10245. return "";
  10246. auto parentType = wdStackFrame->mSubProgram->GetParent();
  10247. if (parentType == NULL)
  10248. return "";
  10249. parentType = parentType->GetPrimaryType();
  10250. language = (int)parentType->GetLanguage();
  10251. return parentType->ToString();
  10252. }
  10253. String WinDebugger::FindCodeAddresses(const StringImpl& fileName, int line, int column, bool allowAutoResolve)
  10254. {
  10255. String result;
  10256. if (mDebugTarget == NULL)
  10257. return "";
  10258. DbgSrcFile* srcFile = mDebugTarget->GetSrcFile(fileName);
  10259. if (srcFile == NULL)
  10260. return result;
  10261. bool foundInSequence = false;
  10262. WdBreakpoint* prevBreakpoint = NULL;
  10263. int bestLineOffset = 0x7FFFFFFF;
  10264. for (auto dbgSubprogram : srcFile->mLineDataRefs)
  10265. {
  10266. for (auto& lineData : dbgSubprogram->mLineInfo->mLines)
  10267. {
  10268. auto lineSrcFile = dbgSubprogram->GetLineSrcFile(lineData);
  10269. if (lineSrcFile != srcFile)
  10270. continue;
  10271. int lineOffset = lineData.mLine - line;
  10272. if ((lineOffset >= 0) && (lineOffset <= 12) && (lineOffset <= bestLineOffset))
  10273. {
  10274. if (lineOffset < bestLineOffset)
  10275. {
  10276. bestLineOffset = lineOffset;
  10277. result = "";
  10278. }
  10279. if (!foundInSequence)
  10280. {
  10281. auto addr = dbgSubprogram->GetLineAddr(lineData);
  10282. result += EncodeDataPtr(addr, false) + "\t" + dbgSubprogram->ToString() + "\n";
  10283. }
  10284. }
  10285. // New sequence?
  10286. if (!lineData.IsStackFrameSetup())
  10287. foundInSequence = false;
  10288. }
  10289. }
  10290. return result;
  10291. }
  10292. String WinDebugger::GetAddressSourceLocation(intptr address)
  10293. {
  10294. DbgSubprogram* subProgram = NULL;
  10295. DbgLineData* lineData = FindLineDataAtAddress(address, &subProgram);
  10296. if (lineData != NULL)
  10297. return StrFormat("%s:%d:%d", subProgram->GetLineSrcFile(*lineData)->GetLocalPath().c_str(), lineData->mLine + 1, lineData->mColumn + 1);
  10298. String outSymbol;
  10299. addr_target offset = 0;
  10300. DbgModule* dbgModule;
  10301. if (mDebugTarget->FindSymbolAt(address, &outSymbol, &offset, &dbgModule))
  10302. {
  10303. if (offset < 0x10000)
  10304. {
  10305. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  10306. if (offset > 0)
  10307. outSymbol += StrFormat("+%x", offset);
  10308. return outSymbol;
  10309. }
  10310. }
  10311. return StrFormat("0x%@", address);
  10312. }
  10313. String WinDebugger::GetAddressSymbolName(intptr address, bool demangle)
  10314. {
  10315. auto subProgram = mDebugTarget->FindSubProgram(address);
  10316. if (subProgram != NULL)
  10317. return subProgram->ToString();
  10318. String outSymbol;
  10319. addr_target offset = 0;
  10320. DbgModule* dbgModule;
  10321. if (mDebugTarget->FindSymbolAt(address, &outSymbol, &offset, &dbgModule))
  10322. {
  10323. if (offset < 0x10000)
  10324. {
  10325. if (demangle)
  10326. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  10327. if (offset > 0)
  10328. outSymbol += StrFormat("+%x", offset);
  10329. return outSymbol;
  10330. }
  10331. }
  10332. return StrFormat("0x%@", address);
  10333. }
  10334. String WinDebugger::DisassembleAtRaw(intptr inAddress)
  10335. {
  10336. addr_target address = (addr_target)inAddress;
  10337. const int addrBorder = 1024;
  10338. for (int offset = 0; offset < 8; offset++)
  10339. {
  10340. String result;
  10341. bool addOffset = true;
  10342. bool hadAddr = false;
  10343. DbgModule* dbgModule = mDebugTarget->FindDbgModuleForAddress(address);
  10344. DbgModuleMemoryCache* memCache = NULL;
  10345. defer
  10346. (
  10347. if (dbgModule == NULL)
  10348. delete memCache;
  10349. );
  10350. if ((dbgModule != NULL) && (dbgModule->mOrigImageData == NULL))
  10351. dbgModule = NULL;
  10352. result += "R\n"; // Raw
  10353. addr_target addrStart = address;
  10354. if (dbgModule != NULL)
  10355. {
  10356. dbgModule->ParseSymbolData();
  10357. memCache = dbgModule->mOrigImageData;
  10358. addrStart = BF_MAX((addr_target)dbgModule->mImageBase, address - addrBorder - offset);
  10359. }
  10360. else
  10361. {
  10362. memCache = new DbgModuleMemoryCache(addrStart & (4096 - 1), 4096 * 2);
  10363. }
  10364. if (memCache->mAddr == 0)
  10365. return "";
  10366. //addr_target imageBase = dbgModule->mImageBase;
  10367. //int imageSize = dbgModule->mImageSize;
  10368. addr_target dataAddr = addrStart;
  10369. addr_target addrEnd = addrStart + addrBorder * 2 + 16;
  10370. while (dataAddr < addrEnd)
  10371. {
  10372. if (dataAddr == address)
  10373. hadAddr = true;
  10374. if (dataAddr > address)
  10375. {
  10376. if (!hadAddr)
  10377. {
  10378. if (offset == 7)
  10379. {
  10380. dataAddr = address;
  10381. }
  10382. break;
  10383. }
  10384. }
  10385. String outSymbol;
  10386. addr_target symOffset = 0;
  10387. DbgModule* symDWARF;
  10388. if (mDebugTarget->FindSymbolAt(dataAddr, &outSymbol, &symOffset, &symDWARF))
  10389. {
  10390. if (symOffset == 0)
  10391. {
  10392. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  10393. if ((symDWARF != NULL) && (!symDWARF->mDisplayName.empty()))
  10394. outSymbol = symDWARF->GetLinkedModule()->mDisplayName + "!" + outSymbol;
  10395. result += "T " + outSymbol + ":\n";
  10396. }
  10397. }
  10398. CPUInst inst;
  10399. if (!mCPU->Decode(dataAddr, memCache, &inst))
  10400. {
  10401. if ((offset == 7) && (!hadAddr))
  10402. {
  10403. uint8 instData[1];
  10404. memCache->Read(dataAddr, instData, 1);
  10405. int instLen = 1;
  10406. #ifdef BF_DBG_32
  10407. result += StrFormat("D %08X: ", dataAddr);
  10408. #else
  10409. result += StrFormat("D %@: ", dataAddr);
  10410. #endif
  10411. for (int i = 0; i < instLen; i++)
  10412. result += StrFormat("%02X ", instData[i]);
  10413. for (int i = instLen; i < 8; i++)
  10414. result += " ";
  10415. result += "\n";
  10416. dataAddr++;
  10417. continue;
  10418. }
  10419. break;
  10420. }
  10421. int instLen = inst.GetLength();
  10422. #ifdef BF_DBG_32
  10423. result += StrFormat("D %08X: ", dataAddr);
  10424. #else
  10425. result += StrFormat("D %@: ", dataAddr);
  10426. #endif
  10427. uint8 instData[32];
  10428. int showInstLen = BF_MIN(32, instLen);
  10429. memCache->Read(dataAddr, instData, showInstLen);
  10430. for (int i = 0; i < showInstLen; i++)
  10431. result += StrFormat("%02X ", instData[i]);
  10432. for (int i = instLen; i < 8; i++)
  10433. result += " ";
  10434. result += mCPU->InstructionToString(&inst, dataAddr);
  10435. if ((inst.IsCall()) || (inst.IsBranch()))
  10436. {
  10437. addr_target targetAddr = inst.GetTarget();
  10438. if (targetAddr != 0)
  10439. {
  10440. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &symOffset))
  10441. {
  10442. if (symOffset < 0x10000)
  10443. {
  10444. outSymbol = BfDemangler::Demangle(outSymbol, DbgLanguage_Unknown);
  10445. result += " ; " + outSymbol;
  10446. if (symOffset > 0)
  10447. result += StrFormat("+%x", symOffset);
  10448. //result += ">";
  10449. }
  10450. }
  10451. }
  10452. }
  10453. result += "\n";
  10454. dataAddr += instLen;
  10455. }
  10456. if (!hadAddr)
  10457. continue;
  10458. return result;
  10459. }
  10460. return "";
  10461. }
  10462. String WinDebugger::DisassembleAt(intptr inAddress)
  10463. {
  10464. BP_ZONE("WinDebugger::DisassembleAt");
  10465. AutoCrit autoCrit(mDebugManager->mCritSect);
  10466. addr_target address = (addr_target)inAddress;
  10467. if (mDebugTarget == NULL)
  10468. return "";
  10469. String result;
  10470. auto dwSubProgram = mDebugTarget->FindSubProgram(address);
  10471. if (dwSubProgram == NULL)
  10472. return DisassembleAtRaw(address);
  10473. dwSubProgram = dwSubProgram->GetRootInlineParent();
  10474. DbgModule* dwarf = dwSubProgram->mCompileUnit->mDbgModule;
  10475. int frameBaseRegister = mDebugTarget->GetFrameBaseRegister(dwSubProgram);
  10476. addr_target addrStart = dwSubProgram->mBlock.mLowPC;
  10477. addr_target addrEnd = dwSubProgram->mBlock.mHighPC;
  10478. auto dwCompileUnit = dwSubProgram->mCompileUnit;
  10479. {
  10480. FixupLineData(dwCompileUnit);
  10481. }
  10482. DbgSrcFile* dwSrcFile = NULL;
  10483. FixupLineDataForSubprogram(dwSubProgram);
  10484. DbgLineData* dwLineData = NULL;
  10485. if (dwSubProgram->mLineInfo != NULL)
  10486. dwLineData = &dwSubProgram->mLineInfo->mLines[0];
  10487. int nextLineDataIdx = 1;
  10488. if (dwSubProgram->mIsOptimized)
  10489. result += "O\n";
  10490. DbgSrcFile* srcFile = NULL;
  10491. int firstLine = 0;
  10492. int curLine = 0;
  10493. if (dwLineData != NULL)
  10494. {
  10495. srcFile = dwSubProgram->GetLineSrcFile(*dwLineData);
  10496. result += "S " + srcFile->GetLocalPath() + "\n";
  10497. if (srcFile->mHashKind != DbgHashKind_None)
  10498. {
  10499. result += "H ";
  10500. srcFile->GetHash(result);
  10501. result += "\n";
  10502. }
  10503. curLine = BF_MAX(0, dwLineData->mLine - 5);
  10504. //for (; curLine <= dwLineData->mLine; curLine++)
  10505. result += StrFormat("L %d %d\n", curLine, dwLineData->mLine - curLine + 1);
  10506. curLine = dwLineData->mLine + 1;
  10507. firstLine = dwLineData->mLine;
  10508. }
  10509. Array<DbgSubprogram*> inlineStack;
  10510. Array<DbgBlock*> blockList;
  10511. blockList.push_back(&dwSubProgram->mBlock);
  10512. addr_target dataAddr = addrStart;
  10513. int decodeFailureCount = 0;
  10514. auto& _PopInlineStack = [&]()
  10515. {
  10516. int depth = inlineStack.size();
  10517. auto curStackEntry = inlineStack.back();
  10518. if (depth > 1)
  10519. result += StrFormat("T <<<%d Inline End ", depth);
  10520. else
  10521. result += "T <<< Inline End ";
  10522. result += curStackEntry->ToString();
  10523. result += "\n";
  10524. inlineStack.pop_back();
  10525. };
  10526. std::function<void(DbgSubprogram* subprogram, int depth)> _UpdateInlineStackHelper = [&](DbgSubprogram* subprogram, int depth)
  10527. {
  10528. int stackIdx = depth - 1;
  10529. if (stackIdx < inlineStack.size())
  10530. {
  10531. auto curStackEntry = inlineStack[stackIdx];
  10532. if (curStackEntry != subprogram)
  10533. _PopInlineStack();
  10534. }
  10535. if (depth > 1)
  10536. {
  10537. _UpdateInlineStackHelper(subprogram->mInlineeInfo->mInlineParent, depth - 1);
  10538. }
  10539. if (stackIdx >= inlineStack.size())
  10540. {
  10541. if (depth > 1)
  10542. result += StrFormat("T >>>%d Inline ", depth);
  10543. else
  10544. result += "T >>> Inline ";
  10545. result += subprogram->ToString();
  10546. result += "\n";
  10547. inlineStack.push_back(subprogram);
  10548. }
  10549. };
  10550. auto _UpdateInlineStack = [&](DbgSubprogram* subprogram)
  10551. {
  10552. if (subprogram == NULL)
  10553. {
  10554. while (!inlineStack.IsEmpty())
  10555. _PopInlineStack();
  10556. return;
  10557. }
  10558. int inlineDepth = subprogram->GetInlineDepth();
  10559. while (inlineDepth < inlineStack.size())
  10560. _PopInlineStack();
  10561. if (inlineDepth > 0)
  10562. _UpdateInlineStackHelper(subprogram, inlineDepth);
  10563. };
  10564. while (dataAddr < addrEnd)
  10565. {
  10566. // Pop off old scopes
  10567. while (blockList.size() > 0)
  10568. {
  10569. auto lastBlock = blockList.back();
  10570. if (dataAddr < lastBlock->mHighPC)
  10571. break;
  10572. blockList.pop_back();
  10573. }
  10574. // Check entry into new child scopes
  10575. auto lastBlock = blockList.back();
  10576. for (auto checkBlock : lastBlock->mSubBlocks)
  10577. {
  10578. if ((dataAddr >= checkBlock->mLowPC) && (dataAddr < checkBlock->mHighPC))
  10579. {
  10580. blockList.push_back(checkBlock);
  10581. break;
  10582. }
  10583. }
  10584. bool allowSourceJump = false;
  10585. if ((dwLineData != NULL) && (dwLineData->mContribSize != 0) && (dataAddr >= dwSubProgram->GetLineAddr(*dwLineData) + dwLineData->mContribSize))
  10586. {
  10587. DbgSubprogram* inlinedSubprogram = NULL;
  10588. auto inlinedLine = dwSubProgram->FindClosestLine(dataAddr, &inlinedSubprogram);
  10589. _UpdateInlineStack(dwSubProgram);
  10590. }
  10591. // Update line data
  10592. while ((dwLineData != NULL) && (dwSubProgram->GetLineAddr(*dwLineData) <= dataAddr))
  10593. {
  10594. _UpdateInlineStack(dwSubProgram->GetLineInlinee(*dwLineData));
  10595. const int lineLimit = 5; // 15
  10596. if (allowSourceJump)
  10597. curLine = dwLineData->mLine;
  10598. auto lineSrcFile = dwSubProgram->GetLineSrcFile(*dwLineData);
  10599. if (lineSrcFile != srcFile)
  10600. {
  10601. srcFile = lineSrcFile;
  10602. result += "S ";
  10603. result += srcFile->GetLocalPath();
  10604. result += "\n";
  10605. // Just show the one line from the new file
  10606. curLine = dwLineData->mLine;
  10607. }
  10608. if (dwLineData->mLine < curLine - 1)
  10609. {
  10610. // Jumping backwards - possibly into inlined method, or possibly in current method.
  10611. // Show previous 6 lines, for context
  10612. curLine = BF_MAX(0, dwLineData->mLine - lineLimit);
  10613. }
  10614. if ((curLine <= firstLine) && (dwLineData->mLine >= firstLine))
  10615. {
  10616. // Jumping from inlined method (declared above) back into main method
  10617. curLine = dwLineData->mLine;
  10618. }
  10619. if (curLine < dwLineData->mLine - lineLimit)
  10620. {
  10621. // Don't show huge span of source - only show the last 6 lines at maximum
  10622. curLine = dwLineData->mLine - lineLimit;
  10623. }
  10624. //for ( ; curLine <= dwLineData->mLine; curLine++)
  10625. result += StrFormat("L %d %d\n", curLine, dwLineData->mLine - curLine + 1);
  10626. curLine = dwLineData->mLine + 1;
  10627. DbgLineData* nextLineData = NULL;
  10628. while (nextLineDataIdx < dwSubProgram->mLineInfo->mLines.mSize)
  10629. {
  10630. nextLineData = &dwSubProgram->mLineInfo->mLines[nextLineDataIdx];
  10631. //TODO:
  10632. /*{
  10633. result += StrFormat("T LineIdx: %d (%@ to %@)", nextLineDataIdx, dwSubProgram->GetLineAddr(*nextLineData), dwSubProgram->GetLineAddr(*nextLineData) + nextLineData->mContribSize);
  10634. auto inlinee = dwSubProgram->GetLineInlinee(*nextLineData);
  10635. if (inlinee != NULL)
  10636. {
  10637. result += StrFormat(" Inlinee: %s Depth: %d", inlinee->mName, inlinee->GetInlineDepth());
  10638. }
  10639. result += "\n";
  10640. }*/
  10641. auto nextLineAddr = dwSubProgram->GetLineAddr(*nextLineData);
  10642. if (nextLineAddr > dataAddr)
  10643. {
  10644. if (nextLineDataIdx + 1 < dwSubProgram->mLineInfo->mLines.mSize)
  10645. {
  10646. auto peekLineData = &dwSubProgram->mLineInfo->mLines[nextLineDataIdx + 1];
  10647. if (peekLineData->mRelAddress == nextLineData->mRelAddress)
  10648. {
  10649. // Use the later entry
  10650. ++nextLineDataIdx;
  10651. continue;
  10652. }
  10653. }
  10654. break;
  10655. }
  10656. // If we go back to an older entry beacuse of a gap then we need to catch back up...
  10657. ++nextLineDataIdx;
  10658. nextLineData = NULL; // Keep searching...
  10659. }
  10660. dwLineData = nextLineData;
  10661. nextLineDataIdx++;
  10662. }
  10663. // Have we gone off the end of the inline function?
  10664. // We may not have an explicit non-inlined line data at the transition point...
  10665. while (!inlineStack.IsEmpty())
  10666. {
  10667. auto subProgram = inlineStack.back();
  10668. if (dataAddr < subProgram->mBlock.mHighPC)
  10669. break;
  10670. _PopInlineStack();
  10671. }
  10672. bool hadDecodeFailure = false;
  10673. CPUInst inst;
  10674. if (!mCPU->Decode(dataAddr, dwarf->mOrigImageData, &inst))
  10675. hadDecodeFailure = true;
  10676. if ((decodeFailureCount == 8) || ((decodeFailureCount > 0) && (!hadDecodeFailure)))
  10677. {
  10678. for (int i = decodeFailureCount; i < 4 + sizeof(addr_target); i++)
  10679. result += " ";
  10680. result += " ???\n";
  10681. decodeFailureCount = 0;
  10682. }
  10683. if (decodeFailureCount == 0)
  10684. {
  10685. #ifdef BF_DBG_32
  10686. result += StrFormat("D %08X: ", dataAddr);
  10687. #else
  10688. result += StrFormat("D %@: ", dataAddr);
  10689. #endif
  10690. }
  10691. if (hadDecodeFailure)
  10692. {
  10693. uint8 byte = 0;
  10694. dwarf->mOrigImageData->Read(dataAddr, &byte, 1);
  10695. result += StrFormat("%02X ", byte);
  10696. dataAddr++;
  10697. decodeFailureCount++;
  10698. continue;
  10699. }
  10700. int instLen = inst.GetLength();
  10701. uint8 instData[32];
  10702. int showInstLen = BF_MIN(32, instLen);
  10703. dwarf->mOrigImageData->Read(dataAddr, instData, showInstLen);
  10704. for (int i = 0; i < showInstLen; i++)
  10705. result += StrFormat("%02X ", instData[i]);
  10706. for (int i = instLen; i < 4 + sizeof(addr_target); i++)
  10707. result += " ";
  10708. result += " ";
  10709. result += mCPU->InstructionToString(&inst, dataAddr);
  10710. int reg;
  10711. int offset;
  10712. if (inst.GetIndexRegisterAndOffset(&reg, &offset))
  10713. {
  10714. for (int blockIdx = (int)blockList.size() - 1; blockIdx >= 0; blockIdx--)
  10715. {
  10716. auto dwBlock = blockList[blockIdx];
  10717. for (auto variable : dwBlock->mVariables)
  10718. {
  10719. int varRegister;
  10720. int varOffset;
  10721. if (mDebugTarget->GetVariableIndexRegisterAndOffset(variable, &varRegister, &varOffset))
  10722. {
  10723. if (varRegister == -1)
  10724. varRegister = frameBaseRegister;
  10725. if ((reg == varRegister) && (offset == varOffset))
  10726. {
  10727. result += " ; ";
  10728. result += variable->mName;
  10729. break;
  10730. }
  10731. }
  10732. }
  10733. }
  10734. }
  10735. else if ((inst.IsCall()) || (inst.IsBranch()) || (inst.IsLoadAddress()))
  10736. {
  10737. addr_target targetAddr = inst.GetTarget();
  10738. if (targetAddr != 0)
  10739. {
  10740. if ((targetAddr >= addrStart) && (targetAddr < addrEnd))
  10741. {
  10742. result += StrFormat("\nJ %s", EncodeDataPtr(targetAddr, false).c_str());
  10743. }
  10744. else
  10745. {
  10746. String outSymbol;
  10747. addr_target offset = 0;
  10748. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &offset))
  10749. {
  10750. if (offset < 0x10000)
  10751. {
  10752. outSymbol = BfDemangler::Demangle(outSymbol, dwSubProgram->GetLanguage());
  10753. result += " ; " + outSymbol;
  10754. if (offset > 0)
  10755. result += StrFormat("+%x", offset);
  10756. }
  10757. }
  10758. }
  10759. }
  10760. }
  10761. result += "\n";
  10762. dataAddr += instLen;
  10763. }
  10764. // Why did we want to "show lines at end"??
  10765. // Show lines at end
  10766. /*if (curLine > 0)
  10767. {
  10768. for (int i = 0; i < 6; i++, curLine++)
  10769. result += StrFormat("L %d\n", curLine);
  10770. }*/
  10771. return result;
  10772. }
  10773. String WinDebugger::FindLineCallAddresses(intptr inAddress)
  10774. {
  10775. String callAddresses;
  10776. addr_target address = (addr_target)inAddress;
  10777. DbgSubprogram* dwSubprogram = NULL;
  10778. DbgLineData* startLineData = FindLineDataAtAddress(address, &dwSubprogram, NULL);
  10779. if (dwSubprogram == NULL)
  10780. return "";
  10781. CPURegisters registers;
  10782. PopulateRegisters(&registers);
  10783. auto inlinerSubprogram = dwSubprogram->GetRootInlineParent();
  10784. FixupLineDataForSubprogram(inlinerSubprogram);
  10785. if (inlinerSubprogram->mLineInfo->mLines.mSize == 0)
  10786. return "";
  10787. auto lineData = &inlinerSubprogram->mLineInfo->mLines[0];
  10788. addr_target addr = dwSubprogram->mBlock.mLowPC;
  10789. addr_target endAddr = dwSubprogram->mBlock.mHighPC;
  10790. DbgSubprogram* checkSubprogram = dwSubprogram;
  10791. DbgLineData* checkLineData = lineData;
  10792. addr_target checkLineAddr = 0;
  10793. int lineIdx = 0;
  10794. while (checkLineData != NULL)
  10795. {
  10796. //auto nextLineData = dwSubprogram->mCompileUnit->mLineDataMap.GetNext(checkLineData);
  10797. ++lineIdx;
  10798. DbgLineData* nextLineData = NULL;
  10799. addr_target nextLineAddr;
  10800. if (lineIdx < inlinerSubprogram->mLineInfo->mLines.size())
  10801. {
  10802. nextLineData = &inlinerSubprogram->mLineInfo->mLines[lineIdx];
  10803. nextLineAddr = dwSubprogram->GetLineAddr(*nextLineData);
  10804. }
  10805. else
  10806. nextLineAddr = inlinerSubprogram->mBlock.mHighPC;
  10807. // This stuff doesn't make sense...
  10808. DbgSubprogram* nextSubProgram;
  10809. if (nextLineData != NULL)
  10810. {
  10811. if (nextLineAddr > dwSubprogram->mBlock.mHighPC)
  10812. break;
  10813. endAddr = nextLineAddr;
  10814. nextSubProgram = mDebugTarget->FindSubProgram(endAddr);
  10815. if (nextSubProgram != NULL)
  10816. {
  10817. auto dbgModule = nextSubProgram->mCompileUnit->mDbgModule;
  10818. dbgModule->ParseSymbolData();
  10819. }
  10820. }
  10821. else
  10822. {
  10823. nextSubProgram = dwSubprogram;
  10824. endAddr = dwSubprogram->mBlock.mHighPC;
  10825. }
  10826. auto _HandleSection = [&]()
  10827. {
  10828. while (addr < endAddr)
  10829. {
  10830. CPUInst inst;
  10831. if (!mDebugTarget->DecodeInstruction(addr, &inst))
  10832. break;
  10833. *registers.GetPCRegisterRef() = addr;
  10834. if (inst.IsCall())
  10835. {
  10836. bool addSymbol = true;
  10837. if (addr < (addr_target)inAddress)
  10838. callAddresses += "-";
  10839. callAddresses += EncodeDataPtr(addr, false);
  10840. addr_target targetAddr = inst.GetTarget(this, &registers);
  10841. if (targetAddr != 0)
  10842. {
  10843. String outSymbol;
  10844. auto subprogram = mDebugTarget->FindSubProgram(targetAddr);
  10845. if (subprogram != NULL)
  10846. {
  10847. CreateFilterName(outSymbol, subprogram);
  10848. addSymbol = true;
  10849. }
  10850. else
  10851. {
  10852. addr_target offset = 0;
  10853. String fullSymbolName;
  10854. if (mDebugTarget->FindSymbolAt(targetAddr, &outSymbol, &offset))
  10855. {
  10856. if (offset < 0x200)
  10857. {
  10858. //outSymbol = BfDemangler::Demangle(outSymbol, dwSubprogram->GetLanguage());
  10859. if (outSymbol == "___chkstk_ms")
  10860. addSymbol = false;
  10861. else
  10862. {
  10863. String demangledName = BfDemangler::Demangle(outSymbol, DbgLanguage_C);
  10864. outSymbol.clear();
  10865. CreateFilterName(outSymbol, demangledName.c_str(), DbgLanguage_C);
  10866. }
  10867. }
  10868. else
  10869. outSymbol.clear();
  10870. }
  10871. }
  10872. if (addSymbol)
  10873. {
  10874. if (outSymbol.empty())
  10875. callAddresses += "\tFunc@" + EncodeDataPtr(targetAddr, false);
  10876. else
  10877. callAddresses += "\t" + outSymbol;
  10878. String attrs;
  10879. bool isFiltered = false;
  10880. if (subprogram != NULL)
  10881. {
  10882. subprogram->PopulateSubprogram();
  10883. isFiltered = subprogram->mIsStepFilteredDefault;
  10884. if (isFiltered)
  10885. attrs += "d"; // 'd' for default filtered
  10886. }
  10887. StepFilter* stepFilterPtr = NULL;
  10888. if (mDebugManager->mStepFilters.TryGetValue(outSymbol, &stepFilterPtr))
  10889. isFiltered = stepFilterPtr->IsFiltered(isFiltered);
  10890. if (isFiltered)
  10891. attrs += "f"; // 'f' for filter
  10892. if (!attrs.IsEmpty())
  10893. callAddresses += "\t" + attrs;
  10894. }
  10895. }
  10896. if (addSymbol)
  10897. callAddresses += "\n";
  10898. }
  10899. inst.PartialSimulate(this, &registers);
  10900. addr += inst.GetLength();
  10901. }
  10902. };
  10903. // For inlining - only add calls that are found either directly in our main block (not an inlined block)
  10904. // But add inlined methods when their parent is our current block
  10905. if ((checkSubprogram == dwSubprogram) && (checkLineData->mLine == startLineData->mLine))
  10906. {
  10907. _HandleSection();
  10908. }
  10909. else if ((checkSubprogram->mInlineeInfo != NULL) && (checkSubprogram->mInlineeInfo->mInlineParent == dwSubprogram))
  10910. {
  10911. if (checkLineAddr == checkSubprogram->mBlock.mLowPC)
  10912. {
  10913. addr_target inlineStartAddr = checkSubprogram->mBlock.mLowPC;
  10914. // Find the calling line
  10915. DbgSubprogram* callingSubprogram = dwSubprogram;
  10916. auto checkLineData = dwSubprogram->FindClosestLine(inlineStartAddr, &callingSubprogram);
  10917. if ((checkLineData != NULL) && (checkLineData->mCtxIdx == startLineData->mCtxIdx) && (checkLineData->mLine == startLineData->mLine))
  10918. {
  10919. if (inlineStartAddr <= (addr_target)inAddress)
  10920. callAddresses += "-";
  10921. callAddresses += EncodeDataPtr(inlineStartAddr, false);
  10922. String outSymbol;
  10923. CreateFilterName(outSymbol, checkSubprogram);
  10924. callAddresses += "\t" + outSymbol;
  10925. bool isFiltered = dwSubprogram->mIsStepFilteredDefault;
  10926. StepFilter* stepFilterPtr;
  10927. if (mDebugManager->mStepFilters.TryGetValue(outSymbol, &stepFilterPtr))
  10928. isFiltered = stepFilterPtr->IsFiltered(isFiltered);
  10929. if (isFiltered)
  10930. callAddresses += "\tf"; // 'f' for filter
  10931. callAddresses += "\n";
  10932. }
  10933. // if (checkSubprogram->mBlock.mHighPC < endAddr)
  10934. // {
  10935. // addr = checkSubprogram->mBlock.mHighPC;
  10936. // _HandleSection();
  10937. // }
  10938. }
  10939. // If we have unattributed data after the end of an inlined method, add that
  10940. if ((endAddr > checkSubprogram->mBlock.mHighPC) && (nextSubProgram == dwSubprogram))
  10941. {
  10942. addr = checkSubprogram->mBlock.mHighPC;
  10943. _HandleSection();
  10944. }
  10945. }
  10946. checkLineData = nextLineData;
  10947. checkSubprogram = nextSubProgram;
  10948. checkLineAddr = nextLineAddr;
  10949. addr = endAddr;
  10950. }
  10951. return callAddresses;
  10952. }
  10953. String WinDebugger::GetCurrentException()
  10954. {
  10955. AutoCrit autoCrit(mDebugManager->mCritSect);
  10956. String result = StrFormat("%s\n%08X",
  10957. EncodeDataPtr((addr_target)(intptr)mCurException.ExceptionAddress, true).c_str(),
  10958. mCurException.ExceptionCode);
  10959. String exStr;
  10960. switch (mCurException.ExceptionCode)
  10961. {
  10962. case EXCEPTION_ACCESS_VIOLATION:
  10963. {
  10964. String accessType;
  10965. if (mCurException.ExceptionInformation[0] == 0)
  10966. accessType = "reading from";
  10967. else if (mCurException.ExceptionInformation[0] == 8)
  10968. accessType = "executing";
  10969. else
  10970. accessType = "writing to";
  10971. exStr = StrFormat("EXCEPTION_ACCESS_VIOLATION %s %s", accessType.c_str(), EncodeDataPtr((addr_target)mCurException.ExceptionInformation[1], true).c_str());
  10972. }
  10973. break;
  10974. case EXCEPTION_DATATYPE_MISALIGNMENT:
  10975. exStr = "EXCEPTION_DATATYPE_MISALIGNMENT";
  10976. case EXCEPTION_SINGLE_STEP:
  10977. exStr = "EXCEPTION_SINGLE_STEP";
  10978. break;
  10979. case EXCEPTION_BREAKPOINT:
  10980. exStr = "EXCEPTION_BREAKPOINT";
  10981. break;
  10982. case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
  10983. exStr = "EXCEPTION_ARRAY_BOUNDS_EXCEEDED";
  10984. break;
  10985. case EXCEPTION_FLT_DENORMAL_OPERAND:
  10986. exStr = "EXCEPTION_FLT_DENORMAL_OPERAND";
  10987. break;
  10988. case EXCEPTION_FLT_DIVIDE_BY_ZERO:
  10989. exStr = "EXCEPTION_FLT_DIVIDE_BY_ZERO";
  10990. break;
  10991. case EXCEPTION_FLT_INEXACT_RESULT:
  10992. exStr = "EXCEPTION_FLT_INEXACT_RESULT";
  10993. break;
  10994. case EXCEPTION_FLT_INVALID_OPERATION:
  10995. exStr = "EXCEPTION_FLT_INVALID_OPERATIO";
  10996. break;
  10997. case EXCEPTION_FLT_OVERFLOW:
  10998. exStr = "EXCEPTION_FLT_OVERFLOW";
  10999. break;
  11000. case EXCEPTION_FLT_STACK_CHECK:
  11001. exStr = "EXCEPTION_FLT_STACK_CHECK";
  11002. break;
  11003. case EXCEPTION_FLT_UNDERFLOW:
  11004. exStr = "EXCEPTION_FLT_UNDERFLOW";
  11005. break;
  11006. case EXCEPTION_INT_DIVIDE_BY_ZERO:
  11007. exStr = "EXCEPTION_INT_DIVIDE_BY_ZERO";
  11008. break;
  11009. case EXCEPTION_INT_OVERFLOW:
  11010. exStr = "EXCEPTION_INT_OVERFLOW";
  11011. break;
  11012. case EXCEPTION_PRIV_INSTRUCTION:
  11013. exStr = "EXCEPTION_PRIV_INSTRUCTION";
  11014. break;
  11015. case EXCEPTION_IN_PAGE_ERROR:
  11016. exStr = "EXCEPTION_IN_PAGE_ERROR";
  11017. break;
  11018. case EXCEPTION_ILLEGAL_INSTRUCTION:
  11019. exStr = "EXCEPTION_ILLEGAL_INSTRUCTION";
  11020. break;
  11021. case EXCEPTION_NONCONTINUABLE_EXCEPTION:
  11022. exStr = "EXCEPTION_NONCONTINUABLE_EXCEPTION";
  11023. break;
  11024. case EXCEPTION_STACK_OVERFLOW:
  11025. exStr = "EXCEPTION_STACK_OVERFLOW";
  11026. break;
  11027. case EXCEPTION_INVALID_DISPOSITION:
  11028. exStr = "EXCEPTION_INVALID_DISPOSITION";
  11029. break;
  11030. case EXCEPTION_GUARD_PAGE:
  11031. exStr = "EXCEPTION_GUARD_PAGE";
  11032. break;
  11033. case EXCEPTION_INVALID_HANDLE:
  11034. exStr = "EXCEPTION_INVALID_HANDLE";
  11035. break;
  11036. case CONTROL_C_EXIT:
  11037. exStr = "CONTROL_C_EXIT";
  11038. break;
  11039. default:
  11040. exStr += StrFormat("EXCEPTION %08X", mCurException.ExceptionCode);
  11041. }
  11042. if (mActiveThread != NULL)
  11043. exStr += StrFormat(" in thread %d", mActiveThread->mThreadId);
  11044. if (!exStr.empty())
  11045. result += "\n" + exStr;
  11046. // After we retrieve the exception then we can go back to just being normal 'paused'
  11047. // This allows us to evaluate stuff, Set Next Statement, etc.
  11048. mRunState = RunState_Paused;
  11049. return result.c_str();
  11050. }
  11051. void WinDebugger::SetAliasPath(const StringImpl& origPath, const StringImpl& localPath)
  11052. {
  11053. AutoCrit autoCrit(mDebugManager->mCritSect);
  11054. String fixedOrigPath = FixPathAndCase(origPath);
  11055. String fixedLocalPath = FixPathAndCase(localPath);
  11056. auto origFile = mDebugTarget->AddSrcFile(origPath);
  11057. origFile->mLocalPath = FixPath(localPath);
  11058. mDebugTarget->mLocalToOrigSrcMap[fixedLocalPath] = fixedOrigPath;
  11059. // We invalidate the step filters, because previously-failing 'CheckSourceFileExist' checks may now succeed
  11060. mDebugManager->mStepFilterVersion++;
  11061. }
  11062. String WinDebugger::GetModulesInfo()
  11063. {
  11064. AutoCrit autoCrit(mDebugManager->mCritSect);
  11065. String str;
  11066. for (auto module : mDebugTarget->mDbgModules)
  11067. {
  11068. COFF* coff = (COFF*)module;
  11069. if (module->mHotIdx > 0)
  11070. continue;
  11071. str += module->mDisplayName;
  11072. str += "\t";
  11073. if (module->mLoadState == DbgModuleLoadState_Loaded)
  11074. {
  11075. str += module->mFilePath;
  11076. }
  11077. else if (module->mLoadState == DbgModuleLoadState_NotLoaded)
  11078. {
  11079. str += module->mFilePath;
  11080. str += " (Loading...)";
  11081. }
  11082. else if (module->mLoadState == DbgModuleLoadState_Failed)
  11083. {
  11084. str += "!";
  11085. str += module->mFilePath;
  11086. }
  11087. if (module->mMappedImageFile != NULL)
  11088. {
  11089. str += " (";
  11090. str += module->mMappedImageFile->mFileName;
  11091. str += ")";
  11092. }
  11093. str += "\t";
  11094. str += coff->mPDBPath;
  11095. str += "\t";
  11096. str += module->mVersion;
  11097. str += StrFormat("\t%@-%@\t%dk\t", module->mImageBase, module->mImageBase + module->mImageSize, module->mImageSize / 1024);
  11098. time_t timestamp = coff->mTimeStamp;
  11099. if (timestamp == 0)
  11100. timestamp = GetFileTimeWrite(coff->mFilePath);
  11101. if (timestamp != 0)
  11102. {
  11103. char timeString[256];
  11104. auto time_info = localtime(&timestamp);
  11105. strftime(timeString, sizeof(timeString), "%D %T", time_info);
  11106. str += timeString;
  11107. }
  11108. str += "\n";
  11109. }
  11110. return str;
  11111. }
  11112. void WinDebugger::CancelSymSrv()
  11113. {
  11114. AutoCrit autoCrit(mDebugManager->mCritSect);
  11115. if (mActiveSymSrvRequest != NULL)
  11116. mActiveSymSrvRequest->Cancel();
  11117. }
  11118. bool WinDebugger::HasPendingDebugLoads()
  11119. {
  11120. AutoCrit autoCrit(mDebugManager->mCritSect);
  11121. return (!mPendingImageLoad.IsEmpty()) || (!mPendingDebugInfoLoad.IsEmpty());
  11122. }
  11123. int WinDebugger::LoadImageForModule(const StringImpl &modulePath, const StringImpl& imagePath)
  11124. {
  11125. AutoCrit autoCrit(mDebugManager->mCritSect);
  11126. for (auto dbgModule : mDebugTarget->mDbgModules)
  11127. {
  11128. if (modulePath.Equals(dbgModule->mFilePath, StringImpl::CompareKind_OrdinalIgnoreCase))
  11129. {
  11130. auto coff = (COFF*)dbgModule;
  11131. if (!coff->LoadModuleImage(imagePath))
  11132. {
  11133. mDebugManager->mOutMessages.push_back("error Failed to load image " + imagePath);
  11134. }
  11135. ModuleChanged(dbgModule);
  11136. return 0;
  11137. }
  11138. }
  11139. return 0;
  11140. }
  11141. int WinDebugger::LoadDebugInfoForModule(DbgModule* dbgModule)
  11142. {
  11143. if (!dbgModule->HasPendingDebugInfo())
  11144. return 0;
  11145. if (dbgModule->RequestDebugInfo())
  11146. {
  11147. ClearCallStack(); // Make this re-resolve with debug info
  11148. return 1;
  11149. }
  11150. DbgPendingDebugInfoLoad* dbgPendingDebugInfoLoad = NULL;
  11151. if (mPendingDebugInfoLoad.TryAdd(dbgModule, NULL, &dbgPendingDebugInfoLoad))
  11152. {
  11153. dbgPendingDebugInfoLoad->mModule = dbgModule;
  11154. dbgPendingDebugInfoLoad->mAllowRemote = true;
  11155. return 2;
  11156. }
  11157. dbgPendingDebugInfoLoad->mAllowRemote = true;
  11158. return 0;
  11159. }
  11160. int WinDebugger::LoadDebugInfoForModule(const StringImpl& moduleName)
  11161. {
  11162. AutoCrit autoCrit(mDebugManager->mCritSect);
  11163. for (auto dbgModule : mDebugTarget->mDbgModules)
  11164. {
  11165. String checkModuleName = GetFileName(dbgModule->mFilePath);
  11166. if (moduleName.Equals(checkModuleName, StringImpl::CompareKind_OrdinalIgnoreCase))
  11167. {
  11168. return LoadDebugInfoForModule(dbgModule);
  11169. }
  11170. }
  11171. return 0;
  11172. }
  11173. int WinDebugger::LoadDebugInfoForModule(const StringImpl& modulePath, const StringImpl& debugFileName)
  11174. {
  11175. AutoCrit autoCrit(mDebugManager->mCritSect);
  11176. for (auto dbgModule : mDebugTarget->mDbgModules)
  11177. {
  11178. if (modulePath.Equals(dbgModule->mFilePath, StringImpl::CompareKind_OrdinalIgnoreCase))
  11179. {
  11180. auto coff = (COFF*)dbgModule;
  11181. String err;
  11182. if (!coff->mPDBLoaded)
  11183. {
  11184. dbgModule->mFailMsgPtr = &err;
  11185. if (coff->TryLoadPDB(debugFileName, coff->mWantPDBGuid, coff->mWantAge))
  11186. {
  11187. ModuleChanged(dbgModule);
  11188. }
  11189. dbgModule->mFailMsgPtr = NULL;
  11190. }
  11191. else
  11192. {
  11193. err = StrFormat("Module '%s' already has debug information loaded", GetFileName(modulePath).c_str());
  11194. }
  11195. if (!err.IsEmpty())
  11196. {
  11197. mDebugManager->mOutMessages.push_back("error " + err);
  11198. }
  11199. return 0;
  11200. }
  11201. }
  11202. return 0;
  11203. }
  11204. void WinDebugger::FixupLineData(DbgCompileUnit* compileUnit)
  11205. {
  11206. if (!compileUnit || !compileUnit->mNeedsLineDataFixup)
  11207. return;
  11208. compileUnit->mNeedsLineDataFixup = false;
  11209. }
  11210. static int CompareLineData(const void* lineDataP1, const void* lineDataP2)
  11211. {
  11212. int cmpResult = (int)(((DbgLineData*)lineDataP1)->mRelAddress - ((DbgLineData*)lineDataP2)->mRelAddress);
  11213. if (cmpResult != 0)
  11214. return cmpResult;
  11215. // A larger contrib size means it's the 'outer' inlinee
  11216. cmpResult = -(((DbgLineData*)lineDataP1)->mContribSize - ((DbgLineData*)lineDataP2)->mContribSize);
  11217. if (cmpResult != 0)
  11218. return cmpResult;
  11219. return -(((DbgLineData*)lineDataP1)->mCtxIdx - ((DbgLineData*)lineDataP2)->mCtxIdx);
  11220. }
  11221. void WinDebugger::FixupLineDataForSubprogram(DbgSubprogram* subProgram)
  11222. {
  11223. if ((subProgram == NULL) || (!subProgram->mNeedLineDataFixup))
  11224. return;
  11225. BP_ZONE("FixupLineDataForSubprogram");
  11226. subProgram->mNeedLineDataFixup = false;
  11227. if (subProgram->mInlineeInfo != NULL)
  11228. FixupLineDataForSubprogram(subProgram->mInlineeInfo->mRootInliner);
  11229. if ((subProgram->mLineInfo == NULL) || (subProgram->mLineInfo->mLines.mSize == 0))
  11230. return;
  11231. //TODO: I think this was covering up a bug in DWARF line encoding? Figure this out
  11232. // if (subProgram->mLineInfo->mLines.mSize >= 2)
  11233. // {
  11234. // DbgLineData* line0 = &subProgram->mLineInfo->mLines[0];
  11235. // DbgLineData* line1 = &subProgram->mLineInfo->mLines[1];
  11236. //
  11237. //
  11238. // if ((line0->mRelAddress == line1->mRelAddress) && (!line0->IsStackFrameSetup()) && (line1->IsStackFrameSetup()))
  11239. // {
  11240. // CPUInst inst;
  11241. // if (mCPU->Decode(line0->mAddress, subProgram->mCompileUnit->mDbgModule->mOrigImageData, &inst))
  11242. // line1->mAddress += inst.GetLength();
  11243. // }
  11244. // }
  11245. qsort(subProgram->mLineInfo->mLines.mVals, subProgram->mLineInfo->mLines.mSize, sizeof(DbgLineData), CompareLineData);
  11246. // If we have multiple lines with the same line/column/context, merge them
  11247. if (!subProgram->mLineInfo->mLines.IsEmpty())
  11248. {
  11249. auto prevLine = &subProgram->mLineInfo->mLines[0];
  11250. for (int i = 1; i < subProgram->mLineInfo->mLines.mSize; i++)
  11251. {
  11252. auto nextLine = &subProgram->mLineInfo->mLines[i];
  11253. if ((nextLine->mLine == prevLine->mLine) && (nextLine->mColumn == prevLine->mColumn) && (nextLine->mCtxIdx == prevLine->mCtxIdx) &&
  11254. (nextLine->mRelAddress == prevLine->mRelAddress + prevLine->mContribSize))
  11255. {
  11256. prevLine->mContribSize += nextLine->mContribSize;
  11257. // This messed up inline cases because mContribSize actually INCLUDES inlined lines so it caused the address to skip too far
  11258. //nextLine->mRelAddress += nextLine->mContribSize;
  11259. //nextLine->mContribSize = 0;
  11260. }
  11261. else
  11262. {
  11263. prevLine = nextLine;
  11264. }
  11265. }
  11266. }
  11267. }
  11268. void WinDebugger::ReserveHotTargetMemory(int size)
  11269. {
  11270. HotTargetMemory hotTargetMemory;
  11271. hotTargetMemory.mOffset = 0;
  11272. hotTargetMemory.mSize = 0;
  11273. hotTargetMemory.mPtr = NULL;
  11274. if (size > 0)
  11275. {
  11276. // In 64-bit mode we have a reserved region on program load that we commit here because the offsets
  11277. // must be within 32-bits of the original EXE image, but in 32-bit mode we don't reserve anything
  11278. // until here
  11279. #ifdef BF_DBG_32
  11280. //hotTargetMemory.mSize = std::max(1024 * 1024, size);
  11281. BF_ASSERT((size & (mPageSize - 1)) == 0);
  11282. hotTargetMemory.mSize = size;
  11283. hotTargetMemory.mPtr = (addr_target)(intptr)VirtualAllocEx(mProcessInfo.hProcess, NULL, hotTargetMemory.mSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
  11284. mDebugTarget->mHotHeap->AddTrackedRegion(hotTargetMemory.mPtr, hotTargetMemory.mSize);
  11285. #else
  11286. hotTargetMemory.mSize = size;
  11287. hotTargetMemory.mPtr = mDebugTarget->mHotHeap->Alloc(size);
  11288. BF_ASSERT(hotTargetMemory.mPtr != 0);
  11289. auto ptr = ::VirtualAllocEx(mProcessInfo.hProcess, (void*)(intptr)hotTargetMemory.mPtr, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  11290. BF_ASSERT(ptr == (void*)(intptr)hotTargetMemory.mPtr);
  11291. #endif
  11292. }
  11293. BfLogDbg("ReserveHotTargetMemory %p %d", hotTargetMemory.mPtr, hotTargetMemory.mSize);
  11294. int err = GetLastError();
  11295. mHotTargetMemory.push_back(hotTargetMemory);
  11296. }
  11297. addr_target WinDebugger::AllocHotTargetMemory(int size, bool canExecute, bool canWrite, int* outAllocSize)
  11298. {
  11299. int prot = PAGE_READWRITE;
  11300. if (canExecute && canWrite)
  11301. prot = PAGE_EXECUTE_READWRITE;
  11302. else if (canExecute)
  11303. prot = PAGE_EXECUTE_READ;
  11304. auto hotTargetMemory = (HotTargetMemory*)&mHotTargetMemory.back();
  11305. if (hotTargetMemory->mPtr == 0)
  11306. {
  11307. Fail("Failed to allocate memory for hot loading");
  11308. return 0;
  11309. }
  11310. size = (size + (mPageSize - 1)) & ~(mPageSize - 1);
  11311. *outAllocSize = size;
  11312. BF_ASSERT(hotTargetMemory->mOffset + size <= hotTargetMemory->mSize);
  11313. addr_target result = hotTargetMemory->mPtr + hotTargetMemory->mOffset;
  11314. ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)result, size, prot, NULL);
  11315. BfLogDbg("AllocHotTargetMemory: %p %d %d %d\n", result, size, canExecute, canWrite);
  11316. hotTargetMemory->mOffset += size;
  11317. return result;
  11318. }
  11319. void WinDebugger::ReleaseHotTargetMemory(addr_target addr, int size)
  11320. {
  11321. #ifdef BF_DBG_32
  11322. ::VirtualFreeEx(mProcessInfo.hProcess, (void*)(intptr)addr, 0, MEM_RELEASE);
  11323. #else
  11324. mDebugTarget->mHotHeap->Release(addr, size);
  11325. ::VirtualFreeEx(mProcessInfo.hProcess, (void*)(intptr)addr, size, MEM_DECOMMIT);
  11326. #endif
  11327. }
  11328. void WinDebugger::CleanupHotHeap()
  11329. {
  11330. mDebugTarget->mLastHotHeapCleanIdx = mDebugTarget->mHotHeap->mBlockAllocIdx;
  11331. // Our criteria for determining whether a hot loaded file is still being used:
  11332. // 1) If we are currently executing a method from that object file.
  11333. // 2) If the symbol map has a symbol with that address.
  11334. // 3) If the static variable map contains a reference - including a conservative scan of the data
  11335. // This handles vdata references
  11336. // This is a conservative check which won't purge hot reloads that contain deleted
  11337. // methods (for example), but it will purge hot reloads where all the changed
  11338. // data has been overwritten.
  11339. // For delegate bindings, the original module declaring the bind creates a "preserve"
  11340. // global such as "bf_hs_preserve@_ZN5TestO4TestEv", whose preserved symbol ensures it
  11341. // doesn't get unloaded. The current version of that method resides in "_ZN5TestO4TestEv",
  11342. // ensuring that the method pointed to by the global variable is valid
  11343. mDebugTarget->mHotHeap->ClearReferencedFlags();
  11344. addr_target lowAddr = mDebugTarget->mHotHeap->mHotAreaStart;
  11345. addr_target highAddr = lowAddr + mDebugTarget->mHotHeap->mHotAreaSize;
  11346. // Do conservative scan through all thread stacks. Stack traces aren't 100% reliable, so we
  11347. // need to do a full conservative scan of any addresses stored in the stack
  11348. // to ensure we don't miss any return addresses
  11349. for (int threadIdx = 0; threadIdx < (int)mThreadList.size(); threadIdx++)
  11350. {
  11351. WdThreadInfo* threadInfo = mThreadList[threadIdx];
  11352. BF_CONTEXT lcContext;
  11353. lcContext.ContextFlags = BF_CONTEXT_CONTROL;
  11354. BF_GetThreadContext(threadInfo->mHThread, &lcContext);
  11355. addr_target checkStackAddr = BF_CONTEXT_SP(lcContext);
  11356. checkStackAddr &= ~(sizeof(addr_target) - 1);
  11357. // Conservative check on registers
  11358. for (int regNum = 0; regNum < sizeof(BF_CONTEXT)/sizeof(addr_target); regNum++)
  11359. {
  11360. addr_target checkAddr = ((addr_target*)&lcContext)[regNum];
  11361. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  11362. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  11363. }
  11364. // Conservative check on all stack data
  11365. while (checkStackAddr < threadInfo->mStartSP)
  11366. {
  11367. addr_target checkAddrArr[1024];
  11368. int numAddrsChecking = BF_MIN(1024, (int)((threadInfo->mStartSP - checkStackAddr) / sizeof(addr_target)));
  11369. ReadMemory(checkStackAddr, numAddrsChecking * sizeof(addr_target), checkAddrArr);
  11370. checkStackAddr += numAddrsChecking * sizeof(addr_target);
  11371. for (int addrIdx = 0; addrIdx < numAddrsChecking; addrIdx++)
  11372. {
  11373. addr_target checkAddr = checkAddrArr[addrIdx];
  11374. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  11375. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  11376. }
  11377. }
  11378. }
  11379. auto mainModule = mDebugTarget->mTargetBinary;
  11380. for (auto entry : mainModule->mSymbolNameMap)
  11381. {
  11382. auto dwSymbol = entry->mValue;
  11383. addr_target checkAddr = dwSymbol->mAddress;
  11384. if ((checkAddr >= lowAddr) && (checkAddr < highAddr))
  11385. mDebugTarget->mHotHeap->MarkBlockReferenced(checkAddr);
  11386. }
  11387. mDebugTarget->CleanupHotHeap();
  11388. BfLogDbg("Hot load memory used: %dk\n", (int)mDebugTarget->mHotHeap->GetUsedSize() / 1024);
  11389. }
  11390. int WinDebugger::EnableWriting(intptr address, int size)
  11391. {
  11392. DWORD oldProt;
  11393. bool success = ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)address, size, PAGE_READWRITE, &oldProt);
  11394. if (!success)
  11395. {
  11396. int err = GetLastError();
  11397. }
  11398. return (int)oldProt;
  11399. }
  11400. int WinDebugger::SetProtection(intptr address, int size, int prot)
  11401. {
  11402. DWORD oldProt;
  11403. ::VirtualProtectEx(mProcessInfo.hProcess, (void*)(intptr)address, size, prot, &oldProt);
  11404. return (int)oldProt;
  11405. }
  11406. void WinDebugger::EnableMemCache()
  11407. {
  11408. mMemCacheAddr = 1;
  11409. }
  11410. void WinDebugger::DisableMemCache()
  11411. {
  11412. mMemCacheAddr = 0;
  11413. }
  11414. bool WinDebugger::ReadMemory(intptr address, uint64 length, void* dest, bool local)
  11415. {
  11416. if (local)
  11417. {
  11418. __try
  11419. {
  11420. memcpy(dest, (void*)address, length);
  11421. return true;
  11422. }
  11423. __except(EXCEPTION_EXECUTE_HANDLER)
  11424. {
  11425. return false;
  11426. }
  11427. }
  11428. if (mMemCacheAddr != 0)
  11429. {
  11430. addr_target targetAddr = (addr_target)address;
  11431. if ((targetAddr >= mMemCacheAddr) && (targetAddr + length <= mMemCacheAddr + WD_MEMCACHE_SIZE) && (mMemCacheAddr > 1))
  11432. {
  11433. memcpy(dest, mMemCacheData + (targetAddr - mMemCacheAddr), length);
  11434. return true;
  11435. }
  11436. // We need a new block
  11437. SIZE_T dwReadBytes;
  11438. if (::ReadProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, mMemCacheData, (SIZE_T)WD_MEMCACHE_SIZE, &dwReadBytes) != 0)
  11439. {
  11440. mMemCacheAddr = targetAddr;
  11441. memcpy(dest, mMemCacheData, length);
  11442. return true;
  11443. }
  11444. // Failed, turn off caching
  11445. mMemCacheAddr = 0;
  11446. }
  11447. SIZE_T dwReadBytes;
  11448. if (::ReadProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, dest, (SIZE_T)length, &dwReadBytes) != 0)
  11449. return true;
  11450. int lastErr = ::GetLastError();
  11451. memset(dest, 0, length);
  11452. return false;
  11453. }
  11454. bool WinDebugger::WriteMemory(intptr address, void* src, uint64 length)
  11455. {
  11456. SIZE_T dwBytesWritten = 0;
  11457. int result = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, src, (SIZE_T)length, &dwBytesWritten);
  11458. return result != 0;
  11459. }
  11460. addr_target WinDebugger::GetTLSOffset(int tlsIndex)
  11461. {
  11462. typedef LONG NTSTATUS;
  11463. typedef DWORD KPRIORITY;
  11464. typedef WORD UWORD;
  11465. enum THREADINFOCLASS
  11466. {
  11467. ThreadBasicInformation,
  11468. };
  11469. struct CLIENT_ID
  11470. {
  11471. HANDLE UniqueProcess;
  11472. HANDLE UniqueThread;
  11473. };
  11474. struct
  11475. {
  11476. NTSTATUS mExitStatus;
  11477. void* mTebBaseAddress;
  11478. CLIENT_ID mClientId;
  11479. KAFFINITY mAffinityMask;
  11480. KPRIORITY mPriority;
  11481. KPRIORITY mBasePriority;
  11482. } threadInfo = { 0 };
  11483. ULONG len = 0;
  11484. bool loadedManually = false;
  11485. static HMODULE module = NULL;
  11486. static NTSTATUS(__stdcall *NtQueryInformationThread)(HANDLE ThreadHandle, THREADINFOCLASS ThreadInformationClass, PVOID ThreadInformation, ULONG ThreadInformationLength, PULONG ReturnLength);
  11487. if (module == NULL)
  11488. {
  11489. module = GetModuleHandleA("ntdll.dll");
  11490. NtQueryInformationThread = reinterpret_cast<decltype(NtQueryInformationThread)>(GetProcAddress(module, "NtQueryInformationThread"));
  11491. }
  11492. if (NtQueryInformationThread == NULL)
  11493. return 0;
  11494. NTSTATUS status = NtQueryInformationThread(mActiveThread->mHThread, (THREADINFOCLASS)0, &threadInfo, sizeof(threadInfo), nullptr);
  11495. if (status < 0)
  11496. return 0;
  11497. #ifdef BF_DBG_32
  11498. addr_target tibAddr = ReadMemory<addr_target>((intptr)threadInfo.mTebBaseAddress + 0x0);
  11499. addr_target tlsTable = ReadMemory<addr_target>((intptr)tibAddr + 0x2C);
  11500. #else
  11501. addr_target tlsTable = ReadMemory<addr_target>((intptr)threadInfo.mTebBaseAddress + 0x58);
  11502. #endif
  11503. return ReadMemory<addr_target>(tlsTable + tlsIndex * sizeof(addr_target));
  11504. }
  11505. bool WinDebugger::WriteInstructions(intptr address, void* src, uint64 length)
  11506. {
  11507. SIZE_T dwBytesWritten = 0;
  11508. bool result = ::WriteProcessMemory(mProcessInfo.hProcess, (void*)(intptr)address, src, (SIZE_T)length, &dwBytesWritten) != 0;
  11509. result |= ::FlushInstructionCache(mProcessInfo.hProcess, (void*)(intptr)address, (SIZE_T)length) != 0;
  11510. BF_ASSERT(result);
  11511. BfLogDbg("WriteInstructions: %p %d\n", address, length);
  11512. return result;
  11513. }
  11514. DbgMemoryFlags WinDebugger::GetMemoryFlags(intptr address)
  11515. {
  11516. MEMORY_BASIC_INFORMATION memBasicInfo;
  11517. if (::VirtualQueryEx(mProcessInfo.hProcess, (void*)address, &memBasicInfo, sizeof(MEMORY_BASIC_INFORMATION)) == 0)
  11518. {
  11519. //BfLogDbg("VirtualQueryEx failed with %d\n", GetLastError());
  11520. return DbgMemoryFlags_None;
  11521. }
  11522. DbgMemoryFlags flags = DbgMemoryFlags_None;
  11523. if (memBasicInfo.AllocationProtect & PAGE_READWRITE)
  11524. {
  11525. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11526. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11527. }
  11528. if (memBasicInfo.AllocationProtect & PAGE_READONLY)
  11529. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11530. if (memBasicInfo.AllocationProtect & PAGE_WRITECOPY)
  11531. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11532. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE)
  11533. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11534. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_READ)
  11535. {
  11536. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11537. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11538. }
  11539. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_READWRITE)
  11540. {
  11541. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11542. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Read);
  11543. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11544. }
  11545. if (memBasicInfo.AllocationProtect & PAGE_EXECUTE_WRITECOPY)
  11546. {
  11547. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Execute);
  11548. flags = (DbgMemoryFlags)(flags | DbgMemoryFlags_Write);
  11549. }
  11550. return flags;
  11551. }
  11552. #ifdef BF_DBG_32
  11553. Debugger* Beefy::CreateDebugger32(DebugManager* debugManager, DbgMiniDump* miniDump)
  11554. #else
  11555. Debugger* Beefy::CreateDebugger64(DebugManager* debugManager, DbgMiniDump* miniDump)
  11556. #endif
  11557. {
  11558. if (miniDump != NULL)
  11559. {
  11560. auto debugger = new MiniDumpDebugger(debugManager, miniDump);
  11561. return debugger;
  11562. }
  11563. return new WinDebugger(debugManager);
  11564. }
  11565. #ifdef BF_DBG_32
  11566. void WdAllocTest()
  11567. {
  11568. Array<BeefyDbg32::WdStackFrame*> stackFrameList;
  11569. for (int i = 0; true; i++)
  11570. {
  11571. WdStackFrame* stackFrame = new WdStackFrame();
  11572. stackFrameList.push_back(stackFrame);
  11573. }
  11574. }
  11575. #endif
  11576. #endif //!defined BF32 || !defined BF_DBG_64