MachODump.cpp 393 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828
  1. //===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the MachO-specific dumper for llvm-objdump.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "MachODump.h"
  13. #include "ObjdumpOptID.h"
  14. #include "llvm-objdump.h"
  15. #include "llvm-c/Disassembler.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/StringExtras.h"
  18. #include "llvm/ADT/Triple.h"
  19. #include "llvm/BinaryFormat/MachO.h"
  20. #include "llvm/Config/config.h"
  21. #include "llvm/DebugInfo/DIContext.h"
  22. #include "llvm/DebugInfo/DWARF/DWARFContext.h"
  23. #include "llvm/Demangle/Demangle.h"
  24. #include "llvm/MC/MCAsmInfo.h"
  25. #include "llvm/MC/MCContext.h"
  26. #include "llvm/MC/MCDisassembler/MCDisassembler.h"
  27. #include "llvm/MC/MCInst.h"
  28. #include "llvm/MC/MCInstPrinter.h"
  29. #include "llvm/MC/MCInstrDesc.h"
  30. #include "llvm/MC/MCInstrInfo.h"
  31. #include "llvm/MC/MCRegisterInfo.h"
  32. #include "llvm/MC/MCSubtargetInfo.h"
  33. #include "llvm/MC/MCTargetOptions.h"
  34. #include "llvm/MC/TargetRegistry.h"
  35. #include "llvm/Object/MachO.h"
  36. #include "llvm/Object/MachOUniversal.h"
  37. #include "llvm/Option/ArgList.h"
  38. #include "llvm/Support/Casting.h"
  39. #include "llvm/Support/Debug.h"
  40. #include "llvm/Support/Endian.h"
  41. #include "llvm/Support/Format.h"
  42. #include "llvm/Support/FormattedStream.h"
  43. #include "llvm/Support/GraphWriter.h"
  44. #include "llvm/Support/LEB128.h"
  45. #include "llvm/Support/MemoryBuffer.h"
  46. #include "llvm/Support/TargetSelect.h"
  47. #include "llvm/Support/ToolOutputFile.h"
  48. #include "llvm/Support/WithColor.h"
  49. #include "llvm/Support/raw_ostream.h"
  50. #include <algorithm>
  51. #include <cstring>
  52. #include <system_error>
  53. #ifdef LLVM_HAVE_LIBXAR
  54. extern "C" {
  55. #error #include <xar/xar.h>
  56. }
  57. #endif
  58. using namespace llvm;
  59. using namespace llvm::object;
  60. using namespace llvm::objdump;
  61. bool objdump::FirstPrivateHeader;
  62. bool objdump::ExportsTrie;
  63. bool objdump::Rebase;
  64. bool objdump::Rpaths;
  65. bool objdump::Bind;
  66. bool objdump::LazyBind;
  67. bool objdump::WeakBind;
  68. static bool UseDbg;
  69. static std::string DSYMFile;
  70. bool objdump::FullLeadingAddr;
  71. bool objdump::LeadingHeaders;
  72. bool objdump::UniversalHeaders;
  73. static bool ArchiveMemberOffsets;
  74. bool objdump::IndirectSymbols;
  75. bool objdump::DataInCode;
  76. FunctionStartsMode objdump::FunctionStartsType =
  77. objdump::FunctionStartsMode::None;
  78. bool objdump::LinkOptHints;
  79. bool objdump::InfoPlist;
  80. bool objdump::ChainedFixups;
  81. bool objdump::DyldInfo;
  82. bool objdump::DylibsUsed;
  83. bool objdump::DylibId;
  84. bool objdump::Verbose;
  85. bool objdump::ObjcMetaData;
  86. std::string objdump::DisSymName;
  87. bool objdump::SymbolicOperands;
  88. static std::vector<std::string> ArchFlags;
  89. static bool ArchAll = false;
  90. static std::string ThumbTripleName;
  91. static StringRef ordinalName(const object::MachOObjectFile *, int);
  92. void objdump::parseMachOOptions(const llvm::opt::InputArgList &InputArgs) {
  93. FirstPrivateHeader = InputArgs.hasArg(OBJDUMP_private_header);
  94. ExportsTrie = InputArgs.hasArg(OBJDUMP_exports_trie);
  95. Rebase = InputArgs.hasArg(OBJDUMP_rebase);
  96. Rpaths = InputArgs.hasArg(OBJDUMP_rpaths);
  97. Bind = InputArgs.hasArg(OBJDUMP_bind);
  98. LazyBind = InputArgs.hasArg(OBJDUMP_lazy_bind);
  99. WeakBind = InputArgs.hasArg(OBJDUMP_weak_bind);
  100. UseDbg = InputArgs.hasArg(OBJDUMP_g);
  101. DSYMFile = InputArgs.getLastArgValue(OBJDUMP_dsym_EQ).str();
  102. FullLeadingAddr = InputArgs.hasArg(OBJDUMP_full_leading_addr);
  103. LeadingHeaders = !InputArgs.hasArg(OBJDUMP_no_leading_headers);
  104. UniversalHeaders = InputArgs.hasArg(OBJDUMP_universal_headers);
  105. ArchiveMemberOffsets = InputArgs.hasArg(OBJDUMP_archive_member_offsets);
  106. IndirectSymbols = InputArgs.hasArg(OBJDUMP_indirect_symbols);
  107. DataInCode = InputArgs.hasArg(OBJDUMP_data_in_code);
  108. if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_function_starts_EQ)) {
  109. FunctionStartsType = StringSwitch<FunctionStartsMode>(A->getValue())
  110. .Case("addrs", FunctionStartsMode::Addrs)
  111. .Case("names", FunctionStartsMode::Names)
  112. .Case("both", FunctionStartsMode::Both)
  113. .Default(FunctionStartsMode::None);
  114. if (FunctionStartsType == FunctionStartsMode::None)
  115. invalidArgValue(A);
  116. }
  117. LinkOptHints = InputArgs.hasArg(OBJDUMP_link_opt_hints);
  118. InfoPlist = InputArgs.hasArg(OBJDUMP_info_plist);
  119. ChainedFixups = InputArgs.hasArg(OBJDUMP_chained_fixups);
  120. DyldInfo = InputArgs.hasArg(OBJDUMP_dyld_info);
  121. DylibsUsed = InputArgs.hasArg(OBJDUMP_dylibs_used);
  122. DylibId = InputArgs.hasArg(OBJDUMP_dylib_id);
  123. Verbose = !InputArgs.hasArg(OBJDUMP_non_verbose);
  124. ObjcMetaData = InputArgs.hasArg(OBJDUMP_objc_meta_data);
  125. DisSymName = InputArgs.getLastArgValue(OBJDUMP_dis_symname).str();
  126. SymbolicOperands = !InputArgs.hasArg(OBJDUMP_no_symbolic_operands);
  127. ArchFlags = InputArgs.getAllArgValues(OBJDUMP_arch_EQ);
  128. }
  129. static const Target *GetTarget(const MachOObjectFile *MachOObj,
  130. const char **McpuDefault,
  131. const Target **ThumbTarget) {
  132. // Figure out the target triple.
  133. Triple TT(TripleName);
  134. if (TripleName.empty()) {
  135. TT = MachOObj->getArchTriple(McpuDefault);
  136. TripleName = TT.str();
  137. }
  138. if (TT.getArch() == Triple::arm) {
  139. // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
  140. // that support ARM are also capable of Thumb mode.
  141. Triple ThumbTriple = TT;
  142. std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
  143. ThumbTriple.setArchName(ThumbName);
  144. ThumbTripleName = ThumbTriple.str();
  145. }
  146. // Get the target specific parser.
  147. std::string Error;
  148. const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
  149. if (TheTarget && ThumbTripleName.empty())
  150. return TheTarget;
  151. *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
  152. if (*ThumbTarget)
  153. return TheTarget;
  154. WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
  155. if (!TheTarget)
  156. errs() << TripleName;
  157. else
  158. errs() << ThumbTripleName;
  159. errs() << "', see --version and --triple.\n";
  160. return nullptr;
  161. }
  162. namespace {
  163. struct SymbolSorter {
  164. bool operator()(const SymbolRef &A, const SymbolRef &B) {
  165. Expected<SymbolRef::Type> ATypeOrErr = A.getType();
  166. if (!ATypeOrErr)
  167. reportError(ATypeOrErr.takeError(), A.getObject()->getFileName());
  168. SymbolRef::Type AType = *ATypeOrErr;
  169. Expected<SymbolRef::Type> BTypeOrErr = B.getType();
  170. if (!BTypeOrErr)
  171. reportError(BTypeOrErr.takeError(), B.getObject()->getFileName());
  172. SymbolRef::Type BType = *BTypeOrErr;
  173. uint64_t AAddr =
  174. (AType != SymbolRef::ST_Function) ? 0 : cantFail(A.getValue());
  175. uint64_t BAddr =
  176. (BType != SymbolRef::ST_Function) ? 0 : cantFail(B.getValue());
  177. return AAddr < BAddr;
  178. }
  179. };
  180. } // namespace
  181. // Types for the storted data in code table that is built before disassembly
  182. // and the predicate function to sort them.
  183. typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
  184. typedef std::vector<DiceTableEntry> DiceTable;
  185. typedef DiceTable::iterator dice_table_iterator;
  186. #ifdef LLVM_HAVE_LIBXAR
  187. namespace {
  188. struct ScopedXarFile {
  189. xar_t xar;
  190. ScopedXarFile(const char *filename, int32_t flags) {
  191. #pragma clang diagnostic push
  192. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  193. xar = xar_open(filename, flags);
  194. #pragma clang diagnostic pop
  195. }
  196. ~ScopedXarFile() {
  197. if (xar)
  198. xar_close(xar);
  199. }
  200. ScopedXarFile(const ScopedXarFile &) = delete;
  201. ScopedXarFile &operator=(const ScopedXarFile &) = delete;
  202. operator xar_t() { return xar; }
  203. };
  204. struct ScopedXarIter {
  205. xar_iter_t iter;
  206. ScopedXarIter() : iter(xar_iter_new()) {}
  207. ~ScopedXarIter() {
  208. if (iter)
  209. xar_iter_free(iter);
  210. }
  211. ScopedXarIter(const ScopedXarIter &) = delete;
  212. ScopedXarIter &operator=(const ScopedXarIter &) = delete;
  213. operator xar_iter_t() { return iter; }
  214. };
  215. } // namespace
  216. #endif // defined(LLVM_HAVE_LIBXAR)
  217. // This is used to search for a data in code table entry for the PC being
  218. // disassembled. The j parameter has the PC in j.first. A single data in code
  219. // table entry can cover many bytes for each of its Kind's. So if the offset,
  220. // aka the i.first value, of the data in code table entry plus its Length
  221. // covers the PC being searched for this will return true. If not it will
  222. // return false.
  223. static bool compareDiceTableEntries(const DiceTableEntry &i,
  224. const DiceTableEntry &j) {
  225. uint16_t Length;
  226. i.second.getLength(Length);
  227. return j.first >= i.first && j.first < i.first + Length;
  228. }
  229. static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
  230. unsigned short Kind) {
  231. uint32_t Value, Size = 1;
  232. switch (Kind) {
  233. default:
  234. case MachO::DICE_KIND_DATA:
  235. if (Length >= 4) {
  236. if (ShowRawInsn)
  237. dumpBytes(ArrayRef(bytes, 4), outs());
  238. Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
  239. outs() << "\t.long " << Value;
  240. Size = 4;
  241. } else if (Length >= 2) {
  242. if (ShowRawInsn)
  243. dumpBytes(ArrayRef(bytes, 2), outs());
  244. Value = bytes[1] << 8 | bytes[0];
  245. outs() << "\t.short " << Value;
  246. Size = 2;
  247. } else {
  248. if (ShowRawInsn)
  249. dumpBytes(ArrayRef(bytes, 2), outs());
  250. Value = bytes[0];
  251. outs() << "\t.byte " << Value;
  252. Size = 1;
  253. }
  254. if (Kind == MachO::DICE_KIND_DATA)
  255. outs() << "\t@ KIND_DATA\n";
  256. else
  257. outs() << "\t@ data in code kind = " << Kind << "\n";
  258. break;
  259. case MachO::DICE_KIND_JUMP_TABLE8:
  260. if (ShowRawInsn)
  261. dumpBytes(ArrayRef(bytes, 1), outs());
  262. Value = bytes[0];
  263. outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
  264. Size = 1;
  265. break;
  266. case MachO::DICE_KIND_JUMP_TABLE16:
  267. if (ShowRawInsn)
  268. dumpBytes(ArrayRef(bytes, 2), outs());
  269. Value = bytes[1] << 8 | bytes[0];
  270. outs() << "\t.short " << format("%5u", Value & 0xffff)
  271. << "\t@ KIND_JUMP_TABLE16\n";
  272. Size = 2;
  273. break;
  274. case MachO::DICE_KIND_JUMP_TABLE32:
  275. case MachO::DICE_KIND_ABS_JUMP_TABLE32:
  276. if (ShowRawInsn)
  277. dumpBytes(ArrayRef(bytes, 4), outs());
  278. Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
  279. outs() << "\t.long " << Value;
  280. if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
  281. outs() << "\t@ KIND_JUMP_TABLE32\n";
  282. else
  283. outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
  284. Size = 4;
  285. break;
  286. }
  287. return Size;
  288. }
  289. static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
  290. std::vector<SectionRef> &Sections,
  291. std::vector<SymbolRef> &Symbols,
  292. SmallVectorImpl<uint64_t> &FoundFns,
  293. uint64_t &BaseSegmentAddress) {
  294. const StringRef FileName = MachOObj->getFileName();
  295. for (const SymbolRef &Symbol : MachOObj->symbols()) {
  296. StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
  297. if (!SymName.startswith("ltmp"))
  298. Symbols.push_back(Symbol);
  299. }
  300. append_range(Sections, MachOObj->sections());
  301. bool BaseSegmentAddressSet = false;
  302. for (const auto &Command : MachOObj->load_commands()) {
  303. if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
  304. // We found a function starts segment, parse the addresses for later
  305. // consumption.
  306. MachO::linkedit_data_command LLC =
  307. MachOObj->getLinkeditDataLoadCommand(Command);
  308. MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
  309. } else if (Command.C.cmd == MachO::LC_SEGMENT) {
  310. MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
  311. StringRef SegName = SLC.segname;
  312. if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
  313. BaseSegmentAddressSet = true;
  314. BaseSegmentAddress = SLC.vmaddr;
  315. }
  316. } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
  317. MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(Command);
  318. StringRef SegName = SLC.segname;
  319. if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
  320. BaseSegmentAddressSet = true;
  321. BaseSegmentAddress = SLC.vmaddr;
  322. }
  323. }
  324. }
  325. }
  326. static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes,
  327. DiceTable &Dices, uint64_t &InstSize) {
  328. // Check the data in code table here to see if this is data not an
  329. // instruction to be disassembled.
  330. DiceTable Dice;
  331. Dice.push_back(std::make_pair(PC, DiceRef()));
  332. dice_table_iterator DTI =
  333. std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
  334. compareDiceTableEntries);
  335. if (DTI != Dices.end()) {
  336. uint16_t Length;
  337. DTI->second.getLength(Length);
  338. uint16_t Kind;
  339. DTI->second.getKind(Kind);
  340. InstSize = DumpDataInCode(bytes, Length, Kind);
  341. if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
  342. (PC == (DTI->first + Length - 1)) && (Length & 1))
  343. InstSize++;
  344. return true;
  345. }
  346. return false;
  347. }
  348. static void printRelocationTargetName(const MachOObjectFile *O,
  349. const MachO::any_relocation_info &RE,
  350. raw_string_ostream &Fmt) {
  351. // Target of a scattered relocation is an address. In the interest of
  352. // generating pretty output, scan through the symbol table looking for a
  353. // symbol that aligns with that address. If we find one, print it.
  354. // Otherwise, we just print the hex address of the target.
  355. const StringRef FileName = O->getFileName();
  356. if (O->isRelocationScattered(RE)) {
  357. uint32_t Val = O->getPlainRelocationSymbolNum(RE);
  358. for (const SymbolRef &Symbol : O->symbols()) {
  359. uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
  360. if (Addr != Val)
  361. continue;
  362. Fmt << unwrapOrError(Symbol.getName(), FileName);
  363. return;
  364. }
  365. // If we couldn't find a symbol that this relocation refers to, try
  366. // to find a section beginning instead.
  367. for (const SectionRef &Section : ToolSectionFilter(*O)) {
  368. uint64_t Addr = Section.getAddress();
  369. if (Addr != Val)
  370. continue;
  371. StringRef NameOrErr = unwrapOrError(Section.getName(), O->getFileName());
  372. Fmt << NameOrErr;
  373. return;
  374. }
  375. Fmt << format("0x%x", Val);
  376. return;
  377. }
  378. StringRef S;
  379. bool isExtern = O->getPlainRelocationExternal(RE);
  380. uint64_t Val = O->getPlainRelocationSymbolNum(RE);
  381. if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND &&
  382. (O->getArch() == Triple::aarch64 || O->getArch() == Triple::aarch64_be)) {
  383. Fmt << format("0x%0" PRIx64, Val);
  384. return;
  385. }
  386. if (isExtern) {
  387. symbol_iterator SI = O->symbol_begin();
  388. std::advance(SI, Val);
  389. S = unwrapOrError(SI->getName(), FileName);
  390. } else {
  391. section_iterator SI = O->section_begin();
  392. // Adjust for the fact that sections are 1-indexed.
  393. if (Val == 0) {
  394. Fmt << "0 (?,?)";
  395. return;
  396. }
  397. uint32_t I = Val - 1;
  398. while (I != 0 && SI != O->section_end()) {
  399. --I;
  400. std::advance(SI, 1);
  401. }
  402. if (SI == O->section_end()) {
  403. Fmt << Val << " (?,?)";
  404. } else {
  405. if (Expected<StringRef> NameOrErr = SI->getName())
  406. S = *NameOrErr;
  407. else
  408. consumeError(NameOrErr.takeError());
  409. }
  410. }
  411. Fmt << S;
  412. }
  413. Error objdump::getMachORelocationValueString(const MachOObjectFile *Obj,
  414. const RelocationRef &RelRef,
  415. SmallVectorImpl<char> &Result) {
  416. DataRefImpl Rel = RelRef.getRawDataRefImpl();
  417. MachO::any_relocation_info RE = Obj->getRelocation(Rel);
  418. unsigned Arch = Obj->getArch();
  419. std::string FmtBuf;
  420. raw_string_ostream Fmt(FmtBuf);
  421. unsigned Type = Obj->getAnyRelocationType(RE);
  422. bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
  423. // Determine any addends that should be displayed with the relocation.
  424. // These require decoding the relocation type, which is triple-specific.
  425. // X86_64 has entirely custom relocation types.
  426. if (Arch == Triple::x86_64) {
  427. switch (Type) {
  428. case MachO::X86_64_RELOC_GOT_LOAD:
  429. case MachO::X86_64_RELOC_GOT: {
  430. printRelocationTargetName(Obj, RE, Fmt);
  431. Fmt << "@GOT";
  432. if (IsPCRel)
  433. Fmt << "PCREL";
  434. break;
  435. }
  436. case MachO::X86_64_RELOC_SUBTRACTOR: {
  437. DataRefImpl RelNext = Rel;
  438. Obj->moveRelocationNext(RelNext);
  439. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  440. // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
  441. // X86_64_RELOC_UNSIGNED.
  442. // NOTE: Scattered relocations don't exist on x86_64.
  443. unsigned RType = Obj->getAnyRelocationType(RENext);
  444. if (RType != MachO::X86_64_RELOC_UNSIGNED)
  445. reportError(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
  446. "X86_64_RELOC_SUBTRACTOR.");
  447. // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
  448. // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
  449. printRelocationTargetName(Obj, RENext, Fmt);
  450. Fmt << "-";
  451. printRelocationTargetName(Obj, RE, Fmt);
  452. break;
  453. }
  454. case MachO::X86_64_RELOC_TLV:
  455. printRelocationTargetName(Obj, RE, Fmt);
  456. Fmt << "@TLV";
  457. if (IsPCRel)
  458. Fmt << "P";
  459. break;
  460. case MachO::X86_64_RELOC_SIGNED_1:
  461. printRelocationTargetName(Obj, RE, Fmt);
  462. Fmt << "-1";
  463. break;
  464. case MachO::X86_64_RELOC_SIGNED_2:
  465. printRelocationTargetName(Obj, RE, Fmt);
  466. Fmt << "-2";
  467. break;
  468. case MachO::X86_64_RELOC_SIGNED_4:
  469. printRelocationTargetName(Obj, RE, Fmt);
  470. Fmt << "-4";
  471. break;
  472. default:
  473. printRelocationTargetName(Obj, RE, Fmt);
  474. break;
  475. }
  476. // X86 and ARM share some relocation types in common.
  477. } else if (Arch == Triple::x86 || Arch == Triple::arm ||
  478. Arch == Triple::ppc) {
  479. // Generic relocation types...
  480. switch (Type) {
  481. case MachO::GENERIC_RELOC_PAIR: // prints no info
  482. return Error::success();
  483. case MachO::GENERIC_RELOC_SECTDIFF: {
  484. DataRefImpl RelNext = Rel;
  485. Obj->moveRelocationNext(RelNext);
  486. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  487. // X86 sect diff's must be followed by a relocation of type
  488. // GENERIC_RELOC_PAIR.
  489. unsigned RType = Obj->getAnyRelocationType(RENext);
  490. if (RType != MachO::GENERIC_RELOC_PAIR)
  491. reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
  492. "GENERIC_RELOC_SECTDIFF.");
  493. printRelocationTargetName(Obj, RE, Fmt);
  494. Fmt << "-";
  495. printRelocationTargetName(Obj, RENext, Fmt);
  496. break;
  497. }
  498. }
  499. if (Arch == Triple::x86 || Arch == Triple::ppc) {
  500. switch (Type) {
  501. case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
  502. DataRefImpl RelNext = Rel;
  503. Obj->moveRelocationNext(RelNext);
  504. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  505. // X86 sect diff's must be followed by a relocation of type
  506. // GENERIC_RELOC_PAIR.
  507. unsigned RType = Obj->getAnyRelocationType(RENext);
  508. if (RType != MachO::GENERIC_RELOC_PAIR)
  509. reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
  510. "GENERIC_RELOC_LOCAL_SECTDIFF.");
  511. printRelocationTargetName(Obj, RE, Fmt);
  512. Fmt << "-";
  513. printRelocationTargetName(Obj, RENext, Fmt);
  514. break;
  515. }
  516. case MachO::GENERIC_RELOC_TLV: {
  517. printRelocationTargetName(Obj, RE, Fmt);
  518. Fmt << "@TLV";
  519. if (IsPCRel)
  520. Fmt << "P";
  521. break;
  522. }
  523. default:
  524. printRelocationTargetName(Obj, RE, Fmt);
  525. }
  526. } else { // ARM-specific relocations
  527. switch (Type) {
  528. case MachO::ARM_RELOC_HALF:
  529. case MachO::ARM_RELOC_HALF_SECTDIFF: {
  530. // Half relocations steal a bit from the length field to encode
  531. // whether this is an upper16 or a lower16 relocation.
  532. bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
  533. if (isUpper)
  534. Fmt << ":upper16:(";
  535. else
  536. Fmt << ":lower16:(";
  537. printRelocationTargetName(Obj, RE, Fmt);
  538. DataRefImpl RelNext = Rel;
  539. Obj->moveRelocationNext(RelNext);
  540. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  541. // ARM half relocs must be followed by a relocation of type
  542. // ARM_RELOC_PAIR.
  543. unsigned RType = Obj->getAnyRelocationType(RENext);
  544. if (RType != MachO::ARM_RELOC_PAIR)
  545. reportError(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
  546. "ARM_RELOC_HALF");
  547. // NOTE: The half of the target virtual address is stashed in the
  548. // address field of the secondary relocation, but we can't reverse
  549. // engineer the constant offset from it without decoding the movw/movt
  550. // instruction to find the other half in its immediate field.
  551. // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
  552. // symbol/section pointer of the follow-on relocation.
  553. if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
  554. Fmt << "-";
  555. printRelocationTargetName(Obj, RENext, Fmt);
  556. }
  557. Fmt << ")";
  558. break;
  559. }
  560. default: {
  561. printRelocationTargetName(Obj, RE, Fmt);
  562. }
  563. }
  564. }
  565. } else
  566. printRelocationTargetName(Obj, RE, Fmt);
  567. Fmt.flush();
  568. Result.append(FmtBuf.begin(), FmtBuf.end());
  569. return Error::success();
  570. }
  571. static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
  572. uint32_t n, uint32_t count,
  573. uint32_t stride, uint64_t addr) {
  574. MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
  575. uint32_t nindirectsyms = Dysymtab.nindirectsyms;
  576. if (n > nindirectsyms)
  577. outs() << " (entries start past the end of the indirect symbol "
  578. "table) (reserved1 field greater than the table size)";
  579. else if (n + count > nindirectsyms)
  580. outs() << " (entries extends past the end of the indirect symbol "
  581. "table)";
  582. outs() << "\n";
  583. uint32_t cputype = O->getHeader().cputype;
  584. if (cputype & MachO::CPU_ARCH_ABI64)
  585. outs() << "address index";
  586. else
  587. outs() << "address index";
  588. if (verbose)
  589. outs() << " name\n";
  590. else
  591. outs() << "\n";
  592. for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
  593. if (cputype & MachO::CPU_ARCH_ABI64)
  594. outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
  595. else
  596. outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
  597. MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
  598. uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
  599. if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
  600. outs() << "LOCAL\n";
  601. continue;
  602. }
  603. if (indirect_symbol ==
  604. (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
  605. outs() << "LOCAL ABSOLUTE\n";
  606. continue;
  607. }
  608. if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
  609. outs() << "ABSOLUTE\n";
  610. continue;
  611. }
  612. outs() << format("%5u ", indirect_symbol);
  613. if (verbose) {
  614. MachO::symtab_command Symtab = O->getSymtabLoadCommand();
  615. if (indirect_symbol < Symtab.nsyms) {
  616. symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
  617. SymbolRef Symbol = *Sym;
  618. outs() << unwrapOrError(Symbol.getName(), O->getFileName());
  619. } else {
  620. outs() << "?";
  621. }
  622. }
  623. outs() << "\n";
  624. }
  625. }
  626. static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
  627. for (const auto &Load : O->load_commands()) {
  628. if (Load.C.cmd == MachO::LC_SEGMENT_64) {
  629. MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
  630. for (unsigned J = 0; J < Seg.nsects; ++J) {
  631. MachO::section_64 Sec = O->getSection64(Load, J);
  632. uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
  633. if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
  634. section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
  635. section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
  636. section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
  637. section_type == MachO::S_SYMBOL_STUBS) {
  638. uint32_t stride;
  639. if (section_type == MachO::S_SYMBOL_STUBS)
  640. stride = Sec.reserved2;
  641. else
  642. stride = 8;
  643. if (stride == 0) {
  644. outs() << "Can't print indirect symbols for (" << Sec.segname << ","
  645. << Sec.sectname << ") "
  646. << "(size of stubs in reserved2 field is zero)\n";
  647. continue;
  648. }
  649. uint32_t count = Sec.size / stride;
  650. outs() << "Indirect symbols for (" << Sec.segname << ","
  651. << Sec.sectname << ") " << count << " entries";
  652. uint32_t n = Sec.reserved1;
  653. PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
  654. }
  655. }
  656. } else if (Load.C.cmd == MachO::LC_SEGMENT) {
  657. MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
  658. for (unsigned J = 0; J < Seg.nsects; ++J) {
  659. MachO::section Sec = O->getSection(Load, J);
  660. uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
  661. if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
  662. section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
  663. section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
  664. section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
  665. section_type == MachO::S_SYMBOL_STUBS) {
  666. uint32_t stride;
  667. if (section_type == MachO::S_SYMBOL_STUBS)
  668. stride = Sec.reserved2;
  669. else
  670. stride = 4;
  671. if (stride == 0) {
  672. outs() << "Can't print indirect symbols for (" << Sec.segname << ","
  673. << Sec.sectname << ") "
  674. << "(size of stubs in reserved2 field is zero)\n";
  675. continue;
  676. }
  677. uint32_t count = Sec.size / stride;
  678. outs() << "Indirect symbols for (" << Sec.segname << ","
  679. << Sec.sectname << ") " << count << " entries";
  680. uint32_t n = Sec.reserved1;
  681. PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
  682. }
  683. }
  684. }
  685. }
  686. }
  687. static void PrintRType(const uint64_t cputype, const unsigned r_type) {
  688. static char const *generic_r_types[] = {
  689. "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
  690. " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
  691. " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
  692. };
  693. static char const *x86_64_r_types[] = {
  694. "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
  695. "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
  696. " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
  697. };
  698. static char const *arm_r_types[] = {
  699. "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
  700. "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
  701. " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
  702. };
  703. static char const *arm64_r_types[] = {
  704. "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
  705. "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
  706. "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
  707. };
  708. if (r_type > 0xf){
  709. outs() << format("%-7u", r_type) << " ";
  710. return;
  711. }
  712. switch (cputype) {
  713. case MachO::CPU_TYPE_I386:
  714. outs() << generic_r_types[r_type];
  715. break;
  716. case MachO::CPU_TYPE_X86_64:
  717. outs() << x86_64_r_types[r_type];
  718. break;
  719. case MachO::CPU_TYPE_ARM:
  720. outs() << arm_r_types[r_type];
  721. break;
  722. case MachO::CPU_TYPE_ARM64:
  723. case MachO::CPU_TYPE_ARM64_32:
  724. outs() << arm64_r_types[r_type];
  725. break;
  726. default:
  727. outs() << format("%-7u ", r_type);
  728. }
  729. }
  730. static void PrintRLength(const uint64_t cputype, const unsigned r_type,
  731. const unsigned r_length, const bool previous_arm_half){
  732. if (cputype == MachO::CPU_TYPE_ARM &&
  733. (r_type == MachO::ARM_RELOC_HALF ||
  734. r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
  735. if ((r_length & 0x1) == 0)
  736. outs() << "lo/";
  737. else
  738. outs() << "hi/";
  739. if ((r_length & 0x1) == 0)
  740. outs() << "arm ";
  741. else
  742. outs() << "thm ";
  743. } else {
  744. switch (r_length) {
  745. case 0:
  746. outs() << "byte ";
  747. break;
  748. case 1:
  749. outs() << "word ";
  750. break;
  751. case 2:
  752. outs() << "long ";
  753. break;
  754. case 3:
  755. if (cputype == MachO::CPU_TYPE_X86_64)
  756. outs() << "quad ";
  757. else
  758. outs() << format("?(%2d) ", r_length);
  759. break;
  760. default:
  761. outs() << format("?(%2d) ", r_length);
  762. }
  763. }
  764. }
  765. static void PrintRelocationEntries(const MachOObjectFile *O,
  766. const relocation_iterator Begin,
  767. const relocation_iterator End,
  768. const uint64_t cputype,
  769. const bool verbose) {
  770. const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
  771. bool previous_arm_half = false;
  772. bool previous_sectdiff = false;
  773. uint32_t sectdiff_r_type = 0;
  774. for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
  775. const DataRefImpl Rel = Reloc->getRawDataRefImpl();
  776. const MachO::any_relocation_info RE = O->getRelocation(Rel);
  777. const unsigned r_type = O->getAnyRelocationType(RE);
  778. const bool r_scattered = O->isRelocationScattered(RE);
  779. const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
  780. const unsigned r_length = O->getAnyRelocationLength(RE);
  781. const unsigned r_address = O->getAnyRelocationAddress(RE);
  782. const bool r_extern = (r_scattered ? false :
  783. O->getPlainRelocationExternal(RE));
  784. const uint32_t r_value = (r_scattered ?
  785. O->getScatteredRelocationValue(RE) : 0);
  786. const unsigned r_symbolnum = (r_scattered ? 0 :
  787. O->getPlainRelocationSymbolNum(RE));
  788. if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
  789. if (verbose) {
  790. // scattered: address
  791. if ((cputype == MachO::CPU_TYPE_I386 &&
  792. r_type == MachO::GENERIC_RELOC_PAIR) ||
  793. (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
  794. outs() << " ";
  795. else
  796. outs() << format("%08x ", (unsigned int)r_address);
  797. // scattered: pcrel
  798. if (r_pcrel)
  799. outs() << "True ";
  800. else
  801. outs() << "False ";
  802. // scattered: length
  803. PrintRLength(cputype, r_type, r_length, previous_arm_half);
  804. // scattered: extern & type
  805. outs() << "n/a ";
  806. PrintRType(cputype, r_type);
  807. // scattered: scattered & value
  808. outs() << format("True 0x%08x", (unsigned int)r_value);
  809. if (previous_sectdiff == false) {
  810. if ((cputype == MachO::CPU_TYPE_ARM &&
  811. r_type == MachO::ARM_RELOC_PAIR))
  812. outs() << format(" half = 0x%04x ", (unsigned int)r_address);
  813. } else if (cputype == MachO::CPU_TYPE_ARM &&
  814. sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
  815. outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
  816. if ((cputype == MachO::CPU_TYPE_I386 &&
  817. (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
  818. r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
  819. (cputype == MachO::CPU_TYPE_ARM &&
  820. (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
  821. sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
  822. sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
  823. previous_sectdiff = true;
  824. sectdiff_r_type = r_type;
  825. } else {
  826. previous_sectdiff = false;
  827. sectdiff_r_type = 0;
  828. }
  829. if (cputype == MachO::CPU_TYPE_ARM &&
  830. (r_type == MachO::ARM_RELOC_HALF ||
  831. r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
  832. previous_arm_half = true;
  833. else
  834. previous_arm_half = false;
  835. outs() << "\n";
  836. }
  837. else {
  838. // scattered: address pcrel length extern type scattered value
  839. outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
  840. (unsigned int)r_address, r_pcrel, r_length, r_type,
  841. (unsigned int)r_value);
  842. }
  843. }
  844. else {
  845. if (verbose) {
  846. // plain: address
  847. if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
  848. outs() << " ";
  849. else
  850. outs() << format("%08x ", (unsigned int)r_address);
  851. // plain: pcrel
  852. if (r_pcrel)
  853. outs() << "True ";
  854. else
  855. outs() << "False ";
  856. // plain: length
  857. PrintRLength(cputype, r_type, r_length, previous_arm_half);
  858. if (r_extern) {
  859. // plain: extern & type & scattered
  860. outs() << "True ";
  861. PrintRType(cputype, r_type);
  862. outs() << "False ";
  863. // plain: symbolnum/value
  864. if (r_symbolnum > Symtab.nsyms)
  865. outs() << format("?(%d)\n", r_symbolnum);
  866. else {
  867. SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
  868. Expected<StringRef> SymNameNext = Symbol.getName();
  869. const char *name = nullptr;
  870. if (SymNameNext)
  871. name = SymNameNext->data();
  872. if (name == nullptr)
  873. outs() << format("?(%d)\n", r_symbolnum);
  874. else
  875. outs() << name << "\n";
  876. }
  877. }
  878. else {
  879. // plain: extern & type & scattered
  880. outs() << "False ";
  881. PrintRType(cputype, r_type);
  882. outs() << "False ";
  883. // plain: symbolnum/value
  884. if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
  885. outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
  886. else if ((cputype == MachO::CPU_TYPE_ARM64 ||
  887. cputype == MachO::CPU_TYPE_ARM64_32) &&
  888. r_type == MachO::ARM64_RELOC_ADDEND)
  889. outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
  890. else {
  891. outs() << format("%d ", r_symbolnum);
  892. if (r_symbolnum == MachO::R_ABS)
  893. outs() << "R_ABS\n";
  894. else {
  895. // in this case, r_symbolnum is actually a 1-based section number
  896. uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
  897. if (r_symbolnum > 0 && r_symbolnum <= nsects) {
  898. object::DataRefImpl DRI;
  899. DRI.d.a = r_symbolnum-1;
  900. StringRef SegName = O->getSectionFinalSegmentName(DRI);
  901. if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
  902. outs() << "(" << SegName << "," << *NameOrErr << ")\n";
  903. else
  904. outs() << "(?,?)\n";
  905. }
  906. else {
  907. outs() << "(?,?)\n";
  908. }
  909. }
  910. }
  911. }
  912. if (cputype == MachO::CPU_TYPE_ARM &&
  913. (r_type == MachO::ARM_RELOC_HALF ||
  914. r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
  915. previous_arm_half = true;
  916. else
  917. previous_arm_half = false;
  918. }
  919. else {
  920. // plain: address pcrel length extern type scattered symbolnum/section
  921. outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
  922. (unsigned int)r_address, r_pcrel, r_length, r_extern,
  923. r_type, r_symbolnum);
  924. }
  925. }
  926. }
  927. }
  928. static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
  929. const uint64_t cputype = O->getHeader().cputype;
  930. const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
  931. if (Dysymtab.nextrel != 0) {
  932. outs() << "External relocation information " << Dysymtab.nextrel
  933. << " entries";
  934. outs() << "\naddress pcrel length extern type scattered "
  935. "symbolnum/value\n";
  936. PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
  937. verbose);
  938. }
  939. if (Dysymtab.nlocrel != 0) {
  940. outs() << format("Local relocation information %u entries",
  941. Dysymtab.nlocrel);
  942. outs() << "\naddress pcrel length extern type scattered "
  943. "symbolnum/value\n";
  944. PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
  945. verbose);
  946. }
  947. for (const auto &Load : O->load_commands()) {
  948. if (Load.C.cmd == MachO::LC_SEGMENT_64) {
  949. const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
  950. for (unsigned J = 0; J < Seg.nsects; ++J) {
  951. const MachO::section_64 Sec = O->getSection64(Load, J);
  952. if (Sec.nreloc != 0) {
  953. DataRefImpl DRI;
  954. DRI.d.a = J;
  955. const StringRef SegName = O->getSectionFinalSegmentName(DRI);
  956. if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
  957. outs() << "Relocation information (" << SegName << "," << *NameOrErr
  958. << format(") %u entries", Sec.nreloc);
  959. else
  960. outs() << "Relocation information (" << SegName << ",?) "
  961. << format("%u entries", Sec.nreloc);
  962. outs() << "\naddress pcrel length extern type scattered "
  963. "symbolnum/value\n";
  964. PrintRelocationEntries(O, O->section_rel_begin(DRI),
  965. O->section_rel_end(DRI), cputype, verbose);
  966. }
  967. }
  968. } else if (Load.C.cmd == MachO::LC_SEGMENT) {
  969. const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
  970. for (unsigned J = 0; J < Seg.nsects; ++J) {
  971. const MachO::section Sec = O->getSection(Load, J);
  972. if (Sec.nreloc != 0) {
  973. DataRefImpl DRI;
  974. DRI.d.a = J;
  975. const StringRef SegName = O->getSectionFinalSegmentName(DRI);
  976. if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
  977. outs() << "Relocation information (" << SegName << "," << *NameOrErr
  978. << format(") %u entries", Sec.nreloc);
  979. else
  980. outs() << "Relocation information (" << SegName << ",?) "
  981. << format("%u entries", Sec.nreloc);
  982. outs() << "\naddress pcrel length extern type scattered "
  983. "symbolnum/value\n";
  984. PrintRelocationEntries(O, O->section_rel_begin(DRI),
  985. O->section_rel_end(DRI), cputype, verbose);
  986. }
  987. }
  988. }
  989. }
  990. }
  991. static void PrintFunctionStarts(MachOObjectFile *O) {
  992. uint64_t BaseSegmentAddress = 0;
  993. for (const MachOObjectFile::LoadCommandInfo &Command : O->load_commands()) {
  994. if (Command.C.cmd == MachO::LC_SEGMENT) {
  995. MachO::segment_command SLC = O->getSegmentLoadCommand(Command);
  996. if (StringRef(SLC.segname) == "__TEXT") {
  997. BaseSegmentAddress = SLC.vmaddr;
  998. break;
  999. }
  1000. } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
  1001. MachO::segment_command_64 SLC = O->getSegment64LoadCommand(Command);
  1002. if (StringRef(SLC.segname) == "__TEXT") {
  1003. BaseSegmentAddress = SLC.vmaddr;
  1004. break;
  1005. }
  1006. }
  1007. }
  1008. SmallVector<uint64_t, 8> FunctionStarts;
  1009. for (const MachOObjectFile::LoadCommandInfo &LC : O->load_commands()) {
  1010. if (LC.C.cmd == MachO::LC_FUNCTION_STARTS) {
  1011. MachO::linkedit_data_command FunctionStartsLC =
  1012. O->getLinkeditDataLoadCommand(LC);
  1013. O->ReadULEB128s(FunctionStartsLC.dataoff, FunctionStarts);
  1014. break;
  1015. }
  1016. }
  1017. DenseMap<uint64_t, StringRef> SymbolNames;
  1018. if (FunctionStartsType == FunctionStartsMode::Names ||
  1019. FunctionStartsType == FunctionStartsMode::Both) {
  1020. for (SymbolRef Sym : O->symbols()) {
  1021. if (Expected<uint64_t> Addr = Sym.getAddress()) {
  1022. if (Expected<StringRef> Name = Sym.getName()) {
  1023. SymbolNames[*Addr] = *Name;
  1024. }
  1025. }
  1026. }
  1027. }
  1028. for (uint64_t S : FunctionStarts) {
  1029. uint64_t Addr = BaseSegmentAddress + S;
  1030. if (FunctionStartsType == FunctionStartsMode::Names) {
  1031. auto It = SymbolNames.find(Addr);
  1032. if (It != SymbolNames.end())
  1033. outs() << It->second << "\n";
  1034. } else {
  1035. if (O->is64Bit())
  1036. outs() << format("%016" PRIx64, Addr);
  1037. else
  1038. outs() << format("%08" PRIx32, static_cast<uint32_t>(Addr));
  1039. if (FunctionStartsType == FunctionStartsMode::Both) {
  1040. auto It = SymbolNames.find(Addr);
  1041. if (It != SymbolNames.end())
  1042. outs() << " " << It->second;
  1043. else
  1044. outs() << " ?";
  1045. }
  1046. outs() << "\n";
  1047. }
  1048. }
  1049. }
  1050. static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
  1051. MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
  1052. uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
  1053. outs() << "Data in code table (" << nentries << " entries)\n";
  1054. outs() << "offset length kind\n";
  1055. for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
  1056. ++DI) {
  1057. uint32_t Offset;
  1058. DI->getOffset(Offset);
  1059. outs() << format("0x%08" PRIx32, Offset) << " ";
  1060. uint16_t Length;
  1061. DI->getLength(Length);
  1062. outs() << format("%6u", Length) << " ";
  1063. uint16_t Kind;
  1064. DI->getKind(Kind);
  1065. if (verbose) {
  1066. switch (Kind) {
  1067. case MachO::DICE_KIND_DATA:
  1068. outs() << "DATA";
  1069. break;
  1070. case MachO::DICE_KIND_JUMP_TABLE8:
  1071. outs() << "JUMP_TABLE8";
  1072. break;
  1073. case MachO::DICE_KIND_JUMP_TABLE16:
  1074. outs() << "JUMP_TABLE16";
  1075. break;
  1076. case MachO::DICE_KIND_JUMP_TABLE32:
  1077. outs() << "JUMP_TABLE32";
  1078. break;
  1079. case MachO::DICE_KIND_ABS_JUMP_TABLE32:
  1080. outs() << "ABS_JUMP_TABLE32";
  1081. break;
  1082. default:
  1083. outs() << format("0x%04" PRIx32, Kind);
  1084. break;
  1085. }
  1086. } else
  1087. outs() << format("0x%04" PRIx32, Kind);
  1088. outs() << "\n";
  1089. }
  1090. }
  1091. static void PrintLinkOptHints(MachOObjectFile *O) {
  1092. MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
  1093. const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
  1094. uint32_t nloh = LohLC.datasize;
  1095. outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
  1096. for (uint32_t i = 0; i < nloh;) {
  1097. unsigned n;
  1098. uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
  1099. i += n;
  1100. outs() << " identifier " << identifier << " ";
  1101. if (i >= nloh)
  1102. return;
  1103. switch (identifier) {
  1104. case 1:
  1105. outs() << "AdrpAdrp\n";
  1106. break;
  1107. case 2:
  1108. outs() << "AdrpLdr\n";
  1109. break;
  1110. case 3:
  1111. outs() << "AdrpAddLdr\n";
  1112. break;
  1113. case 4:
  1114. outs() << "AdrpLdrGotLdr\n";
  1115. break;
  1116. case 5:
  1117. outs() << "AdrpAddStr\n";
  1118. break;
  1119. case 6:
  1120. outs() << "AdrpLdrGotStr\n";
  1121. break;
  1122. case 7:
  1123. outs() << "AdrpAdd\n";
  1124. break;
  1125. case 8:
  1126. outs() << "AdrpLdrGot\n";
  1127. break;
  1128. default:
  1129. outs() << "Unknown identifier value\n";
  1130. break;
  1131. }
  1132. uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
  1133. i += n;
  1134. outs() << " narguments " << narguments << "\n";
  1135. if (i >= nloh)
  1136. return;
  1137. for (uint32_t j = 0; j < narguments; j++) {
  1138. uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
  1139. i += n;
  1140. outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
  1141. if (i >= nloh)
  1142. return;
  1143. }
  1144. }
  1145. }
  1146. static SmallVector<std::string> GetSegmentNames(object::MachOObjectFile *O) {
  1147. SmallVector<std::string> Ret;
  1148. for (const MachOObjectFile::LoadCommandInfo &Command : O->load_commands()) {
  1149. if (Command.C.cmd == MachO::LC_SEGMENT) {
  1150. MachO::segment_command SLC = O->getSegmentLoadCommand(Command);
  1151. Ret.push_back(SLC.segname);
  1152. } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
  1153. MachO::segment_command_64 SLC = O->getSegment64LoadCommand(Command);
  1154. Ret.push_back(SLC.segname);
  1155. }
  1156. }
  1157. return Ret;
  1158. }
  1159. static void
  1160. PrintChainedFixupsHeader(const MachO::dyld_chained_fixups_header &H) {
  1161. outs() << "chained fixups header (LC_DYLD_CHAINED_FIXUPS)\n";
  1162. outs() << " fixups_version = " << H.fixups_version << '\n';
  1163. outs() << " starts_offset = " << H.starts_offset << '\n';
  1164. outs() << " imports_offset = " << H.imports_offset << '\n';
  1165. outs() << " symbols_offset = " << H.symbols_offset << '\n';
  1166. outs() << " imports_count = " << H.imports_count << '\n';
  1167. outs() << " imports_format = " << H.imports_format;
  1168. switch (H.imports_format) {
  1169. case llvm::MachO::DYLD_CHAINED_IMPORT:
  1170. outs() << " (DYLD_CHAINED_IMPORT)";
  1171. break;
  1172. case llvm::MachO::DYLD_CHAINED_IMPORT_ADDEND:
  1173. outs() << " (DYLD_CHAINED_IMPORT_ADDEND)";
  1174. break;
  1175. case llvm::MachO::DYLD_CHAINED_IMPORT_ADDEND64:
  1176. outs() << " (DYLD_CHAINED_IMPORT_ADDEND64)";
  1177. break;
  1178. }
  1179. outs() << '\n';
  1180. outs() << " symbols_format = " << H.symbols_format;
  1181. if (H.symbols_format == llvm::MachO::DYLD_CHAINED_SYMBOL_ZLIB)
  1182. outs() << " (zlib compressed)";
  1183. outs() << '\n';
  1184. }
  1185. static constexpr std::array<StringRef, 13> PointerFormats{
  1186. "DYLD_CHAINED_PTR_ARM64E",
  1187. "DYLD_CHAINED_PTR_64",
  1188. "DYLD_CHAINED_PTR_32",
  1189. "DYLD_CHAINED_PTR_32_CACHE",
  1190. "DYLD_CHAINED_PTR_32_FIRMWARE",
  1191. "DYLD_CHAINED_PTR_64_OFFSET",
  1192. "DYLD_CHAINED_PTR_ARM64E_KERNEL",
  1193. "DYLD_CHAINED_PTR_64_KERNEL_CACHE",
  1194. "DYLD_CHAINED_PTR_ARM64E_USERLAND",
  1195. "DYLD_CHAINED_PTR_ARM64E_FIRMWARE",
  1196. "DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE",
  1197. "DYLD_CHAINED_PTR_ARM64E_USERLAND24",
  1198. };
  1199. static void PrintChainedFixupsSegment(const ChainedFixupsSegment &Segment,
  1200. StringRef SegName) {
  1201. outs() << "chained starts in segment " << Segment.SegIdx << " (" << SegName
  1202. << ")\n";
  1203. outs() << " size = " << Segment.Header.size << '\n';
  1204. outs() << " page_size = " << format("0x%0" PRIx16, Segment.Header.page_size)
  1205. << '\n';
  1206. outs() << " pointer_format = " << Segment.Header.pointer_format;
  1207. if ((Segment.Header.pointer_format - 1) <
  1208. MachO::DYLD_CHAINED_PTR_ARM64E_USERLAND24)
  1209. outs() << " (" << PointerFormats[Segment.Header.pointer_format - 1] << ")";
  1210. outs() << '\n';
  1211. outs() << " segment_offset = "
  1212. << format("0x%0" PRIx64, Segment.Header.segment_offset) << '\n';
  1213. outs() << " max_valid_pointer = " << Segment.Header.max_valid_pointer
  1214. << '\n';
  1215. outs() << " page_count = " << Segment.Header.page_count << '\n';
  1216. for (auto [Index, PageStart] : enumerate(Segment.PageStarts)) {
  1217. outs() << " page_start[" << Index << "] = " << PageStart;
  1218. // FIXME: Support DYLD_CHAINED_PTR_START_MULTI (32-bit only)
  1219. if (PageStart == MachO::DYLD_CHAINED_PTR_START_NONE)
  1220. outs() << " (DYLD_CHAINED_PTR_START_NONE)";
  1221. outs() << '\n';
  1222. }
  1223. }
  1224. static void PrintChainedFixupTarget(ChainedFixupTarget &Target, size_t Idx,
  1225. int Format, MachOObjectFile *O) {
  1226. if (Format == MachO::DYLD_CHAINED_IMPORT)
  1227. outs() << "dyld chained import";
  1228. else if (Format == MachO::DYLD_CHAINED_IMPORT_ADDEND)
  1229. outs() << "dyld chained import addend";
  1230. else if (Format == MachO::DYLD_CHAINED_IMPORT_ADDEND64)
  1231. outs() << "dyld chained import addend64";
  1232. // FIXME: otool prints the encoded value as well.
  1233. outs() << '[' << Idx << "]\n";
  1234. outs() << " lib_ordinal = " << Target.libOrdinal() << " ("
  1235. << ordinalName(O, Target.libOrdinal()) << ")\n";
  1236. outs() << " weak_import = " << Target.weakImport() << '\n';
  1237. outs() << " name_offset = " << Target.nameOffset() << " ("
  1238. << Target.symbolName() << ")\n";
  1239. if (Format != MachO::DYLD_CHAINED_IMPORT)
  1240. outs() << " addend = " << (int64_t)Target.addend() << '\n';
  1241. }
  1242. static void PrintChainedFixups(MachOObjectFile *O) {
  1243. // MachOObjectFile::getChainedFixupsHeader() reads LC_DYLD_CHAINED_FIXUPS.
  1244. // FIXME: Support chained fixups in __TEXT,__chain_starts section too.
  1245. auto ChainedFixupHeader =
  1246. unwrapOrError(O->getChainedFixupsHeader(), O->getFileName());
  1247. if (!ChainedFixupHeader)
  1248. return;
  1249. PrintChainedFixupsHeader(*ChainedFixupHeader);
  1250. auto [SegCount, Segments] =
  1251. unwrapOrError(O->getChainedFixupsSegments(), O->getFileName());
  1252. auto SegNames = GetSegmentNames(O);
  1253. size_t StartsIdx = 0;
  1254. outs() << "chained starts in image\n";
  1255. outs() << " seg_count = " << SegCount << '\n';
  1256. for (size_t I = 0; I < SegCount; ++I) {
  1257. uint64_t SegOffset = 0;
  1258. if (StartsIdx < Segments.size() && I == Segments[StartsIdx].SegIdx) {
  1259. SegOffset = Segments[StartsIdx].Offset;
  1260. ++StartsIdx;
  1261. }
  1262. outs() << " seg_offset[" << I << "] = " << SegOffset << " ("
  1263. << SegNames[I] << ")\n";
  1264. }
  1265. for (const ChainedFixupsSegment &S : Segments)
  1266. PrintChainedFixupsSegment(S, SegNames[S.SegIdx]);
  1267. auto FixupTargets =
  1268. unwrapOrError(O->getDyldChainedFixupTargets(), O->getFileName());
  1269. uint32_t ImportsFormat = ChainedFixupHeader->imports_format;
  1270. for (auto [Idx, Target] : enumerate(FixupTargets))
  1271. PrintChainedFixupTarget(Target, Idx, ImportsFormat, O);
  1272. }
  1273. static void PrintDyldInfo(MachOObjectFile *O) {
  1274. Error Err = Error::success();
  1275. size_t SegmentWidth = strlen("segment");
  1276. size_t SectionWidth = strlen("section");
  1277. size_t AddressWidth = strlen("address");
  1278. size_t AddendWidth = strlen("addend");
  1279. size_t DylibWidth = strlen("dylib");
  1280. const size_t PointerWidth = 2 + O->getBytesInAddress() * 2;
  1281. auto HexLength = [](uint64_t Num) {
  1282. return Num ? (size_t)divideCeil(Log2_64(Num), 4) : 1;
  1283. };
  1284. for (const object::MachOChainedFixupEntry &Entry : O->fixupTable(Err)) {
  1285. SegmentWidth = std::max(SegmentWidth, Entry.segmentName().size());
  1286. SectionWidth = std::max(SectionWidth, Entry.sectionName().size());
  1287. AddressWidth = std::max(AddressWidth, HexLength(Entry.address()) + 2);
  1288. if (Entry.isBind()) {
  1289. AddendWidth = std::max(AddendWidth, HexLength(Entry.addend()) + 2);
  1290. DylibWidth = std::max(DylibWidth, Entry.symbolName().size());
  1291. }
  1292. }
  1293. // Errors will be handled when printing the table.
  1294. if (Err)
  1295. consumeError(std::move(Err));
  1296. outs() << "dyld information:\n";
  1297. outs() << left_justify("segment", SegmentWidth) << ' '
  1298. << left_justify("section", SectionWidth) << ' '
  1299. << left_justify("address", AddressWidth) << ' '
  1300. << left_justify("pointer", PointerWidth) << " type "
  1301. << left_justify("addend", AddendWidth) << ' '
  1302. << left_justify("dylib", DylibWidth) << " symbol/vm address\n";
  1303. for (const object::MachOChainedFixupEntry &Entry : O->fixupTable(Err)) {
  1304. outs() << left_justify(Entry.segmentName(), SegmentWidth) << ' '
  1305. << left_justify(Entry.sectionName(), SectionWidth) << ' ' << "0x"
  1306. << left_justify(utohexstr(Entry.address()), AddressWidth - 2) << ' '
  1307. << format_hex(Entry.rawValue(), PointerWidth, true) << ' ';
  1308. if (Entry.isBind()) {
  1309. outs() << "bind "
  1310. << "0x" << left_justify(utohexstr(Entry.addend()), AddendWidth - 2)
  1311. << ' ' << left_justify(ordinalName(O, Entry.ordinal()), DylibWidth)
  1312. << ' ' << Entry.symbolName();
  1313. if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
  1314. outs() << " (weak import)";
  1315. outs() << '\n';
  1316. } else {
  1317. assert(Entry.isRebase());
  1318. outs() << "rebase";
  1319. outs().indent(AddendWidth + DylibWidth + 2);
  1320. outs() << format("0x%" PRIX64, Entry.pointerValue()) << '\n';
  1321. }
  1322. }
  1323. if (Err)
  1324. reportError(std::move(Err), O->getFileName());
  1325. // TODO: Print opcode-based fixups if the object uses those.
  1326. }
  1327. static void PrintDylibs(MachOObjectFile *O, bool JustId) {
  1328. unsigned Index = 0;
  1329. for (const auto &Load : O->load_commands()) {
  1330. if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
  1331. (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
  1332. Load.C.cmd == MachO::LC_LOAD_DYLIB ||
  1333. Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
  1334. Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
  1335. Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
  1336. Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
  1337. MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
  1338. if (dl.dylib.name < dl.cmdsize) {
  1339. const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
  1340. if (JustId)
  1341. outs() << p << "\n";
  1342. else {
  1343. outs() << "\t" << p;
  1344. outs() << " (compatibility version "
  1345. << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
  1346. << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
  1347. << (dl.dylib.compatibility_version & 0xff) << ",";
  1348. outs() << " current version "
  1349. << ((dl.dylib.current_version >> 16) & 0xffff) << "."
  1350. << ((dl.dylib.current_version >> 8) & 0xff) << "."
  1351. << (dl.dylib.current_version & 0xff);
  1352. if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
  1353. outs() << ", weak";
  1354. if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
  1355. outs() << ", reexport";
  1356. if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
  1357. outs() << ", upward";
  1358. if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
  1359. outs() << ", lazy";
  1360. outs() << ")\n";
  1361. }
  1362. } else {
  1363. outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
  1364. if (Load.C.cmd == MachO::LC_ID_DYLIB)
  1365. outs() << "LC_ID_DYLIB ";
  1366. else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
  1367. outs() << "LC_LOAD_DYLIB ";
  1368. else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
  1369. outs() << "LC_LOAD_WEAK_DYLIB ";
  1370. else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
  1371. outs() << "LC_LAZY_LOAD_DYLIB ";
  1372. else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
  1373. outs() << "LC_REEXPORT_DYLIB ";
  1374. else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
  1375. outs() << "LC_LOAD_UPWARD_DYLIB ";
  1376. else
  1377. outs() << "LC_??? ";
  1378. outs() << "command " << Index++ << "\n";
  1379. }
  1380. }
  1381. }
  1382. }
  1383. static void printRpaths(MachOObjectFile *O) {
  1384. for (const auto &Command : O->load_commands()) {
  1385. if (Command.C.cmd == MachO::LC_RPATH) {
  1386. auto Rpath = O->getRpathCommand(Command);
  1387. const char *P = (const char *)(Command.Ptr) + Rpath.path;
  1388. outs() << P << "\n";
  1389. }
  1390. }
  1391. }
  1392. typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
  1393. static void CreateSymbolAddressMap(MachOObjectFile *O,
  1394. SymbolAddressMap *AddrMap) {
  1395. // Create a map of symbol addresses to symbol names.
  1396. const StringRef FileName = O->getFileName();
  1397. for (const SymbolRef &Symbol : O->symbols()) {
  1398. SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
  1399. if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
  1400. ST == SymbolRef::ST_Other) {
  1401. uint64_t Address = cantFail(Symbol.getValue());
  1402. StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
  1403. if (!SymName.startswith(".objc"))
  1404. (*AddrMap)[Address] = SymName;
  1405. }
  1406. }
  1407. }
  1408. // GuessSymbolName is passed the address of what might be a symbol and a
  1409. // pointer to the SymbolAddressMap. It returns the name of a symbol
  1410. // with that address or nullptr if no symbol is found with that address.
  1411. static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
  1412. const char *SymbolName = nullptr;
  1413. // A DenseMap can't lookup up some values.
  1414. if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
  1415. StringRef name = AddrMap->lookup(value);
  1416. if (!name.empty())
  1417. SymbolName = name.data();
  1418. }
  1419. return SymbolName;
  1420. }
  1421. static void DumpCstringChar(const char c) {
  1422. char p[2];
  1423. p[0] = c;
  1424. p[1] = '\0';
  1425. outs().write_escaped(p);
  1426. }
  1427. static void DumpCstringSection(MachOObjectFile *O, const char *sect,
  1428. uint32_t sect_size, uint64_t sect_addr,
  1429. bool print_addresses) {
  1430. for (uint32_t i = 0; i < sect_size; i++) {
  1431. if (print_addresses) {
  1432. if (O->is64Bit())
  1433. outs() << format("%016" PRIx64, sect_addr + i) << " ";
  1434. else
  1435. outs() << format("%08" PRIx64, sect_addr + i) << " ";
  1436. }
  1437. for (; i < sect_size && sect[i] != '\0'; i++)
  1438. DumpCstringChar(sect[i]);
  1439. if (i < sect_size && sect[i] == '\0')
  1440. outs() << "\n";
  1441. }
  1442. }
  1443. static void DumpLiteral4(uint32_t l, float f) {
  1444. outs() << format("0x%08" PRIx32, l);
  1445. if ((l & 0x7f800000) != 0x7f800000)
  1446. outs() << format(" (%.16e)\n", f);
  1447. else {
  1448. if (l == 0x7f800000)
  1449. outs() << " (+Infinity)\n";
  1450. else if (l == 0xff800000)
  1451. outs() << " (-Infinity)\n";
  1452. else if ((l & 0x00400000) == 0x00400000)
  1453. outs() << " (non-signaling Not-a-Number)\n";
  1454. else
  1455. outs() << " (signaling Not-a-Number)\n";
  1456. }
  1457. }
  1458. static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
  1459. uint32_t sect_size, uint64_t sect_addr,
  1460. bool print_addresses) {
  1461. for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
  1462. if (print_addresses) {
  1463. if (O->is64Bit())
  1464. outs() << format("%016" PRIx64, sect_addr + i) << " ";
  1465. else
  1466. outs() << format("%08" PRIx64, sect_addr + i) << " ";
  1467. }
  1468. float f;
  1469. memcpy(&f, sect + i, sizeof(float));
  1470. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1471. sys::swapByteOrder(f);
  1472. uint32_t l;
  1473. memcpy(&l, sect + i, sizeof(uint32_t));
  1474. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1475. sys::swapByteOrder(l);
  1476. DumpLiteral4(l, f);
  1477. }
  1478. }
  1479. static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
  1480. double d) {
  1481. outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
  1482. uint32_t Hi, Lo;
  1483. Hi = (O->isLittleEndian()) ? l1 : l0;
  1484. Lo = (O->isLittleEndian()) ? l0 : l1;
  1485. // Hi is the high word, so this is equivalent to if(isfinite(d))
  1486. if ((Hi & 0x7ff00000) != 0x7ff00000)
  1487. outs() << format(" (%.16e)\n", d);
  1488. else {
  1489. if (Hi == 0x7ff00000 && Lo == 0)
  1490. outs() << " (+Infinity)\n";
  1491. else if (Hi == 0xfff00000 && Lo == 0)
  1492. outs() << " (-Infinity)\n";
  1493. else if ((Hi & 0x00080000) == 0x00080000)
  1494. outs() << " (non-signaling Not-a-Number)\n";
  1495. else
  1496. outs() << " (signaling Not-a-Number)\n";
  1497. }
  1498. }
  1499. static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
  1500. uint32_t sect_size, uint64_t sect_addr,
  1501. bool print_addresses) {
  1502. for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
  1503. if (print_addresses) {
  1504. if (O->is64Bit())
  1505. outs() << format("%016" PRIx64, sect_addr + i) << " ";
  1506. else
  1507. outs() << format("%08" PRIx64, sect_addr + i) << " ";
  1508. }
  1509. double d;
  1510. memcpy(&d, sect + i, sizeof(double));
  1511. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1512. sys::swapByteOrder(d);
  1513. uint32_t l0, l1;
  1514. memcpy(&l0, sect + i, sizeof(uint32_t));
  1515. memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
  1516. if (O->isLittleEndian() != sys::IsLittleEndianHost) {
  1517. sys::swapByteOrder(l0);
  1518. sys::swapByteOrder(l1);
  1519. }
  1520. DumpLiteral8(O, l0, l1, d);
  1521. }
  1522. }
  1523. static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
  1524. outs() << format("0x%08" PRIx32, l0) << " ";
  1525. outs() << format("0x%08" PRIx32, l1) << " ";
  1526. outs() << format("0x%08" PRIx32, l2) << " ";
  1527. outs() << format("0x%08" PRIx32, l3) << "\n";
  1528. }
  1529. static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
  1530. uint32_t sect_size, uint64_t sect_addr,
  1531. bool print_addresses) {
  1532. for (uint32_t i = 0; i < sect_size; i += 16) {
  1533. if (print_addresses) {
  1534. if (O->is64Bit())
  1535. outs() << format("%016" PRIx64, sect_addr + i) << " ";
  1536. else
  1537. outs() << format("%08" PRIx64, sect_addr + i) << " ";
  1538. }
  1539. uint32_t l0, l1, l2, l3;
  1540. memcpy(&l0, sect + i, sizeof(uint32_t));
  1541. memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
  1542. memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
  1543. memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
  1544. if (O->isLittleEndian() != sys::IsLittleEndianHost) {
  1545. sys::swapByteOrder(l0);
  1546. sys::swapByteOrder(l1);
  1547. sys::swapByteOrder(l2);
  1548. sys::swapByteOrder(l3);
  1549. }
  1550. DumpLiteral16(l0, l1, l2, l3);
  1551. }
  1552. }
  1553. static void DumpLiteralPointerSection(MachOObjectFile *O,
  1554. const SectionRef &Section,
  1555. const char *sect, uint32_t sect_size,
  1556. uint64_t sect_addr,
  1557. bool print_addresses) {
  1558. // Collect the literal sections in this Mach-O file.
  1559. std::vector<SectionRef> LiteralSections;
  1560. for (const SectionRef &Section : O->sections()) {
  1561. DataRefImpl Ref = Section.getRawDataRefImpl();
  1562. uint32_t section_type;
  1563. if (O->is64Bit()) {
  1564. const MachO::section_64 Sec = O->getSection64(Ref);
  1565. section_type = Sec.flags & MachO::SECTION_TYPE;
  1566. } else {
  1567. const MachO::section Sec = O->getSection(Ref);
  1568. section_type = Sec.flags & MachO::SECTION_TYPE;
  1569. }
  1570. if (section_type == MachO::S_CSTRING_LITERALS ||
  1571. section_type == MachO::S_4BYTE_LITERALS ||
  1572. section_type == MachO::S_8BYTE_LITERALS ||
  1573. section_type == MachO::S_16BYTE_LITERALS)
  1574. LiteralSections.push_back(Section);
  1575. }
  1576. // Set the size of the literal pointer.
  1577. uint32_t lp_size = O->is64Bit() ? 8 : 4;
  1578. // Collect the external relocation symbols for the literal pointers.
  1579. std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
  1580. for (const RelocationRef &Reloc : Section.relocations()) {
  1581. DataRefImpl Rel;
  1582. MachO::any_relocation_info RE;
  1583. bool isExtern = false;
  1584. Rel = Reloc.getRawDataRefImpl();
  1585. RE = O->getRelocation(Rel);
  1586. isExtern = O->getPlainRelocationExternal(RE);
  1587. if (isExtern) {
  1588. uint64_t RelocOffset = Reloc.getOffset();
  1589. symbol_iterator RelocSym = Reloc.getSymbol();
  1590. Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
  1591. }
  1592. }
  1593. array_pod_sort(Relocs.begin(), Relocs.end());
  1594. // Dump each literal pointer.
  1595. for (uint32_t i = 0; i < sect_size; i += lp_size) {
  1596. if (print_addresses) {
  1597. if (O->is64Bit())
  1598. outs() << format("%016" PRIx64, sect_addr + i) << " ";
  1599. else
  1600. outs() << format("%08" PRIx64, sect_addr + i) << " ";
  1601. }
  1602. uint64_t lp;
  1603. if (O->is64Bit()) {
  1604. memcpy(&lp, sect + i, sizeof(uint64_t));
  1605. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1606. sys::swapByteOrder(lp);
  1607. } else {
  1608. uint32_t li;
  1609. memcpy(&li, sect + i, sizeof(uint32_t));
  1610. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1611. sys::swapByteOrder(li);
  1612. lp = li;
  1613. }
  1614. // First look for an external relocation entry for this literal pointer.
  1615. auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
  1616. return P.first == i;
  1617. });
  1618. if (Reloc != Relocs.end()) {
  1619. symbol_iterator RelocSym = Reloc->second;
  1620. StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
  1621. outs() << "external relocation entry for symbol:" << SymName << "\n";
  1622. continue;
  1623. }
  1624. // For local references see what the section the literal pointer points to.
  1625. auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
  1626. return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
  1627. });
  1628. if (Sect == LiteralSections.end()) {
  1629. outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
  1630. continue;
  1631. }
  1632. uint64_t SectAddress = Sect->getAddress();
  1633. uint64_t SectSize = Sect->getSize();
  1634. StringRef SectName;
  1635. Expected<StringRef> SectNameOrErr = Sect->getName();
  1636. if (SectNameOrErr)
  1637. SectName = *SectNameOrErr;
  1638. else
  1639. consumeError(SectNameOrErr.takeError());
  1640. DataRefImpl Ref = Sect->getRawDataRefImpl();
  1641. StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
  1642. outs() << SegmentName << ":" << SectName << ":";
  1643. uint32_t section_type;
  1644. if (O->is64Bit()) {
  1645. const MachO::section_64 Sec = O->getSection64(Ref);
  1646. section_type = Sec.flags & MachO::SECTION_TYPE;
  1647. } else {
  1648. const MachO::section Sec = O->getSection(Ref);
  1649. section_type = Sec.flags & MachO::SECTION_TYPE;
  1650. }
  1651. StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName());
  1652. const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
  1653. switch (section_type) {
  1654. case MachO::S_CSTRING_LITERALS:
  1655. for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
  1656. i++) {
  1657. DumpCstringChar(Contents[i]);
  1658. }
  1659. outs() << "\n";
  1660. break;
  1661. case MachO::S_4BYTE_LITERALS:
  1662. float f;
  1663. memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
  1664. uint32_t l;
  1665. memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
  1666. if (O->isLittleEndian() != sys::IsLittleEndianHost) {
  1667. sys::swapByteOrder(f);
  1668. sys::swapByteOrder(l);
  1669. }
  1670. DumpLiteral4(l, f);
  1671. break;
  1672. case MachO::S_8BYTE_LITERALS: {
  1673. double d;
  1674. memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
  1675. uint32_t l0, l1;
  1676. memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
  1677. memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
  1678. sizeof(uint32_t));
  1679. if (O->isLittleEndian() != sys::IsLittleEndianHost) {
  1680. sys::swapByteOrder(f);
  1681. sys::swapByteOrder(l0);
  1682. sys::swapByteOrder(l1);
  1683. }
  1684. DumpLiteral8(O, l0, l1, d);
  1685. break;
  1686. }
  1687. case MachO::S_16BYTE_LITERALS: {
  1688. uint32_t l0, l1, l2, l3;
  1689. memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
  1690. memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
  1691. sizeof(uint32_t));
  1692. memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
  1693. sizeof(uint32_t));
  1694. memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
  1695. sizeof(uint32_t));
  1696. if (O->isLittleEndian() != sys::IsLittleEndianHost) {
  1697. sys::swapByteOrder(l0);
  1698. sys::swapByteOrder(l1);
  1699. sys::swapByteOrder(l2);
  1700. sys::swapByteOrder(l3);
  1701. }
  1702. DumpLiteral16(l0, l1, l2, l3);
  1703. break;
  1704. }
  1705. }
  1706. }
  1707. }
  1708. static void DumpInitTermPointerSection(MachOObjectFile *O,
  1709. const SectionRef &Section,
  1710. const char *sect,
  1711. uint32_t sect_size, uint64_t sect_addr,
  1712. SymbolAddressMap *AddrMap,
  1713. bool verbose) {
  1714. uint32_t stride;
  1715. stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
  1716. // Collect the external relocation symbols for the pointers.
  1717. std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
  1718. for (const RelocationRef &Reloc : Section.relocations()) {
  1719. DataRefImpl Rel;
  1720. MachO::any_relocation_info RE;
  1721. bool isExtern = false;
  1722. Rel = Reloc.getRawDataRefImpl();
  1723. RE = O->getRelocation(Rel);
  1724. isExtern = O->getPlainRelocationExternal(RE);
  1725. if (isExtern) {
  1726. uint64_t RelocOffset = Reloc.getOffset();
  1727. symbol_iterator RelocSym = Reloc.getSymbol();
  1728. Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
  1729. }
  1730. }
  1731. array_pod_sort(Relocs.begin(), Relocs.end());
  1732. for (uint32_t i = 0; i < sect_size; i += stride) {
  1733. const char *SymbolName = nullptr;
  1734. uint64_t p;
  1735. if (O->is64Bit()) {
  1736. outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
  1737. uint64_t pointer_value;
  1738. memcpy(&pointer_value, sect + i, stride);
  1739. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1740. sys::swapByteOrder(pointer_value);
  1741. outs() << format("0x%016" PRIx64, pointer_value);
  1742. p = pointer_value;
  1743. } else {
  1744. outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
  1745. uint32_t pointer_value;
  1746. memcpy(&pointer_value, sect + i, stride);
  1747. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1748. sys::swapByteOrder(pointer_value);
  1749. outs() << format("0x%08" PRIx32, pointer_value);
  1750. p = pointer_value;
  1751. }
  1752. if (verbose) {
  1753. // First look for an external relocation entry for this pointer.
  1754. auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
  1755. return P.first == i;
  1756. });
  1757. if (Reloc != Relocs.end()) {
  1758. symbol_iterator RelocSym = Reloc->second;
  1759. outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
  1760. } else {
  1761. SymbolName = GuessSymbolName(p, AddrMap);
  1762. if (SymbolName)
  1763. outs() << " " << SymbolName;
  1764. }
  1765. }
  1766. outs() << "\n";
  1767. }
  1768. }
  1769. static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
  1770. uint32_t size, uint64_t addr) {
  1771. uint32_t cputype = O->getHeader().cputype;
  1772. if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
  1773. uint32_t j;
  1774. for (uint32_t i = 0; i < size; i += j, addr += j) {
  1775. if (O->is64Bit())
  1776. outs() << format("%016" PRIx64, addr) << "\t";
  1777. else
  1778. outs() << format("%08" PRIx64, addr) << "\t";
  1779. for (j = 0; j < 16 && i + j < size; j++) {
  1780. uint8_t byte_word = *(sect + i + j);
  1781. outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
  1782. }
  1783. outs() << "\n";
  1784. }
  1785. } else {
  1786. uint32_t j;
  1787. for (uint32_t i = 0; i < size; i += j, addr += j) {
  1788. if (O->is64Bit())
  1789. outs() << format("%016" PRIx64, addr) << "\t";
  1790. else
  1791. outs() << format("%08" PRIx64, addr) << "\t";
  1792. for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
  1793. j += sizeof(int32_t)) {
  1794. if (i + j + sizeof(int32_t) <= size) {
  1795. uint32_t long_word;
  1796. memcpy(&long_word, sect + i + j, sizeof(int32_t));
  1797. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1798. sys::swapByteOrder(long_word);
  1799. outs() << format("%08" PRIx32, long_word) << " ";
  1800. } else {
  1801. for (uint32_t k = 0; i + j + k < size; k++) {
  1802. uint8_t byte_word = *(sect + i + j + k);
  1803. outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
  1804. }
  1805. }
  1806. }
  1807. outs() << "\n";
  1808. }
  1809. }
  1810. }
  1811. static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
  1812. StringRef DisSegName, StringRef DisSectName);
  1813. static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
  1814. uint32_t size, uint32_t addr);
  1815. #ifdef LLVM_HAVE_LIBXAR
  1816. static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
  1817. uint32_t size, bool verbose,
  1818. bool PrintXarHeader, bool PrintXarFileHeaders,
  1819. std::string XarMemberName);
  1820. #endif // defined(LLVM_HAVE_LIBXAR)
  1821. static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
  1822. bool verbose) {
  1823. SymbolAddressMap AddrMap;
  1824. if (verbose)
  1825. CreateSymbolAddressMap(O, &AddrMap);
  1826. for (unsigned i = 0; i < FilterSections.size(); ++i) {
  1827. StringRef DumpSection = FilterSections[i];
  1828. std::pair<StringRef, StringRef> DumpSegSectName;
  1829. DumpSegSectName = DumpSection.split(',');
  1830. StringRef DumpSegName, DumpSectName;
  1831. if (!DumpSegSectName.second.empty()) {
  1832. DumpSegName = DumpSegSectName.first;
  1833. DumpSectName = DumpSegSectName.second;
  1834. } else {
  1835. DumpSegName = "";
  1836. DumpSectName = DumpSegSectName.first;
  1837. }
  1838. for (const SectionRef &Section : O->sections()) {
  1839. StringRef SectName;
  1840. Expected<StringRef> SecNameOrErr = Section.getName();
  1841. if (SecNameOrErr)
  1842. SectName = *SecNameOrErr;
  1843. else
  1844. consumeError(SecNameOrErr.takeError());
  1845. if (!DumpSection.empty())
  1846. FoundSectionSet.insert(DumpSection);
  1847. DataRefImpl Ref = Section.getRawDataRefImpl();
  1848. StringRef SegName = O->getSectionFinalSegmentName(Ref);
  1849. if ((DumpSegName.empty() || SegName == DumpSegName) &&
  1850. (SectName == DumpSectName)) {
  1851. uint32_t section_flags;
  1852. if (O->is64Bit()) {
  1853. const MachO::section_64 Sec = O->getSection64(Ref);
  1854. section_flags = Sec.flags;
  1855. } else {
  1856. const MachO::section Sec = O->getSection(Ref);
  1857. section_flags = Sec.flags;
  1858. }
  1859. uint32_t section_type = section_flags & MachO::SECTION_TYPE;
  1860. StringRef BytesStr =
  1861. unwrapOrError(Section.getContents(), O->getFileName());
  1862. const char *sect = reinterpret_cast<const char *>(BytesStr.data());
  1863. uint32_t sect_size = BytesStr.size();
  1864. uint64_t sect_addr = Section.getAddress();
  1865. if (LeadingHeaders)
  1866. outs() << "Contents of (" << SegName << "," << SectName
  1867. << ") section\n";
  1868. if (verbose) {
  1869. if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
  1870. (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
  1871. DisassembleMachO(Filename, O, SegName, SectName);
  1872. continue;
  1873. }
  1874. if (SegName == "__TEXT" && SectName == "__info_plist") {
  1875. outs() << sect;
  1876. continue;
  1877. }
  1878. if (SegName == "__OBJC" && SectName == "__protocol") {
  1879. DumpProtocolSection(O, sect, sect_size, sect_addr);
  1880. continue;
  1881. }
  1882. #ifdef LLVM_HAVE_LIBXAR
  1883. if (SegName == "__LLVM" && SectName == "__bundle") {
  1884. DumpBitcodeSection(O, sect, sect_size, verbose, SymbolicOperands,
  1885. ArchiveHeaders, "");
  1886. continue;
  1887. }
  1888. #endif // defined(LLVM_HAVE_LIBXAR)
  1889. switch (section_type) {
  1890. case MachO::S_REGULAR:
  1891. DumpRawSectionContents(O, sect, sect_size, sect_addr);
  1892. break;
  1893. case MachO::S_ZEROFILL:
  1894. outs() << "zerofill section and has no contents in the file\n";
  1895. break;
  1896. case MachO::S_CSTRING_LITERALS:
  1897. DumpCstringSection(O, sect, sect_size, sect_addr, LeadingAddr);
  1898. break;
  1899. case MachO::S_4BYTE_LITERALS:
  1900. DumpLiteral4Section(O, sect, sect_size, sect_addr, LeadingAddr);
  1901. break;
  1902. case MachO::S_8BYTE_LITERALS:
  1903. DumpLiteral8Section(O, sect, sect_size, sect_addr, LeadingAddr);
  1904. break;
  1905. case MachO::S_16BYTE_LITERALS:
  1906. DumpLiteral16Section(O, sect, sect_size, sect_addr, LeadingAddr);
  1907. break;
  1908. case MachO::S_LITERAL_POINTERS:
  1909. DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
  1910. LeadingAddr);
  1911. break;
  1912. case MachO::S_MOD_INIT_FUNC_POINTERS:
  1913. case MachO::S_MOD_TERM_FUNC_POINTERS:
  1914. DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
  1915. &AddrMap, verbose);
  1916. break;
  1917. default:
  1918. outs() << "Unknown section type ("
  1919. << format("0x%08" PRIx32, section_type) << ")\n";
  1920. DumpRawSectionContents(O, sect, sect_size, sect_addr);
  1921. break;
  1922. }
  1923. } else {
  1924. if (section_type == MachO::S_ZEROFILL)
  1925. outs() << "zerofill section and has no contents in the file\n";
  1926. else
  1927. DumpRawSectionContents(O, sect, sect_size, sect_addr);
  1928. }
  1929. }
  1930. }
  1931. }
  1932. }
  1933. static void DumpInfoPlistSectionContents(StringRef Filename,
  1934. MachOObjectFile *O) {
  1935. for (const SectionRef &Section : O->sections()) {
  1936. StringRef SectName;
  1937. Expected<StringRef> SecNameOrErr = Section.getName();
  1938. if (SecNameOrErr)
  1939. SectName = *SecNameOrErr;
  1940. else
  1941. consumeError(SecNameOrErr.takeError());
  1942. DataRefImpl Ref = Section.getRawDataRefImpl();
  1943. StringRef SegName = O->getSectionFinalSegmentName(Ref);
  1944. if (SegName == "__TEXT" && SectName == "__info_plist") {
  1945. if (LeadingHeaders)
  1946. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  1947. StringRef BytesStr =
  1948. unwrapOrError(Section.getContents(), O->getFileName());
  1949. const char *sect = reinterpret_cast<const char *>(BytesStr.data());
  1950. outs() << format("%.*s", BytesStr.size(), sect) << "\n";
  1951. return;
  1952. }
  1953. }
  1954. }
  1955. // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
  1956. // and if it is and there is a list of architecture flags is specified then
  1957. // check to make sure this Mach-O file is one of those architectures or all
  1958. // architectures were specified. If not then an error is generated and this
  1959. // routine returns false. Else it returns true.
  1960. static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
  1961. auto *MachO = dyn_cast<MachOObjectFile>(O);
  1962. if (!MachO || ArchAll || ArchFlags.empty())
  1963. return true;
  1964. MachO::mach_header H;
  1965. MachO::mach_header_64 H_64;
  1966. Triple T;
  1967. const char *McpuDefault, *ArchFlag;
  1968. if (MachO->is64Bit()) {
  1969. H_64 = MachO->MachOObjectFile::getHeader64();
  1970. T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
  1971. &McpuDefault, &ArchFlag);
  1972. } else {
  1973. H = MachO->MachOObjectFile::getHeader();
  1974. T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
  1975. &McpuDefault, &ArchFlag);
  1976. }
  1977. const std::string ArchFlagName(ArchFlag);
  1978. if (!llvm::is_contained(ArchFlags, ArchFlagName)) {
  1979. WithColor::error(errs(), "llvm-objdump")
  1980. << Filename << ": no architecture specified.\n";
  1981. return false;
  1982. }
  1983. return true;
  1984. }
  1985. static void printObjcMetaData(MachOObjectFile *O, bool verbose);
  1986. // ProcessMachO() is passed a single opened Mach-O file, which may be an
  1987. // archive member and or in a slice of a universal file. It prints the
  1988. // the file name and header info and then processes it according to the
  1989. // command line options.
  1990. static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
  1991. StringRef ArchiveMemberName = StringRef(),
  1992. StringRef ArchitectureName = StringRef()) {
  1993. // If we are doing some processing here on the Mach-O file print the header
  1994. // info. And don't print it otherwise like in the case of printing the
  1995. // UniversalHeaders or ArchiveHeaders.
  1996. if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
  1997. Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
  1998. DataInCode || FunctionStartsType != FunctionStartsMode::None ||
  1999. LinkOptHints || ChainedFixups || DyldInfo || DylibsUsed || DylibId ||
  2000. Rpaths || ObjcMetaData || (!FilterSections.empty())) {
  2001. if (LeadingHeaders) {
  2002. outs() << Name;
  2003. if (!ArchiveMemberName.empty())
  2004. outs() << '(' << ArchiveMemberName << ')';
  2005. if (!ArchitectureName.empty())
  2006. outs() << " (architecture " << ArchitectureName << ")";
  2007. outs() << ":\n";
  2008. }
  2009. }
  2010. // To use the report_error() form with an ArchiveName and FileName set
  2011. // these up based on what is passed for Name and ArchiveMemberName.
  2012. StringRef ArchiveName;
  2013. StringRef FileName;
  2014. if (!ArchiveMemberName.empty()) {
  2015. ArchiveName = Name;
  2016. FileName = ArchiveMemberName;
  2017. } else {
  2018. ArchiveName = StringRef();
  2019. FileName = Name;
  2020. }
  2021. // If we need the symbol table to do the operation then check it here to
  2022. // produce a good error message as to where the Mach-O file comes from in
  2023. // the error message.
  2024. if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
  2025. if (Error Err = MachOOF->checkSymbolTable())
  2026. reportError(std::move(Err), FileName, ArchiveName, ArchitectureName);
  2027. if (DisassembleAll) {
  2028. for (const SectionRef &Section : MachOOF->sections()) {
  2029. StringRef SectName;
  2030. if (Expected<StringRef> NameOrErr = Section.getName())
  2031. SectName = *NameOrErr;
  2032. else
  2033. consumeError(NameOrErr.takeError());
  2034. if (SectName.equals("__text")) {
  2035. DataRefImpl Ref = Section.getRawDataRefImpl();
  2036. StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
  2037. DisassembleMachO(FileName, MachOOF, SegName, SectName);
  2038. }
  2039. }
  2040. }
  2041. else if (Disassemble) {
  2042. if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
  2043. MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
  2044. DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
  2045. else
  2046. DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
  2047. }
  2048. if (IndirectSymbols)
  2049. PrintIndirectSymbols(MachOOF, Verbose);
  2050. if (DataInCode)
  2051. PrintDataInCodeTable(MachOOF, Verbose);
  2052. if (FunctionStartsType != FunctionStartsMode::None)
  2053. PrintFunctionStarts(MachOOF);
  2054. if (LinkOptHints)
  2055. PrintLinkOptHints(MachOOF);
  2056. if (Relocations)
  2057. PrintRelocations(MachOOF, Verbose);
  2058. if (SectionHeaders)
  2059. printSectionHeaders(*MachOOF);
  2060. if (SectionContents)
  2061. printSectionContents(MachOOF);
  2062. if (!FilterSections.empty())
  2063. DumpSectionContents(FileName, MachOOF, Verbose);
  2064. if (InfoPlist)
  2065. DumpInfoPlistSectionContents(FileName, MachOOF);
  2066. if (DyldInfo)
  2067. PrintDyldInfo(MachOOF);
  2068. if (ChainedFixups)
  2069. PrintChainedFixups(MachOOF);
  2070. if (DylibsUsed)
  2071. PrintDylibs(MachOOF, false);
  2072. if (DylibId)
  2073. PrintDylibs(MachOOF, true);
  2074. if (SymbolTable)
  2075. printSymbolTable(*MachOOF, ArchiveName, ArchitectureName);
  2076. if (UnwindInfo)
  2077. printMachOUnwindInfo(MachOOF);
  2078. if (PrivateHeaders) {
  2079. printMachOFileHeader(MachOOF);
  2080. printMachOLoadCommands(MachOOF);
  2081. }
  2082. if (FirstPrivateHeader)
  2083. printMachOFileHeader(MachOOF);
  2084. if (ObjcMetaData)
  2085. printObjcMetaData(MachOOF, Verbose);
  2086. if (ExportsTrie)
  2087. printExportsTrie(MachOOF);
  2088. if (Rebase)
  2089. printRebaseTable(MachOOF);
  2090. if (Rpaths)
  2091. printRpaths(MachOOF);
  2092. if (Bind)
  2093. printBindTable(MachOOF);
  2094. if (LazyBind)
  2095. printLazyBindTable(MachOOF);
  2096. if (WeakBind)
  2097. printWeakBindTable(MachOOF);
  2098. if (DwarfDumpType != DIDT_Null) {
  2099. std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
  2100. // Dump the complete DWARF structure.
  2101. DIDumpOptions DumpOpts;
  2102. DumpOpts.DumpType = DwarfDumpType;
  2103. DICtx->dump(outs(), DumpOpts);
  2104. }
  2105. }
  2106. // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
  2107. static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
  2108. outs() << " cputype (" << cputype << ")\n";
  2109. outs() << " cpusubtype (" << cpusubtype << ")\n";
  2110. }
  2111. // printCPUType() helps print_fat_headers by printing the cputype and
  2112. // pusubtype (symbolically for the one's it knows about).
  2113. static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
  2114. switch (cputype) {
  2115. case MachO::CPU_TYPE_I386:
  2116. switch (cpusubtype) {
  2117. case MachO::CPU_SUBTYPE_I386_ALL:
  2118. outs() << " cputype CPU_TYPE_I386\n";
  2119. outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
  2120. break;
  2121. default:
  2122. printUnknownCPUType(cputype, cpusubtype);
  2123. break;
  2124. }
  2125. break;
  2126. case MachO::CPU_TYPE_X86_64:
  2127. switch (cpusubtype) {
  2128. case MachO::CPU_SUBTYPE_X86_64_ALL:
  2129. outs() << " cputype CPU_TYPE_X86_64\n";
  2130. outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
  2131. break;
  2132. case MachO::CPU_SUBTYPE_X86_64_H:
  2133. outs() << " cputype CPU_TYPE_X86_64\n";
  2134. outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
  2135. break;
  2136. default:
  2137. printUnknownCPUType(cputype, cpusubtype);
  2138. break;
  2139. }
  2140. break;
  2141. case MachO::CPU_TYPE_ARM:
  2142. switch (cpusubtype) {
  2143. case MachO::CPU_SUBTYPE_ARM_ALL:
  2144. outs() << " cputype CPU_TYPE_ARM\n";
  2145. outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
  2146. break;
  2147. case MachO::CPU_SUBTYPE_ARM_V4T:
  2148. outs() << " cputype CPU_TYPE_ARM\n";
  2149. outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
  2150. break;
  2151. case MachO::CPU_SUBTYPE_ARM_V5TEJ:
  2152. outs() << " cputype CPU_TYPE_ARM\n";
  2153. outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
  2154. break;
  2155. case MachO::CPU_SUBTYPE_ARM_XSCALE:
  2156. outs() << " cputype CPU_TYPE_ARM\n";
  2157. outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
  2158. break;
  2159. case MachO::CPU_SUBTYPE_ARM_V6:
  2160. outs() << " cputype CPU_TYPE_ARM\n";
  2161. outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
  2162. break;
  2163. case MachO::CPU_SUBTYPE_ARM_V6M:
  2164. outs() << " cputype CPU_TYPE_ARM\n";
  2165. outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
  2166. break;
  2167. case MachO::CPU_SUBTYPE_ARM_V7:
  2168. outs() << " cputype CPU_TYPE_ARM\n";
  2169. outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
  2170. break;
  2171. case MachO::CPU_SUBTYPE_ARM_V7EM:
  2172. outs() << " cputype CPU_TYPE_ARM\n";
  2173. outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
  2174. break;
  2175. case MachO::CPU_SUBTYPE_ARM_V7K:
  2176. outs() << " cputype CPU_TYPE_ARM\n";
  2177. outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
  2178. break;
  2179. case MachO::CPU_SUBTYPE_ARM_V7M:
  2180. outs() << " cputype CPU_TYPE_ARM\n";
  2181. outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
  2182. break;
  2183. case MachO::CPU_SUBTYPE_ARM_V7S:
  2184. outs() << " cputype CPU_TYPE_ARM\n";
  2185. outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
  2186. break;
  2187. default:
  2188. printUnknownCPUType(cputype, cpusubtype);
  2189. break;
  2190. }
  2191. break;
  2192. case MachO::CPU_TYPE_ARM64:
  2193. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  2194. case MachO::CPU_SUBTYPE_ARM64_ALL:
  2195. outs() << " cputype CPU_TYPE_ARM64\n";
  2196. outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
  2197. break;
  2198. case MachO::CPU_SUBTYPE_ARM64_V8:
  2199. outs() << " cputype CPU_TYPE_ARM64\n";
  2200. outs() << " cpusubtype CPU_SUBTYPE_ARM64_V8\n";
  2201. break;
  2202. case MachO::CPU_SUBTYPE_ARM64E:
  2203. outs() << " cputype CPU_TYPE_ARM64\n";
  2204. outs() << " cpusubtype CPU_SUBTYPE_ARM64E\n";
  2205. break;
  2206. default:
  2207. printUnknownCPUType(cputype, cpusubtype);
  2208. break;
  2209. }
  2210. break;
  2211. case MachO::CPU_TYPE_ARM64_32:
  2212. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  2213. case MachO::CPU_SUBTYPE_ARM64_32_V8:
  2214. outs() << " cputype CPU_TYPE_ARM64_32\n";
  2215. outs() << " cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
  2216. break;
  2217. default:
  2218. printUnknownCPUType(cputype, cpusubtype);
  2219. break;
  2220. }
  2221. break;
  2222. default:
  2223. printUnknownCPUType(cputype, cpusubtype);
  2224. break;
  2225. }
  2226. }
  2227. static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
  2228. bool verbose) {
  2229. outs() << "Fat headers\n";
  2230. if (verbose) {
  2231. if (UB->getMagic() == MachO::FAT_MAGIC)
  2232. outs() << "fat_magic FAT_MAGIC\n";
  2233. else // UB->getMagic() == MachO::FAT_MAGIC_64
  2234. outs() << "fat_magic FAT_MAGIC_64\n";
  2235. } else
  2236. outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
  2237. uint32_t nfat_arch = UB->getNumberOfObjects();
  2238. StringRef Buf = UB->getData();
  2239. uint64_t size = Buf.size();
  2240. uint64_t big_size = sizeof(struct MachO::fat_header) +
  2241. nfat_arch * sizeof(struct MachO::fat_arch);
  2242. outs() << "nfat_arch " << UB->getNumberOfObjects();
  2243. if (nfat_arch == 0)
  2244. outs() << " (malformed, contains zero architecture types)\n";
  2245. else if (big_size > size)
  2246. outs() << " (malformed, architectures past end of file)\n";
  2247. else
  2248. outs() << "\n";
  2249. for (uint32_t i = 0; i < nfat_arch; ++i) {
  2250. MachOUniversalBinary::ObjectForArch OFA(UB, i);
  2251. uint32_t cputype = OFA.getCPUType();
  2252. uint32_t cpusubtype = OFA.getCPUSubType();
  2253. outs() << "architecture ";
  2254. for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
  2255. MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
  2256. uint32_t other_cputype = other_OFA.getCPUType();
  2257. uint32_t other_cpusubtype = other_OFA.getCPUSubType();
  2258. if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
  2259. (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
  2260. (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
  2261. outs() << "(illegal duplicate architecture) ";
  2262. break;
  2263. }
  2264. }
  2265. if (verbose) {
  2266. outs() << OFA.getArchFlagName() << "\n";
  2267. printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  2268. } else {
  2269. outs() << i << "\n";
  2270. outs() << " cputype " << cputype << "\n";
  2271. outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
  2272. << "\n";
  2273. }
  2274. if (verbose &&
  2275. (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
  2276. outs() << " capabilities CPU_SUBTYPE_LIB64\n";
  2277. else
  2278. outs() << " capabilities "
  2279. << format("0x%" PRIx32,
  2280. (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
  2281. outs() << " offset " << OFA.getOffset();
  2282. if (OFA.getOffset() > size)
  2283. outs() << " (past end of file)";
  2284. if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0)
  2285. outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
  2286. outs() << "\n";
  2287. outs() << " size " << OFA.getSize();
  2288. big_size = OFA.getOffset() + OFA.getSize();
  2289. if (big_size > size)
  2290. outs() << " (past end of file)";
  2291. outs() << "\n";
  2292. outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
  2293. << ")\n";
  2294. }
  2295. }
  2296. static void printArchiveChild(StringRef Filename, const Archive::Child &C,
  2297. size_t ChildIndex, bool verbose,
  2298. bool print_offset,
  2299. StringRef ArchitectureName = StringRef()) {
  2300. if (print_offset)
  2301. outs() << C.getChildOffset() << "\t";
  2302. sys::fs::perms Mode =
  2303. unwrapOrError(C.getAccessMode(), getFileNameForError(C, ChildIndex),
  2304. Filename, ArchitectureName);
  2305. if (verbose) {
  2306. // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
  2307. // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
  2308. outs() << "-";
  2309. outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
  2310. outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
  2311. outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
  2312. outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
  2313. outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
  2314. outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
  2315. outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
  2316. outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
  2317. outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
  2318. } else {
  2319. outs() << format("0%o ", Mode);
  2320. }
  2321. outs() << format("%3d/%-3d %5" PRId64 " ",
  2322. unwrapOrError(C.getUID(), getFileNameForError(C, ChildIndex),
  2323. Filename, ArchitectureName),
  2324. unwrapOrError(C.getGID(), getFileNameForError(C, ChildIndex),
  2325. Filename, ArchitectureName),
  2326. unwrapOrError(C.getRawSize(),
  2327. getFileNameForError(C, ChildIndex), Filename,
  2328. ArchitectureName));
  2329. StringRef RawLastModified = C.getRawLastModified();
  2330. if (verbose) {
  2331. unsigned Seconds;
  2332. if (RawLastModified.getAsInteger(10, Seconds))
  2333. outs() << "(date: \"" << RawLastModified
  2334. << "\" contains non-decimal chars) ";
  2335. else {
  2336. // Since cime(3) returns a 26 character string of the form:
  2337. // "Sun Sep 16 01:03:52 1973\n\0"
  2338. // just print 24 characters.
  2339. time_t t = Seconds;
  2340. outs() << format("%.24s ", ctime(&t));
  2341. }
  2342. } else {
  2343. outs() << RawLastModified << " ";
  2344. }
  2345. if (verbose) {
  2346. Expected<StringRef> NameOrErr = C.getName();
  2347. if (!NameOrErr) {
  2348. consumeError(NameOrErr.takeError());
  2349. outs() << unwrapOrError(C.getRawName(),
  2350. getFileNameForError(C, ChildIndex), Filename,
  2351. ArchitectureName)
  2352. << "\n";
  2353. } else {
  2354. StringRef Name = NameOrErr.get();
  2355. outs() << Name << "\n";
  2356. }
  2357. } else {
  2358. outs() << unwrapOrError(C.getRawName(), getFileNameForError(C, ChildIndex),
  2359. Filename, ArchitectureName)
  2360. << "\n";
  2361. }
  2362. }
  2363. static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
  2364. bool print_offset,
  2365. StringRef ArchitectureName = StringRef()) {
  2366. Error Err = Error::success();
  2367. size_t I = 0;
  2368. for (const auto &C : A->children(Err, false))
  2369. printArchiveChild(Filename, C, I++, verbose, print_offset,
  2370. ArchitectureName);
  2371. if (Err)
  2372. reportError(std::move(Err), Filename, "", ArchitectureName);
  2373. }
  2374. static bool ValidateArchFlags() {
  2375. // Check for -arch all and verifiy the -arch flags are valid.
  2376. for (unsigned i = 0; i < ArchFlags.size(); ++i) {
  2377. if (ArchFlags[i] == "all") {
  2378. ArchAll = true;
  2379. } else {
  2380. if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
  2381. WithColor::error(errs(), "llvm-objdump")
  2382. << "unknown architecture named '" + ArchFlags[i] +
  2383. "'for the -arch option\n";
  2384. return false;
  2385. }
  2386. }
  2387. }
  2388. return true;
  2389. }
  2390. // ParseInputMachO() parses the named Mach-O file in Filename and handles the
  2391. // -arch flags selecting just those slices as specified by them and also parses
  2392. // archive files. Then for each individual Mach-O file ProcessMachO() is
  2393. // called to process the file based on the command line options.
  2394. void objdump::parseInputMachO(StringRef Filename) {
  2395. if (!ValidateArchFlags())
  2396. return;
  2397. // Attempt to open the binary.
  2398. Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
  2399. if (!BinaryOrErr) {
  2400. if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
  2401. reportError(std::move(E), Filename);
  2402. else
  2403. outs() << Filename << ": is not an object file\n";
  2404. return;
  2405. }
  2406. Binary &Bin = *BinaryOrErr.get().getBinary();
  2407. if (Archive *A = dyn_cast<Archive>(&Bin)) {
  2408. outs() << "Archive : " << Filename << "\n";
  2409. if (ArchiveHeaders)
  2410. printArchiveHeaders(Filename, A, Verbose, ArchiveMemberOffsets);
  2411. Error Err = Error::success();
  2412. unsigned I = -1;
  2413. for (auto &C : A->children(Err)) {
  2414. ++I;
  2415. Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
  2416. if (!ChildOrErr) {
  2417. if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
  2418. reportError(std::move(E), getFileNameForError(C, I), Filename);
  2419. continue;
  2420. }
  2421. if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
  2422. if (!checkMachOAndArchFlags(O, Filename))
  2423. return;
  2424. ProcessMachO(Filename, O, O->getFileName());
  2425. }
  2426. }
  2427. if (Err)
  2428. reportError(std::move(Err), Filename);
  2429. return;
  2430. }
  2431. if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
  2432. parseInputMachO(UB);
  2433. return;
  2434. }
  2435. if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
  2436. if (!checkMachOAndArchFlags(O, Filename))
  2437. return;
  2438. if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
  2439. ProcessMachO(Filename, MachOOF);
  2440. else
  2441. WithColor::error(errs(), "llvm-objdump")
  2442. << Filename << "': "
  2443. << "object is not a Mach-O file type.\n";
  2444. return;
  2445. }
  2446. llvm_unreachable("Input object can't be invalid at this point");
  2447. }
  2448. void objdump::parseInputMachO(MachOUniversalBinary *UB) {
  2449. if (!ValidateArchFlags())
  2450. return;
  2451. auto Filename = UB->getFileName();
  2452. if (UniversalHeaders)
  2453. printMachOUniversalHeaders(UB, Verbose);
  2454. // If we have a list of architecture flags specified dump only those.
  2455. if (!ArchAll && !ArchFlags.empty()) {
  2456. // Look for a slice in the universal binary that matches each ArchFlag.
  2457. bool ArchFound;
  2458. for (unsigned i = 0; i < ArchFlags.size(); ++i) {
  2459. ArchFound = false;
  2460. for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
  2461. E = UB->end_objects();
  2462. I != E; ++I) {
  2463. if (ArchFlags[i] == I->getArchFlagName()) {
  2464. ArchFound = true;
  2465. Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
  2466. I->getAsObjectFile();
  2467. std::string ArchitectureName;
  2468. if (ArchFlags.size() > 1)
  2469. ArchitectureName = I->getArchFlagName();
  2470. if (ObjOrErr) {
  2471. ObjectFile &O = *ObjOrErr.get();
  2472. if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
  2473. ProcessMachO(Filename, MachOOF, "", ArchitectureName);
  2474. } else if (Error E = isNotObjectErrorInvalidFileType(
  2475. ObjOrErr.takeError())) {
  2476. reportError(std::move(E), "", Filename, ArchitectureName);
  2477. continue;
  2478. } else if (Expected<std::unique_ptr<Archive>> AOrErr =
  2479. I->getAsArchive()) {
  2480. std::unique_ptr<Archive> &A = *AOrErr;
  2481. outs() << "Archive : " << Filename;
  2482. if (!ArchitectureName.empty())
  2483. outs() << " (architecture " << ArchitectureName << ")";
  2484. outs() << "\n";
  2485. if (ArchiveHeaders)
  2486. printArchiveHeaders(Filename, A.get(), Verbose,
  2487. ArchiveMemberOffsets, ArchitectureName);
  2488. Error Err = Error::success();
  2489. unsigned I = -1;
  2490. for (auto &C : A->children(Err)) {
  2491. ++I;
  2492. Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
  2493. if (!ChildOrErr) {
  2494. if (Error E =
  2495. isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
  2496. reportError(std::move(E), getFileNameForError(C, I), Filename,
  2497. ArchitectureName);
  2498. continue;
  2499. }
  2500. if (MachOObjectFile *O =
  2501. dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
  2502. ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
  2503. }
  2504. if (Err)
  2505. reportError(std::move(Err), Filename);
  2506. } else {
  2507. consumeError(AOrErr.takeError());
  2508. reportError(Filename,
  2509. "Mach-O universal file for architecture " +
  2510. StringRef(I->getArchFlagName()) +
  2511. " is not a Mach-O file or an archive file");
  2512. }
  2513. }
  2514. }
  2515. if (!ArchFound) {
  2516. WithColor::error(errs(), "llvm-objdump")
  2517. << "file: " + Filename + " does not contain "
  2518. << "architecture: " + ArchFlags[i] + "\n";
  2519. return;
  2520. }
  2521. }
  2522. return;
  2523. }
  2524. // No architecture flags were specified so if this contains a slice that
  2525. // matches the host architecture dump only that.
  2526. if (!ArchAll) {
  2527. for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
  2528. E = UB->end_objects();
  2529. I != E; ++I) {
  2530. if (MachOObjectFile::getHostArch().getArchName() ==
  2531. I->getArchFlagName()) {
  2532. Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
  2533. std::string ArchiveName;
  2534. ArchiveName.clear();
  2535. if (ObjOrErr) {
  2536. ObjectFile &O = *ObjOrErr.get();
  2537. if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
  2538. ProcessMachO(Filename, MachOOF);
  2539. } else if (Error E =
  2540. isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
  2541. reportError(std::move(E), Filename);
  2542. } else if (Expected<std::unique_ptr<Archive>> AOrErr =
  2543. I->getAsArchive()) {
  2544. std::unique_ptr<Archive> &A = *AOrErr;
  2545. outs() << "Archive : " << Filename << "\n";
  2546. if (ArchiveHeaders)
  2547. printArchiveHeaders(Filename, A.get(), Verbose,
  2548. ArchiveMemberOffsets);
  2549. Error Err = Error::success();
  2550. unsigned I = -1;
  2551. for (auto &C : A->children(Err)) {
  2552. ++I;
  2553. Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
  2554. if (!ChildOrErr) {
  2555. if (Error E =
  2556. isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
  2557. reportError(std::move(E), getFileNameForError(C, I), Filename);
  2558. continue;
  2559. }
  2560. if (MachOObjectFile *O =
  2561. dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
  2562. ProcessMachO(Filename, O, O->getFileName());
  2563. }
  2564. if (Err)
  2565. reportError(std::move(Err), Filename);
  2566. } else {
  2567. consumeError(AOrErr.takeError());
  2568. reportError(Filename, "Mach-O universal file for architecture " +
  2569. StringRef(I->getArchFlagName()) +
  2570. " is not a Mach-O file or an archive file");
  2571. }
  2572. return;
  2573. }
  2574. }
  2575. }
  2576. // Either all architectures have been specified or none have been specified
  2577. // and this does not contain the host architecture so dump all the slices.
  2578. bool moreThanOneArch = UB->getNumberOfObjects() > 1;
  2579. for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
  2580. E = UB->end_objects();
  2581. I != E; ++I) {
  2582. Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
  2583. std::string ArchitectureName;
  2584. if (moreThanOneArch)
  2585. ArchitectureName = I->getArchFlagName();
  2586. if (ObjOrErr) {
  2587. ObjectFile &Obj = *ObjOrErr.get();
  2588. if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
  2589. ProcessMachO(Filename, MachOOF, "", ArchitectureName);
  2590. } else if (Error E =
  2591. isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
  2592. reportError(std::move(E), Filename, "", ArchitectureName);
  2593. } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
  2594. std::unique_ptr<Archive> &A = *AOrErr;
  2595. outs() << "Archive : " << Filename;
  2596. if (!ArchitectureName.empty())
  2597. outs() << " (architecture " << ArchitectureName << ")";
  2598. outs() << "\n";
  2599. if (ArchiveHeaders)
  2600. printArchiveHeaders(Filename, A.get(), Verbose, ArchiveMemberOffsets,
  2601. ArchitectureName);
  2602. Error Err = Error::success();
  2603. unsigned I = -1;
  2604. for (auto &C : A->children(Err)) {
  2605. ++I;
  2606. Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
  2607. if (!ChildOrErr) {
  2608. if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
  2609. reportError(std::move(E), getFileNameForError(C, I), Filename,
  2610. ArchitectureName);
  2611. continue;
  2612. }
  2613. if (MachOObjectFile *O =
  2614. dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
  2615. if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
  2616. ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
  2617. ArchitectureName);
  2618. }
  2619. }
  2620. if (Err)
  2621. reportError(std::move(Err), Filename);
  2622. } else {
  2623. consumeError(AOrErr.takeError());
  2624. reportError(Filename, "Mach-O universal file for architecture " +
  2625. StringRef(I->getArchFlagName()) +
  2626. " is not a Mach-O file or an archive file");
  2627. }
  2628. }
  2629. }
  2630. namespace {
  2631. // The block of info used by the Symbolizer call backs.
  2632. struct DisassembleInfo {
  2633. DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
  2634. std::vector<SectionRef> *Sections, bool verbose)
  2635. : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
  2636. bool verbose;
  2637. MachOObjectFile *O;
  2638. SectionRef S;
  2639. SymbolAddressMap *AddrMap;
  2640. std::vector<SectionRef> *Sections;
  2641. const char *class_name = nullptr;
  2642. const char *selector_name = nullptr;
  2643. std::unique_ptr<char[]> method = nullptr;
  2644. char *demangled_name = nullptr;
  2645. uint64_t adrp_addr = 0;
  2646. uint32_t adrp_inst = 0;
  2647. std::unique_ptr<SymbolAddressMap> bindtable;
  2648. uint32_t depth = 0;
  2649. };
  2650. } // namespace
  2651. // SymbolizerGetOpInfo() is the operand information call back function.
  2652. // This is called to get the symbolic information for operand(s) of an
  2653. // instruction when it is being done. This routine does this from
  2654. // the relocation information, symbol table, etc. That block of information
  2655. // is a pointer to the struct DisassembleInfo that was passed when the
  2656. // disassembler context was created and passed to back to here when
  2657. // called back by the disassembler for instruction operands that could have
  2658. // relocation information. The address of the instruction containing operand is
  2659. // at the Pc parameter. The immediate value the operand has is passed in
  2660. // op_info->Value and is at Offset past the start of the instruction and has a
  2661. // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
  2662. // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
  2663. // names and addends of the symbolic expression to add for the operand. The
  2664. // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
  2665. // information is returned then this function returns 1 else it returns 0.
  2666. static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
  2667. uint64_t OpSize, uint64_t InstSize, int TagType,
  2668. void *TagBuf) {
  2669. struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
  2670. struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
  2671. uint64_t value = op_info->Value;
  2672. // Make sure all fields returned are zero if we don't set them.
  2673. memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
  2674. op_info->Value = value;
  2675. // If the TagType is not the value 1 which it code knows about or if no
  2676. // verbose symbolic information is wanted then just return 0, indicating no
  2677. // information is being returned.
  2678. if (TagType != 1 || !info->verbose)
  2679. return 0;
  2680. unsigned int Arch = info->O->getArch();
  2681. if (Arch == Triple::x86) {
  2682. if (OpSize != 1 && OpSize != 2 && OpSize != 4 && OpSize != 0)
  2683. return 0;
  2684. if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
  2685. // TODO:
  2686. // Search the external relocation entries of a fully linked image
  2687. // (if any) for an entry that matches this segment offset.
  2688. // uint32_t seg_offset = (Pc + Offset);
  2689. return 0;
  2690. }
  2691. // In MH_OBJECT filetypes search the section's relocation entries (if any)
  2692. // for an entry for this section offset.
  2693. uint32_t sect_addr = info->S.getAddress();
  2694. uint32_t sect_offset = (Pc + Offset) - sect_addr;
  2695. bool reloc_found = false;
  2696. DataRefImpl Rel;
  2697. MachO::any_relocation_info RE;
  2698. bool isExtern = false;
  2699. SymbolRef Symbol;
  2700. bool r_scattered = false;
  2701. uint32_t r_value, pair_r_value, r_type;
  2702. for (const RelocationRef &Reloc : info->S.relocations()) {
  2703. uint64_t RelocOffset = Reloc.getOffset();
  2704. if (RelocOffset == sect_offset) {
  2705. Rel = Reloc.getRawDataRefImpl();
  2706. RE = info->O->getRelocation(Rel);
  2707. r_type = info->O->getAnyRelocationType(RE);
  2708. r_scattered = info->O->isRelocationScattered(RE);
  2709. if (r_scattered) {
  2710. r_value = info->O->getScatteredRelocationValue(RE);
  2711. if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
  2712. r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
  2713. DataRefImpl RelNext = Rel;
  2714. info->O->moveRelocationNext(RelNext);
  2715. MachO::any_relocation_info RENext;
  2716. RENext = info->O->getRelocation(RelNext);
  2717. if (info->O->isRelocationScattered(RENext))
  2718. pair_r_value = info->O->getScatteredRelocationValue(RENext);
  2719. else
  2720. return 0;
  2721. }
  2722. } else {
  2723. isExtern = info->O->getPlainRelocationExternal(RE);
  2724. if (isExtern) {
  2725. symbol_iterator RelocSym = Reloc.getSymbol();
  2726. Symbol = *RelocSym;
  2727. }
  2728. }
  2729. reloc_found = true;
  2730. break;
  2731. }
  2732. }
  2733. if (reloc_found && isExtern) {
  2734. op_info->AddSymbol.Present = 1;
  2735. op_info->AddSymbol.Name =
  2736. unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
  2737. // For i386 extern relocation entries the value in the instruction is
  2738. // the offset from the symbol, and value is already set in op_info->Value.
  2739. return 1;
  2740. }
  2741. if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
  2742. r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
  2743. const char *add = GuessSymbolName(r_value, info->AddrMap);
  2744. const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
  2745. uint32_t offset = value - (r_value - pair_r_value);
  2746. op_info->AddSymbol.Present = 1;
  2747. if (add != nullptr)
  2748. op_info->AddSymbol.Name = add;
  2749. else
  2750. op_info->AddSymbol.Value = r_value;
  2751. op_info->SubtractSymbol.Present = 1;
  2752. if (sub != nullptr)
  2753. op_info->SubtractSymbol.Name = sub;
  2754. else
  2755. op_info->SubtractSymbol.Value = pair_r_value;
  2756. op_info->Value = offset;
  2757. return 1;
  2758. }
  2759. return 0;
  2760. }
  2761. if (Arch == Triple::x86_64) {
  2762. if (OpSize != 1 && OpSize != 2 && OpSize != 4 && OpSize != 0)
  2763. return 0;
  2764. // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
  2765. // relocation entries of a linked image (if any) for an entry that matches
  2766. // this segment offset.
  2767. if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
  2768. uint64_t seg_offset = Pc + Offset;
  2769. bool reloc_found = false;
  2770. DataRefImpl Rel;
  2771. MachO::any_relocation_info RE;
  2772. bool isExtern = false;
  2773. SymbolRef Symbol;
  2774. for (const RelocationRef &Reloc : info->O->external_relocations()) {
  2775. uint64_t RelocOffset = Reloc.getOffset();
  2776. if (RelocOffset == seg_offset) {
  2777. Rel = Reloc.getRawDataRefImpl();
  2778. RE = info->O->getRelocation(Rel);
  2779. // external relocation entries should always be external.
  2780. isExtern = info->O->getPlainRelocationExternal(RE);
  2781. if (isExtern) {
  2782. symbol_iterator RelocSym = Reloc.getSymbol();
  2783. Symbol = *RelocSym;
  2784. }
  2785. reloc_found = true;
  2786. break;
  2787. }
  2788. }
  2789. if (reloc_found && isExtern) {
  2790. // The Value passed in will be adjusted by the Pc if the instruction
  2791. // adds the Pc. But for x86_64 external relocation entries the Value
  2792. // is the offset from the external symbol.
  2793. if (info->O->getAnyRelocationPCRel(RE))
  2794. op_info->Value -= Pc + InstSize;
  2795. const char *name =
  2796. unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
  2797. op_info->AddSymbol.Present = 1;
  2798. op_info->AddSymbol.Name = name;
  2799. return 1;
  2800. }
  2801. return 0;
  2802. }
  2803. // In MH_OBJECT filetypes search the section's relocation entries (if any)
  2804. // for an entry for this section offset.
  2805. uint64_t sect_addr = info->S.getAddress();
  2806. uint64_t sect_offset = (Pc + Offset) - sect_addr;
  2807. bool reloc_found = false;
  2808. DataRefImpl Rel;
  2809. MachO::any_relocation_info RE;
  2810. bool isExtern = false;
  2811. SymbolRef Symbol;
  2812. for (const RelocationRef &Reloc : info->S.relocations()) {
  2813. uint64_t RelocOffset = Reloc.getOffset();
  2814. if (RelocOffset == sect_offset) {
  2815. Rel = Reloc.getRawDataRefImpl();
  2816. RE = info->O->getRelocation(Rel);
  2817. // NOTE: Scattered relocations don't exist on x86_64.
  2818. isExtern = info->O->getPlainRelocationExternal(RE);
  2819. if (isExtern) {
  2820. symbol_iterator RelocSym = Reloc.getSymbol();
  2821. Symbol = *RelocSym;
  2822. }
  2823. reloc_found = true;
  2824. break;
  2825. }
  2826. }
  2827. if (reloc_found && isExtern) {
  2828. // The Value passed in will be adjusted by the Pc if the instruction
  2829. // adds the Pc. But for x86_64 external relocation entries the Value
  2830. // is the offset from the external symbol.
  2831. if (info->O->getAnyRelocationPCRel(RE))
  2832. op_info->Value -= Pc + InstSize;
  2833. const char *name =
  2834. unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
  2835. unsigned Type = info->O->getAnyRelocationType(RE);
  2836. if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
  2837. DataRefImpl RelNext = Rel;
  2838. info->O->moveRelocationNext(RelNext);
  2839. MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
  2840. unsigned TypeNext = info->O->getAnyRelocationType(RENext);
  2841. bool isExternNext = info->O->getPlainRelocationExternal(RENext);
  2842. unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
  2843. if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
  2844. op_info->SubtractSymbol.Present = 1;
  2845. op_info->SubtractSymbol.Name = name;
  2846. symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
  2847. Symbol = *RelocSymNext;
  2848. name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
  2849. }
  2850. }
  2851. // TODO: add the VariantKinds to op_info->VariantKind for relocation types
  2852. // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
  2853. op_info->AddSymbol.Present = 1;
  2854. op_info->AddSymbol.Name = name;
  2855. return 1;
  2856. }
  2857. return 0;
  2858. }
  2859. if (Arch == Triple::arm) {
  2860. if (Offset != 0 || (InstSize != 4 && InstSize != 2))
  2861. return 0;
  2862. if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
  2863. // TODO:
  2864. // Search the external relocation entries of a fully linked image
  2865. // (if any) for an entry that matches this segment offset.
  2866. // uint32_t seg_offset = (Pc + Offset);
  2867. return 0;
  2868. }
  2869. // In MH_OBJECT filetypes search the section's relocation entries (if any)
  2870. // for an entry for this section offset.
  2871. uint32_t sect_addr = info->S.getAddress();
  2872. uint32_t sect_offset = (Pc + Offset) - sect_addr;
  2873. DataRefImpl Rel;
  2874. MachO::any_relocation_info RE;
  2875. bool isExtern = false;
  2876. SymbolRef Symbol;
  2877. bool r_scattered = false;
  2878. uint32_t r_value, pair_r_value, r_type, r_length, other_half;
  2879. auto Reloc =
  2880. find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
  2881. uint64_t RelocOffset = Reloc.getOffset();
  2882. return RelocOffset == sect_offset;
  2883. });
  2884. if (Reloc == info->S.relocations().end())
  2885. return 0;
  2886. Rel = Reloc->getRawDataRefImpl();
  2887. RE = info->O->getRelocation(Rel);
  2888. r_length = info->O->getAnyRelocationLength(RE);
  2889. r_scattered = info->O->isRelocationScattered(RE);
  2890. if (r_scattered) {
  2891. r_value = info->O->getScatteredRelocationValue(RE);
  2892. r_type = info->O->getScatteredRelocationType(RE);
  2893. } else {
  2894. r_type = info->O->getAnyRelocationType(RE);
  2895. isExtern = info->O->getPlainRelocationExternal(RE);
  2896. if (isExtern) {
  2897. symbol_iterator RelocSym = Reloc->getSymbol();
  2898. Symbol = *RelocSym;
  2899. }
  2900. }
  2901. if (r_type == MachO::ARM_RELOC_HALF ||
  2902. r_type == MachO::ARM_RELOC_SECTDIFF ||
  2903. r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
  2904. r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
  2905. DataRefImpl RelNext = Rel;
  2906. info->O->moveRelocationNext(RelNext);
  2907. MachO::any_relocation_info RENext;
  2908. RENext = info->O->getRelocation(RelNext);
  2909. other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
  2910. if (info->O->isRelocationScattered(RENext))
  2911. pair_r_value = info->O->getScatteredRelocationValue(RENext);
  2912. }
  2913. if (isExtern) {
  2914. const char *name =
  2915. unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
  2916. op_info->AddSymbol.Present = 1;
  2917. op_info->AddSymbol.Name = name;
  2918. switch (r_type) {
  2919. case MachO::ARM_RELOC_HALF:
  2920. if ((r_length & 0x1) == 1) {
  2921. op_info->Value = value << 16 | other_half;
  2922. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
  2923. } else {
  2924. op_info->Value = other_half << 16 | value;
  2925. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
  2926. }
  2927. break;
  2928. default:
  2929. break;
  2930. }
  2931. return 1;
  2932. }
  2933. // If we have a branch that is not an external relocation entry then
  2934. // return 0 so the code in tryAddingSymbolicOperand() can use the
  2935. // SymbolLookUp call back with the branch target address to look up the
  2936. // symbol and possibility add an annotation for a symbol stub.
  2937. if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
  2938. r_type == MachO::ARM_THUMB_RELOC_BR22))
  2939. return 0;
  2940. uint32_t offset = 0;
  2941. if (r_type == MachO::ARM_RELOC_HALF ||
  2942. r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
  2943. if ((r_length & 0x1) == 1)
  2944. value = value << 16 | other_half;
  2945. else
  2946. value = other_half << 16 | value;
  2947. }
  2948. if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
  2949. r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
  2950. offset = value - r_value;
  2951. value = r_value;
  2952. }
  2953. if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
  2954. if ((r_length & 0x1) == 1)
  2955. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
  2956. else
  2957. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
  2958. const char *add = GuessSymbolName(r_value, info->AddrMap);
  2959. const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
  2960. int32_t offset = value - (r_value - pair_r_value);
  2961. op_info->AddSymbol.Present = 1;
  2962. if (add != nullptr)
  2963. op_info->AddSymbol.Name = add;
  2964. else
  2965. op_info->AddSymbol.Value = r_value;
  2966. op_info->SubtractSymbol.Present = 1;
  2967. if (sub != nullptr)
  2968. op_info->SubtractSymbol.Name = sub;
  2969. else
  2970. op_info->SubtractSymbol.Value = pair_r_value;
  2971. op_info->Value = offset;
  2972. return 1;
  2973. }
  2974. op_info->AddSymbol.Present = 1;
  2975. op_info->Value = offset;
  2976. if (r_type == MachO::ARM_RELOC_HALF) {
  2977. if ((r_length & 0x1) == 1)
  2978. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
  2979. else
  2980. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
  2981. }
  2982. const char *add = GuessSymbolName(value, info->AddrMap);
  2983. if (add != nullptr) {
  2984. op_info->AddSymbol.Name = add;
  2985. return 1;
  2986. }
  2987. op_info->AddSymbol.Value = value;
  2988. return 1;
  2989. }
  2990. if (Arch == Triple::aarch64) {
  2991. if (Offset != 0 || InstSize != 4)
  2992. return 0;
  2993. if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
  2994. // TODO:
  2995. // Search the external relocation entries of a fully linked image
  2996. // (if any) for an entry that matches this segment offset.
  2997. // uint64_t seg_offset = (Pc + Offset);
  2998. return 0;
  2999. }
  3000. // In MH_OBJECT filetypes search the section's relocation entries (if any)
  3001. // for an entry for this section offset.
  3002. uint64_t sect_addr = info->S.getAddress();
  3003. uint64_t sect_offset = (Pc + Offset) - sect_addr;
  3004. auto Reloc =
  3005. find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
  3006. uint64_t RelocOffset = Reloc.getOffset();
  3007. return RelocOffset == sect_offset;
  3008. });
  3009. if (Reloc == info->S.relocations().end())
  3010. return 0;
  3011. DataRefImpl Rel = Reloc->getRawDataRefImpl();
  3012. MachO::any_relocation_info RE = info->O->getRelocation(Rel);
  3013. uint32_t r_type = info->O->getAnyRelocationType(RE);
  3014. if (r_type == MachO::ARM64_RELOC_ADDEND) {
  3015. DataRefImpl RelNext = Rel;
  3016. info->O->moveRelocationNext(RelNext);
  3017. MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
  3018. if (value == 0) {
  3019. value = info->O->getPlainRelocationSymbolNum(RENext);
  3020. op_info->Value = value;
  3021. }
  3022. }
  3023. // NOTE: Scattered relocations don't exist on arm64.
  3024. if (!info->O->getPlainRelocationExternal(RE))
  3025. return 0;
  3026. const char *name =
  3027. unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
  3028. .data();
  3029. op_info->AddSymbol.Present = 1;
  3030. op_info->AddSymbol.Name = name;
  3031. switch (r_type) {
  3032. case MachO::ARM64_RELOC_PAGE21:
  3033. /* @page */
  3034. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
  3035. break;
  3036. case MachO::ARM64_RELOC_PAGEOFF12:
  3037. /* @pageoff */
  3038. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
  3039. break;
  3040. case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
  3041. /* @gotpage */
  3042. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
  3043. break;
  3044. case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
  3045. /* @gotpageoff */
  3046. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
  3047. break;
  3048. case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
  3049. /* @tvlppage is not implemented in llvm-mc */
  3050. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
  3051. break;
  3052. case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
  3053. /* @tvlppageoff is not implemented in llvm-mc */
  3054. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
  3055. break;
  3056. default:
  3057. case MachO::ARM64_RELOC_BRANCH26:
  3058. op_info->VariantKind = LLVMDisassembler_VariantKind_None;
  3059. break;
  3060. }
  3061. return 1;
  3062. }
  3063. return 0;
  3064. }
  3065. // GuessCstringPointer is passed the address of what might be a pointer to a
  3066. // literal string in a cstring section. If that address is in a cstring section
  3067. // it returns a pointer to that string. Else it returns nullptr.
  3068. static const char *GuessCstringPointer(uint64_t ReferenceValue,
  3069. struct DisassembleInfo *info) {
  3070. for (const auto &Load : info->O->load_commands()) {
  3071. if (Load.C.cmd == MachO::LC_SEGMENT_64) {
  3072. MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
  3073. for (unsigned J = 0; J < Seg.nsects; ++J) {
  3074. MachO::section_64 Sec = info->O->getSection64(Load, J);
  3075. uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
  3076. if (section_type == MachO::S_CSTRING_LITERALS &&
  3077. ReferenceValue >= Sec.addr &&
  3078. ReferenceValue < Sec.addr + Sec.size) {
  3079. uint64_t sect_offset = ReferenceValue - Sec.addr;
  3080. uint64_t object_offset = Sec.offset + sect_offset;
  3081. StringRef MachOContents = info->O->getData();
  3082. uint64_t object_size = MachOContents.size();
  3083. const char *object_addr = (const char *)MachOContents.data();
  3084. if (object_offset < object_size) {
  3085. const char *name = object_addr + object_offset;
  3086. return name;
  3087. } else {
  3088. return nullptr;
  3089. }
  3090. }
  3091. }
  3092. } else if (Load.C.cmd == MachO::LC_SEGMENT) {
  3093. MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
  3094. for (unsigned J = 0; J < Seg.nsects; ++J) {
  3095. MachO::section Sec = info->O->getSection(Load, J);
  3096. uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
  3097. if (section_type == MachO::S_CSTRING_LITERALS &&
  3098. ReferenceValue >= Sec.addr &&
  3099. ReferenceValue < Sec.addr + Sec.size) {
  3100. uint64_t sect_offset = ReferenceValue - Sec.addr;
  3101. uint64_t object_offset = Sec.offset + sect_offset;
  3102. StringRef MachOContents = info->O->getData();
  3103. uint64_t object_size = MachOContents.size();
  3104. const char *object_addr = (const char *)MachOContents.data();
  3105. if (object_offset < object_size) {
  3106. const char *name = object_addr + object_offset;
  3107. return name;
  3108. } else {
  3109. return nullptr;
  3110. }
  3111. }
  3112. }
  3113. }
  3114. }
  3115. return nullptr;
  3116. }
  3117. // GuessIndirectSymbol returns the name of the indirect symbol for the
  3118. // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
  3119. // an address of a symbol stub or a lazy or non-lazy pointer to associate the
  3120. // symbol name being referenced by the stub or pointer.
  3121. static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
  3122. struct DisassembleInfo *info) {
  3123. MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
  3124. MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
  3125. for (const auto &Load : info->O->load_commands()) {
  3126. if (Load.C.cmd == MachO::LC_SEGMENT_64) {
  3127. MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
  3128. for (unsigned J = 0; J < Seg.nsects; ++J) {
  3129. MachO::section_64 Sec = info->O->getSection64(Load, J);
  3130. uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
  3131. if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
  3132. section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
  3133. section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
  3134. section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
  3135. section_type == MachO::S_SYMBOL_STUBS) &&
  3136. ReferenceValue >= Sec.addr &&
  3137. ReferenceValue < Sec.addr + Sec.size) {
  3138. uint32_t stride;
  3139. if (section_type == MachO::S_SYMBOL_STUBS)
  3140. stride = Sec.reserved2;
  3141. else
  3142. stride = 8;
  3143. if (stride == 0)
  3144. return nullptr;
  3145. uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
  3146. if (index < Dysymtab.nindirectsyms) {
  3147. uint32_t indirect_symbol =
  3148. info->O->getIndirectSymbolTableEntry(Dysymtab, index);
  3149. if (indirect_symbol < Symtab.nsyms) {
  3150. symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
  3151. return unwrapOrError(Sym->getName(), info->O->getFileName())
  3152. .data();
  3153. }
  3154. }
  3155. }
  3156. }
  3157. } else if (Load.C.cmd == MachO::LC_SEGMENT) {
  3158. MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
  3159. for (unsigned J = 0; J < Seg.nsects; ++J) {
  3160. MachO::section Sec = info->O->getSection(Load, J);
  3161. uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
  3162. if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
  3163. section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
  3164. section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
  3165. section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
  3166. section_type == MachO::S_SYMBOL_STUBS) &&
  3167. ReferenceValue >= Sec.addr &&
  3168. ReferenceValue < Sec.addr + Sec.size) {
  3169. uint32_t stride;
  3170. if (section_type == MachO::S_SYMBOL_STUBS)
  3171. stride = Sec.reserved2;
  3172. else
  3173. stride = 4;
  3174. if (stride == 0)
  3175. return nullptr;
  3176. uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
  3177. if (index < Dysymtab.nindirectsyms) {
  3178. uint32_t indirect_symbol =
  3179. info->O->getIndirectSymbolTableEntry(Dysymtab, index);
  3180. if (indirect_symbol < Symtab.nsyms) {
  3181. symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
  3182. return unwrapOrError(Sym->getName(), info->O->getFileName())
  3183. .data();
  3184. }
  3185. }
  3186. }
  3187. }
  3188. }
  3189. }
  3190. return nullptr;
  3191. }
  3192. // method_reference() is called passing it the ReferenceName that might be
  3193. // a reference it to an Objective-C method call. If so then it allocates and
  3194. // assembles a method call string with the values last seen and saved in
  3195. // the DisassembleInfo's class_name and selector_name fields. This is saved
  3196. // into the method field of the info and any previous string is free'ed.
  3197. // Then the class_name field in the info is set to nullptr. The method call
  3198. // string is set into ReferenceName and ReferenceType is set to
  3199. // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
  3200. // then both ReferenceType and ReferenceName are left unchanged.
  3201. static void method_reference(struct DisassembleInfo *info,
  3202. uint64_t *ReferenceType,
  3203. const char **ReferenceName) {
  3204. unsigned int Arch = info->O->getArch();
  3205. if (*ReferenceName != nullptr) {
  3206. if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
  3207. if (info->selector_name != nullptr) {
  3208. if (info->class_name != nullptr) {
  3209. info->method = std::make_unique<char[]>(
  3210. 5 + strlen(info->class_name) + strlen(info->selector_name));
  3211. char *method = info->method.get();
  3212. if (method != nullptr) {
  3213. strcpy(method, "+[");
  3214. strcat(method, info->class_name);
  3215. strcat(method, " ");
  3216. strcat(method, info->selector_name);
  3217. strcat(method, "]");
  3218. *ReferenceName = method;
  3219. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
  3220. }
  3221. } else {
  3222. info->method =
  3223. std::make_unique<char[]>(9 + strlen(info->selector_name));
  3224. char *method = info->method.get();
  3225. if (method != nullptr) {
  3226. if (Arch == Triple::x86_64)
  3227. strcpy(method, "-[%rdi ");
  3228. else if (Arch == Triple::aarch64)
  3229. strcpy(method, "-[x0 ");
  3230. else
  3231. strcpy(method, "-[r? ");
  3232. strcat(method, info->selector_name);
  3233. strcat(method, "]");
  3234. *ReferenceName = method;
  3235. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
  3236. }
  3237. }
  3238. info->class_name = nullptr;
  3239. }
  3240. } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
  3241. if (info->selector_name != nullptr) {
  3242. info->method =
  3243. std::make_unique<char[]>(17 + strlen(info->selector_name));
  3244. char *method = info->method.get();
  3245. if (method != nullptr) {
  3246. if (Arch == Triple::x86_64)
  3247. strcpy(method, "-[[%rdi super] ");
  3248. else if (Arch == Triple::aarch64)
  3249. strcpy(method, "-[[x0 super] ");
  3250. else
  3251. strcpy(method, "-[[r? super] ");
  3252. strcat(method, info->selector_name);
  3253. strcat(method, "]");
  3254. *ReferenceName = method;
  3255. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
  3256. }
  3257. info->class_name = nullptr;
  3258. }
  3259. }
  3260. }
  3261. }
  3262. // GuessPointerPointer() is passed the address of what might be a pointer to
  3263. // a reference to an Objective-C class, selector, message ref or cfstring.
  3264. // If so the value of the pointer is returned and one of the booleans are set
  3265. // to true. If not zero is returned and all the booleans are set to false.
  3266. static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
  3267. struct DisassembleInfo *info,
  3268. bool &classref, bool &selref, bool &msgref,
  3269. bool &cfstring) {
  3270. classref = false;
  3271. selref = false;
  3272. msgref = false;
  3273. cfstring = false;
  3274. for (const auto &Load : info->O->load_commands()) {
  3275. if (Load.C.cmd == MachO::LC_SEGMENT_64) {
  3276. MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
  3277. for (unsigned J = 0; J < Seg.nsects; ++J) {
  3278. MachO::section_64 Sec = info->O->getSection64(Load, J);
  3279. if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
  3280. strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
  3281. strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
  3282. strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
  3283. strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
  3284. ReferenceValue >= Sec.addr &&
  3285. ReferenceValue < Sec.addr + Sec.size) {
  3286. uint64_t sect_offset = ReferenceValue - Sec.addr;
  3287. uint64_t object_offset = Sec.offset + sect_offset;
  3288. StringRef MachOContents = info->O->getData();
  3289. uint64_t object_size = MachOContents.size();
  3290. const char *object_addr = (const char *)MachOContents.data();
  3291. if (object_offset < object_size) {
  3292. uint64_t pointer_value;
  3293. memcpy(&pointer_value, object_addr + object_offset,
  3294. sizeof(uint64_t));
  3295. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3296. sys::swapByteOrder(pointer_value);
  3297. if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
  3298. selref = true;
  3299. else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
  3300. strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
  3301. classref = true;
  3302. else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
  3303. ReferenceValue + 8 < Sec.addr + Sec.size) {
  3304. msgref = true;
  3305. memcpy(&pointer_value, object_addr + object_offset + 8,
  3306. sizeof(uint64_t));
  3307. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3308. sys::swapByteOrder(pointer_value);
  3309. } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
  3310. cfstring = true;
  3311. return pointer_value;
  3312. } else {
  3313. return 0;
  3314. }
  3315. }
  3316. }
  3317. }
  3318. // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
  3319. }
  3320. return 0;
  3321. }
  3322. // get_pointer_64 returns a pointer to the bytes in the object file at the
  3323. // Address from a section in the Mach-O file. And indirectly returns the
  3324. // offset into the section, number of bytes left in the section past the offset
  3325. // and which section is was being referenced. If the Address is not in a
  3326. // section nullptr is returned.
  3327. static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
  3328. uint32_t &left, SectionRef &S,
  3329. DisassembleInfo *info,
  3330. bool objc_only = false) {
  3331. offset = 0;
  3332. left = 0;
  3333. S = SectionRef();
  3334. for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
  3335. uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
  3336. uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
  3337. if (SectSize == 0)
  3338. continue;
  3339. if (objc_only) {
  3340. StringRef SectName;
  3341. Expected<StringRef> SecNameOrErr =
  3342. ((*(info->Sections))[SectIdx]).getName();
  3343. if (SecNameOrErr)
  3344. SectName = *SecNameOrErr;
  3345. else
  3346. consumeError(SecNameOrErr.takeError());
  3347. DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
  3348. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  3349. if (SegName != "__OBJC" && SectName != "__cstring")
  3350. continue;
  3351. }
  3352. if (Address >= SectAddress && Address < SectAddress + SectSize) {
  3353. S = (*(info->Sections))[SectIdx];
  3354. offset = Address - SectAddress;
  3355. left = SectSize - offset;
  3356. StringRef SectContents = unwrapOrError(
  3357. ((*(info->Sections))[SectIdx]).getContents(), info->O->getFileName());
  3358. return SectContents.data() + offset;
  3359. }
  3360. }
  3361. return nullptr;
  3362. }
  3363. static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
  3364. uint32_t &left, SectionRef &S,
  3365. DisassembleInfo *info,
  3366. bool objc_only = false) {
  3367. return get_pointer_64(Address, offset, left, S, info, objc_only);
  3368. }
  3369. // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
  3370. // the symbol indirectly through n_value. Based on the relocation information
  3371. // for the specified section offset in the specified section reference.
  3372. // If no relocation information is found and a non-zero ReferenceValue for the
  3373. // symbol is passed, look up that address in the info's AddrMap.
  3374. static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
  3375. DisassembleInfo *info, uint64_t &n_value,
  3376. uint64_t ReferenceValue = 0) {
  3377. n_value = 0;
  3378. if (!info->verbose)
  3379. return nullptr;
  3380. // See if there is an external relocation entry at the sect_offset.
  3381. bool reloc_found = false;
  3382. DataRefImpl Rel;
  3383. MachO::any_relocation_info RE;
  3384. bool isExtern = false;
  3385. SymbolRef Symbol;
  3386. for (const RelocationRef &Reloc : S.relocations()) {
  3387. uint64_t RelocOffset = Reloc.getOffset();
  3388. if (RelocOffset == sect_offset) {
  3389. Rel = Reloc.getRawDataRefImpl();
  3390. RE = info->O->getRelocation(Rel);
  3391. if (info->O->isRelocationScattered(RE))
  3392. continue;
  3393. isExtern = info->O->getPlainRelocationExternal(RE);
  3394. if (isExtern) {
  3395. symbol_iterator RelocSym = Reloc.getSymbol();
  3396. Symbol = *RelocSym;
  3397. }
  3398. reloc_found = true;
  3399. break;
  3400. }
  3401. }
  3402. // If there is an external relocation entry for a symbol in this section
  3403. // at this section_offset then use that symbol's value for the n_value
  3404. // and return its name.
  3405. const char *SymbolName = nullptr;
  3406. if (reloc_found && isExtern) {
  3407. n_value = cantFail(Symbol.getValue());
  3408. StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
  3409. if (!Name.empty()) {
  3410. SymbolName = Name.data();
  3411. return SymbolName;
  3412. }
  3413. }
  3414. // TODO: For fully linked images, look through the external relocation
  3415. // entries off the dynamic symtab command. For these the r_offset is from the
  3416. // start of the first writeable segment in the Mach-O file. So the offset
  3417. // to this section from that segment is passed to this routine by the caller,
  3418. // as the database_offset. Which is the difference of the section's starting
  3419. // address and the first writable segment.
  3420. //
  3421. // NOTE: need add passing the database_offset to this routine.
  3422. // We did not find an external relocation entry so look up the ReferenceValue
  3423. // as an address of a symbol and if found return that symbol's name.
  3424. SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
  3425. return SymbolName;
  3426. }
  3427. static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
  3428. DisassembleInfo *info,
  3429. uint32_t ReferenceValue) {
  3430. uint64_t n_value64;
  3431. return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
  3432. }
  3433. namespace {
  3434. // These are structs in the Objective-C meta data and read to produce the
  3435. // comments for disassembly. While these are part of the ABI they are no
  3436. // public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
  3437. // .
  3438. // The cfstring object in a 64-bit Mach-O file.
  3439. struct cfstring64_t {
  3440. uint64_t isa; // class64_t * (64-bit pointer)
  3441. uint64_t flags; // flag bits
  3442. uint64_t characters; // char * (64-bit pointer)
  3443. uint64_t length; // number of non-NULL characters in above
  3444. };
  3445. // The class object in a 64-bit Mach-O file.
  3446. struct class64_t {
  3447. uint64_t isa; // class64_t * (64-bit pointer)
  3448. uint64_t superclass; // class64_t * (64-bit pointer)
  3449. uint64_t cache; // Cache (64-bit pointer)
  3450. uint64_t vtable; // IMP * (64-bit pointer)
  3451. uint64_t data; // class_ro64_t * (64-bit pointer)
  3452. };
  3453. struct class32_t {
  3454. uint32_t isa; /* class32_t * (32-bit pointer) */
  3455. uint32_t superclass; /* class32_t * (32-bit pointer) */
  3456. uint32_t cache; /* Cache (32-bit pointer) */
  3457. uint32_t vtable; /* IMP * (32-bit pointer) */
  3458. uint32_t data; /* class_ro32_t * (32-bit pointer) */
  3459. };
  3460. struct class_ro64_t {
  3461. uint32_t flags;
  3462. uint32_t instanceStart;
  3463. uint32_t instanceSize;
  3464. uint32_t reserved;
  3465. uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
  3466. uint64_t name; // const char * (64-bit pointer)
  3467. uint64_t baseMethods; // const method_list_t * (64-bit pointer)
  3468. uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
  3469. uint64_t ivars; // const ivar_list_t * (64-bit pointer)
  3470. uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
  3471. uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
  3472. };
  3473. struct class_ro32_t {
  3474. uint32_t flags;
  3475. uint32_t instanceStart;
  3476. uint32_t instanceSize;
  3477. uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
  3478. uint32_t name; /* const char * (32-bit pointer) */
  3479. uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
  3480. uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
  3481. uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
  3482. uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
  3483. uint32_t baseProperties; /* const struct objc_property_list *
  3484. (32-bit pointer) */
  3485. };
  3486. /* Values for class_ro{64,32}_t->flags */
  3487. #define RO_META (1 << 0)
  3488. #define RO_ROOT (1 << 1)
  3489. #define RO_HAS_CXX_STRUCTORS (1 << 2)
  3490. struct method_list64_t {
  3491. uint32_t entsize;
  3492. uint32_t count;
  3493. /* struct method64_t first; These structures follow inline */
  3494. };
  3495. struct method_list32_t {
  3496. uint32_t entsize;
  3497. uint32_t count;
  3498. /* struct method32_t first; These structures follow inline */
  3499. };
  3500. struct method64_t {
  3501. uint64_t name; /* SEL (64-bit pointer) */
  3502. uint64_t types; /* const char * (64-bit pointer) */
  3503. uint64_t imp; /* IMP (64-bit pointer) */
  3504. };
  3505. struct method32_t {
  3506. uint32_t name; /* SEL (32-bit pointer) */
  3507. uint32_t types; /* const char * (32-bit pointer) */
  3508. uint32_t imp; /* IMP (32-bit pointer) */
  3509. };
  3510. struct protocol_list64_t {
  3511. uint64_t count; /* uintptr_t (a 64-bit value) */
  3512. /* struct protocol64_t * list[0]; These pointers follow inline */
  3513. };
  3514. struct protocol_list32_t {
  3515. uint32_t count; /* uintptr_t (a 32-bit value) */
  3516. /* struct protocol32_t * list[0]; These pointers follow inline */
  3517. };
  3518. struct protocol64_t {
  3519. uint64_t isa; /* id * (64-bit pointer) */
  3520. uint64_t name; /* const char * (64-bit pointer) */
  3521. uint64_t protocols; /* struct protocol_list64_t *
  3522. (64-bit pointer) */
  3523. uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
  3524. uint64_t classMethods; /* method_list_t * (64-bit pointer) */
  3525. uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
  3526. uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
  3527. uint64_t instanceProperties; /* struct objc_property_list *
  3528. (64-bit pointer) */
  3529. };
  3530. struct protocol32_t {
  3531. uint32_t isa; /* id * (32-bit pointer) */
  3532. uint32_t name; /* const char * (32-bit pointer) */
  3533. uint32_t protocols; /* struct protocol_list_t *
  3534. (32-bit pointer) */
  3535. uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
  3536. uint32_t classMethods; /* method_list_t * (32-bit pointer) */
  3537. uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
  3538. uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
  3539. uint32_t instanceProperties; /* struct objc_property_list *
  3540. (32-bit pointer) */
  3541. };
  3542. struct ivar_list64_t {
  3543. uint32_t entsize;
  3544. uint32_t count;
  3545. /* struct ivar64_t first; These structures follow inline */
  3546. };
  3547. struct ivar_list32_t {
  3548. uint32_t entsize;
  3549. uint32_t count;
  3550. /* struct ivar32_t first; These structures follow inline */
  3551. };
  3552. struct ivar64_t {
  3553. uint64_t offset; /* uintptr_t * (64-bit pointer) */
  3554. uint64_t name; /* const char * (64-bit pointer) */
  3555. uint64_t type; /* const char * (64-bit pointer) */
  3556. uint32_t alignment;
  3557. uint32_t size;
  3558. };
  3559. struct ivar32_t {
  3560. uint32_t offset; /* uintptr_t * (32-bit pointer) */
  3561. uint32_t name; /* const char * (32-bit pointer) */
  3562. uint32_t type; /* const char * (32-bit pointer) */
  3563. uint32_t alignment;
  3564. uint32_t size;
  3565. };
  3566. struct objc_property_list64 {
  3567. uint32_t entsize;
  3568. uint32_t count;
  3569. /* struct objc_property64 first; These structures follow inline */
  3570. };
  3571. struct objc_property_list32 {
  3572. uint32_t entsize;
  3573. uint32_t count;
  3574. /* struct objc_property32 first; These structures follow inline */
  3575. };
  3576. struct objc_property64 {
  3577. uint64_t name; /* const char * (64-bit pointer) */
  3578. uint64_t attributes; /* const char * (64-bit pointer) */
  3579. };
  3580. struct objc_property32 {
  3581. uint32_t name; /* const char * (32-bit pointer) */
  3582. uint32_t attributes; /* const char * (32-bit pointer) */
  3583. };
  3584. struct category64_t {
  3585. uint64_t name; /* const char * (64-bit pointer) */
  3586. uint64_t cls; /* struct class_t * (64-bit pointer) */
  3587. uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
  3588. uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
  3589. uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
  3590. uint64_t instanceProperties; /* struct objc_property_list *
  3591. (64-bit pointer) */
  3592. };
  3593. struct category32_t {
  3594. uint32_t name; /* const char * (32-bit pointer) */
  3595. uint32_t cls; /* struct class_t * (32-bit pointer) */
  3596. uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
  3597. uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
  3598. uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
  3599. uint32_t instanceProperties; /* struct objc_property_list *
  3600. (32-bit pointer) */
  3601. };
  3602. struct objc_image_info64 {
  3603. uint32_t version;
  3604. uint32_t flags;
  3605. };
  3606. struct objc_image_info32 {
  3607. uint32_t version;
  3608. uint32_t flags;
  3609. };
  3610. struct imageInfo_t {
  3611. uint32_t version;
  3612. uint32_t flags;
  3613. };
  3614. /* masks for objc_image_info.flags */
  3615. #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
  3616. #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
  3617. #define OBJC_IMAGE_IS_SIMULATED (1 << 5)
  3618. #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
  3619. struct message_ref64 {
  3620. uint64_t imp; /* IMP (64-bit pointer) */
  3621. uint64_t sel; /* SEL (64-bit pointer) */
  3622. };
  3623. struct message_ref32 {
  3624. uint32_t imp; /* IMP (32-bit pointer) */
  3625. uint32_t sel; /* SEL (32-bit pointer) */
  3626. };
  3627. // Objective-C 1 (32-bit only) meta data structs.
  3628. struct objc_module_t {
  3629. uint32_t version;
  3630. uint32_t size;
  3631. uint32_t name; /* char * (32-bit pointer) */
  3632. uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
  3633. };
  3634. struct objc_symtab_t {
  3635. uint32_t sel_ref_cnt;
  3636. uint32_t refs; /* SEL * (32-bit pointer) */
  3637. uint16_t cls_def_cnt;
  3638. uint16_t cat_def_cnt;
  3639. // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
  3640. };
  3641. struct objc_class_t {
  3642. uint32_t isa; /* struct objc_class * (32-bit pointer) */
  3643. uint32_t super_class; /* struct objc_class * (32-bit pointer) */
  3644. uint32_t name; /* const char * (32-bit pointer) */
  3645. int32_t version;
  3646. int32_t info;
  3647. int32_t instance_size;
  3648. uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
  3649. uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
  3650. uint32_t cache; /* struct objc_cache * (32-bit pointer) */
  3651. uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
  3652. };
  3653. #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
  3654. // class is not a metaclass
  3655. #define CLS_CLASS 0x1
  3656. // class is a metaclass
  3657. #define CLS_META 0x2
  3658. struct objc_category_t {
  3659. uint32_t category_name; /* char * (32-bit pointer) */
  3660. uint32_t class_name; /* char * (32-bit pointer) */
  3661. uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
  3662. uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
  3663. uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
  3664. };
  3665. struct objc_ivar_t {
  3666. uint32_t ivar_name; /* char * (32-bit pointer) */
  3667. uint32_t ivar_type; /* char * (32-bit pointer) */
  3668. int32_t ivar_offset;
  3669. };
  3670. struct objc_ivar_list_t {
  3671. int32_t ivar_count;
  3672. // struct objc_ivar_t ivar_list[1]; /* variable length structure */
  3673. };
  3674. struct objc_method_list_t {
  3675. uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
  3676. int32_t method_count;
  3677. // struct objc_method_t method_list[1]; /* variable length structure */
  3678. };
  3679. struct objc_method_t {
  3680. uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
  3681. uint32_t method_types; /* char * (32-bit pointer) */
  3682. uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
  3683. (32-bit pointer) */
  3684. };
  3685. struct objc_protocol_list_t {
  3686. uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
  3687. int32_t count;
  3688. // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
  3689. // (32-bit pointer) */
  3690. };
  3691. struct objc_protocol_t {
  3692. uint32_t isa; /* struct objc_class * (32-bit pointer) */
  3693. uint32_t protocol_name; /* char * (32-bit pointer) */
  3694. uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
  3695. uint32_t instance_methods; /* struct objc_method_description_list *
  3696. (32-bit pointer) */
  3697. uint32_t class_methods; /* struct objc_method_description_list *
  3698. (32-bit pointer) */
  3699. };
  3700. struct objc_method_description_list_t {
  3701. int32_t count;
  3702. // struct objc_method_description_t list[1];
  3703. };
  3704. struct objc_method_description_t {
  3705. uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
  3706. uint32_t types; /* char * (32-bit pointer) */
  3707. };
  3708. inline void swapStruct(struct cfstring64_t &cfs) {
  3709. sys::swapByteOrder(cfs.isa);
  3710. sys::swapByteOrder(cfs.flags);
  3711. sys::swapByteOrder(cfs.characters);
  3712. sys::swapByteOrder(cfs.length);
  3713. }
  3714. inline void swapStruct(struct class64_t &c) {
  3715. sys::swapByteOrder(c.isa);
  3716. sys::swapByteOrder(c.superclass);
  3717. sys::swapByteOrder(c.cache);
  3718. sys::swapByteOrder(c.vtable);
  3719. sys::swapByteOrder(c.data);
  3720. }
  3721. inline void swapStruct(struct class32_t &c) {
  3722. sys::swapByteOrder(c.isa);
  3723. sys::swapByteOrder(c.superclass);
  3724. sys::swapByteOrder(c.cache);
  3725. sys::swapByteOrder(c.vtable);
  3726. sys::swapByteOrder(c.data);
  3727. }
  3728. inline void swapStruct(struct class_ro64_t &cro) {
  3729. sys::swapByteOrder(cro.flags);
  3730. sys::swapByteOrder(cro.instanceStart);
  3731. sys::swapByteOrder(cro.instanceSize);
  3732. sys::swapByteOrder(cro.reserved);
  3733. sys::swapByteOrder(cro.ivarLayout);
  3734. sys::swapByteOrder(cro.name);
  3735. sys::swapByteOrder(cro.baseMethods);
  3736. sys::swapByteOrder(cro.baseProtocols);
  3737. sys::swapByteOrder(cro.ivars);
  3738. sys::swapByteOrder(cro.weakIvarLayout);
  3739. sys::swapByteOrder(cro.baseProperties);
  3740. }
  3741. inline void swapStruct(struct class_ro32_t &cro) {
  3742. sys::swapByteOrder(cro.flags);
  3743. sys::swapByteOrder(cro.instanceStart);
  3744. sys::swapByteOrder(cro.instanceSize);
  3745. sys::swapByteOrder(cro.ivarLayout);
  3746. sys::swapByteOrder(cro.name);
  3747. sys::swapByteOrder(cro.baseMethods);
  3748. sys::swapByteOrder(cro.baseProtocols);
  3749. sys::swapByteOrder(cro.ivars);
  3750. sys::swapByteOrder(cro.weakIvarLayout);
  3751. sys::swapByteOrder(cro.baseProperties);
  3752. }
  3753. inline void swapStruct(struct method_list64_t &ml) {
  3754. sys::swapByteOrder(ml.entsize);
  3755. sys::swapByteOrder(ml.count);
  3756. }
  3757. inline void swapStruct(struct method_list32_t &ml) {
  3758. sys::swapByteOrder(ml.entsize);
  3759. sys::swapByteOrder(ml.count);
  3760. }
  3761. inline void swapStruct(struct method64_t &m) {
  3762. sys::swapByteOrder(m.name);
  3763. sys::swapByteOrder(m.types);
  3764. sys::swapByteOrder(m.imp);
  3765. }
  3766. inline void swapStruct(struct method32_t &m) {
  3767. sys::swapByteOrder(m.name);
  3768. sys::swapByteOrder(m.types);
  3769. sys::swapByteOrder(m.imp);
  3770. }
  3771. inline void swapStruct(struct protocol_list64_t &pl) {
  3772. sys::swapByteOrder(pl.count);
  3773. }
  3774. inline void swapStruct(struct protocol_list32_t &pl) {
  3775. sys::swapByteOrder(pl.count);
  3776. }
  3777. inline void swapStruct(struct protocol64_t &p) {
  3778. sys::swapByteOrder(p.isa);
  3779. sys::swapByteOrder(p.name);
  3780. sys::swapByteOrder(p.protocols);
  3781. sys::swapByteOrder(p.instanceMethods);
  3782. sys::swapByteOrder(p.classMethods);
  3783. sys::swapByteOrder(p.optionalInstanceMethods);
  3784. sys::swapByteOrder(p.optionalClassMethods);
  3785. sys::swapByteOrder(p.instanceProperties);
  3786. }
  3787. inline void swapStruct(struct protocol32_t &p) {
  3788. sys::swapByteOrder(p.isa);
  3789. sys::swapByteOrder(p.name);
  3790. sys::swapByteOrder(p.protocols);
  3791. sys::swapByteOrder(p.instanceMethods);
  3792. sys::swapByteOrder(p.classMethods);
  3793. sys::swapByteOrder(p.optionalInstanceMethods);
  3794. sys::swapByteOrder(p.optionalClassMethods);
  3795. sys::swapByteOrder(p.instanceProperties);
  3796. }
  3797. inline void swapStruct(struct ivar_list64_t &il) {
  3798. sys::swapByteOrder(il.entsize);
  3799. sys::swapByteOrder(il.count);
  3800. }
  3801. inline void swapStruct(struct ivar_list32_t &il) {
  3802. sys::swapByteOrder(il.entsize);
  3803. sys::swapByteOrder(il.count);
  3804. }
  3805. inline void swapStruct(struct ivar64_t &i) {
  3806. sys::swapByteOrder(i.offset);
  3807. sys::swapByteOrder(i.name);
  3808. sys::swapByteOrder(i.type);
  3809. sys::swapByteOrder(i.alignment);
  3810. sys::swapByteOrder(i.size);
  3811. }
  3812. inline void swapStruct(struct ivar32_t &i) {
  3813. sys::swapByteOrder(i.offset);
  3814. sys::swapByteOrder(i.name);
  3815. sys::swapByteOrder(i.type);
  3816. sys::swapByteOrder(i.alignment);
  3817. sys::swapByteOrder(i.size);
  3818. }
  3819. inline void swapStruct(struct objc_property_list64 &pl) {
  3820. sys::swapByteOrder(pl.entsize);
  3821. sys::swapByteOrder(pl.count);
  3822. }
  3823. inline void swapStruct(struct objc_property_list32 &pl) {
  3824. sys::swapByteOrder(pl.entsize);
  3825. sys::swapByteOrder(pl.count);
  3826. }
  3827. inline void swapStruct(struct objc_property64 &op) {
  3828. sys::swapByteOrder(op.name);
  3829. sys::swapByteOrder(op.attributes);
  3830. }
  3831. inline void swapStruct(struct objc_property32 &op) {
  3832. sys::swapByteOrder(op.name);
  3833. sys::swapByteOrder(op.attributes);
  3834. }
  3835. inline void swapStruct(struct category64_t &c) {
  3836. sys::swapByteOrder(c.name);
  3837. sys::swapByteOrder(c.cls);
  3838. sys::swapByteOrder(c.instanceMethods);
  3839. sys::swapByteOrder(c.classMethods);
  3840. sys::swapByteOrder(c.protocols);
  3841. sys::swapByteOrder(c.instanceProperties);
  3842. }
  3843. inline void swapStruct(struct category32_t &c) {
  3844. sys::swapByteOrder(c.name);
  3845. sys::swapByteOrder(c.cls);
  3846. sys::swapByteOrder(c.instanceMethods);
  3847. sys::swapByteOrder(c.classMethods);
  3848. sys::swapByteOrder(c.protocols);
  3849. sys::swapByteOrder(c.instanceProperties);
  3850. }
  3851. inline void swapStruct(struct objc_image_info64 &o) {
  3852. sys::swapByteOrder(o.version);
  3853. sys::swapByteOrder(o.flags);
  3854. }
  3855. inline void swapStruct(struct objc_image_info32 &o) {
  3856. sys::swapByteOrder(o.version);
  3857. sys::swapByteOrder(o.flags);
  3858. }
  3859. inline void swapStruct(struct imageInfo_t &o) {
  3860. sys::swapByteOrder(o.version);
  3861. sys::swapByteOrder(o.flags);
  3862. }
  3863. inline void swapStruct(struct message_ref64 &mr) {
  3864. sys::swapByteOrder(mr.imp);
  3865. sys::swapByteOrder(mr.sel);
  3866. }
  3867. inline void swapStruct(struct message_ref32 &mr) {
  3868. sys::swapByteOrder(mr.imp);
  3869. sys::swapByteOrder(mr.sel);
  3870. }
  3871. inline void swapStruct(struct objc_module_t &module) {
  3872. sys::swapByteOrder(module.version);
  3873. sys::swapByteOrder(module.size);
  3874. sys::swapByteOrder(module.name);
  3875. sys::swapByteOrder(module.symtab);
  3876. }
  3877. inline void swapStruct(struct objc_symtab_t &symtab) {
  3878. sys::swapByteOrder(symtab.sel_ref_cnt);
  3879. sys::swapByteOrder(symtab.refs);
  3880. sys::swapByteOrder(symtab.cls_def_cnt);
  3881. sys::swapByteOrder(symtab.cat_def_cnt);
  3882. }
  3883. inline void swapStruct(struct objc_class_t &objc_class) {
  3884. sys::swapByteOrder(objc_class.isa);
  3885. sys::swapByteOrder(objc_class.super_class);
  3886. sys::swapByteOrder(objc_class.name);
  3887. sys::swapByteOrder(objc_class.version);
  3888. sys::swapByteOrder(objc_class.info);
  3889. sys::swapByteOrder(objc_class.instance_size);
  3890. sys::swapByteOrder(objc_class.ivars);
  3891. sys::swapByteOrder(objc_class.methodLists);
  3892. sys::swapByteOrder(objc_class.cache);
  3893. sys::swapByteOrder(objc_class.protocols);
  3894. }
  3895. inline void swapStruct(struct objc_category_t &objc_category) {
  3896. sys::swapByteOrder(objc_category.category_name);
  3897. sys::swapByteOrder(objc_category.class_name);
  3898. sys::swapByteOrder(objc_category.instance_methods);
  3899. sys::swapByteOrder(objc_category.class_methods);
  3900. sys::swapByteOrder(objc_category.protocols);
  3901. }
  3902. inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
  3903. sys::swapByteOrder(objc_ivar_list.ivar_count);
  3904. }
  3905. inline void swapStruct(struct objc_ivar_t &objc_ivar) {
  3906. sys::swapByteOrder(objc_ivar.ivar_name);
  3907. sys::swapByteOrder(objc_ivar.ivar_type);
  3908. sys::swapByteOrder(objc_ivar.ivar_offset);
  3909. }
  3910. inline void swapStruct(struct objc_method_list_t &method_list) {
  3911. sys::swapByteOrder(method_list.obsolete);
  3912. sys::swapByteOrder(method_list.method_count);
  3913. }
  3914. inline void swapStruct(struct objc_method_t &method) {
  3915. sys::swapByteOrder(method.method_name);
  3916. sys::swapByteOrder(method.method_types);
  3917. sys::swapByteOrder(method.method_imp);
  3918. }
  3919. inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
  3920. sys::swapByteOrder(protocol_list.next);
  3921. sys::swapByteOrder(protocol_list.count);
  3922. }
  3923. inline void swapStruct(struct objc_protocol_t &protocol) {
  3924. sys::swapByteOrder(protocol.isa);
  3925. sys::swapByteOrder(protocol.protocol_name);
  3926. sys::swapByteOrder(protocol.protocol_list);
  3927. sys::swapByteOrder(protocol.instance_methods);
  3928. sys::swapByteOrder(protocol.class_methods);
  3929. }
  3930. inline void swapStruct(struct objc_method_description_list_t &mdl) {
  3931. sys::swapByteOrder(mdl.count);
  3932. }
  3933. inline void swapStruct(struct objc_method_description_t &md) {
  3934. sys::swapByteOrder(md.name);
  3935. sys::swapByteOrder(md.types);
  3936. }
  3937. } // namespace
  3938. static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
  3939. struct DisassembleInfo *info);
  3940. // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
  3941. // to an Objective-C class and returns the class name. It is also passed the
  3942. // address of the pointer, so when the pointer is zero as it can be in an .o
  3943. // file, that is used to look for an external relocation entry with a symbol
  3944. // name.
  3945. static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
  3946. uint64_t ReferenceValue,
  3947. struct DisassembleInfo *info) {
  3948. const char *r;
  3949. uint32_t offset, left;
  3950. SectionRef S;
  3951. // The pointer_value can be 0 in an object file and have a relocation
  3952. // entry for the class symbol at the ReferenceValue (the address of the
  3953. // pointer).
  3954. if (pointer_value == 0) {
  3955. r = get_pointer_64(ReferenceValue, offset, left, S, info);
  3956. if (r == nullptr || left < sizeof(uint64_t))
  3957. return nullptr;
  3958. uint64_t n_value;
  3959. const char *symbol_name = get_symbol_64(offset, S, info, n_value);
  3960. if (symbol_name == nullptr)
  3961. return nullptr;
  3962. const char *class_name = strrchr(symbol_name, '$');
  3963. if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
  3964. return class_name + 2;
  3965. else
  3966. return nullptr;
  3967. }
  3968. // The case were the pointer_value is non-zero and points to a class defined
  3969. // in this Mach-O file.
  3970. r = get_pointer_64(pointer_value, offset, left, S, info);
  3971. if (r == nullptr || left < sizeof(struct class64_t))
  3972. return nullptr;
  3973. struct class64_t c;
  3974. memcpy(&c, r, sizeof(struct class64_t));
  3975. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3976. swapStruct(c);
  3977. if (c.data == 0)
  3978. return nullptr;
  3979. r = get_pointer_64(c.data, offset, left, S, info);
  3980. if (r == nullptr || left < sizeof(struct class_ro64_t))
  3981. return nullptr;
  3982. struct class_ro64_t cro;
  3983. memcpy(&cro, r, sizeof(struct class_ro64_t));
  3984. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3985. swapStruct(cro);
  3986. if (cro.name == 0)
  3987. return nullptr;
  3988. const char *name = get_pointer_64(cro.name, offset, left, S, info);
  3989. return name;
  3990. }
  3991. // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
  3992. // pointer to a cfstring and returns its name or nullptr.
  3993. static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
  3994. struct DisassembleInfo *info) {
  3995. const char *r, *name;
  3996. uint32_t offset, left;
  3997. SectionRef S;
  3998. struct cfstring64_t cfs;
  3999. uint64_t cfs_characters;
  4000. r = get_pointer_64(ReferenceValue, offset, left, S, info);
  4001. if (r == nullptr || left < sizeof(struct cfstring64_t))
  4002. return nullptr;
  4003. memcpy(&cfs, r, sizeof(struct cfstring64_t));
  4004. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4005. swapStruct(cfs);
  4006. if (cfs.characters == 0) {
  4007. uint64_t n_value;
  4008. const char *symbol_name = get_symbol_64(
  4009. offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
  4010. if (symbol_name == nullptr)
  4011. return nullptr;
  4012. cfs_characters = n_value;
  4013. } else
  4014. cfs_characters = cfs.characters;
  4015. name = get_pointer_64(cfs_characters, offset, left, S, info);
  4016. return name;
  4017. }
  4018. // get_objc2_64bit_selref() is used for disassembly and is passed a the address
  4019. // of a pointer to an Objective-C selector reference when the pointer value is
  4020. // zero as in a .o file and is likely to have a external relocation entry with
  4021. // who's symbol's n_value is the real pointer to the selector name. If that is
  4022. // the case the real pointer to the selector name is returned else 0 is
  4023. // returned
  4024. static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
  4025. struct DisassembleInfo *info) {
  4026. uint32_t offset, left;
  4027. SectionRef S;
  4028. const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
  4029. if (r == nullptr || left < sizeof(uint64_t))
  4030. return 0;
  4031. uint64_t n_value;
  4032. const char *symbol_name = get_symbol_64(offset, S, info, n_value);
  4033. if (symbol_name == nullptr)
  4034. return 0;
  4035. return n_value;
  4036. }
  4037. static const SectionRef get_section(MachOObjectFile *O, const char *segname,
  4038. const char *sectname) {
  4039. for (const SectionRef &Section : O->sections()) {
  4040. StringRef SectName;
  4041. Expected<StringRef> SecNameOrErr = Section.getName();
  4042. if (SecNameOrErr)
  4043. SectName = *SecNameOrErr;
  4044. else
  4045. consumeError(SecNameOrErr.takeError());
  4046. DataRefImpl Ref = Section.getRawDataRefImpl();
  4047. StringRef SegName = O->getSectionFinalSegmentName(Ref);
  4048. if (SegName == segname && SectName == sectname)
  4049. return Section;
  4050. }
  4051. return SectionRef();
  4052. }
  4053. static void
  4054. walk_pointer_list_64(const char *listname, const SectionRef S,
  4055. MachOObjectFile *O, struct DisassembleInfo *info,
  4056. void (*func)(uint64_t, struct DisassembleInfo *info)) {
  4057. if (S == SectionRef())
  4058. return;
  4059. StringRef SectName;
  4060. Expected<StringRef> SecNameOrErr = S.getName();
  4061. if (SecNameOrErr)
  4062. SectName = *SecNameOrErr;
  4063. else
  4064. consumeError(SecNameOrErr.takeError());
  4065. DataRefImpl Ref = S.getRawDataRefImpl();
  4066. StringRef SegName = O->getSectionFinalSegmentName(Ref);
  4067. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  4068. StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
  4069. const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
  4070. for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
  4071. uint32_t left = S.getSize() - i;
  4072. uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
  4073. uint64_t p = 0;
  4074. memcpy(&p, Contents + i, size);
  4075. if (i + sizeof(uint64_t) > S.getSize())
  4076. outs() << listname << " list pointer extends past end of (" << SegName
  4077. << "," << SectName << ") section\n";
  4078. outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
  4079. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  4080. sys::swapByteOrder(p);
  4081. uint64_t n_value = 0;
  4082. const char *name = get_symbol_64(i, S, info, n_value, p);
  4083. if (name == nullptr)
  4084. name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
  4085. if (n_value != 0) {
  4086. outs() << format("0x%" PRIx64, n_value);
  4087. if (p != 0)
  4088. outs() << " + " << format("0x%" PRIx64, p);
  4089. } else
  4090. outs() << format("0x%" PRIx64, p);
  4091. if (name != nullptr)
  4092. outs() << " " << name;
  4093. outs() << "\n";
  4094. p += n_value;
  4095. if (func)
  4096. func(p, info);
  4097. }
  4098. }
  4099. static void
  4100. walk_pointer_list_32(const char *listname, const SectionRef S,
  4101. MachOObjectFile *O, struct DisassembleInfo *info,
  4102. void (*func)(uint32_t, struct DisassembleInfo *info)) {
  4103. if (S == SectionRef())
  4104. return;
  4105. StringRef SectName = unwrapOrError(S.getName(), O->getFileName());
  4106. DataRefImpl Ref = S.getRawDataRefImpl();
  4107. StringRef SegName = O->getSectionFinalSegmentName(Ref);
  4108. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  4109. StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
  4110. const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
  4111. for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
  4112. uint32_t left = S.getSize() - i;
  4113. uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
  4114. uint32_t p = 0;
  4115. memcpy(&p, Contents + i, size);
  4116. if (i + sizeof(uint32_t) > S.getSize())
  4117. outs() << listname << " list pointer extends past end of (" << SegName
  4118. << "," << SectName << ") section\n";
  4119. uint32_t Address = S.getAddress() + i;
  4120. outs() << format("%08" PRIx32, Address) << " ";
  4121. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  4122. sys::swapByteOrder(p);
  4123. outs() << format("0x%" PRIx32, p);
  4124. const char *name = get_symbol_32(i, S, info, p);
  4125. if (name != nullptr)
  4126. outs() << " " << name;
  4127. outs() << "\n";
  4128. if (func)
  4129. func(p, info);
  4130. }
  4131. }
  4132. static void print_layout_map(const char *layout_map, uint32_t left) {
  4133. if (layout_map == nullptr)
  4134. return;
  4135. outs() << " layout map: ";
  4136. do {
  4137. outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
  4138. left--;
  4139. layout_map++;
  4140. } while (*layout_map != '\0' && left != 0);
  4141. outs() << "\n";
  4142. }
  4143. static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
  4144. uint32_t offset, left;
  4145. SectionRef S;
  4146. const char *layout_map;
  4147. if (p == 0)
  4148. return;
  4149. layout_map = get_pointer_64(p, offset, left, S, info);
  4150. print_layout_map(layout_map, left);
  4151. }
  4152. static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
  4153. uint32_t offset, left;
  4154. SectionRef S;
  4155. const char *layout_map;
  4156. if (p == 0)
  4157. return;
  4158. layout_map = get_pointer_32(p, offset, left, S, info);
  4159. print_layout_map(layout_map, left);
  4160. }
  4161. static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
  4162. const char *indent) {
  4163. struct method_list64_t ml;
  4164. struct method64_t m;
  4165. const char *r;
  4166. uint32_t offset, xoffset, left, i;
  4167. SectionRef S, xS;
  4168. const char *name, *sym_name;
  4169. uint64_t n_value;
  4170. r = get_pointer_64(p, offset, left, S, info);
  4171. if (r == nullptr)
  4172. return;
  4173. memset(&ml, '\0', sizeof(struct method_list64_t));
  4174. if (left < sizeof(struct method_list64_t)) {
  4175. memcpy(&ml, r, left);
  4176. outs() << " (method_list_t entends past the end of the section)\n";
  4177. } else
  4178. memcpy(&ml, r, sizeof(struct method_list64_t));
  4179. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4180. swapStruct(ml);
  4181. outs() << indent << "\t\t entsize " << ml.entsize << "\n";
  4182. outs() << indent << "\t\t count " << ml.count << "\n";
  4183. p += sizeof(struct method_list64_t);
  4184. offset += sizeof(struct method_list64_t);
  4185. for (i = 0; i < ml.count; i++) {
  4186. r = get_pointer_64(p, offset, left, S, info);
  4187. if (r == nullptr)
  4188. return;
  4189. memset(&m, '\0', sizeof(struct method64_t));
  4190. if (left < sizeof(struct method64_t)) {
  4191. memcpy(&m, r, left);
  4192. outs() << indent << " (method_t extends past the end of the section)\n";
  4193. } else
  4194. memcpy(&m, r, sizeof(struct method64_t));
  4195. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4196. swapStruct(m);
  4197. outs() << indent << "\t\t name ";
  4198. sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
  4199. info, n_value, m.name);
  4200. if (n_value != 0) {
  4201. if (info->verbose && sym_name != nullptr)
  4202. outs() << sym_name;
  4203. else
  4204. outs() << format("0x%" PRIx64, n_value);
  4205. if (m.name != 0)
  4206. outs() << " + " << format("0x%" PRIx64, m.name);
  4207. } else
  4208. outs() << format("0x%" PRIx64, m.name);
  4209. name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
  4210. if (name != nullptr)
  4211. outs() << format(" %.*s", left, name);
  4212. outs() << "\n";
  4213. outs() << indent << "\t\t types ";
  4214. sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
  4215. info, n_value, m.types);
  4216. if (n_value != 0) {
  4217. if (info->verbose && sym_name != nullptr)
  4218. outs() << sym_name;
  4219. else
  4220. outs() << format("0x%" PRIx64, n_value);
  4221. if (m.types != 0)
  4222. outs() << " + " << format("0x%" PRIx64, m.types);
  4223. } else
  4224. outs() << format("0x%" PRIx64, m.types);
  4225. name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
  4226. if (name != nullptr)
  4227. outs() << format(" %.*s", left, name);
  4228. outs() << "\n";
  4229. outs() << indent << "\t\t imp ";
  4230. name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
  4231. n_value, m.imp);
  4232. if (info->verbose && name == nullptr) {
  4233. if (n_value != 0) {
  4234. outs() << format("0x%" PRIx64, n_value) << " ";
  4235. if (m.imp != 0)
  4236. outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
  4237. } else
  4238. outs() << format("0x%" PRIx64, m.imp) << " ";
  4239. }
  4240. if (name != nullptr)
  4241. outs() << name;
  4242. outs() << "\n";
  4243. p += sizeof(struct method64_t);
  4244. offset += sizeof(struct method64_t);
  4245. }
  4246. }
  4247. static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
  4248. const char *indent) {
  4249. struct method_list32_t ml;
  4250. struct method32_t m;
  4251. const char *r, *name;
  4252. uint32_t offset, xoffset, left, i;
  4253. SectionRef S, xS;
  4254. r = get_pointer_32(p, offset, left, S, info);
  4255. if (r == nullptr)
  4256. return;
  4257. memset(&ml, '\0', sizeof(struct method_list32_t));
  4258. if (left < sizeof(struct method_list32_t)) {
  4259. memcpy(&ml, r, left);
  4260. outs() << " (method_list_t entends past the end of the section)\n";
  4261. } else
  4262. memcpy(&ml, r, sizeof(struct method_list32_t));
  4263. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4264. swapStruct(ml);
  4265. outs() << indent << "\t\t entsize " << ml.entsize << "\n";
  4266. outs() << indent << "\t\t count " << ml.count << "\n";
  4267. p += sizeof(struct method_list32_t);
  4268. offset += sizeof(struct method_list32_t);
  4269. for (i = 0; i < ml.count; i++) {
  4270. r = get_pointer_32(p, offset, left, S, info);
  4271. if (r == nullptr)
  4272. return;
  4273. memset(&m, '\0', sizeof(struct method32_t));
  4274. if (left < sizeof(struct method32_t)) {
  4275. memcpy(&ml, r, left);
  4276. outs() << indent << " (method_t entends past the end of the section)\n";
  4277. } else
  4278. memcpy(&m, r, sizeof(struct method32_t));
  4279. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4280. swapStruct(m);
  4281. outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
  4282. name = get_pointer_32(m.name, xoffset, left, xS, info);
  4283. if (name != nullptr)
  4284. outs() << format(" %.*s", left, name);
  4285. outs() << "\n";
  4286. outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
  4287. name = get_pointer_32(m.types, xoffset, left, xS, info);
  4288. if (name != nullptr)
  4289. outs() << format(" %.*s", left, name);
  4290. outs() << "\n";
  4291. outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
  4292. name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
  4293. m.imp);
  4294. if (name != nullptr)
  4295. outs() << " " << name;
  4296. outs() << "\n";
  4297. p += sizeof(struct method32_t);
  4298. offset += sizeof(struct method32_t);
  4299. }
  4300. }
  4301. static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
  4302. uint32_t offset, left, xleft;
  4303. SectionRef S;
  4304. struct objc_method_list_t method_list;
  4305. struct objc_method_t method;
  4306. const char *r, *methods, *name, *SymbolName;
  4307. int32_t i;
  4308. r = get_pointer_32(p, offset, left, S, info, true);
  4309. if (r == nullptr)
  4310. return true;
  4311. outs() << "\n";
  4312. if (left > sizeof(struct objc_method_list_t)) {
  4313. memcpy(&method_list, r, sizeof(struct objc_method_list_t));
  4314. } else {
  4315. outs() << "\t\t objc_method_list extends past end of the section\n";
  4316. memset(&method_list, '\0', sizeof(struct objc_method_list_t));
  4317. memcpy(&method_list, r, left);
  4318. }
  4319. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4320. swapStruct(method_list);
  4321. outs() << "\t\t obsolete "
  4322. << format("0x%08" PRIx32, method_list.obsolete) << "\n";
  4323. outs() << "\t\t method_count " << method_list.method_count << "\n";
  4324. methods = r + sizeof(struct objc_method_list_t);
  4325. for (i = 0; i < method_list.method_count; i++) {
  4326. if ((i + 1) * sizeof(struct objc_method_t) > left) {
  4327. outs() << "\t\t remaining method's extend past the of the section\n";
  4328. break;
  4329. }
  4330. memcpy(&method, methods + i * sizeof(struct objc_method_t),
  4331. sizeof(struct objc_method_t));
  4332. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4333. swapStruct(method);
  4334. outs() << "\t\t method_name "
  4335. << format("0x%08" PRIx32, method.method_name);
  4336. if (info->verbose) {
  4337. name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
  4338. if (name != nullptr)
  4339. outs() << format(" %.*s", xleft, name);
  4340. else
  4341. outs() << " (not in an __OBJC section)";
  4342. }
  4343. outs() << "\n";
  4344. outs() << "\t\t method_types "
  4345. << format("0x%08" PRIx32, method.method_types);
  4346. if (info->verbose) {
  4347. name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
  4348. if (name != nullptr)
  4349. outs() << format(" %.*s", xleft, name);
  4350. else
  4351. outs() << " (not in an __OBJC section)";
  4352. }
  4353. outs() << "\n";
  4354. outs() << "\t\t method_imp "
  4355. << format("0x%08" PRIx32, method.method_imp) << " ";
  4356. if (info->verbose) {
  4357. SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
  4358. if (SymbolName != nullptr)
  4359. outs() << SymbolName;
  4360. }
  4361. outs() << "\n";
  4362. }
  4363. return false;
  4364. }
  4365. static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
  4366. struct protocol_list64_t pl;
  4367. uint64_t q, n_value;
  4368. struct protocol64_t pc;
  4369. const char *r;
  4370. uint32_t offset, xoffset, left, i;
  4371. SectionRef S, xS;
  4372. const char *name, *sym_name;
  4373. r = get_pointer_64(p, offset, left, S, info);
  4374. if (r == nullptr)
  4375. return;
  4376. memset(&pl, '\0', sizeof(struct protocol_list64_t));
  4377. if (left < sizeof(struct protocol_list64_t)) {
  4378. memcpy(&pl, r, left);
  4379. outs() << " (protocol_list_t entends past the end of the section)\n";
  4380. } else
  4381. memcpy(&pl, r, sizeof(struct protocol_list64_t));
  4382. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4383. swapStruct(pl);
  4384. outs() << " count " << pl.count << "\n";
  4385. p += sizeof(struct protocol_list64_t);
  4386. offset += sizeof(struct protocol_list64_t);
  4387. for (i = 0; i < pl.count; i++) {
  4388. r = get_pointer_64(p, offset, left, S, info);
  4389. if (r == nullptr)
  4390. return;
  4391. q = 0;
  4392. if (left < sizeof(uint64_t)) {
  4393. memcpy(&q, r, left);
  4394. outs() << " (protocol_t * entends past the end of the section)\n";
  4395. } else
  4396. memcpy(&q, r, sizeof(uint64_t));
  4397. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4398. sys::swapByteOrder(q);
  4399. outs() << "\t\t list[" << i << "] ";
  4400. sym_name = get_symbol_64(offset, S, info, n_value, q);
  4401. if (n_value != 0) {
  4402. if (info->verbose && sym_name != nullptr)
  4403. outs() << sym_name;
  4404. else
  4405. outs() << format("0x%" PRIx64, n_value);
  4406. if (q != 0)
  4407. outs() << " + " << format("0x%" PRIx64, q);
  4408. } else
  4409. outs() << format("0x%" PRIx64, q);
  4410. outs() << " (struct protocol_t *)\n";
  4411. r = get_pointer_64(q + n_value, offset, left, S, info);
  4412. if (r == nullptr)
  4413. return;
  4414. memset(&pc, '\0', sizeof(struct protocol64_t));
  4415. if (left < sizeof(struct protocol64_t)) {
  4416. memcpy(&pc, r, left);
  4417. outs() << " (protocol_t entends past the end of the section)\n";
  4418. } else
  4419. memcpy(&pc, r, sizeof(struct protocol64_t));
  4420. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4421. swapStruct(pc);
  4422. outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
  4423. outs() << "\t\t\t name ";
  4424. sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
  4425. info, n_value, pc.name);
  4426. if (n_value != 0) {
  4427. if (info->verbose && sym_name != nullptr)
  4428. outs() << sym_name;
  4429. else
  4430. outs() << format("0x%" PRIx64, n_value);
  4431. if (pc.name != 0)
  4432. outs() << " + " << format("0x%" PRIx64, pc.name);
  4433. } else
  4434. outs() << format("0x%" PRIx64, pc.name);
  4435. name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
  4436. if (name != nullptr)
  4437. outs() << format(" %.*s", left, name);
  4438. outs() << "\n";
  4439. outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
  4440. outs() << "\t\t instanceMethods ";
  4441. sym_name =
  4442. get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
  4443. S, info, n_value, pc.instanceMethods);
  4444. if (n_value != 0) {
  4445. if (info->verbose && sym_name != nullptr)
  4446. outs() << sym_name;
  4447. else
  4448. outs() << format("0x%" PRIx64, n_value);
  4449. if (pc.instanceMethods != 0)
  4450. outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
  4451. } else
  4452. outs() << format("0x%" PRIx64, pc.instanceMethods);
  4453. outs() << " (struct method_list_t *)\n";
  4454. if (pc.instanceMethods + n_value != 0)
  4455. print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
  4456. outs() << "\t\t classMethods ";
  4457. sym_name =
  4458. get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
  4459. info, n_value, pc.classMethods);
  4460. if (n_value != 0) {
  4461. if (info->verbose && sym_name != nullptr)
  4462. outs() << sym_name;
  4463. else
  4464. outs() << format("0x%" PRIx64, n_value);
  4465. if (pc.classMethods != 0)
  4466. outs() << " + " << format("0x%" PRIx64, pc.classMethods);
  4467. } else
  4468. outs() << format("0x%" PRIx64, pc.classMethods);
  4469. outs() << " (struct method_list_t *)\n";
  4470. if (pc.classMethods + n_value != 0)
  4471. print_method_list64_t(pc.classMethods + n_value, info, "\t");
  4472. outs() << "\t optionalInstanceMethods "
  4473. << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
  4474. outs() << "\t optionalClassMethods "
  4475. << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
  4476. outs() << "\t instanceProperties "
  4477. << format("0x%" PRIx64, pc.instanceProperties) << "\n";
  4478. p += sizeof(uint64_t);
  4479. offset += sizeof(uint64_t);
  4480. }
  4481. }
  4482. static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
  4483. struct protocol_list32_t pl;
  4484. uint32_t q;
  4485. struct protocol32_t pc;
  4486. const char *r;
  4487. uint32_t offset, xoffset, left, i;
  4488. SectionRef S, xS;
  4489. const char *name;
  4490. r = get_pointer_32(p, offset, left, S, info);
  4491. if (r == nullptr)
  4492. return;
  4493. memset(&pl, '\0', sizeof(struct protocol_list32_t));
  4494. if (left < sizeof(struct protocol_list32_t)) {
  4495. memcpy(&pl, r, left);
  4496. outs() << " (protocol_list_t entends past the end of the section)\n";
  4497. } else
  4498. memcpy(&pl, r, sizeof(struct protocol_list32_t));
  4499. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4500. swapStruct(pl);
  4501. outs() << " count " << pl.count << "\n";
  4502. p += sizeof(struct protocol_list32_t);
  4503. offset += sizeof(struct protocol_list32_t);
  4504. for (i = 0; i < pl.count; i++) {
  4505. r = get_pointer_32(p, offset, left, S, info);
  4506. if (r == nullptr)
  4507. return;
  4508. q = 0;
  4509. if (left < sizeof(uint32_t)) {
  4510. memcpy(&q, r, left);
  4511. outs() << " (protocol_t * entends past the end of the section)\n";
  4512. } else
  4513. memcpy(&q, r, sizeof(uint32_t));
  4514. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4515. sys::swapByteOrder(q);
  4516. outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
  4517. << " (struct protocol_t *)\n";
  4518. r = get_pointer_32(q, offset, left, S, info);
  4519. if (r == nullptr)
  4520. return;
  4521. memset(&pc, '\0', sizeof(struct protocol32_t));
  4522. if (left < sizeof(struct protocol32_t)) {
  4523. memcpy(&pc, r, left);
  4524. outs() << " (protocol_t entends past the end of the section)\n";
  4525. } else
  4526. memcpy(&pc, r, sizeof(struct protocol32_t));
  4527. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4528. swapStruct(pc);
  4529. outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
  4530. outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
  4531. name = get_pointer_32(pc.name, xoffset, left, xS, info);
  4532. if (name != nullptr)
  4533. outs() << format(" %.*s", left, name);
  4534. outs() << "\n";
  4535. outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
  4536. outs() << "\t\t instanceMethods "
  4537. << format("0x%" PRIx32, pc.instanceMethods)
  4538. << " (struct method_list_t *)\n";
  4539. if (pc.instanceMethods != 0)
  4540. print_method_list32_t(pc.instanceMethods, info, "\t");
  4541. outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
  4542. << " (struct method_list_t *)\n";
  4543. if (pc.classMethods != 0)
  4544. print_method_list32_t(pc.classMethods, info, "\t");
  4545. outs() << "\t optionalInstanceMethods "
  4546. << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
  4547. outs() << "\t optionalClassMethods "
  4548. << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
  4549. outs() << "\t instanceProperties "
  4550. << format("0x%" PRIx32, pc.instanceProperties) << "\n";
  4551. p += sizeof(uint32_t);
  4552. offset += sizeof(uint32_t);
  4553. }
  4554. }
  4555. static void print_indent(uint32_t indent) {
  4556. for (uint32_t i = 0; i < indent;) {
  4557. if (indent - i >= 8) {
  4558. outs() << "\t";
  4559. i += 8;
  4560. } else {
  4561. for (uint32_t j = i; j < indent; j++)
  4562. outs() << " ";
  4563. return;
  4564. }
  4565. }
  4566. }
  4567. static bool print_method_description_list(uint32_t p, uint32_t indent,
  4568. struct DisassembleInfo *info) {
  4569. uint32_t offset, left, xleft;
  4570. SectionRef S;
  4571. struct objc_method_description_list_t mdl;
  4572. struct objc_method_description_t md;
  4573. const char *r, *list, *name;
  4574. int32_t i;
  4575. r = get_pointer_32(p, offset, left, S, info, true);
  4576. if (r == nullptr)
  4577. return true;
  4578. outs() << "\n";
  4579. if (left > sizeof(struct objc_method_description_list_t)) {
  4580. memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
  4581. } else {
  4582. print_indent(indent);
  4583. outs() << " objc_method_description_list extends past end of the section\n";
  4584. memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
  4585. memcpy(&mdl, r, left);
  4586. }
  4587. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4588. swapStruct(mdl);
  4589. print_indent(indent);
  4590. outs() << " count " << mdl.count << "\n";
  4591. list = r + sizeof(struct objc_method_description_list_t);
  4592. for (i = 0; i < mdl.count; i++) {
  4593. if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
  4594. print_indent(indent);
  4595. outs() << " remaining list entries extend past the of the section\n";
  4596. break;
  4597. }
  4598. print_indent(indent);
  4599. outs() << " list[" << i << "]\n";
  4600. memcpy(&md, list + i * sizeof(struct objc_method_description_t),
  4601. sizeof(struct objc_method_description_t));
  4602. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4603. swapStruct(md);
  4604. print_indent(indent);
  4605. outs() << " name " << format("0x%08" PRIx32, md.name);
  4606. if (info->verbose) {
  4607. name = get_pointer_32(md.name, offset, xleft, S, info, true);
  4608. if (name != nullptr)
  4609. outs() << format(" %.*s", xleft, name);
  4610. else
  4611. outs() << " (not in an __OBJC section)";
  4612. }
  4613. outs() << "\n";
  4614. print_indent(indent);
  4615. outs() << " types " << format("0x%08" PRIx32, md.types);
  4616. if (info->verbose) {
  4617. name = get_pointer_32(md.types, offset, xleft, S, info, true);
  4618. if (name != nullptr)
  4619. outs() << format(" %.*s", xleft, name);
  4620. else
  4621. outs() << " (not in an __OBJC section)";
  4622. }
  4623. outs() << "\n";
  4624. }
  4625. return false;
  4626. }
  4627. static bool print_protocol_list(uint32_t p, uint32_t indent,
  4628. struct DisassembleInfo *info);
  4629. static bool print_protocol(uint32_t p, uint32_t indent,
  4630. struct DisassembleInfo *info) {
  4631. uint32_t offset, left;
  4632. SectionRef S;
  4633. struct objc_protocol_t protocol;
  4634. const char *r, *name;
  4635. r = get_pointer_32(p, offset, left, S, info, true);
  4636. if (r == nullptr)
  4637. return true;
  4638. outs() << "\n";
  4639. if (left >= sizeof(struct objc_protocol_t)) {
  4640. memcpy(&protocol, r, sizeof(struct objc_protocol_t));
  4641. } else {
  4642. print_indent(indent);
  4643. outs() << " Protocol extends past end of the section\n";
  4644. memset(&protocol, '\0', sizeof(struct objc_protocol_t));
  4645. memcpy(&protocol, r, left);
  4646. }
  4647. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4648. swapStruct(protocol);
  4649. print_indent(indent);
  4650. outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
  4651. << "\n";
  4652. print_indent(indent);
  4653. outs() << " protocol_name "
  4654. << format("0x%08" PRIx32, protocol.protocol_name);
  4655. if (info->verbose) {
  4656. name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
  4657. if (name != nullptr)
  4658. outs() << format(" %.*s", left, name);
  4659. else
  4660. outs() << " (not in an __OBJC section)";
  4661. }
  4662. outs() << "\n";
  4663. print_indent(indent);
  4664. outs() << " protocol_list "
  4665. << format("0x%08" PRIx32, protocol.protocol_list);
  4666. if (print_protocol_list(protocol.protocol_list, indent + 4, info))
  4667. outs() << " (not in an __OBJC section)\n";
  4668. print_indent(indent);
  4669. outs() << " instance_methods "
  4670. << format("0x%08" PRIx32, protocol.instance_methods);
  4671. if (print_method_description_list(protocol.instance_methods, indent, info))
  4672. outs() << " (not in an __OBJC section)\n";
  4673. print_indent(indent);
  4674. outs() << " class_methods "
  4675. << format("0x%08" PRIx32, protocol.class_methods);
  4676. if (print_method_description_list(protocol.class_methods, indent, info))
  4677. outs() << " (not in an __OBJC section)\n";
  4678. return false;
  4679. }
  4680. static bool print_protocol_list(uint32_t p, uint32_t indent,
  4681. struct DisassembleInfo *info) {
  4682. uint32_t offset, left, l;
  4683. SectionRef S;
  4684. struct objc_protocol_list_t protocol_list;
  4685. const char *r, *list;
  4686. int32_t i;
  4687. r = get_pointer_32(p, offset, left, S, info, true);
  4688. if (r == nullptr)
  4689. return true;
  4690. outs() << "\n";
  4691. if (left > sizeof(struct objc_protocol_list_t)) {
  4692. memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
  4693. } else {
  4694. outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
  4695. memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
  4696. memcpy(&protocol_list, r, left);
  4697. }
  4698. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4699. swapStruct(protocol_list);
  4700. print_indent(indent);
  4701. outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
  4702. << "\n";
  4703. print_indent(indent);
  4704. outs() << " count " << protocol_list.count << "\n";
  4705. list = r + sizeof(struct objc_protocol_list_t);
  4706. for (i = 0; i < protocol_list.count; i++) {
  4707. if ((i + 1) * sizeof(uint32_t) > left) {
  4708. outs() << "\t\t remaining list entries extend past the of the section\n";
  4709. break;
  4710. }
  4711. memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
  4712. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4713. sys::swapByteOrder(l);
  4714. print_indent(indent);
  4715. outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
  4716. if (print_protocol(l, indent, info))
  4717. outs() << "(not in an __OBJC section)\n";
  4718. }
  4719. return false;
  4720. }
  4721. static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
  4722. struct ivar_list64_t il;
  4723. struct ivar64_t i;
  4724. const char *r;
  4725. uint32_t offset, xoffset, left, j;
  4726. SectionRef S, xS;
  4727. const char *name, *sym_name, *ivar_offset_p;
  4728. uint64_t ivar_offset, n_value;
  4729. r = get_pointer_64(p, offset, left, S, info);
  4730. if (r == nullptr)
  4731. return;
  4732. memset(&il, '\0', sizeof(struct ivar_list64_t));
  4733. if (left < sizeof(struct ivar_list64_t)) {
  4734. memcpy(&il, r, left);
  4735. outs() << " (ivar_list_t entends past the end of the section)\n";
  4736. } else
  4737. memcpy(&il, r, sizeof(struct ivar_list64_t));
  4738. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4739. swapStruct(il);
  4740. outs() << " entsize " << il.entsize << "\n";
  4741. outs() << " count " << il.count << "\n";
  4742. p += sizeof(struct ivar_list64_t);
  4743. offset += sizeof(struct ivar_list64_t);
  4744. for (j = 0; j < il.count; j++) {
  4745. r = get_pointer_64(p, offset, left, S, info);
  4746. if (r == nullptr)
  4747. return;
  4748. memset(&i, '\0', sizeof(struct ivar64_t));
  4749. if (left < sizeof(struct ivar64_t)) {
  4750. memcpy(&i, r, left);
  4751. outs() << " (ivar_t entends past the end of the section)\n";
  4752. } else
  4753. memcpy(&i, r, sizeof(struct ivar64_t));
  4754. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4755. swapStruct(i);
  4756. outs() << "\t\t\t offset ";
  4757. sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
  4758. info, n_value, i.offset);
  4759. if (n_value != 0) {
  4760. if (info->verbose && sym_name != nullptr)
  4761. outs() << sym_name;
  4762. else
  4763. outs() << format("0x%" PRIx64, n_value);
  4764. if (i.offset != 0)
  4765. outs() << " + " << format("0x%" PRIx64, i.offset);
  4766. } else
  4767. outs() << format("0x%" PRIx64, i.offset);
  4768. ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
  4769. if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
  4770. memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
  4771. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4772. sys::swapByteOrder(ivar_offset);
  4773. outs() << " " << ivar_offset << "\n";
  4774. } else
  4775. outs() << "\n";
  4776. outs() << "\t\t\t name ";
  4777. sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
  4778. n_value, i.name);
  4779. if (n_value != 0) {
  4780. if (info->verbose && sym_name != nullptr)
  4781. outs() << sym_name;
  4782. else
  4783. outs() << format("0x%" PRIx64, n_value);
  4784. if (i.name != 0)
  4785. outs() << " + " << format("0x%" PRIx64, i.name);
  4786. } else
  4787. outs() << format("0x%" PRIx64, i.name);
  4788. name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
  4789. if (name != nullptr)
  4790. outs() << format(" %.*s", left, name);
  4791. outs() << "\n";
  4792. outs() << "\t\t\t type ";
  4793. sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
  4794. n_value, i.name);
  4795. name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
  4796. if (n_value != 0) {
  4797. if (info->verbose && sym_name != nullptr)
  4798. outs() << sym_name;
  4799. else
  4800. outs() << format("0x%" PRIx64, n_value);
  4801. if (i.type != 0)
  4802. outs() << " + " << format("0x%" PRIx64, i.type);
  4803. } else
  4804. outs() << format("0x%" PRIx64, i.type);
  4805. if (name != nullptr)
  4806. outs() << format(" %.*s", left, name);
  4807. outs() << "\n";
  4808. outs() << "\t\t\talignment " << i.alignment << "\n";
  4809. outs() << "\t\t\t size " << i.size << "\n";
  4810. p += sizeof(struct ivar64_t);
  4811. offset += sizeof(struct ivar64_t);
  4812. }
  4813. }
  4814. static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
  4815. struct ivar_list32_t il;
  4816. struct ivar32_t i;
  4817. const char *r;
  4818. uint32_t offset, xoffset, left, j;
  4819. SectionRef S, xS;
  4820. const char *name, *ivar_offset_p;
  4821. uint32_t ivar_offset;
  4822. r = get_pointer_32(p, offset, left, S, info);
  4823. if (r == nullptr)
  4824. return;
  4825. memset(&il, '\0', sizeof(struct ivar_list32_t));
  4826. if (left < sizeof(struct ivar_list32_t)) {
  4827. memcpy(&il, r, left);
  4828. outs() << " (ivar_list_t entends past the end of the section)\n";
  4829. } else
  4830. memcpy(&il, r, sizeof(struct ivar_list32_t));
  4831. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4832. swapStruct(il);
  4833. outs() << " entsize " << il.entsize << "\n";
  4834. outs() << " count " << il.count << "\n";
  4835. p += sizeof(struct ivar_list32_t);
  4836. offset += sizeof(struct ivar_list32_t);
  4837. for (j = 0; j < il.count; j++) {
  4838. r = get_pointer_32(p, offset, left, S, info);
  4839. if (r == nullptr)
  4840. return;
  4841. memset(&i, '\0', sizeof(struct ivar32_t));
  4842. if (left < sizeof(struct ivar32_t)) {
  4843. memcpy(&i, r, left);
  4844. outs() << " (ivar_t entends past the end of the section)\n";
  4845. } else
  4846. memcpy(&i, r, sizeof(struct ivar32_t));
  4847. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4848. swapStruct(i);
  4849. outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
  4850. ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
  4851. if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
  4852. memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
  4853. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4854. sys::swapByteOrder(ivar_offset);
  4855. outs() << " " << ivar_offset << "\n";
  4856. } else
  4857. outs() << "\n";
  4858. outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
  4859. name = get_pointer_32(i.name, xoffset, left, xS, info);
  4860. if (name != nullptr)
  4861. outs() << format(" %.*s", left, name);
  4862. outs() << "\n";
  4863. outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
  4864. name = get_pointer_32(i.type, xoffset, left, xS, info);
  4865. if (name != nullptr)
  4866. outs() << format(" %.*s", left, name);
  4867. outs() << "\n";
  4868. outs() << "\t\t\talignment " << i.alignment << "\n";
  4869. outs() << "\t\t\t size " << i.size << "\n";
  4870. p += sizeof(struct ivar32_t);
  4871. offset += sizeof(struct ivar32_t);
  4872. }
  4873. }
  4874. static void print_objc_property_list64(uint64_t p,
  4875. struct DisassembleInfo *info) {
  4876. struct objc_property_list64 opl;
  4877. struct objc_property64 op;
  4878. const char *r;
  4879. uint32_t offset, xoffset, left, j;
  4880. SectionRef S, xS;
  4881. const char *name, *sym_name;
  4882. uint64_t n_value;
  4883. r = get_pointer_64(p, offset, left, S, info);
  4884. if (r == nullptr)
  4885. return;
  4886. memset(&opl, '\0', sizeof(struct objc_property_list64));
  4887. if (left < sizeof(struct objc_property_list64)) {
  4888. memcpy(&opl, r, left);
  4889. outs() << " (objc_property_list entends past the end of the section)\n";
  4890. } else
  4891. memcpy(&opl, r, sizeof(struct objc_property_list64));
  4892. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4893. swapStruct(opl);
  4894. outs() << " entsize " << opl.entsize << "\n";
  4895. outs() << " count " << opl.count << "\n";
  4896. p += sizeof(struct objc_property_list64);
  4897. offset += sizeof(struct objc_property_list64);
  4898. for (j = 0; j < opl.count; j++) {
  4899. r = get_pointer_64(p, offset, left, S, info);
  4900. if (r == nullptr)
  4901. return;
  4902. memset(&op, '\0', sizeof(struct objc_property64));
  4903. if (left < sizeof(struct objc_property64)) {
  4904. memcpy(&op, r, left);
  4905. outs() << " (objc_property entends past the end of the section)\n";
  4906. } else
  4907. memcpy(&op, r, sizeof(struct objc_property64));
  4908. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4909. swapStruct(op);
  4910. outs() << "\t\t\t name ";
  4911. sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
  4912. info, n_value, op.name);
  4913. if (n_value != 0) {
  4914. if (info->verbose && sym_name != nullptr)
  4915. outs() << sym_name;
  4916. else
  4917. outs() << format("0x%" PRIx64, n_value);
  4918. if (op.name != 0)
  4919. outs() << " + " << format("0x%" PRIx64, op.name);
  4920. } else
  4921. outs() << format("0x%" PRIx64, op.name);
  4922. name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
  4923. if (name != nullptr)
  4924. outs() << format(" %.*s", left, name);
  4925. outs() << "\n";
  4926. outs() << "\t\t\tattributes ";
  4927. sym_name =
  4928. get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
  4929. info, n_value, op.attributes);
  4930. if (n_value != 0) {
  4931. if (info->verbose && sym_name != nullptr)
  4932. outs() << sym_name;
  4933. else
  4934. outs() << format("0x%" PRIx64, n_value);
  4935. if (op.attributes != 0)
  4936. outs() << " + " << format("0x%" PRIx64, op.attributes);
  4937. } else
  4938. outs() << format("0x%" PRIx64, op.attributes);
  4939. name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
  4940. if (name != nullptr)
  4941. outs() << format(" %.*s", left, name);
  4942. outs() << "\n";
  4943. p += sizeof(struct objc_property64);
  4944. offset += sizeof(struct objc_property64);
  4945. }
  4946. }
  4947. static void print_objc_property_list32(uint32_t p,
  4948. struct DisassembleInfo *info) {
  4949. struct objc_property_list32 opl;
  4950. struct objc_property32 op;
  4951. const char *r;
  4952. uint32_t offset, xoffset, left, j;
  4953. SectionRef S, xS;
  4954. const char *name;
  4955. r = get_pointer_32(p, offset, left, S, info);
  4956. if (r == nullptr)
  4957. return;
  4958. memset(&opl, '\0', sizeof(struct objc_property_list32));
  4959. if (left < sizeof(struct objc_property_list32)) {
  4960. memcpy(&opl, r, left);
  4961. outs() << " (objc_property_list entends past the end of the section)\n";
  4962. } else
  4963. memcpy(&opl, r, sizeof(struct objc_property_list32));
  4964. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4965. swapStruct(opl);
  4966. outs() << " entsize " << opl.entsize << "\n";
  4967. outs() << " count " << opl.count << "\n";
  4968. p += sizeof(struct objc_property_list32);
  4969. offset += sizeof(struct objc_property_list32);
  4970. for (j = 0; j < opl.count; j++) {
  4971. r = get_pointer_32(p, offset, left, S, info);
  4972. if (r == nullptr)
  4973. return;
  4974. memset(&op, '\0', sizeof(struct objc_property32));
  4975. if (left < sizeof(struct objc_property32)) {
  4976. memcpy(&op, r, left);
  4977. outs() << " (objc_property entends past the end of the section)\n";
  4978. } else
  4979. memcpy(&op, r, sizeof(struct objc_property32));
  4980. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4981. swapStruct(op);
  4982. outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
  4983. name = get_pointer_32(op.name, xoffset, left, xS, info);
  4984. if (name != nullptr)
  4985. outs() << format(" %.*s", left, name);
  4986. outs() << "\n";
  4987. outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
  4988. name = get_pointer_32(op.attributes, xoffset, left, xS, info);
  4989. if (name != nullptr)
  4990. outs() << format(" %.*s", left, name);
  4991. outs() << "\n";
  4992. p += sizeof(struct objc_property32);
  4993. offset += sizeof(struct objc_property32);
  4994. }
  4995. }
  4996. static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
  4997. bool &is_meta_class) {
  4998. struct class_ro64_t cro;
  4999. const char *r;
  5000. uint32_t offset, xoffset, left;
  5001. SectionRef S, xS;
  5002. const char *name, *sym_name;
  5003. uint64_t n_value;
  5004. r = get_pointer_64(p, offset, left, S, info);
  5005. if (r == nullptr || left < sizeof(struct class_ro64_t))
  5006. return false;
  5007. memcpy(&cro, r, sizeof(struct class_ro64_t));
  5008. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5009. swapStruct(cro);
  5010. outs() << " flags " << format("0x%" PRIx32, cro.flags);
  5011. if (cro.flags & RO_META)
  5012. outs() << " RO_META";
  5013. if (cro.flags & RO_ROOT)
  5014. outs() << " RO_ROOT";
  5015. if (cro.flags & RO_HAS_CXX_STRUCTORS)
  5016. outs() << " RO_HAS_CXX_STRUCTORS";
  5017. outs() << "\n";
  5018. outs() << " instanceStart " << cro.instanceStart << "\n";
  5019. outs() << " instanceSize " << cro.instanceSize << "\n";
  5020. outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
  5021. << "\n";
  5022. outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
  5023. << "\n";
  5024. print_layout_map64(cro.ivarLayout, info);
  5025. outs() << " name ";
  5026. sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
  5027. info, n_value, cro.name);
  5028. if (n_value != 0) {
  5029. if (info->verbose && sym_name != nullptr)
  5030. outs() << sym_name;
  5031. else
  5032. outs() << format("0x%" PRIx64, n_value);
  5033. if (cro.name != 0)
  5034. outs() << " + " << format("0x%" PRIx64, cro.name);
  5035. } else
  5036. outs() << format("0x%" PRIx64, cro.name);
  5037. name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
  5038. if (name != nullptr)
  5039. outs() << format(" %.*s", left, name);
  5040. outs() << "\n";
  5041. outs() << " baseMethods ";
  5042. sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
  5043. S, info, n_value, cro.baseMethods);
  5044. if (n_value != 0) {
  5045. if (info->verbose && sym_name != nullptr)
  5046. outs() << sym_name;
  5047. else
  5048. outs() << format("0x%" PRIx64, n_value);
  5049. if (cro.baseMethods != 0)
  5050. outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
  5051. } else
  5052. outs() << format("0x%" PRIx64, cro.baseMethods);
  5053. outs() << " (struct method_list_t *)\n";
  5054. if (cro.baseMethods + n_value != 0)
  5055. print_method_list64_t(cro.baseMethods + n_value, info, "");
  5056. outs() << " baseProtocols ";
  5057. sym_name =
  5058. get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
  5059. info, n_value, cro.baseProtocols);
  5060. if (n_value != 0) {
  5061. if (info->verbose && sym_name != nullptr)
  5062. outs() << sym_name;
  5063. else
  5064. outs() << format("0x%" PRIx64, n_value);
  5065. if (cro.baseProtocols != 0)
  5066. outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
  5067. } else
  5068. outs() << format("0x%" PRIx64, cro.baseProtocols);
  5069. outs() << "\n";
  5070. if (cro.baseProtocols + n_value != 0)
  5071. print_protocol_list64_t(cro.baseProtocols + n_value, info);
  5072. outs() << " ivars ";
  5073. sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
  5074. info, n_value, cro.ivars);
  5075. if (n_value != 0) {
  5076. if (info->verbose && sym_name != nullptr)
  5077. outs() << sym_name;
  5078. else
  5079. outs() << format("0x%" PRIx64, n_value);
  5080. if (cro.ivars != 0)
  5081. outs() << " + " << format("0x%" PRIx64, cro.ivars);
  5082. } else
  5083. outs() << format("0x%" PRIx64, cro.ivars);
  5084. outs() << "\n";
  5085. if (cro.ivars + n_value != 0)
  5086. print_ivar_list64_t(cro.ivars + n_value, info);
  5087. outs() << " weakIvarLayout ";
  5088. sym_name =
  5089. get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
  5090. info, n_value, cro.weakIvarLayout);
  5091. if (n_value != 0) {
  5092. if (info->verbose && sym_name != nullptr)
  5093. outs() << sym_name;
  5094. else
  5095. outs() << format("0x%" PRIx64, n_value);
  5096. if (cro.weakIvarLayout != 0)
  5097. outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
  5098. } else
  5099. outs() << format("0x%" PRIx64, cro.weakIvarLayout);
  5100. outs() << "\n";
  5101. print_layout_map64(cro.weakIvarLayout + n_value, info);
  5102. outs() << " baseProperties ";
  5103. sym_name =
  5104. get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
  5105. info, n_value, cro.baseProperties);
  5106. if (n_value != 0) {
  5107. if (info->verbose && sym_name != nullptr)
  5108. outs() << sym_name;
  5109. else
  5110. outs() << format("0x%" PRIx64, n_value);
  5111. if (cro.baseProperties != 0)
  5112. outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
  5113. } else
  5114. outs() << format("0x%" PRIx64, cro.baseProperties);
  5115. outs() << "\n";
  5116. if (cro.baseProperties + n_value != 0)
  5117. print_objc_property_list64(cro.baseProperties + n_value, info);
  5118. is_meta_class = (cro.flags & RO_META) != 0;
  5119. return true;
  5120. }
  5121. static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
  5122. bool &is_meta_class) {
  5123. struct class_ro32_t cro;
  5124. const char *r;
  5125. uint32_t offset, xoffset, left;
  5126. SectionRef S, xS;
  5127. const char *name;
  5128. r = get_pointer_32(p, offset, left, S, info);
  5129. if (r == nullptr)
  5130. return false;
  5131. memset(&cro, '\0', sizeof(struct class_ro32_t));
  5132. if (left < sizeof(struct class_ro32_t)) {
  5133. memcpy(&cro, r, left);
  5134. outs() << " (class_ro_t entends past the end of the section)\n";
  5135. } else
  5136. memcpy(&cro, r, sizeof(struct class_ro32_t));
  5137. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5138. swapStruct(cro);
  5139. outs() << " flags " << format("0x%" PRIx32, cro.flags);
  5140. if (cro.flags & RO_META)
  5141. outs() << " RO_META";
  5142. if (cro.flags & RO_ROOT)
  5143. outs() << " RO_ROOT";
  5144. if (cro.flags & RO_HAS_CXX_STRUCTORS)
  5145. outs() << " RO_HAS_CXX_STRUCTORS";
  5146. outs() << "\n";
  5147. outs() << " instanceStart " << cro.instanceStart << "\n";
  5148. outs() << " instanceSize " << cro.instanceSize << "\n";
  5149. outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
  5150. << "\n";
  5151. print_layout_map32(cro.ivarLayout, info);
  5152. outs() << " name " << format("0x%" PRIx32, cro.name);
  5153. name = get_pointer_32(cro.name, xoffset, left, xS, info);
  5154. if (name != nullptr)
  5155. outs() << format(" %.*s", left, name);
  5156. outs() << "\n";
  5157. outs() << " baseMethods "
  5158. << format("0x%" PRIx32, cro.baseMethods)
  5159. << " (struct method_list_t *)\n";
  5160. if (cro.baseMethods != 0)
  5161. print_method_list32_t(cro.baseMethods, info, "");
  5162. outs() << " baseProtocols "
  5163. << format("0x%" PRIx32, cro.baseProtocols) << "\n";
  5164. if (cro.baseProtocols != 0)
  5165. print_protocol_list32_t(cro.baseProtocols, info);
  5166. outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
  5167. << "\n";
  5168. if (cro.ivars != 0)
  5169. print_ivar_list32_t(cro.ivars, info);
  5170. outs() << " weakIvarLayout "
  5171. << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
  5172. print_layout_map32(cro.weakIvarLayout, info);
  5173. outs() << " baseProperties "
  5174. << format("0x%" PRIx32, cro.baseProperties) << "\n";
  5175. if (cro.baseProperties != 0)
  5176. print_objc_property_list32(cro.baseProperties, info);
  5177. is_meta_class = (cro.flags & RO_META) != 0;
  5178. return true;
  5179. }
  5180. static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
  5181. struct class64_t c;
  5182. const char *r;
  5183. uint32_t offset, left;
  5184. SectionRef S;
  5185. const char *name;
  5186. uint64_t isa_n_value, n_value;
  5187. r = get_pointer_64(p, offset, left, S, info);
  5188. if (r == nullptr || left < sizeof(struct class64_t))
  5189. return;
  5190. memcpy(&c, r, sizeof(struct class64_t));
  5191. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5192. swapStruct(c);
  5193. outs() << " isa " << format("0x%" PRIx64, c.isa);
  5194. name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
  5195. isa_n_value, c.isa);
  5196. if (name != nullptr)
  5197. outs() << " " << name;
  5198. outs() << "\n";
  5199. outs() << " superclass " << format("0x%" PRIx64, c.superclass);
  5200. name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
  5201. n_value, c.superclass);
  5202. if (name != nullptr)
  5203. outs() << " " << name;
  5204. else {
  5205. name = get_dyld_bind_info_symbolname(S.getAddress() +
  5206. offset + offsetof(struct class64_t, superclass), info);
  5207. if (name != nullptr)
  5208. outs() << " " << name;
  5209. }
  5210. outs() << "\n";
  5211. outs() << " cache " << format("0x%" PRIx64, c.cache);
  5212. name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
  5213. n_value, c.cache);
  5214. if (name != nullptr)
  5215. outs() << " " << name;
  5216. outs() << "\n";
  5217. outs() << " vtable " << format("0x%" PRIx64, c.vtable);
  5218. name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
  5219. n_value, c.vtable);
  5220. if (name != nullptr)
  5221. outs() << " " << name;
  5222. outs() << "\n";
  5223. name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
  5224. n_value, c.data);
  5225. outs() << " data ";
  5226. if (n_value != 0) {
  5227. if (info->verbose && name != nullptr)
  5228. outs() << name;
  5229. else
  5230. outs() << format("0x%" PRIx64, n_value);
  5231. if (c.data != 0)
  5232. outs() << " + " << format("0x%" PRIx64, c.data);
  5233. } else
  5234. outs() << format("0x%" PRIx64, c.data);
  5235. outs() << " (struct class_ro_t *)";
  5236. // This is a Swift class if some of the low bits of the pointer are set.
  5237. if ((c.data + n_value) & 0x7)
  5238. outs() << " Swift class";
  5239. outs() << "\n";
  5240. bool is_meta_class;
  5241. if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
  5242. return;
  5243. if (!is_meta_class &&
  5244. c.isa + isa_n_value != p &&
  5245. c.isa + isa_n_value != 0 &&
  5246. info->depth < 100) {
  5247. info->depth++;
  5248. outs() << "Meta Class\n";
  5249. print_class64_t(c.isa + isa_n_value, info);
  5250. }
  5251. }
  5252. static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
  5253. struct class32_t c;
  5254. const char *r;
  5255. uint32_t offset, left;
  5256. SectionRef S;
  5257. const char *name;
  5258. r = get_pointer_32(p, offset, left, S, info);
  5259. if (r == nullptr)
  5260. return;
  5261. memset(&c, '\0', sizeof(struct class32_t));
  5262. if (left < sizeof(struct class32_t)) {
  5263. memcpy(&c, r, left);
  5264. outs() << " (class_t entends past the end of the section)\n";
  5265. } else
  5266. memcpy(&c, r, sizeof(struct class32_t));
  5267. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5268. swapStruct(c);
  5269. outs() << " isa " << format("0x%" PRIx32, c.isa);
  5270. name =
  5271. get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
  5272. if (name != nullptr)
  5273. outs() << " " << name;
  5274. outs() << "\n";
  5275. outs() << " superclass " << format("0x%" PRIx32, c.superclass);
  5276. name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
  5277. c.superclass);
  5278. if (name != nullptr)
  5279. outs() << " " << name;
  5280. outs() << "\n";
  5281. outs() << " cache " << format("0x%" PRIx32, c.cache);
  5282. name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
  5283. c.cache);
  5284. if (name != nullptr)
  5285. outs() << " " << name;
  5286. outs() << "\n";
  5287. outs() << " vtable " << format("0x%" PRIx32, c.vtable);
  5288. name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
  5289. c.vtable);
  5290. if (name != nullptr)
  5291. outs() << " " << name;
  5292. outs() << "\n";
  5293. name =
  5294. get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
  5295. outs() << " data " << format("0x%" PRIx32, c.data)
  5296. << " (struct class_ro_t *)";
  5297. // This is a Swift class if some of the low bits of the pointer are set.
  5298. if (c.data & 0x3)
  5299. outs() << " Swift class";
  5300. outs() << "\n";
  5301. bool is_meta_class;
  5302. if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
  5303. return;
  5304. if (!is_meta_class) {
  5305. outs() << "Meta Class\n";
  5306. print_class32_t(c.isa, info);
  5307. }
  5308. }
  5309. static void print_objc_class_t(struct objc_class_t *objc_class,
  5310. struct DisassembleInfo *info) {
  5311. uint32_t offset, left, xleft;
  5312. const char *name, *p, *ivar_list;
  5313. SectionRef S;
  5314. int32_t i;
  5315. struct objc_ivar_list_t objc_ivar_list;
  5316. struct objc_ivar_t ivar;
  5317. outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
  5318. if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
  5319. name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
  5320. if (name != nullptr)
  5321. outs() << format(" %.*s", left, name);
  5322. else
  5323. outs() << " (not in an __OBJC section)";
  5324. }
  5325. outs() << "\n";
  5326. outs() << "\t super_class "
  5327. << format("0x%08" PRIx32, objc_class->super_class);
  5328. if (info->verbose) {
  5329. name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
  5330. if (name != nullptr)
  5331. outs() << format(" %.*s", left, name);
  5332. else
  5333. outs() << " (not in an __OBJC section)";
  5334. }
  5335. outs() << "\n";
  5336. outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
  5337. if (info->verbose) {
  5338. name = get_pointer_32(objc_class->name, offset, left, S, info, true);
  5339. if (name != nullptr)
  5340. outs() << format(" %.*s", left, name);
  5341. else
  5342. outs() << " (not in an __OBJC section)";
  5343. }
  5344. outs() << "\n";
  5345. outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
  5346. << "\n";
  5347. outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
  5348. if (info->verbose) {
  5349. if (CLS_GETINFO(objc_class, CLS_CLASS))
  5350. outs() << " CLS_CLASS";
  5351. else if (CLS_GETINFO(objc_class, CLS_META))
  5352. outs() << " CLS_META";
  5353. }
  5354. outs() << "\n";
  5355. outs() << "\t instance_size "
  5356. << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
  5357. p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
  5358. outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
  5359. if (p != nullptr) {
  5360. if (left > sizeof(struct objc_ivar_list_t)) {
  5361. outs() << "\n";
  5362. memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
  5363. } else {
  5364. outs() << " (entends past the end of the section)\n";
  5365. memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
  5366. memcpy(&objc_ivar_list, p, left);
  5367. }
  5368. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5369. swapStruct(objc_ivar_list);
  5370. outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
  5371. ivar_list = p + sizeof(struct objc_ivar_list_t);
  5372. for (i = 0; i < objc_ivar_list.ivar_count; i++) {
  5373. if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
  5374. outs() << "\t\t remaining ivar's extend past the of the section\n";
  5375. break;
  5376. }
  5377. memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
  5378. sizeof(struct objc_ivar_t));
  5379. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5380. swapStruct(ivar);
  5381. outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
  5382. if (info->verbose) {
  5383. name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
  5384. if (name != nullptr)
  5385. outs() << format(" %.*s", xleft, name);
  5386. else
  5387. outs() << " (not in an __OBJC section)";
  5388. }
  5389. outs() << "\n";
  5390. outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
  5391. if (info->verbose) {
  5392. name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
  5393. if (name != nullptr)
  5394. outs() << format(" %.*s", xleft, name);
  5395. else
  5396. outs() << " (not in an __OBJC section)";
  5397. }
  5398. outs() << "\n";
  5399. outs() << "\t\t ivar_offset "
  5400. << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
  5401. }
  5402. } else {
  5403. outs() << " (not in an __OBJC section)\n";
  5404. }
  5405. outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
  5406. if (print_method_list(objc_class->methodLists, info))
  5407. outs() << " (not in an __OBJC section)\n";
  5408. outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
  5409. << "\n";
  5410. outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
  5411. if (print_protocol_list(objc_class->protocols, 16, info))
  5412. outs() << " (not in an __OBJC section)\n";
  5413. }
  5414. static void print_objc_objc_category_t(struct objc_category_t *objc_category,
  5415. struct DisassembleInfo *info) {
  5416. uint32_t offset, left;
  5417. const char *name;
  5418. SectionRef S;
  5419. outs() << "\t category name "
  5420. << format("0x%08" PRIx32, objc_category->category_name);
  5421. if (info->verbose) {
  5422. name = get_pointer_32(objc_category->category_name, offset, left, S, info,
  5423. true);
  5424. if (name != nullptr)
  5425. outs() << format(" %.*s", left, name);
  5426. else
  5427. outs() << " (not in an __OBJC section)";
  5428. }
  5429. outs() << "\n";
  5430. outs() << "\t\t class name "
  5431. << format("0x%08" PRIx32, objc_category->class_name);
  5432. if (info->verbose) {
  5433. name =
  5434. get_pointer_32(objc_category->class_name, offset, left, S, info, true);
  5435. if (name != nullptr)
  5436. outs() << format(" %.*s", left, name);
  5437. else
  5438. outs() << " (not in an __OBJC section)";
  5439. }
  5440. outs() << "\n";
  5441. outs() << "\t instance methods "
  5442. << format("0x%08" PRIx32, objc_category->instance_methods);
  5443. if (print_method_list(objc_category->instance_methods, info))
  5444. outs() << " (not in an __OBJC section)\n";
  5445. outs() << "\t class methods "
  5446. << format("0x%08" PRIx32, objc_category->class_methods);
  5447. if (print_method_list(objc_category->class_methods, info))
  5448. outs() << " (not in an __OBJC section)\n";
  5449. }
  5450. static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
  5451. struct category64_t c;
  5452. const char *r;
  5453. uint32_t offset, xoffset, left;
  5454. SectionRef S, xS;
  5455. const char *name, *sym_name;
  5456. uint64_t n_value;
  5457. r = get_pointer_64(p, offset, left, S, info);
  5458. if (r == nullptr)
  5459. return;
  5460. memset(&c, '\0', sizeof(struct category64_t));
  5461. if (left < sizeof(struct category64_t)) {
  5462. memcpy(&c, r, left);
  5463. outs() << " (category_t entends past the end of the section)\n";
  5464. } else
  5465. memcpy(&c, r, sizeof(struct category64_t));
  5466. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5467. swapStruct(c);
  5468. outs() << " name ";
  5469. sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
  5470. info, n_value, c.name);
  5471. if (n_value != 0) {
  5472. if (info->verbose && sym_name != nullptr)
  5473. outs() << sym_name;
  5474. else
  5475. outs() << format("0x%" PRIx64, n_value);
  5476. if (c.name != 0)
  5477. outs() << " + " << format("0x%" PRIx64, c.name);
  5478. } else
  5479. outs() << format("0x%" PRIx64, c.name);
  5480. name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
  5481. if (name != nullptr)
  5482. outs() << format(" %.*s", left, name);
  5483. outs() << "\n";
  5484. outs() << " cls ";
  5485. sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
  5486. n_value, c.cls);
  5487. if (n_value != 0) {
  5488. if (info->verbose && sym_name != nullptr)
  5489. outs() << sym_name;
  5490. else
  5491. outs() << format("0x%" PRIx64, n_value);
  5492. if (c.cls != 0)
  5493. outs() << " + " << format("0x%" PRIx64, c.cls);
  5494. } else
  5495. outs() << format("0x%" PRIx64, c.cls);
  5496. outs() << "\n";
  5497. if (c.cls + n_value != 0)
  5498. print_class64_t(c.cls + n_value, info);
  5499. outs() << " instanceMethods ";
  5500. sym_name =
  5501. get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
  5502. info, n_value, c.instanceMethods);
  5503. if (n_value != 0) {
  5504. if (info->verbose && sym_name != nullptr)
  5505. outs() << sym_name;
  5506. else
  5507. outs() << format("0x%" PRIx64, n_value);
  5508. if (c.instanceMethods != 0)
  5509. outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
  5510. } else
  5511. outs() << format("0x%" PRIx64, c.instanceMethods);
  5512. outs() << "\n";
  5513. if (c.instanceMethods + n_value != 0)
  5514. print_method_list64_t(c.instanceMethods + n_value, info, "");
  5515. outs() << " classMethods ";
  5516. sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
  5517. S, info, n_value, c.classMethods);
  5518. if (n_value != 0) {
  5519. if (info->verbose && sym_name != nullptr)
  5520. outs() << sym_name;
  5521. else
  5522. outs() << format("0x%" PRIx64, n_value);
  5523. if (c.classMethods != 0)
  5524. outs() << " + " << format("0x%" PRIx64, c.classMethods);
  5525. } else
  5526. outs() << format("0x%" PRIx64, c.classMethods);
  5527. outs() << "\n";
  5528. if (c.classMethods + n_value != 0)
  5529. print_method_list64_t(c.classMethods + n_value, info, "");
  5530. outs() << " protocols ";
  5531. sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
  5532. info, n_value, c.protocols);
  5533. if (n_value != 0) {
  5534. if (info->verbose && sym_name != nullptr)
  5535. outs() << sym_name;
  5536. else
  5537. outs() << format("0x%" PRIx64, n_value);
  5538. if (c.protocols != 0)
  5539. outs() << " + " << format("0x%" PRIx64, c.protocols);
  5540. } else
  5541. outs() << format("0x%" PRIx64, c.protocols);
  5542. outs() << "\n";
  5543. if (c.protocols + n_value != 0)
  5544. print_protocol_list64_t(c.protocols + n_value, info);
  5545. outs() << "instanceProperties ";
  5546. sym_name =
  5547. get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
  5548. S, info, n_value, c.instanceProperties);
  5549. if (n_value != 0) {
  5550. if (info->verbose && sym_name != nullptr)
  5551. outs() << sym_name;
  5552. else
  5553. outs() << format("0x%" PRIx64, n_value);
  5554. if (c.instanceProperties != 0)
  5555. outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
  5556. } else
  5557. outs() << format("0x%" PRIx64, c.instanceProperties);
  5558. outs() << "\n";
  5559. if (c.instanceProperties + n_value != 0)
  5560. print_objc_property_list64(c.instanceProperties + n_value, info);
  5561. }
  5562. static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
  5563. struct category32_t c;
  5564. const char *r;
  5565. uint32_t offset, left;
  5566. SectionRef S, xS;
  5567. const char *name;
  5568. r = get_pointer_32(p, offset, left, S, info);
  5569. if (r == nullptr)
  5570. return;
  5571. memset(&c, '\0', sizeof(struct category32_t));
  5572. if (left < sizeof(struct category32_t)) {
  5573. memcpy(&c, r, left);
  5574. outs() << " (category_t entends past the end of the section)\n";
  5575. } else
  5576. memcpy(&c, r, sizeof(struct category32_t));
  5577. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5578. swapStruct(c);
  5579. outs() << " name " << format("0x%" PRIx32, c.name);
  5580. name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
  5581. c.name);
  5582. if (name)
  5583. outs() << " " << name;
  5584. outs() << "\n";
  5585. outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
  5586. if (c.cls != 0)
  5587. print_class32_t(c.cls, info);
  5588. outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
  5589. << "\n";
  5590. if (c.instanceMethods != 0)
  5591. print_method_list32_t(c.instanceMethods, info, "");
  5592. outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
  5593. << "\n";
  5594. if (c.classMethods != 0)
  5595. print_method_list32_t(c.classMethods, info, "");
  5596. outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
  5597. if (c.protocols != 0)
  5598. print_protocol_list32_t(c.protocols, info);
  5599. outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
  5600. << "\n";
  5601. if (c.instanceProperties != 0)
  5602. print_objc_property_list32(c.instanceProperties, info);
  5603. }
  5604. static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
  5605. uint32_t i, left, offset, xoffset;
  5606. uint64_t p, n_value;
  5607. struct message_ref64 mr;
  5608. const char *name, *sym_name;
  5609. const char *r;
  5610. SectionRef xS;
  5611. if (S == SectionRef())
  5612. return;
  5613. StringRef SectName;
  5614. Expected<StringRef> SecNameOrErr = S.getName();
  5615. if (SecNameOrErr)
  5616. SectName = *SecNameOrErr;
  5617. else
  5618. consumeError(SecNameOrErr.takeError());
  5619. DataRefImpl Ref = S.getRawDataRefImpl();
  5620. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  5621. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  5622. offset = 0;
  5623. for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
  5624. p = S.getAddress() + i;
  5625. r = get_pointer_64(p, offset, left, S, info);
  5626. if (r == nullptr)
  5627. return;
  5628. memset(&mr, '\0', sizeof(struct message_ref64));
  5629. if (left < sizeof(struct message_ref64)) {
  5630. memcpy(&mr, r, left);
  5631. outs() << " (message_ref entends past the end of the section)\n";
  5632. } else
  5633. memcpy(&mr, r, sizeof(struct message_ref64));
  5634. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5635. swapStruct(mr);
  5636. outs() << " imp ";
  5637. name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
  5638. n_value, mr.imp);
  5639. if (n_value != 0) {
  5640. outs() << format("0x%" PRIx64, n_value) << " ";
  5641. if (mr.imp != 0)
  5642. outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
  5643. } else
  5644. outs() << format("0x%" PRIx64, mr.imp) << " ";
  5645. if (name != nullptr)
  5646. outs() << " " << name;
  5647. outs() << "\n";
  5648. outs() << " sel ";
  5649. sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
  5650. info, n_value, mr.sel);
  5651. if (n_value != 0) {
  5652. if (info->verbose && sym_name != nullptr)
  5653. outs() << sym_name;
  5654. else
  5655. outs() << format("0x%" PRIx64, n_value);
  5656. if (mr.sel != 0)
  5657. outs() << " + " << format("0x%" PRIx64, mr.sel);
  5658. } else
  5659. outs() << format("0x%" PRIx64, mr.sel);
  5660. name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
  5661. if (name != nullptr)
  5662. outs() << format(" %.*s", left, name);
  5663. outs() << "\n";
  5664. offset += sizeof(struct message_ref64);
  5665. }
  5666. }
  5667. static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
  5668. uint32_t i, left, offset, xoffset, p;
  5669. struct message_ref32 mr;
  5670. const char *name, *r;
  5671. SectionRef xS;
  5672. if (S == SectionRef())
  5673. return;
  5674. StringRef SectName;
  5675. Expected<StringRef> SecNameOrErr = S.getName();
  5676. if (SecNameOrErr)
  5677. SectName = *SecNameOrErr;
  5678. else
  5679. consumeError(SecNameOrErr.takeError());
  5680. DataRefImpl Ref = S.getRawDataRefImpl();
  5681. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  5682. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  5683. offset = 0;
  5684. for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
  5685. p = S.getAddress() + i;
  5686. r = get_pointer_32(p, offset, left, S, info);
  5687. if (r == nullptr)
  5688. return;
  5689. memset(&mr, '\0', sizeof(struct message_ref32));
  5690. if (left < sizeof(struct message_ref32)) {
  5691. memcpy(&mr, r, left);
  5692. outs() << " (message_ref entends past the end of the section)\n";
  5693. } else
  5694. memcpy(&mr, r, sizeof(struct message_ref32));
  5695. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5696. swapStruct(mr);
  5697. outs() << " imp " << format("0x%" PRIx32, mr.imp);
  5698. name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
  5699. mr.imp);
  5700. if (name != nullptr)
  5701. outs() << " " << name;
  5702. outs() << "\n";
  5703. outs() << " sel " << format("0x%" PRIx32, mr.sel);
  5704. name = get_pointer_32(mr.sel, xoffset, left, xS, info);
  5705. if (name != nullptr)
  5706. outs() << " " << name;
  5707. outs() << "\n";
  5708. offset += sizeof(struct message_ref32);
  5709. }
  5710. }
  5711. static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
  5712. uint32_t left, offset, swift_version;
  5713. uint64_t p;
  5714. struct objc_image_info64 o;
  5715. const char *r;
  5716. if (S == SectionRef())
  5717. return;
  5718. StringRef SectName;
  5719. Expected<StringRef> SecNameOrErr = S.getName();
  5720. if (SecNameOrErr)
  5721. SectName = *SecNameOrErr;
  5722. else
  5723. consumeError(SecNameOrErr.takeError());
  5724. DataRefImpl Ref = S.getRawDataRefImpl();
  5725. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  5726. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  5727. p = S.getAddress();
  5728. r = get_pointer_64(p, offset, left, S, info);
  5729. if (r == nullptr)
  5730. return;
  5731. memset(&o, '\0', sizeof(struct objc_image_info64));
  5732. if (left < sizeof(struct objc_image_info64)) {
  5733. memcpy(&o, r, left);
  5734. outs() << " (objc_image_info entends past the end of the section)\n";
  5735. } else
  5736. memcpy(&o, r, sizeof(struct objc_image_info64));
  5737. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5738. swapStruct(o);
  5739. outs() << " version " << o.version << "\n";
  5740. outs() << " flags " << format("0x%" PRIx32, o.flags);
  5741. if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
  5742. outs() << " OBJC_IMAGE_IS_REPLACEMENT";
  5743. if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
  5744. outs() << " OBJC_IMAGE_SUPPORTS_GC";
  5745. if (o.flags & OBJC_IMAGE_IS_SIMULATED)
  5746. outs() << " OBJC_IMAGE_IS_SIMULATED";
  5747. if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
  5748. outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
  5749. swift_version = (o.flags >> 8) & 0xff;
  5750. if (swift_version != 0) {
  5751. if (swift_version == 1)
  5752. outs() << " Swift 1.0";
  5753. else if (swift_version == 2)
  5754. outs() << " Swift 1.1";
  5755. else if(swift_version == 3)
  5756. outs() << " Swift 2.0";
  5757. else if(swift_version == 4)
  5758. outs() << " Swift 3.0";
  5759. else if(swift_version == 5)
  5760. outs() << " Swift 4.0";
  5761. else if(swift_version == 6)
  5762. outs() << " Swift 4.1/Swift 4.2";
  5763. else if(swift_version == 7)
  5764. outs() << " Swift 5 or later";
  5765. else
  5766. outs() << " unknown future Swift version (" << swift_version << ")";
  5767. }
  5768. outs() << "\n";
  5769. }
  5770. static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
  5771. uint32_t left, offset, swift_version, p;
  5772. struct objc_image_info32 o;
  5773. const char *r;
  5774. if (S == SectionRef())
  5775. return;
  5776. StringRef SectName;
  5777. Expected<StringRef> SecNameOrErr = S.getName();
  5778. if (SecNameOrErr)
  5779. SectName = *SecNameOrErr;
  5780. else
  5781. consumeError(SecNameOrErr.takeError());
  5782. DataRefImpl Ref = S.getRawDataRefImpl();
  5783. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  5784. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  5785. p = S.getAddress();
  5786. r = get_pointer_32(p, offset, left, S, info);
  5787. if (r == nullptr)
  5788. return;
  5789. memset(&o, '\0', sizeof(struct objc_image_info32));
  5790. if (left < sizeof(struct objc_image_info32)) {
  5791. memcpy(&o, r, left);
  5792. outs() << " (objc_image_info entends past the end of the section)\n";
  5793. } else
  5794. memcpy(&o, r, sizeof(struct objc_image_info32));
  5795. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5796. swapStruct(o);
  5797. outs() << " version " << o.version << "\n";
  5798. outs() << " flags " << format("0x%" PRIx32, o.flags);
  5799. if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
  5800. outs() << " OBJC_IMAGE_IS_REPLACEMENT";
  5801. if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
  5802. outs() << " OBJC_IMAGE_SUPPORTS_GC";
  5803. swift_version = (o.flags >> 8) & 0xff;
  5804. if (swift_version != 0) {
  5805. if (swift_version == 1)
  5806. outs() << " Swift 1.0";
  5807. else if (swift_version == 2)
  5808. outs() << " Swift 1.1";
  5809. else if(swift_version == 3)
  5810. outs() << " Swift 2.0";
  5811. else if(swift_version == 4)
  5812. outs() << " Swift 3.0";
  5813. else if(swift_version == 5)
  5814. outs() << " Swift 4.0";
  5815. else if(swift_version == 6)
  5816. outs() << " Swift 4.1/Swift 4.2";
  5817. else if(swift_version == 7)
  5818. outs() << " Swift 5 or later";
  5819. else
  5820. outs() << " unknown future Swift version (" << swift_version << ")";
  5821. }
  5822. outs() << "\n";
  5823. }
  5824. static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
  5825. uint32_t left, offset, p;
  5826. struct imageInfo_t o;
  5827. const char *r;
  5828. StringRef SectName;
  5829. Expected<StringRef> SecNameOrErr = S.getName();
  5830. if (SecNameOrErr)
  5831. SectName = *SecNameOrErr;
  5832. else
  5833. consumeError(SecNameOrErr.takeError());
  5834. DataRefImpl Ref = S.getRawDataRefImpl();
  5835. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  5836. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  5837. p = S.getAddress();
  5838. r = get_pointer_32(p, offset, left, S, info);
  5839. if (r == nullptr)
  5840. return;
  5841. memset(&o, '\0', sizeof(struct imageInfo_t));
  5842. if (left < sizeof(struct imageInfo_t)) {
  5843. memcpy(&o, r, left);
  5844. outs() << " (imageInfo entends past the end of the section)\n";
  5845. } else
  5846. memcpy(&o, r, sizeof(struct imageInfo_t));
  5847. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5848. swapStruct(o);
  5849. outs() << " version " << o.version << "\n";
  5850. outs() << " flags " << format("0x%" PRIx32, o.flags);
  5851. if (o.flags & 0x1)
  5852. outs() << " F&C";
  5853. if (o.flags & 0x2)
  5854. outs() << " GC";
  5855. if (o.flags & 0x4)
  5856. outs() << " GC-only";
  5857. else
  5858. outs() << " RR";
  5859. outs() << "\n";
  5860. }
  5861. static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
  5862. SymbolAddressMap AddrMap;
  5863. if (verbose)
  5864. CreateSymbolAddressMap(O, &AddrMap);
  5865. std::vector<SectionRef> Sections;
  5866. append_range(Sections, O->sections());
  5867. struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
  5868. SectionRef CL = get_section(O, "__OBJC2", "__class_list");
  5869. if (CL == SectionRef())
  5870. CL = get_section(O, "__DATA", "__objc_classlist");
  5871. if (CL == SectionRef())
  5872. CL = get_section(O, "__DATA_CONST", "__objc_classlist");
  5873. if (CL == SectionRef())
  5874. CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
  5875. info.S = CL;
  5876. walk_pointer_list_64("class", CL, O, &info, print_class64_t);
  5877. SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
  5878. if (CR == SectionRef())
  5879. CR = get_section(O, "__DATA", "__objc_classrefs");
  5880. if (CR == SectionRef())
  5881. CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
  5882. if (CR == SectionRef())
  5883. CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
  5884. info.S = CR;
  5885. walk_pointer_list_64("class refs", CR, O, &info, nullptr);
  5886. SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
  5887. if (SR == SectionRef())
  5888. SR = get_section(O, "__DATA", "__objc_superrefs");
  5889. if (SR == SectionRef())
  5890. SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
  5891. if (SR == SectionRef())
  5892. SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
  5893. info.S = SR;
  5894. walk_pointer_list_64("super refs", SR, O, &info, nullptr);
  5895. SectionRef CA = get_section(O, "__OBJC2", "__category_list");
  5896. if (CA == SectionRef())
  5897. CA = get_section(O, "__DATA", "__objc_catlist");
  5898. if (CA == SectionRef())
  5899. CA = get_section(O, "__DATA_CONST", "__objc_catlist");
  5900. if (CA == SectionRef())
  5901. CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
  5902. info.S = CA;
  5903. walk_pointer_list_64("category", CA, O, &info, print_category64_t);
  5904. SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
  5905. if (PL == SectionRef())
  5906. PL = get_section(O, "__DATA", "__objc_protolist");
  5907. if (PL == SectionRef())
  5908. PL = get_section(O, "__DATA_CONST", "__objc_protolist");
  5909. if (PL == SectionRef())
  5910. PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
  5911. info.S = PL;
  5912. walk_pointer_list_64("protocol", PL, O, &info, nullptr);
  5913. SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
  5914. if (MR == SectionRef())
  5915. MR = get_section(O, "__DATA", "__objc_msgrefs");
  5916. if (MR == SectionRef())
  5917. MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
  5918. if (MR == SectionRef())
  5919. MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
  5920. info.S = MR;
  5921. print_message_refs64(MR, &info);
  5922. SectionRef II = get_section(O, "__OBJC2", "__image_info");
  5923. if (II == SectionRef())
  5924. II = get_section(O, "__DATA", "__objc_imageinfo");
  5925. if (II == SectionRef())
  5926. II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
  5927. if (II == SectionRef())
  5928. II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
  5929. info.S = II;
  5930. print_image_info64(II, &info);
  5931. }
  5932. static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
  5933. SymbolAddressMap AddrMap;
  5934. if (verbose)
  5935. CreateSymbolAddressMap(O, &AddrMap);
  5936. std::vector<SectionRef> Sections;
  5937. append_range(Sections, O->sections());
  5938. struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
  5939. SectionRef CL = get_section(O, "__OBJC2", "__class_list");
  5940. if (CL == SectionRef())
  5941. CL = get_section(O, "__DATA", "__objc_classlist");
  5942. if (CL == SectionRef())
  5943. CL = get_section(O, "__DATA_CONST", "__objc_classlist");
  5944. if (CL == SectionRef())
  5945. CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
  5946. info.S = CL;
  5947. walk_pointer_list_32("class", CL, O, &info, print_class32_t);
  5948. SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
  5949. if (CR == SectionRef())
  5950. CR = get_section(O, "__DATA", "__objc_classrefs");
  5951. if (CR == SectionRef())
  5952. CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
  5953. if (CR == SectionRef())
  5954. CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
  5955. info.S = CR;
  5956. walk_pointer_list_32("class refs", CR, O, &info, nullptr);
  5957. SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
  5958. if (SR == SectionRef())
  5959. SR = get_section(O, "__DATA", "__objc_superrefs");
  5960. if (SR == SectionRef())
  5961. SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
  5962. if (SR == SectionRef())
  5963. SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
  5964. info.S = SR;
  5965. walk_pointer_list_32("super refs", SR, O, &info, nullptr);
  5966. SectionRef CA = get_section(O, "__OBJC2", "__category_list");
  5967. if (CA == SectionRef())
  5968. CA = get_section(O, "__DATA", "__objc_catlist");
  5969. if (CA == SectionRef())
  5970. CA = get_section(O, "__DATA_CONST", "__objc_catlist");
  5971. if (CA == SectionRef())
  5972. CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
  5973. info.S = CA;
  5974. walk_pointer_list_32("category", CA, O, &info, print_category32_t);
  5975. SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
  5976. if (PL == SectionRef())
  5977. PL = get_section(O, "__DATA", "__objc_protolist");
  5978. if (PL == SectionRef())
  5979. PL = get_section(O, "__DATA_CONST", "__objc_protolist");
  5980. if (PL == SectionRef())
  5981. PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
  5982. info.S = PL;
  5983. walk_pointer_list_32("protocol", PL, O, &info, nullptr);
  5984. SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
  5985. if (MR == SectionRef())
  5986. MR = get_section(O, "__DATA", "__objc_msgrefs");
  5987. if (MR == SectionRef())
  5988. MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
  5989. if (MR == SectionRef())
  5990. MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
  5991. info.S = MR;
  5992. print_message_refs32(MR, &info);
  5993. SectionRef II = get_section(O, "__OBJC2", "__image_info");
  5994. if (II == SectionRef())
  5995. II = get_section(O, "__DATA", "__objc_imageinfo");
  5996. if (II == SectionRef())
  5997. II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
  5998. if (II == SectionRef())
  5999. II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
  6000. info.S = II;
  6001. print_image_info32(II, &info);
  6002. }
  6003. static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
  6004. uint32_t i, j, p, offset, xoffset, left, defs_left, def;
  6005. const char *r, *name, *defs;
  6006. struct objc_module_t module;
  6007. SectionRef S, xS;
  6008. struct objc_symtab_t symtab;
  6009. struct objc_class_t objc_class;
  6010. struct objc_category_t objc_category;
  6011. outs() << "Objective-C segment\n";
  6012. S = get_section(O, "__OBJC", "__module_info");
  6013. if (S == SectionRef())
  6014. return false;
  6015. SymbolAddressMap AddrMap;
  6016. if (verbose)
  6017. CreateSymbolAddressMap(O, &AddrMap);
  6018. std::vector<SectionRef> Sections;
  6019. append_range(Sections, O->sections());
  6020. struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
  6021. for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
  6022. p = S.getAddress() + i;
  6023. r = get_pointer_32(p, offset, left, S, &info, true);
  6024. if (r == nullptr)
  6025. return true;
  6026. memset(&module, '\0', sizeof(struct objc_module_t));
  6027. if (left < sizeof(struct objc_module_t)) {
  6028. memcpy(&module, r, left);
  6029. outs() << " (module extends past end of __module_info section)\n";
  6030. } else
  6031. memcpy(&module, r, sizeof(struct objc_module_t));
  6032. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  6033. swapStruct(module);
  6034. outs() << "Module " << format("0x%" PRIx32, p) << "\n";
  6035. outs() << " version " << module.version << "\n";
  6036. outs() << " size " << module.size << "\n";
  6037. outs() << " name ";
  6038. name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
  6039. if (name != nullptr)
  6040. outs() << format("%.*s", left, name);
  6041. else
  6042. outs() << format("0x%08" PRIx32, module.name)
  6043. << "(not in an __OBJC section)";
  6044. outs() << "\n";
  6045. r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
  6046. if (module.symtab == 0 || r == nullptr) {
  6047. outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
  6048. << " (not in an __OBJC section)\n";
  6049. continue;
  6050. }
  6051. outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
  6052. memset(&symtab, '\0', sizeof(struct objc_symtab_t));
  6053. defs_left = 0;
  6054. defs = nullptr;
  6055. if (left < sizeof(struct objc_symtab_t)) {
  6056. memcpy(&symtab, r, left);
  6057. outs() << "\tsymtab extends past end of an __OBJC section)\n";
  6058. } else {
  6059. memcpy(&symtab, r, sizeof(struct objc_symtab_t));
  6060. if (left > sizeof(struct objc_symtab_t)) {
  6061. defs_left = left - sizeof(struct objc_symtab_t);
  6062. defs = r + sizeof(struct objc_symtab_t);
  6063. }
  6064. }
  6065. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  6066. swapStruct(symtab);
  6067. outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
  6068. r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
  6069. outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
  6070. if (r == nullptr)
  6071. outs() << " (not in an __OBJC section)";
  6072. outs() << "\n";
  6073. outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
  6074. outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
  6075. if (symtab.cls_def_cnt > 0)
  6076. outs() << "\tClass Definitions\n";
  6077. for (j = 0; j < symtab.cls_def_cnt; j++) {
  6078. if ((j + 1) * sizeof(uint32_t) > defs_left) {
  6079. outs() << "\t(remaining class defs entries entends past the end of the "
  6080. << "section)\n";
  6081. break;
  6082. }
  6083. memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
  6084. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  6085. sys::swapByteOrder(def);
  6086. r = get_pointer_32(def, xoffset, left, xS, &info, true);
  6087. outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
  6088. if (r != nullptr) {
  6089. if (left > sizeof(struct objc_class_t)) {
  6090. outs() << "\n";
  6091. memcpy(&objc_class, r, sizeof(struct objc_class_t));
  6092. } else {
  6093. outs() << " (entends past the end of the section)\n";
  6094. memset(&objc_class, '\0', sizeof(struct objc_class_t));
  6095. memcpy(&objc_class, r, left);
  6096. }
  6097. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  6098. swapStruct(objc_class);
  6099. print_objc_class_t(&objc_class, &info);
  6100. } else {
  6101. outs() << "(not in an __OBJC section)\n";
  6102. }
  6103. if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
  6104. outs() << "\tMeta Class";
  6105. r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
  6106. if (r != nullptr) {
  6107. if (left > sizeof(struct objc_class_t)) {
  6108. outs() << "\n";
  6109. memcpy(&objc_class, r, sizeof(struct objc_class_t));
  6110. } else {
  6111. outs() << " (entends past the end of the section)\n";
  6112. memset(&objc_class, '\0', sizeof(struct objc_class_t));
  6113. memcpy(&objc_class, r, left);
  6114. }
  6115. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  6116. swapStruct(objc_class);
  6117. print_objc_class_t(&objc_class, &info);
  6118. } else {
  6119. outs() << "(not in an __OBJC section)\n";
  6120. }
  6121. }
  6122. }
  6123. if (symtab.cat_def_cnt > 0)
  6124. outs() << "\tCategory Definitions\n";
  6125. for (j = 0; j < symtab.cat_def_cnt; j++) {
  6126. if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
  6127. outs() << "\t(remaining category defs entries entends past the end of "
  6128. << "the section)\n";
  6129. break;
  6130. }
  6131. memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
  6132. sizeof(uint32_t));
  6133. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  6134. sys::swapByteOrder(def);
  6135. r = get_pointer_32(def, xoffset, left, xS, &info, true);
  6136. outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
  6137. << format("0x%08" PRIx32, def);
  6138. if (r != nullptr) {
  6139. if (left > sizeof(struct objc_category_t)) {
  6140. outs() << "\n";
  6141. memcpy(&objc_category, r, sizeof(struct objc_category_t));
  6142. } else {
  6143. outs() << " (entends past the end of the section)\n";
  6144. memset(&objc_category, '\0', sizeof(struct objc_category_t));
  6145. memcpy(&objc_category, r, left);
  6146. }
  6147. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  6148. swapStruct(objc_category);
  6149. print_objc_objc_category_t(&objc_category, &info);
  6150. } else {
  6151. outs() << "(not in an __OBJC section)\n";
  6152. }
  6153. }
  6154. }
  6155. const SectionRef II = get_section(O, "__OBJC", "__image_info");
  6156. if (II != SectionRef())
  6157. print_image_info(II, &info);
  6158. return true;
  6159. }
  6160. static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
  6161. uint32_t size, uint32_t addr) {
  6162. SymbolAddressMap AddrMap;
  6163. CreateSymbolAddressMap(O, &AddrMap);
  6164. std::vector<SectionRef> Sections;
  6165. append_range(Sections, O->sections());
  6166. struct DisassembleInfo info(O, &AddrMap, &Sections, true);
  6167. const char *p;
  6168. struct objc_protocol_t protocol;
  6169. uint32_t left, paddr;
  6170. for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
  6171. memset(&protocol, '\0', sizeof(struct objc_protocol_t));
  6172. left = size - (p - sect);
  6173. if (left < sizeof(struct objc_protocol_t)) {
  6174. outs() << "Protocol extends past end of __protocol section\n";
  6175. memcpy(&protocol, p, left);
  6176. } else
  6177. memcpy(&protocol, p, sizeof(struct objc_protocol_t));
  6178. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  6179. swapStruct(protocol);
  6180. paddr = addr + (p - sect);
  6181. outs() << "Protocol " << format("0x%" PRIx32, paddr);
  6182. if (print_protocol(paddr, 0, &info))
  6183. outs() << "(not in an __OBJC section)\n";
  6184. }
  6185. }
  6186. #ifdef LLVM_HAVE_LIBXAR
  6187. static inline void swapStruct(struct xar_header &xar) {
  6188. sys::swapByteOrder(xar.magic);
  6189. sys::swapByteOrder(xar.size);
  6190. sys::swapByteOrder(xar.version);
  6191. sys::swapByteOrder(xar.toc_length_compressed);
  6192. sys::swapByteOrder(xar.toc_length_uncompressed);
  6193. sys::swapByteOrder(xar.cksum_alg);
  6194. }
  6195. static void PrintModeVerbose(uint32_t mode) {
  6196. switch(mode & S_IFMT){
  6197. case S_IFDIR:
  6198. outs() << "d";
  6199. break;
  6200. case S_IFCHR:
  6201. outs() << "c";
  6202. break;
  6203. case S_IFBLK:
  6204. outs() << "b";
  6205. break;
  6206. case S_IFREG:
  6207. outs() << "-";
  6208. break;
  6209. case S_IFLNK:
  6210. outs() << "l";
  6211. break;
  6212. case S_IFSOCK:
  6213. outs() << "s";
  6214. break;
  6215. default:
  6216. outs() << "?";
  6217. break;
  6218. }
  6219. /* owner permissions */
  6220. if(mode & S_IREAD)
  6221. outs() << "r";
  6222. else
  6223. outs() << "-";
  6224. if(mode & S_IWRITE)
  6225. outs() << "w";
  6226. else
  6227. outs() << "-";
  6228. if(mode & S_ISUID)
  6229. outs() << "s";
  6230. else if(mode & S_IEXEC)
  6231. outs() << "x";
  6232. else
  6233. outs() << "-";
  6234. /* group permissions */
  6235. if(mode & (S_IREAD >> 3))
  6236. outs() << "r";
  6237. else
  6238. outs() << "-";
  6239. if(mode & (S_IWRITE >> 3))
  6240. outs() << "w";
  6241. else
  6242. outs() << "-";
  6243. if(mode & S_ISGID)
  6244. outs() << "s";
  6245. else if(mode & (S_IEXEC >> 3))
  6246. outs() << "x";
  6247. else
  6248. outs() << "-";
  6249. /* other permissions */
  6250. if(mode & (S_IREAD >> 6))
  6251. outs() << "r";
  6252. else
  6253. outs() << "-";
  6254. if(mode & (S_IWRITE >> 6))
  6255. outs() << "w";
  6256. else
  6257. outs() << "-";
  6258. if(mode & S_ISVTX)
  6259. outs() << "t";
  6260. else if(mode & (S_IEXEC >> 6))
  6261. outs() << "x";
  6262. else
  6263. outs() << "-";
  6264. }
  6265. static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
  6266. xar_file_t xf;
  6267. const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
  6268. char *endp;
  6269. uint32_t mode_value;
  6270. ScopedXarIter xi;
  6271. if (!xi) {
  6272. WithColor::error(errs(), "llvm-objdump")
  6273. << "can't obtain an xar iterator for xar archive " << XarFilename
  6274. << "\n";
  6275. return;
  6276. }
  6277. // Go through the xar's files.
  6278. for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
  6279. ScopedXarIter xp;
  6280. if(!xp){
  6281. WithColor::error(errs(), "llvm-objdump")
  6282. << "can't obtain an xar iterator for xar archive " << XarFilename
  6283. << "\n";
  6284. return;
  6285. }
  6286. type = nullptr;
  6287. mode = nullptr;
  6288. user = nullptr;
  6289. group = nullptr;
  6290. size = nullptr;
  6291. mtime = nullptr;
  6292. name = nullptr;
  6293. for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
  6294. const char *val = nullptr;
  6295. xar_prop_get(xf, key, &val);
  6296. #if 0 // Useful for debugging.
  6297. outs() << "key: " << key << " value: " << val << "\n";
  6298. #endif
  6299. if(strcmp(key, "type") == 0)
  6300. type = val;
  6301. if(strcmp(key, "mode") == 0)
  6302. mode = val;
  6303. if(strcmp(key, "user") == 0)
  6304. user = val;
  6305. if(strcmp(key, "group") == 0)
  6306. group = val;
  6307. if(strcmp(key, "data/size") == 0)
  6308. size = val;
  6309. if(strcmp(key, "mtime") == 0)
  6310. mtime = val;
  6311. if(strcmp(key, "name") == 0)
  6312. name = val;
  6313. }
  6314. if(mode != nullptr){
  6315. mode_value = strtoul(mode, &endp, 8);
  6316. if(*endp != '\0')
  6317. outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
  6318. if(strcmp(type, "file") == 0)
  6319. mode_value |= S_IFREG;
  6320. PrintModeVerbose(mode_value);
  6321. outs() << " ";
  6322. }
  6323. if(user != nullptr)
  6324. outs() << format("%10s/", user);
  6325. if(group != nullptr)
  6326. outs() << format("%-10s ", group);
  6327. if(size != nullptr)
  6328. outs() << format("%7s ", size);
  6329. if(mtime != nullptr){
  6330. for(m = mtime; *m != 'T' && *m != '\0'; m++)
  6331. outs() << *m;
  6332. if(*m == 'T')
  6333. m++;
  6334. outs() << " ";
  6335. for( ; *m != 'Z' && *m != '\0'; m++)
  6336. outs() << *m;
  6337. outs() << " ";
  6338. }
  6339. if(name != nullptr)
  6340. outs() << name;
  6341. outs() << "\n";
  6342. }
  6343. }
  6344. static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
  6345. uint32_t size, bool verbose,
  6346. bool PrintXarHeader, bool PrintXarFileHeaders,
  6347. std::string XarMemberName) {
  6348. if(size < sizeof(struct xar_header)) {
  6349. outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
  6350. "of struct xar_header)\n";
  6351. return;
  6352. }
  6353. struct xar_header XarHeader;
  6354. memcpy(&XarHeader, sect, sizeof(struct xar_header));
  6355. if (sys::IsLittleEndianHost)
  6356. swapStruct(XarHeader);
  6357. if (PrintXarHeader) {
  6358. if (!XarMemberName.empty())
  6359. outs() << "In xar member " << XarMemberName << ": ";
  6360. else
  6361. outs() << "For (__LLVM,__bundle) section: ";
  6362. outs() << "xar header\n";
  6363. if (XarHeader.magic == XAR_HEADER_MAGIC)
  6364. outs() << " magic XAR_HEADER_MAGIC\n";
  6365. else
  6366. outs() << " magic "
  6367. << format_hex(XarHeader.magic, 10, true)
  6368. << " (not XAR_HEADER_MAGIC)\n";
  6369. outs() << " size " << XarHeader.size << "\n";
  6370. outs() << " version " << XarHeader.version << "\n";
  6371. outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
  6372. << "\n";
  6373. outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
  6374. << "\n";
  6375. outs() << " cksum_alg ";
  6376. switch (XarHeader.cksum_alg) {
  6377. case XAR_CKSUM_NONE:
  6378. outs() << "XAR_CKSUM_NONE\n";
  6379. break;
  6380. case XAR_CKSUM_SHA1:
  6381. outs() << "XAR_CKSUM_SHA1\n";
  6382. break;
  6383. case XAR_CKSUM_MD5:
  6384. outs() << "XAR_CKSUM_MD5\n";
  6385. break;
  6386. #ifdef XAR_CKSUM_SHA256
  6387. case XAR_CKSUM_SHA256:
  6388. outs() << "XAR_CKSUM_SHA256\n";
  6389. break;
  6390. #endif
  6391. #ifdef XAR_CKSUM_SHA512
  6392. case XAR_CKSUM_SHA512:
  6393. outs() << "XAR_CKSUM_SHA512\n";
  6394. break;
  6395. #endif
  6396. default:
  6397. outs() << XarHeader.cksum_alg << "\n";
  6398. }
  6399. }
  6400. SmallString<128> XarFilename;
  6401. int FD;
  6402. std::error_code XarEC =
  6403. sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
  6404. if (XarEC) {
  6405. WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
  6406. return;
  6407. }
  6408. ToolOutputFile XarFile(XarFilename, FD);
  6409. raw_fd_ostream &XarOut = XarFile.os();
  6410. StringRef XarContents(sect, size);
  6411. XarOut << XarContents;
  6412. XarOut.close();
  6413. if (XarOut.has_error())
  6414. return;
  6415. ScopedXarFile xar(XarFilename.c_str(), READ);
  6416. if (!xar) {
  6417. WithColor::error(errs(), "llvm-objdump")
  6418. << "can't create temporary xar archive " << XarFilename << "\n";
  6419. return;
  6420. }
  6421. SmallString<128> TocFilename;
  6422. std::error_code TocEC =
  6423. sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
  6424. if (TocEC) {
  6425. WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
  6426. return;
  6427. }
  6428. xar_serialize(xar, TocFilename.c_str());
  6429. if (PrintXarFileHeaders) {
  6430. if (!XarMemberName.empty())
  6431. outs() << "In xar member " << XarMemberName << ": ";
  6432. else
  6433. outs() << "For (__LLVM,__bundle) section: ";
  6434. outs() << "xar archive files:\n";
  6435. PrintXarFilesSummary(XarFilename.c_str(), xar);
  6436. }
  6437. ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
  6438. MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
  6439. if (std::error_code EC = FileOrErr.getError()) {
  6440. WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
  6441. return;
  6442. }
  6443. std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
  6444. if (!XarMemberName.empty())
  6445. outs() << "In xar member " << XarMemberName << ": ";
  6446. else
  6447. outs() << "For (__LLVM,__bundle) section: ";
  6448. outs() << "xar table of contents:\n";
  6449. outs() << Buffer->getBuffer() << "\n";
  6450. // TODO: Go through the xar's files.
  6451. ScopedXarIter xi;
  6452. if(!xi){
  6453. WithColor::error(errs(), "llvm-objdump")
  6454. << "can't obtain an xar iterator for xar archive "
  6455. << XarFilename.c_str() << "\n";
  6456. return;
  6457. }
  6458. for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
  6459. const char *key;
  6460. const char *member_name, *member_type, *member_size_string;
  6461. size_t member_size;
  6462. ScopedXarIter xp;
  6463. if(!xp){
  6464. WithColor::error(errs(), "llvm-objdump")
  6465. << "can't obtain an xar iterator for xar archive "
  6466. << XarFilename.c_str() << "\n";
  6467. return;
  6468. }
  6469. member_name = NULL;
  6470. member_type = NULL;
  6471. member_size_string = NULL;
  6472. for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
  6473. const char *val = nullptr;
  6474. xar_prop_get(xf, key, &val);
  6475. #if 0 // Useful for debugging.
  6476. outs() << "key: " << key << " value: " << val << "\n";
  6477. #endif
  6478. if (strcmp(key, "name") == 0)
  6479. member_name = val;
  6480. if (strcmp(key, "type") == 0)
  6481. member_type = val;
  6482. if (strcmp(key, "data/size") == 0)
  6483. member_size_string = val;
  6484. }
  6485. /*
  6486. * If we find a file with a name, date/size and type properties
  6487. * and with the type being "file" see if that is a xar file.
  6488. */
  6489. if (member_name != NULL && member_type != NULL &&
  6490. strcmp(member_type, "file") == 0 &&
  6491. member_size_string != NULL){
  6492. // Extract the file into a buffer.
  6493. char *endptr;
  6494. member_size = strtoul(member_size_string, &endptr, 10);
  6495. if (*endptr == '\0' && member_size != 0) {
  6496. char *buffer;
  6497. if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
  6498. #if 0 // Useful for debugging.
  6499. outs() << "xar member: " << member_name << " extracted\n";
  6500. #endif
  6501. // Set the XarMemberName we want to see printed in the header.
  6502. std::string OldXarMemberName;
  6503. // If XarMemberName is already set this is nested. So
  6504. // save the old name and create the nested name.
  6505. if (!XarMemberName.empty()) {
  6506. OldXarMemberName = XarMemberName;
  6507. XarMemberName =
  6508. (Twine("[") + XarMemberName + "]" + member_name).str();
  6509. } else {
  6510. OldXarMemberName = "";
  6511. XarMemberName = member_name;
  6512. }
  6513. // See if this is could be a xar file (nested).
  6514. if (member_size >= sizeof(struct xar_header)) {
  6515. #if 0 // Useful for debugging.
  6516. outs() << "could be a xar file: " << member_name << "\n";
  6517. #endif
  6518. memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
  6519. if (sys::IsLittleEndianHost)
  6520. swapStruct(XarHeader);
  6521. if (XarHeader.magic == XAR_HEADER_MAGIC)
  6522. DumpBitcodeSection(O, buffer, member_size, verbose,
  6523. PrintXarHeader, PrintXarFileHeaders,
  6524. XarMemberName);
  6525. }
  6526. XarMemberName = OldXarMemberName;
  6527. delete buffer;
  6528. }
  6529. }
  6530. }
  6531. }
  6532. }
  6533. #endif // defined(LLVM_HAVE_LIBXAR)
  6534. static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
  6535. if (O->is64Bit())
  6536. printObjc2_64bit_MetaData(O, verbose);
  6537. else {
  6538. MachO::mach_header H;
  6539. H = O->getHeader();
  6540. if (H.cputype == MachO::CPU_TYPE_ARM)
  6541. printObjc2_32bit_MetaData(O, verbose);
  6542. else {
  6543. // This is the 32-bit non-arm cputype case. Which is normally
  6544. // the first Objective-C ABI. But it may be the case of a
  6545. // binary for the iOS simulator which is the second Objective-C
  6546. // ABI. In that case printObjc1_32bit_MetaData() will determine that
  6547. // and return false.
  6548. if (!printObjc1_32bit_MetaData(O, verbose))
  6549. printObjc2_32bit_MetaData(O, verbose);
  6550. }
  6551. }
  6552. }
  6553. // GuessLiteralPointer returns a string which for the item in the Mach-O file
  6554. // for the address passed in as ReferenceValue for printing as a comment with
  6555. // the instruction and also returns the corresponding type of that item
  6556. // indirectly through ReferenceType.
  6557. //
  6558. // If ReferenceValue is an address of literal cstring then a pointer to the
  6559. // cstring is returned and ReferenceType is set to
  6560. // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
  6561. //
  6562. // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
  6563. // Class ref that name is returned and the ReferenceType is set accordingly.
  6564. //
  6565. // Lastly, literals which are Symbol address in a literal pool are looked for
  6566. // and if found the symbol name is returned and ReferenceType is set to
  6567. // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
  6568. //
  6569. // If there is no item in the Mach-O file for the address passed in as
  6570. // ReferenceValue nullptr is returned and ReferenceType is unchanged.
  6571. static const char *GuessLiteralPointer(uint64_t ReferenceValue,
  6572. uint64_t ReferencePC,
  6573. uint64_t *ReferenceType,
  6574. struct DisassembleInfo *info) {
  6575. // First see if there is an external relocation entry at the ReferencePC.
  6576. if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
  6577. uint64_t sect_addr = info->S.getAddress();
  6578. uint64_t sect_offset = ReferencePC - sect_addr;
  6579. bool reloc_found = false;
  6580. DataRefImpl Rel;
  6581. MachO::any_relocation_info RE;
  6582. bool isExtern = false;
  6583. SymbolRef Symbol;
  6584. for (const RelocationRef &Reloc : info->S.relocations()) {
  6585. uint64_t RelocOffset = Reloc.getOffset();
  6586. if (RelocOffset == sect_offset) {
  6587. Rel = Reloc.getRawDataRefImpl();
  6588. RE = info->O->getRelocation(Rel);
  6589. if (info->O->isRelocationScattered(RE))
  6590. continue;
  6591. isExtern = info->O->getPlainRelocationExternal(RE);
  6592. if (isExtern) {
  6593. symbol_iterator RelocSym = Reloc.getSymbol();
  6594. Symbol = *RelocSym;
  6595. }
  6596. reloc_found = true;
  6597. break;
  6598. }
  6599. }
  6600. // If there is an external relocation entry for a symbol in a section
  6601. // then used that symbol's value for the value of the reference.
  6602. if (reloc_found && isExtern) {
  6603. if (info->O->getAnyRelocationPCRel(RE)) {
  6604. unsigned Type = info->O->getAnyRelocationType(RE);
  6605. if (Type == MachO::X86_64_RELOC_SIGNED) {
  6606. ReferenceValue = cantFail(Symbol.getValue());
  6607. }
  6608. }
  6609. }
  6610. }
  6611. // Look for literals such as Objective-C CFStrings refs, Selector refs,
  6612. // Message refs and Class refs.
  6613. bool classref, selref, msgref, cfstring;
  6614. uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
  6615. selref, msgref, cfstring);
  6616. if (classref && pointer_value == 0) {
  6617. // Note the ReferenceValue is a pointer into the __objc_classrefs section.
  6618. // And the pointer_value in that section is typically zero as it will be
  6619. // set by dyld as part of the "bind information".
  6620. const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
  6621. if (name != nullptr) {
  6622. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
  6623. const char *class_name = strrchr(name, '$');
  6624. if (class_name != nullptr && class_name[1] == '_' &&
  6625. class_name[2] != '\0') {
  6626. info->class_name = class_name + 2;
  6627. return name;
  6628. }
  6629. }
  6630. }
  6631. if (classref) {
  6632. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
  6633. const char *name =
  6634. get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
  6635. if (name != nullptr)
  6636. info->class_name = name;
  6637. else
  6638. name = "bad class ref";
  6639. return name;
  6640. }
  6641. if (cfstring) {
  6642. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
  6643. const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
  6644. return name;
  6645. }
  6646. if (selref && pointer_value == 0)
  6647. pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
  6648. if (pointer_value != 0)
  6649. ReferenceValue = pointer_value;
  6650. const char *name = GuessCstringPointer(ReferenceValue, info);
  6651. if (name) {
  6652. if (pointer_value != 0 && selref) {
  6653. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
  6654. info->selector_name = name;
  6655. } else if (pointer_value != 0 && msgref) {
  6656. info->class_name = nullptr;
  6657. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
  6658. info->selector_name = name;
  6659. } else
  6660. *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
  6661. return name;
  6662. }
  6663. // Lastly look for an indirect symbol with this ReferenceValue which is in
  6664. // a literal pool. If found return that symbol name.
  6665. name = GuessIndirectSymbol(ReferenceValue, info);
  6666. if (name) {
  6667. *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
  6668. return name;
  6669. }
  6670. return nullptr;
  6671. }
  6672. // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
  6673. // the Symbolizer. It looks up the ReferenceValue using the info passed via the
  6674. // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
  6675. // is created and returns the symbol name that matches the ReferenceValue or
  6676. // nullptr if none. The ReferenceType is passed in for the IN type of
  6677. // reference the instruction is making from the values in defined in the header
  6678. // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
  6679. // Out type and the ReferenceName will also be set which is added as a comment
  6680. // to the disassembled instruction.
  6681. //
  6682. // If the symbol name is a C++ mangled name then the demangled name is
  6683. // returned through ReferenceName and ReferenceType is set to
  6684. // LLVMDisassembler_ReferenceType_DeMangled_Name .
  6685. //
  6686. // When this is called to get a symbol name for a branch target then the
  6687. // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
  6688. // SymbolValue will be looked for in the indirect symbol table to determine if
  6689. // it is an address for a symbol stub. If so then the symbol name for that
  6690. // stub is returned indirectly through ReferenceName and then ReferenceType is
  6691. // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
  6692. //
  6693. // When this is called with an value loaded via a PC relative load then
  6694. // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
  6695. // SymbolValue is checked to be an address of literal pointer, symbol pointer,
  6696. // or an Objective-C meta data reference. If so the output ReferenceType is
  6697. // set to correspond to that as well as setting the ReferenceName.
  6698. static const char *SymbolizerSymbolLookUp(void *DisInfo,
  6699. uint64_t ReferenceValue,
  6700. uint64_t *ReferenceType,
  6701. uint64_t ReferencePC,
  6702. const char **ReferenceName) {
  6703. struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
  6704. // If no verbose symbolic information is wanted then just return nullptr.
  6705. if (!info->verbose) {
  6706. *ReferenceName = nullptr;
  6707. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6708. return nullptr;
  6709. }
  6710. const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
  6711. if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
  6712. *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
  6713. if (*ReferenceName != nullptr) {
  6714. method_reference(info, ReferenceType, ReferenceName);
  6715. if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
  6716. *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
  6717. } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
  6718. if (info->demangled_name != nullptr)
  6719. free(info->demangled_name);
  6720. int status;
  6721. info->demangled_name =
  6722. itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
  6723. if (info->demangled_name != nullptr) {
  6724. *ReferenceName = info->demangled_name;
  6725. *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
  6726. } else
  6727. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6728. } else
  6729. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6730. } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
  6731. *ReferenceName =
  6732. GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
  6733. if (*ReferenceName)
  6734. method_reference(info, ReferenceType, ReferenceName);
  6735. else
  6736. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6737. // If this is arm64 and the reference is an adrp instruction save the
  6738. // instruction, passed in ReferenceValue and the address of the instruction
  6739. // for use later if we see and add immediate instruction.
  6740. } else if (info->O->getArch() == Triple::aarch64 &&
  6741. *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
  6742. info->adrp_inst = ReferenceValue;
  6743. info->adrp_addr = ReferencePC;
  6744. SymbolName = nullptr;
  6745. *ReferenceName = nullptr;
  6746. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6747. // If this is arm64 and reference is an add immediate instruction and we
  6748. // have
  6749. // seen an adrp instruction just before it and the adrp's Xd register
  6750. // matches
  6751. // this add's Xn register reconstruct the value being referenced and look to
  6752. // see if it is a literal pointer. Note the add immediate instruction is
  6753. // passed in ReferenceValue.
  6754. } else if (info->O->getArch() == Triple::aarch64 &&
  6755. *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
  6756. ReferencePC - 4 == info->adrp_addr &&
  6757. (info->adrp_inst & 0x9f000000) == 0x90000000 &&
  6758. (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
  6759. uint32_t addxri_inst;
  6760. uint64_t adrp_imm, addxri_imm;
  6761. adrp_imm =
  6762. ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
  6763. if (info->adrp_inst & 0x0200000)
  6764. adrp_imm |= 0xfffffffffc000000LL;
  6765. addxri_inst = ReferenceValue;
  6766. addxri_imm = (addxri_inst >> 10) & 0xfff;
  6767. if (((addxri_inst >> 22) & 0x3) == 1)
  6768. addxri_imm <<= 12;
  6769. ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
  6770. (adrp_imm << 12) + addxri_imm;
  6771. *ReferenceName =
  6772. GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
  6773. if (*ReferenceName == nullptr)
  6774. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6775. // If this is arm64 and the reference is a load register instruction and we
  6776. // have seen an adrp instruction just before it and the adrp's Xd register
  6777. // matches this add's Xn register reconstruct the value being referenced and
  6778. // look to see if it is a literal pointer. Note the load register
  6779. // instruction is passed in ReferenceValue.
  6780. } else if (info->O->getArch() == Triple::aarch64 &&
  6781. *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
  6782. ReferencePC - 4 == info->adrp_addr &&
  6783. (info->adrp_inst & 0x9f000000) == 0x90000000 &&
  6784. (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
  6785. uint32_t ldrxui_inst;
  6786. uint64_t adrp_imm, ldrxui_imm;
  6787. adrp_imm =
  6788. ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
  6789. if (info->adrp_inst & 0x0200000)
  6790. adrp_imm |= 0xfffffffffc000000LL;
  6791. ldrxui_inst = ReferenceValue;
  6792. ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
  6793. ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
  6794. (adrp_imm << 12) + (ldrxui_imm << 3);
  6795. *ReferenceName =
  6796. GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
  6797. if (*ReferenceName == nullptr)
  6798. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6799. }
  6800. // If this arm64 and is an load register (PC-relative) instruction the
  6801. // ReferenceValue is the PC plus the immediate value.
  6802. else if (info->O->getArch() == Triple::aarch64 &&
  6803. (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
  6804. *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
  6805. *ReferenceName =
  6806. GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
  6807. if (*ReferenceName == nullptr)
  6808. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6809. } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
  6810. if (info->demangled_name != nullptr)
  6811. free(info->demangled_name);
  6812. int status;
  6813. info->demangled_name =
  6814. itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
  6815. if (info->demangled_name != nullptr) {
  6816. *ReferenceName = info->demangled_name;
  6817. *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
  6818. }
  6819. }
  6820. else {
  6821. *ReferenceName = nullptr;
  6822. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6823. }
  6824. return SymbolName;
  6825. }
  6826. /// Emits the comments that are stored in the CommentStream.
  6827. /// Each comment in the CommentStream must end with a newline.
  6828. static void emitComments(raw_svector_ostream &CommentStream,
  6829. SmallString<128> &CommentsToEmit,
  6830. formatted_raw_ostream &FormattedOS,
  6831. const MCAsmInfo &MAI) {
  6832. // Flush the stream before taking its content.
  6833. StringRef Comments = CommentsToEmit.str();
  6834. // Get the default information for printing a comment.
  6835. StringRef CommentBegin = MAI.getCommentString();
  6836. unsigned CommentColumn = MAI.getCommentColumn();
  6837. ListSeparator LS("\n");
  6838. while (!Comments.empty()) {
  6839. FormattedOS << LS;
  6840. // Emit a line of comments.
  6841. FormattedOS.PadToColumn(CommentColumn);
  6842. size_t Position = Comments.find('\n');
  6843. FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
  6844. // Move after the newline character.
  6845. Comments = Comments.substr(Position + 1);
  6846. }
  6847. FormattedOS.flush();
  6848. // Tell the comment stream that the vector changed underneath it.
  6849. CommentsToEmit.clear();
  6850. }
  6851. const MachOObjectFile *
  6852. objdump::getMachODSymObject(const MachOObjectFile *MachOOF, StringRef Filename,
  6853. std::unique_ptr<Binary> &DSYMBinary,
  6854. std::unique_ptr<MemoryBuffer> &DSYMBuf) {
  6855. const MachOObjectFile *DbgObj = MachOOF;
  6856. std::string DSYMPath;
  6857. // Auto-detect w/o --dsym.
  6858. if (DSYMFile.empty()) {
  6859. sys::fs::file_status DSYMStatus;
  6860. Twine FilenameDSYM = Filename + ".dSYM";
  6861. if (!status(FilenameDSYM, DSYMStatus)) {
  6862. if (sys::fs::is_directory(DSYMStatus)) {
  6863. SmallString<1024> Path;
  6864. FilenameDSYM.toVector(Path);
  6865. sys::path::append(Path, "Contents", "Resources", "DWARF",
  6866. sys::path::filename(Filename));
  6867. DSYMPath = std::string(Path);
  6868. } else if (sys::fs::is_regular_file(DSYMStatus)) {
  6869. DSYMPath = FilenameDSYM.str();
  6870. }
  6871. }
  6872. }
  6873. if (DSYMPath.empty() && !DSYMFile.empty()) {
  6874. // If DSYMPath is a .dSYM directory, append the Mach-O file.
  6875. if (sys::fs::is_directory(DSYMFile) &&
  6876. sys::path::extension(DSYMFile) == ".dSYM") {
  6877. SmallString<128> ShortName(sys::path::filename(DSYMFile));
  6878. sys::path::replace_extension(ShortName, "");
  6879. SmallString<1024> FullPath(DSYMFile);
  6880. sys::path::append(FullPath, "Contents", "Resources", "DWARF", ShortName);
  6881. DSYMPath = FullPath.str();
  6882. } else {
  6883. DSYMPath = DSYMFile;
  6884. }
  6885. }
  6886. if (!DSYMPath.empty()) {
  6887. // Load the file.
  6888. ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
  6889. MemoryBuffer::getFileOrSTDIN(DSYMPath);
  6890. if (std::error_code EC = BufOrErr.getError()) {
  6891. reportError(errorCodeToError(EC), DSYMPath);
  6892. return nullptr;
  6893. }
  6894. // We need to keep the file alive, because we're replacing DbgObj with it.
  6895. DSYMBuf = std::move(BufOrErr.get());
  6896. Expected<std::unique_ptr<Binary>> BinaryOrErr =
  6897. createBinary(DSYMBuf.get()->getMemBufferRef());
  6898. if (!BinaryOrErr) {
  6899. reportError(BinaryOrErr.takeError(), DSYMPath);
  6900. return nullptr;
  6901. }
  6902. // We need to keep the Binary alive with the buffer
  6903. DSYMBinary = std::move(BinaryOrErr.get());
  6904. if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) {
  6905. // this is a Mach-O object file, use it
  6906. if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) {
  6907. DbgObj = MachDSYM;
  6908. } else {
  6909. WithColor::error(errs(), "llvm-objdump")
  6910. << DSYMPath << " is not a Mach-O file type.\n";
  6911. return nullptr;
  6912. }
  6913. } else if (auto *UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())) {
  6914. // this is a Universal Binary, find a Mach-O for this architecture
  6915. uint32_t CPUType, CPUSubType;
  6916. const char *ArchFlag;
  6917. if (MachOOF->is64Bit()) {
  6918. const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
  6919. CPUType = H_64.cputype;
  6920. CPUSubType = H_64.cpusubtype;
  6921. } else {
  6922. const MachO::mach_header H = MachOOF->getHeader();
  6923. CPUType = H.cputype;
  6924. CPUSubType = H.cpusubtype;
  6925. }
  6926. Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr,
  6927. &ArchFlag);
  6928. Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
  6929. UB->getMachOObjectForArch(ArchFlag);
  6930. if (!MachDSYM) {
  6931. reportError(MachDSYM.takeError(), DSYMPath);
  6932. return nullptr;
  6933. }
  6934. // We need to keep the Binary alive with the buffer
  6935. DbgObj = &*MachDSYM.get();
  6936. DSYMBinary = std::move(*MachDSYM);
  6937. } else {
  6938. WithColor::error(errs(), "llvm-objdump")
  6939. << DSYMPath << " is not a Mach-O or Universal file type.\n";
  6940. return nullptr;
  6941. }
  6942. }
  6943. return DbgObj;
  6944. }
  6945. static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
  6946. StringRef DisSegName, StringRef DisSectName) {
  6947. const char *McpuDefault = nullptr;
  6948. const Target *ThumbTarget = nullptr;
  6949. const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
  6950. if (!TheTarget) {
  6951. // GetTarget prints out stuff.
  6952. return;
  6953. }
  6954. std::string MachOMCPU;
  6955. if (MCPU.empty() && McpuDefault)
  6956. MachOMCPU = McpuDefault;
  6957. else
  6958. MachOMCPU = MCPU;
  6959. #define CHECK_TARGET_INFO_CREATION(NAME) \
  6960. do { \
  6961. if (!NAME) { \
  6962. WithColor::error(errs(), "llvm-objdump") \
  6963. << "couldn't initialize disassembler for target " << TripleName \
  6964. << '\n'; \
  6965. return; \
  6966. } \
  6967. } while (false)
  6968. #define CHECK_THUMB_TARGET_INFO_CREATION(NAME) \
  6969. do { \
  6970. if (!NAME) { \
  6971. WithColor::error(errs(), "llvm-objdump") \
  6972. << "couldn't initialize disassembler for target " << ThumbTripleName \
  6973. << '\n'; \
  6974. return; \
  6975. } \
  6976. } while (false)
  6977. std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
  6978. CHECK_TARGET_INFO_CREATION(InstrInfo);
  6979. std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
  6980. if (ThumbTarget) {
  6981. ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
  6982. CHECK_THUMB_TARGET_INFO_CREATION(ThumbInstrInfo);
  6983. }
  6984. // Package up features to be passed to target/subtarget
  6985. std::string FeaturesStr;
  6986. if (!MAttrs.empty()) {
  6987. SubtargetFeatures Features;
  6988. for (unsigned i = 0; i != MAttrs.size(); ++i)
  6989. Features.AddFeature(MAttrs[i]);
  6990. FeaturesStr = Features.getString();
  6991. }
  6992. MCTargetOptions MCOptions;
  6993. // Set up disassembler.
  6994. std::unique_ptr<const MCRegisterInfo> MRI(
  6995. TheTarget->createMCRegInfo(TripleName));
  6996. CHECK_TARGET_INFO_CREATION(MRI);
  6997. std::unique_ptr<const MCAsmInfo> AsmInfo(
  6998. TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
  6999. CHECK_TARGET_INFO_CREATION(AsmInfo);
  7000. std::unique_ptr<const MCSubtargetInfo> STI(
  7001. TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
  7002. CHECK_TARGET_INFO_CREATION(STI);
  7003. MCContext Ctx(Triple(TripleName), AsmInfo.get(), MRI.get(), STI.get());
  7004. std::unique_ptr<MCDisassembler> DisAsm(
  7005. TheTarget->createMCDisassembler(*STI, Ctx));
  7006. CHECK_TARGET_INFO_CREATION(DisAsm);
  7007. std::unique_ptr<MCSymbolizer> Symbolizer;
  7008. struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
  7009. std::unique_ptr<MCRelocationInfo> RelInfo(
  7010. TheTarget->createMCRelocationInfo(TripleName, Ctx));
  7011. if (RelInfo) {
  7012. Symbolizer.reset(TheTarget->createMCSymbolizer(
  7013. TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
  7014. &SymbolizerInfo, &Ctx, std::move(RelInfo)));
  7015. DisAsm->setSymbolizer(std::move(Symbolizer));
  7016. }
  7017. int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
  7018. std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
  7019. Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
  7020. CHECK_TARGET_INFO_CREATION(IP);
  7021. // Set the display preference for hex vs. decimal immediates.
  7022. IP->setPrintImmHex(PrintImmHex);
  7023. // Comment stream and backing vector.
  7024. SmallString<128> CommentsToEmit;
  7025. raw_svector_ostream CommentStream(CommentsToEmit);
  7026. // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
  7027. // if it is done then arm64 comments for string literals don't get printed
  7028. // and some constant get printed instead and not setting it causes intel
  7029. // (32-bit and 64-bit) comments printed with different spacing before the
  7030. // comment causing different diffs with the 'C' disassembler library API.
  7031. // IP->setCommentStream(CommentStream);
  7032. // Set up separate thumb disassembler if needed.
  7033. std::unique_ptr<const MCRegisterInfo> ThumbMRI;
  7034. std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
  7035. std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
  7036. std::unique_ptr<MCDisassembler> ThumbDisAsm;
  7037. std::unique_ptr<MCInstPrinter> ThumbIP;
  7038. std::unique_ptr<MCContext> ThumbCtx;
  7039. std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
  7040. struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
  7041. std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
  7042. if (ThumbTarget) {
  7043. ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
  7044. CHECK_THUMB_TARGET_INFO_CREATION(ThumbMRI);
  7045. ThumbAsmInfo.reset(
  7046. ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName, MCOptions));
  7047. CHECK_THUMB_TARGET_INFO_CREATION(ThumbAsmInfo);
  7048. ThumbSTI.reset(
  7049. ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
  7050. FeaturesStr));
  7051. CHECK_THUMB_TARGET_INFO_CREATION(ThumbSTI);
  7052. ThumbCtx.reset(new MCContext(Triple(ThumbTripleName), ThumbAsmInfo.get(),
  7053. ThumbMRI.get(), ThumbSTI.get()));
  7054. ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
  7055. CHECK_THUMB_TARGET_INFO_CREATION(ThumbDisAsm);
  7056. MCContext *PtrThumbCtx = ThumbCtx.get();
  7057. ThumbRelInfo.reset(
  7058. ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
  7059. if (ThumbRelInfo) {
  7060. ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
  7061. ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
  7062. &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
  7063. ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
  7064. }
  7065. int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
  7066. ThumbIP.reset(ThumbTarget->createMCInstPrinter(
  7067. Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
  7068. *ThumbInstrInfo, *ThumbMRI));
  7069. CHECK_THUMB_TARGET_INFO_CREATION(ThumbIP);
  7070. // Set the display preference for hex vs. decimal immediates.
  7071. ThumbIP->setPrintImmHex(PrintImmHex);
  7072. }
  7073. #undef CHECK_TARGET_INFO_CREATION
  7074. #undef CHECK_THUMB_TARGET_INFO_CREATION
  7075. MachO::mach_header Header = MachOOF->getHeader();
  7076. // FIXME: Using the -cfg command line option, this code used to be able to
  7077. // annotate relocations with the referenced symbol's name, and if this was
  7078. // inside a __[cf]string section, the data it points to. This is now replaced
  7079. // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
  7080. std::vector<SectionRef> Sections;
  7081. std::vector<SymbolRef> Symbols;
  7082. SmallVector<uint64_t, 8> FoundFns;
  7083. uint64_t BaseSegmentAddress = 0;
  7084. getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
  7085. BaseSegmentAddress);
  7086. // Sort the symbols by address, just in case they didn't come in that way.
  7087. llvm::stable_sort(Symbols, SymbolSorter());
  7088. // Build a data in code table that is sorted on by the address of each entry.
  7089. uint64_t BaseAddress = 0;
  7090. if (Header.filetype == MachO::MH_OBJECT)
  7091. BaseAddress = Sections[0].getAddress();
  7092. else
  7093. BaseAddress = BaseSegmentAddress;
  7094. DiceTable Dices;
  7095. for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
  7096. DI != DE; ++DI) {
  7097. uint32_t Offset;
  7098. DI->getOffset(Offset);
  7099. Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
  7100. }
  7101. array_pod_sort(Dices.begin(), Dices.end());
  7102. // Try to find debug info and set up the DIContext for it.
  7103. std::unique_ptr<DIContext> diContext;
  7104. std::unique_ptr<Binary> DSYMBinary;
  7105. std::unique_ptr<MemoryBuffer> DSYMBuf;
  7106. if (UseDbg) {
  7107. // If separate DSym file path was specified, parse it as a macho file,
  7108. // get the sections and supply it to the section name parsing machinery.
  7109. if (const ObjectFile *DbgObj =
  7110. getMachODSymObject(MachOOF, Filename, DSYMBinary, DSYMBuf)) {
  7111. // Setup the DIContext
  7112. diContext = DWARFContext::create(*DbgObj);
  7113. } else {
  7114. return;
  7115. }
  7116. }
  7117. if (FilterSections.empty())
  7118. outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
  7119. for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
  7120. Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName();
  7121. if (!SecNameOrErr) {
  7122. consumeError(SecNameOrErr.takeError());
  7123. continue;
  7124. }
  7125. if (*SecNameOrErr != DisSectName)
  7126. continue;
  7127. DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
  7128. StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
  7129. if (SegmentName != DisSegName)
  7130. continue;
  7131. StringRef BytesStr =
  7132. unwrapOrError(Sections[SectIdx].getContents(), Filename);
  7133. ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
  7134. uint64_t SectAddress = Sections[SectIdx].getAddress();
  7135. bool symbolTableWorked = false;
  7136. // Create a map of symbol addresses to symbol names for use by
  7137. // the SymbolizerSymbolLookUp() routine.
  7138. SymbolAddressMap AddrMap;
  7139. bool DisSymNameFound = false;
  7140. for (const SymbolRef &Symbol : MachOOF->symbols()) {
  7141. SymbolRef::Type ST =
  7142. unwrapOrError(Symbol.getType(), MachOOF->getFileName());
  7143. if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
  7144. ST == SymbolRef::ST_Other) {
  7145. uint64_t Address = cantFail(Symbol.getValue());
  7146. StringRef SymName =
  7147. unwrapOrError(Symbol.getName(), MachOOF->getFileName());
  7148. AddrMap[Address] = SymName;
  7149. if (!DisSymName.empty() && DisSymName == SymName)
  7150. DisSymNameFound = true;
  7151. }
  7152. }
  7153. if (!DisSymName.empty() && !DisSymNameFound) {
  7154. outs() << "Can't find -dis-symname: " << DisSymName << "\n";
  7155. return;
  7156. }
  7157. // Set up the block of info used by the Symbolizer call backs.
  7158. SymbolizerInfo.verbose = SymbolicOperands;
  7159. SymbolizerInfo.O = MachOOF;
  7160. SymbolizerInfo.S = Sections[SectIdx];
  7161. SymbolizerInfo.AddrMap = &AddrMap;
  7162. SymbolizerInfo.Sections = &Sections;
  7163. // Same for the ThumbSymbolizer
  7164. ThumbSymbolizerInfo.verbose = SymbolicOperands;
  7165. ThumbSymbolizerInfo.O = MachOOF;
  7166. ThumbSymbolizerInfo.S = Sections[SectIdx];
  7167. ThumbSymbolizerInfo.AddrMap = &AddrMap;
  7168. ThumbSymbolizerInfo.Sections = &Sections;
  7169. unsigned int Arch = MachOOF->getArch();
  7170. // Skip all symbols if this is a stubs file.
  7171. if (Bytes.empty())
  7172. return;
  7173. // If the section has symbols but no symbol at the start of the section
  7174. // these are used to make sure the bytes before the first symbol are
  7175. // disassembled.
  7176. bool FirstSymbol = true;
  7177. bool FirstSymbolAtSectionStart = true;
  7178. // Disassemble symbol by symbol.
  7179. for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
  7180. StringRef SymName =
  7181. unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
  7182. SymbolRef::Type ST =
  7183. unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
  7184. if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
  7185. continue;
  7186. // Make sure the symbol is defined in this section.
  7187. bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
  7188. if (!containsSym) {
  7189. if (!DisSymName.empty() && DisSymName == SymName) {
  7190. outs() << "-dis-symname: " << DisSymName << " not in the section\n";
  7191. return;
  7192. }
  7193. continue;
  7194. }
  7195. // The __mh_execute_header is special and we need to deal with that fact
  7196. // this symbol is before the start of the (__TEXT,__text) section and at the
  7197. // address of the start of the __TEXT segment. This is because this symbol
  7198. // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
  7199. // start of the section in a standard MH_EXECUTE filetype.
  7200. if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
  7201. outs() << "-dis-symname: __mh_execute_header not in any section\n";
  7202. return;
  7203. }
  7204. // When this code is trying to disassemble a symbol at a time and in the
  7205. // case there is only the __mh_execute_header symbol left as in a stripped
  7206. // executable, we need to deal with this by ignoring this symbol so the
  7207. // whole section is disassembled and this symbol is then not displayed.
  7208. if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
  7209. SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
  7210. SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
  7211. continue;
  7212. // If we are only disassembling one symbol see if this is that symbol.
  7213. if (!DisSymName.empty() && DisSymName != SymName)
  7214. continue;
  7215. // Start at the address of the symbol relative to the section's address.
  7216. uint64_t SectSize = Sections[SectIdx].getSize();
  7217. uint64_t Start = cantFail(Symbols[SymIdx].getValue());
  7218. uint64_t SectionAddress = Sections[SectIdx].getAddress();
  7219. Start -= SectionAddress;
  7220. if (Start > SectSize) {
  7221. outs() << "section data ends, " << SymName
  7222. << " lies outside valid range\n";
  7223. return;
  7224. }
  7225. // Stop disassembling either at the beginning of the next symbol or at
  7226. // the end of the section.
  7227. bool containsNextSym = false;
  7228. uint64_t NextSym = 0;
  7229. uint64_t NextSymIdx = SymIdx + 1;
  7230. while (Symbols.size() > NextSymIdx) {
  7231. SymbolRef::Type NextSymType = unwrapOrError(
  7232. Symbols[NextSymIdx].getType(), MachOOF->getFileName());
  7233. if (NextSymType == SymbolRef::ST_Function) {
  7234. containsNextSym =
  7235. Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
  7236. NextSym = cantFail(Symbols[NextSymIdx].getValue());
  7237. NextSym -= SectionAddress;
  7238. break;
  7239. }
  7240. ++NextSymIdx;
  7241. }
  7242. uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
  7243. uint64_t Size;
  7244. symbolTableWorked = true;
  7245. DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
  7246. uint32_t SymbolFlags = cantFail(MachOOF->getSymbolFlags(Symb));
  7247. bool IsThumb = SymbolFlags & SymbolRef::SF_Thumb;
  7248. // We only need the dedicated Thumb target if there's a real choice
  7249. // (i.e. we're not targeting M-class) and the function is Thumb.
  7250. bool UseThumbTarget = IsThumb && ThumbTarget;
  7251. // If we are not specifying a symbol to start disassembly with and this
  7252. // is the first symbol in the section but not at the start of the section
  7253. // then move the disassembly index to the start of the section and
  7254. // don't print the symbol name just yet. This is so the bytes before the
  7255. // first symbol are disassembled.
  7256. uint64_t SymbolStart = Start;
  7257. if (DisSymName.empty() && FirstSymbol && Start != 0) {
  7258. FirstSymbolAtSectionStart = false;
  7259. Start = 0;
  7260. }
  7261. else
  7262. outs() << SymName << ":\n";
  7263. DILineInfo lastLine;
  7264. for (uint64_t Index = Start; Index < End; Index += Size) {
  7265. MCInst Inst;
  7266. // If this is the first symbol in the section and it was not at the
  7267. // start of the section, see if we are at its Index now and if so print
  7268. // the symbol name.
  7269. if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
  7270. outs() << SymName << ":\n";
  7271. uint64_t PC = SectAddress + Index;
  7272. if (LeadingAddr) {
  7273. if (FullLeadingAddr) {
  7274. if (MachOOF->is64Bit())
  7275. outs() << format("%016" PRIx64, PC);
  7276. else
  7277. outs() << format("%08" PRIx64, PC);
  7278. } else {
  7279. outs() << format("%8" PRIx64 ":", PC);
  7280. }
  7281. }
  7282. if (ShowRawInsn || Arch == Triple::arm)
  7283. outs() << "\t";
  7284. if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, Size))
  7285. continue;
  7286. SmallVector<char, 64> AnnotationsBytes;
  7287. raw_svector_ostream Annotations(AnnotationsBytes);
  7288. bool gotInst;
  7289. if (UseThumbTarget)
  7290. gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
  7291. PC, Annotations);
  7292. else
  7293. gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
  7294. Annotations);
  7295. if (gotInst) {
  7296. if (ShowRawInsn || Arch == Triple::arm) {
  7297. dumpBytes(ArrayRef(Bytes.data() + Index, Size), outs());
  7298. }
  7299. formatted_raw_ostream FormattedOS(outs());
  7300. StringRef AnnotationsStr = Annotations.str();
  7301. if (UseThumbTarget)
  7302. ThumbIP->printInst(&Inst, PC, AnnotationsStr, *ThumbSTI,
  7303. FormattedOS);
  7304. else
  7305. IP->printInst(&Inst, PC, AnnotationsStr, *STI, FormattedOS);
  7306. emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
  7307. // Print debug info.
  7308. if (diContext) {
  7309. DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
  7310. // Print valid line info if it changed.
  7311. if (dli != lastLine && dli.Line != 0)
  7312. outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
  7313. << dli.Column;
  7314. lastLine = dli;
  7315. }
  7316. outs() << "\n";
  7317. } else {
  7318. if (MachOOF->getArchTriple().isX86()) {
  7319. outs() << format("\t.byte 0x%02x #bad opcode\n",
  7320. *(Bytes.data() + Index) & 0xff);
  7321. Size = 1; // skip exactly one illegible byte and move on.
  7322. } else if (Arch == Triple::aarch64 ||
  7323. (Arch == Triple::arm && !IsThumb)) {
  7324. uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
  7325. (*(Bytes.data() + Index + 1) & 0xff) << 8 |
  7326. (*(Bytes.data() + Index + 2) & 0xff) << 16 |
  7327. (*(Bytes.data() + Index + 3) & 0xff) << 24;
  7328. outs() << format("\t.long\t0x%08x\n", opcode);
  7329. Size = 4;
  7330. } else if (Arch == Triple::arm) {
  7331. assert(IsThumb && "ARM mode should have been dealt with above");
  7332. uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
  7333. (*(Bytes.data() + Index + 1) & 0xff) << 8;
  7334. outs() << format("\t.short\t0x%04x\n", opcode);
  7335. Size = 2;
  7336. } else{
  7337. WithColor::warning(errs(), "llvm-objdump")
  7338. << "invalid instruction encoding\n";
  7339. if (Size == 0)
  7340. Size = 1; // skip illegible bytes
  7341. }
  7342. }
  7343. }
  7344. // Now that we are done disassembled the first symbol set the bool that
  7345. // were doing this to false.
  7346. FirstSymbol = false;
  7347. }
  7348. if (!symbolTableWorked) {
  7349. // Reading the symbol table didn't work, disassemble the whole section.
  7350. uint64_t SectAddress = Sections[SectIdx].getAddress();
  7351. uint64_t SectSize = Sections[SectIdx].getSize();
  7352. uint64_t InstSize;
  7353. for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
  7354. MCInst Inst;
  7355. uint64_t PC = SectAddress + Index;
  7356. if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, InstSize))
  7357. continue;
  7358. SmallVector<char, 64> AnnotationsBytes;
  7359. raw_svector_ostream Annotations(AnnotationsBytes);
  7360. if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
  7361. Annotations)) {
  7362. if (LeadingAddr) {
  7363. if (FullLeadingAddr) {
  7364. if (MachOOF->is64Bit())
  7365. outs() << format("%016" PRIx64, PC);
  7366. else
  7367. outs() << format("%08" PRIx64, PC);
  7368. } else {
  7369. outs() << format("%8" PRIx64 ":", PC);
  7370. }
  7371. }
  7372. if (ShowRawInsn || Arch == Triple::arm) {
  7373. outs() << "\t";
  7374. dumpBytes(ArrayRef(Bytes.data() + Index, InstSize), outs());
  7375. }
  7376. StringRef AnnotationsStr = Annotations.str();
  7377. IP->printInst(&Inst, PC, AnnotationsStr, *STI, outs());
  7378. outs() << "\n";
  7379. } else {
  7380. if (MachOOF->getArchTriple().isX86()) {
  7381. outs() << format("\t.byte 0x%02x #bad opcode\n",
  7382. *(Bytes.data() + Index) & 0xff);
  7383. InstSize = 1; // skip exactly one illegible byte and move on.
  7384. } else {
  7385. WithColor::warning(errs(), "llvm-objdump")
  7386. << "invalid instruction encoding\n";
  7387. if (InstSize == 0)
  7388. InstSize = 1; // skip illegible bytes
  7389. }
  7390. }
  7391. }
  7392. }
  7393. // The TripleName's need to be reset if we are called again for a different
  7394. // architecture.
  7395. TripleName = "";
  7396. ThumbTripleName = "";
  7397. if (SymbolizerInfo.demangled_name != nullptr)
  7398. free(SymbolizerInfo.demangled_name);
  7399. if (ThumbSymbolizerInfo.demangled_name != nullptr)
  7400. free(ThumbSymbolizerInfo.demangled_name);
  7401. }
  7402. }
  7403. //===----------------------------------------------------------------------===//
  7404. // __compact_unwind section dumping
  7405. //===----------------------------------------------------------------------===//
  7406. namespace {
  7407. template <typename T>
  7408. static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
  7409. using llvm::support::little;
  7410. using llvm::support::unaligned;
  7411. if (Offset + sizeof(T) > Contents.size()) {
  7412. outs() << "warning: attempt to read past end of buffer\n";
  7413. return T();
  7414. }
  7415. uint64_t Val =
  7416. support::endian::read<T, little, unaligned>(Contents.data() + Offset);
  7417. return Val;
  7418. }
  7419. template <typename T>
  7420. static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
  7421. T Val = read<T>(Contents, Offset);
  7422. Offset += sizeof(T);
  7423. return Val;
  7424. }
  7425. struct CompactUnwindEntry {
  7426. uint32_t OffsetInSection;
  7427. uint64_t FunctionAddr;
  7428. uint32_t Length;
  7429. uint32_t CompactEncoding;
  7430. uint64_t PersonalityAddr;
  7431. uint64_t LSDAAddr;
  7432. RelocationRef FunctionReloc;
  7433. RelocationRef PersonalityReloc;
  7434. RelocationRef LSDAReloc;
  7435. CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
  7436. : OffsetInSection(Offset) {
  7437. if (Is64)
  7438. read<uint64_t>(Contents, Offset);
  7439. else
  7440. read<uint32_t>(Contents, Offset);
  7441. }
  7442. private:
  7443. template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
  7444. FunctionAddr = readNext<UIntPtr>(Contents, Offset);
  7445. Length = readNext<uint32_t>(Contents, Offset);
  7446. CompactEncoding = readNext<uint32_t>(Contents, Offset);
  7447. PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
  7448. LSDAAddr = readNext<UIntPtr>(Contents, Offset);
  7449. }
  7450. };
  7451. }
  7452. /// Given a relocation from __compact_unwind, consisting of the RelocationRef
  7453. /// and data being relocated, determine the best base Name and Addend to use for
  7454. /// display purposes.
  7455. ///
  7456. /// 1. An Extern relocation will directly reference a symbol (and the data is
  7457. /// then already an addend), so use that.
  7458. /// 2. Otherwise the data is an offset in the object file's layout; try to find
  7459. // a symbol before it in the same section, and use the offset from there.
  7460. /// 3. Finally, if all that fails, fall back to an offset from the start of the
  7461. /// referenced section.
  7462. static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
  7463. std::map<uint64_t, SymbolRef> &Symbols,
  7464. const RelocationRef &Reloc, uint64_t Addr,
  7465. StringRef &Name, uint64_t &Addend) {
  7466. if (Reloc.getSymbol() != Obj->symbol_end()) {
  7467. Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
  7468. Addend = Addr;
  7469. return;
  7470. }
  7471. auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
  7472. SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
  7473. uint64_t SectionAddr = RelocSection.getAddress();
  7474. auto Sym = Symbols.upper_bound(Addr);
  7475. if (Sym == Symbols.begin()) {
  7476. // The first symbol in the object is after this reference, the best we can
  7477. // do is section-relative notation.
  7478. if (Expected<StringRef> NameOrErr = RelocSection.getName())
  7479. Name = *NameOrErr;
  7480. else
  7481. consumeError(NameOrErr.takeError());
  7482. Addend = Addr - SectionAddr;
  7483. return;
  7484. }
  7485. // Go back one so that SymbolAddress <= Addr.
  7486. --Sym;
  7487. section_iterator SymSection =
  7488. unwrapOrError(Sym->second.getSection(), Obj->getFileName());
  7489. if (RelocSection == *SymSection) {
  7490. // There's a valid symbol in the same section before this reference.
  7491. Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
  7492. Addend = Addr - Sym->first;
  7493. return;
  7494. }
  7495. // There is a symbol before this reference, but it's in a different
  7496. // section. Probably not helpful to mention it, so use the section name.
  7497. if (Expected<StringRef> NameOrErr = RelocSection.getName())
  7498. Name = *NameOrErr;
  7499. else
  7500. consumeError(NameOrErr.takeError());
  7501. Addend = Addr - SectionAddr;
  7502. }
  7503. static void printUnwindRelocDest(const MachOObjectFile *Obj,
  7504. std::map<uint64_t, SymbolRef> &Symbols,
  7505. const RelocationRef &Reloc, uint64_t Addr) {
  7506. StringRef Name;
  7507. uint64_t Addend;
  7508. if (!Reloc.getObject())
  7509. return;
  7510. findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
  7511. outs() << Name;
  7512. if (Addend)
  7513. outs() << " + " << format("0x%" PRIx64, Addend);
  7514. }
  7515. static void
  7516. printMachOCompactUnwindSection(const MachOObjectFile *Obj,
  7517. std::map<uint64_t, SymbolRef> &Symbols,
  7518. const SectionRef &CompactUnwind) {
  7519. if (!Obj->isLittleEndian()) {
  7520. outs() << "Skipping big-endian __compact_unwind section\n";
  7521. return;
  7522. }
  7523. bool Is64 = Obj->is64Bit();
  7524. uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
  7525. uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
  7526. StringRef Contents =
  7527. unwrapOrError(CompactUnwind.getContents(), Obj->getFileName());
  7528. SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
  7529. // First populate the initial raw offsets, encodings and so on from the entry.
  7530. for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
  7531. CompactUnwindEntry Entry(Contents, Offset, Is64);
  7532. CompactUnwinds.push_back(Entry);
  7533. }
  7534. // Next we need to look at the relocations to find out what objects are
  7535. // actually being referred to.
  7536. for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
  7537. uint64_t RelocAddress = Reloc.getOffset();
  7538. uint32_t EntryIdx = RelocAddress / EntrySize;
  7539. uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
  7540. CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
  7541. if (OffsetInEntry == 0)
  7542. Entry.FunctionReloc = Reloc;
  7543. else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
  7544. Entry.PersonalityReloc = Reloc;
  7545. else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
  7546. Entry.LSDAReloc = Reloc;
  7547. else {
  7548. outs() << "Invalid relocation in __compact_unwind section\n";
  7549. return;
  7550. }
  7551. }
  7552. // Finally, we're ready to print the data we've gathered.
  7553. outs() << "Contents of __compact_unwind section:\n";
  7554. for (auto &Entry : CompactUnwinds) {
  7555. outs() << " Entry at offset "
  7556. << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
  7557. // 1. Start of the region this entry applies to.
  7558. outs() << " start: " << format("0x%" PRIx64,
  7559. Entry.FunctionAddr) << ' ';
  7560. printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
  7561. outs() << '\n';
  7562. // 2. Length of the region this entry applies to.
  7563. outs() << " length: " << format("0x%" PRIx32, Entry.Length)
  7564. << '\n';
  7565. // 3. The 32-bit compact encoding.
  7566. outs() << " compact encoding: "
  7567. << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
  7568. // 4. The personality function, if present.
  7569. if (Entry.PersonalityReloc.getObject()) {
  7570. outs() << " personality function: "
  7571. << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
  7572. printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
  7573. Entry.PersonalityAddr);
  7574. outs() << '\n';
  7575. }
  7576. // 5. This entry's language-specific data area.
  7577. if (Entry.LSDAReloc.getObject()) {
  7578. outs() << " LSDA: " << format("0x%" PRIx64,
  7579. Entry.LSDAAddr) << ' ';
  7580. printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
  7581. outs() << '\n';
  7582. }
  7583. }
  7584. }
  7585. //===----------------------------------------------------------------------===//
  7586. // __unwind_info section dumping
  7587. //===----------------------------------------------------------------------===//
  7588. static void printRegularSecondLevelUnwindPage(StringRef PageData) {
  7589. ptrdiff_t Pos = 0;
  7590. uint32_t Kind = readNext<uint32_t>(PageData, Pos);
  7591. (void)Kind;
  7592. assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
  7593. uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
  7594. uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
  7595. Pos = EntriesStart;
  7596. for (unsigned i = 0; i < NumEntries; ++i) {
  7597. uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
  7598. uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
  7599. outs() << " [" << i << "]: "
  7600. << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
  7601. << ", "
  7602. << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
  7603. }
  7604. }
  7605. static void printCompressedSecondLevelUnwindPage(
  7606. StringRef PageData, uint32_t FunctionBase,
  7607. const SmallVectorImpl<uint32_t> &CommonEncodings) {
  7608. ptrdiff_t Pos = 0;
  7609. uint32_t Kind = readNext<uint32_t>(PageData, Pos);
  7610. (void)Kind;
  7611. assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
  7612. uint32_t NumCommonEncodings = CommonEncodings.size();
  7613. uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
  7614. uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
  7615. uint16_t PageEncodingsStart = readNext<uint16_t>(PageData, Pos);
  7616. uint16_t NumPageEncodings = readNext<uint16_t>(PageData, Pos);
  7617. SmallVector<uint32_t, 64> PageEncodings;
  7618. if (NumPageEncodings) {
  7619. outs() << " Page encodings: (count = " << NumPageEncodings << ")\n";
  7620. Pos = PageEncodingsStart;
  7621. for (unsigned i = 0; i < NumPageEncodings; ++i) {
  7622. uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
  7623. PageEncodings.push_back(Encoding);
  7624. outs() << " encoding[" << (i + NumCommonEncodings)
  7625. << "]: " << format("0x%08" PRIx32, Encoding) << '\n';
  7626. }
  7627. }
  7628. Pos = EntriesStart;
  7629. for (unsigned i = 0; i < NumEntries; ++i) {
  7630. uint32_t Entry = readNext<uint32_t>(PageData, Pos);
  7631. uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
  7632. uint32_t EncodingIdx = Entry >> 24;
  7633. uint32_t Encoding;
  7634. if (EncodingIdx < NumCommonEncodings)
  7635. Encoding = CommonEncodings[EncodingIdx];
  7636. else
  7637. Encoding = PageEncodings[EncodingIdx - NumCommonEncodings];
  7638. outs() << " [" << i << "]: "
  7639. << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
  7640. << ", "
  7641. << "encoding[" << EncodingIdx
  7642. << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
  7643. }
  7644. }
  7645. static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
  7646. std::map<uint64_t, SymbolRef> &Symbols,
  7647. const SectionRef &UnwindInfo) {
  7648. if (!Obj->isLittleEndian()) {
  7649. outs() << "Skipping big-endian __unwind_info section\n";
  7650. return;
  7651. }
  7652. outs() << "Contents of __unwind_info section:\n";
  7653. StringRef Contents =
  7654. unwrapOrError(UnwindInfo.getContents(), Obj->getFileName());
  7655. ptrdiff_t Pos = 0;
  7656. //===----------------------------------
  7657. // Section header
  7658. //===----------------------------------
  7659. uint32_t Version = readNext<uint32_t>(Contents, Pos);
  7660. outs() << " Version: "
  7661. << format("0x%" PRIx32, Version) << '\n';
  7662. if (Version != 1) {
  7663. outs() << " Skipping section with unknown version\n";
  7664. return;
  7665. }
  7666. uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
  7667. outs() << " Common encodings array section offset: "
  7668. << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
  7669. uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
  7670. outs() << " Number of common encodings in array: "
  7671. << format("0x%" PRIx32, NumCommonEncodings) << '\n';
  7672. uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
  7673. outs() << " Personality function array section offset: "
  7674. << format("0x%" PRIx32, PersonalitiesStart) << '\n';
  7675. uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
  7676. outs() << " Number of personality functions in array: "
  7677. << format("0x%" PRIx32, NumPersonalities) << '\n';
  7678. uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
  7679. outs() << " Index array section offset: "
  7680. << format("0x%" PRIx32, IndicesStart) << '\n';
  7681. uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
  7682. outs() << " Number of indices in array: "
  7683. << format("0x%" PRIx32, NumIndices) << '\n';
  7684. //===----------------------------------
  7685. // A shared list of common encodings
  7686. //===----------------------------------
  7687. // These occupy indices in the range [0, N] whenever an encoding is referenced
  7688. // from a compressed 2nd level index table. In practice the linker only
  7689. // creates ~128 of these, so that indices are available to embed encodings in
  7690. // the 2nd level index.
  7691. SmallVector<uint32_t, 64> CommonEncodings;
  7692. outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
  7693. Pos = CommonEncodingsStart;
  7694. for (unsigned i = 0; i < NumCommonEncodings; ++i) {
  7695. uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
  7696. CommonEncodings.push_back(Encoding);
  7697. outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
  7698. << '\n';
  7699. }
  7700. //===----------------------------------
  7701. // Personality functions used in this executable
  7702. //===----------------------------------
  7703. // There should be only a handful of these (one per source language,
  7704. // roughly). Particularly since they only get 2 bits in the compact encoding.
  7705. outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
  7706. Pos = PersonalitiesStart;
  7707. for (unsigned i = 0; i < NumPersonalities; ++i) {
  7708. uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
  7709. outs() << " personality[" << i + 1
  7710. << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
  7711. }
  7712. //===----------------------------------
  7713. // The level 1 index entries
  7714. //===----------------------------------
  7715. // These specify an approximate place to start searching for the more detailed
  7716. // information, sorted by PC.
  7717. struct IndexEntry {
  7718. uint32_t FunctionOffset;
  7719. uint32_t SecondLevelPageStart;
  7720. uint32_t LSDAStart;
  7721. };
  7722. SmallVector<IndexEntry, 4> IndexEntries;
  7723. outs() << " Top level indices: (count = " << NumIndices << ")\n";
  7724. Pos = IndicesStart;
  7725. for (unsigned i = 0; i < NumIndices; ++i) {
  7726. IndexEntry Entry;
  7727. Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
  7728. Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
  7729. Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
  7730. IndexEntries.push_back(Entry);
  7731. outs() << " [" << i << "]: "
  7732. << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
  7733. << ", "
  7734. << "2nd level page offset="
  7735. << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
  7736. << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
  7737. }
  7738. //===----------------------------------
  7739. // Next come the LSDA tables
  7740. //===----------------------------------
  7741. // The LSDA layout is rather implicit: it's a contiguous array of entries from
  7742. // the first top-level index's LSDAOffset to the last (sentinel).
  7743. outs() << " LSDA descriptors:\n";
  7744. Pos = IndexEntries[0].LSDAStart;
  7745. const uint32_t LSDASize = 2 * sizeof(uint32_t);
  7746. int NumLSDAs =
  7747. (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
  7748. for (int i = 0; i < NumLSDAs; ++i) {
  7749. uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
  7750. uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
  7751. outs() << " [" << i << "]: "
  7752. << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
  7753. << ", "
  7754. << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
  7755. }
  7756. //===----------------------------------
  7757. // Finally, the 2nd level indices
  7758. //===----------------------------------
  7759. // Generally these are 4K in size, and have 2 possible forms:
  7760. // + Regular stores up to 511 entries with disparate encodings
  7761. // + Compressed stores up to 1021 entries if few enough compact encoding
  7762. // values are used.
  7763. outs() << " Second level indices:\n";
  7764. for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
  7765. // The final sentinel top-level index has no associated 2nd level page
  7766. if (IndexEntries[i].SecondLevelPageStart == 0)
  7767. break;
  7768. outs() << " Second level index[" << i << "]: "
  7769. << "offset in section="
  7770. << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
  7771. << ", "
  7772. << "base function offset="
  7773. << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
  7774. Pos = IndexEntries[i].SecondLevelPageStart;
  7775. if (Pos + sizeof(uint32_t) > Contents.size()) {
  7776. outs() << "warning: invalid offset for second level page: " << Pos << '\n';
  7777. continue;
  7778. }
  7779. uint32_t Kind =
  7780. *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
  7781. if (Kind == 2)
  7782. printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
  7783. else if (Kind == 3)
  7784. printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
  7785. IndexEntries[i].FunctionOffset,
  7786. CommonEncodings);
  7787. else
  7788. outs() << " Skipping 2nd level page with unknown kind " << Kind
  7789. << '\n';
  7790. }
  7791. }
  7792. void objdump::printMachOUnwindInfo(const MachOObjectFile *Obj) {
  7793. std::map<uint64_t, SymbolRef> Symbols;
  7794. for (const SymbolRef &SymRef : Obj->symbols()) {
  7795. // Discard any undefined or absolute symbols. They're not going to take part
  7796. // in the convenience lookup for unwind info and just take up resources.
  7797. auto SectOrErr = SymRef.getSection();
  7798. if (!SectOrErr) {
  7799. // TODO: Actually report errors helpfully.
  7800. consumeError(SectOrErr.takeError());
  7801. continue;
  7802. }
  7803. section_iterator Section = *SectOrErr;
  7804. if (Section == Obj->section_end())
  7805. continue;
  7806. uint64_t Addr = cantFail(SymRef.getValue());
  7807. Symbols.insert(std::make_pair(Addr, SymRef));
  7808. }
  7809. for (const SectionRef &Section : Obj->sections()) {
  7810. StringRef SectName;
  7811. if (Expected<StringRef> NameOrErr = Section.getName())
  7812. SectName = *NameOrErr;
  7813. else
  7814. consumeError(NameOrErr.takeError());
  7815. if (SectName == "__compact_unwind")
  7816. printMachOCompactUnwindSection(Obj, Symbols, Section);
  7817. else if (SectName == "__unwind_info")
  7818. printMachOUnwindInfoSection(Obj, Symbols, Section);
  7819. }
  7820. }
  7821. static void PrintMachHeader(uint32_t magic, uint32_t cputype,
  7822. uint32_t cpusubtype, uint32_t filetype,
  7823. uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
  7824. bool verbose) {
  7825. outs() << "Mach header\n";
  7826. outs() << " magic cputype cpusubtype caps filetype ncmds "
  7827. "sizeofcmds flags\n";
  7828. if (verbose) {
  7829. if (magic == MachO::MH_MAGIC)
  7830. outs() << " MH_MAGIC";
  7831. else if (magic == MachO::MH_MAGIC_64)
  7832. outs() << "MH_MAGIC_64";
  7833. else
  7834. outs() << format(" 0x%08" PRIx32, magic);
  7835. switch (cputype) {
  7836. case MachO::CPU_TYPE_I386:
  7837. outs() << " I386";
  7838. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7839. case MachO::CPU_SUBTYPE_I386_ALL:
  7840. outs() << " ALL";
  7841. break;
  7842. default:
  7843. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7844. break;
  7845. }
  7846. break;
  7847. case MachO::CPU_TYPE_X86_64:
  7848. outs() << " X86_64";
  7849. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7850. case MachO::CPU_SUBTYPE_X86_64_ALL:
  7851. outs() << " ALL";
  7852. break;
  7853. case MachO::CPU_SUBTYPE_X86_64_H:
  7854. outs() << " Haswell";
  7855. break;
  7856. default:
  7857. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7858. break;
  7859. }
  7860. break;
  7861. case MachO::CPU_TYPE_ARM:
  7862. outs() << " ARM";
  7863. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7864. case MachO::CPU_SUBTYPE_ARM_ALL:
  7865. outs() << " ALL";
  7866. break;
  7867. case MachO::CPU_SUBTYPE_ARM_V4T:
  7868. outs() << " V4T";
  7869. break;
  7870. case MachO::CPU_SUBTYPE_ARM_V5TEJ:
  7871. outs() << " V5TEJ";
  7872. break;
  7873. case MachO::CPU_SUBTYPE_ARM_XSCALE:
  7874. outs() << " XSCALE";
  7875. break;
  7876. case MachO::CPU_SUBTYPE_ARM_V6:
  7877. outs() << " V6";
  7878. break;
  7879. case MachO::CPU_SUBTYPE_ARM_V6M:
  7880. outs() << " V6M";
  7881. break;
  7882. case MachO::CPU_SUBTYPE_ARM_V7:
  7883. outs() << " V7";
  7884. break;
  7885. case MachO::CPU_SUBTYPE_ARM_V7EM:
  7886. outs() << " V7EM";
  7887. break;
  7888. case MachO::CPU_SUBTYPE_ARM_V7K:
  7889. outs() << " V7K";
  7890. break;
  7891. case MachO::CPU_SUBTYPE_ARM_V7M:
  7892. outs() << " V7M";
  7893. break;
  7894. case MachO::CPU_SUBTYPE_ARM_V7S:
  7895. outs() << " V7S";
  7896. break;
  7897. default:
  7898. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7899. break;
  7900. }
  7901. break;
  7902. case MachO::CPU_TYPE_ARM64:
  7903. outs() << " ARM64";
  7904. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7905. case MachO::CPU_SUBTYPE_ARM64_ALL:
  7906. outs() << " ALL";
  7907. break;
  7908. case MachO::CPU_SUBTYPE_ARM64_V8:
  7909. outs() << " V8";
  7910. break;
  7911. case MachO::CPU_SUBTYPE_ARM64E:
  7912. outs() << " E";
  7913. break;
  7914. default:
  7915. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7916. break;
  7917. }
  7918. break;
  7919. case MachO::CPU_TYPE_ARM64_32:
  7920. outs() << " ARM64_32";
  7921. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7922. case MachO::CPU_SUBTYPE_ARM64_32_V8:
  7923. outs() << " V8";
  7924. break;
  7925. default:
  7926. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7927. break;
  7928. }
  7929. break;
  7930. case MachO::CPU_TYPE_POWERPC:
  7931. outs() << " PPC";
  7932. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7933. case MachO::CPU_SUBTYPE_POWERPC_ALL:
  7934. outs() << " ALL";
  7935. break;
  7936. default:
  7937. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7938. break;
  7939. }
  7940. break;
  7941. case MachO::CPU_TYPE_POWERPC64:
  7942. outs() << " PPC64";
  7943. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7944. case MachO::CPU_SUBTYPE_POWERPC_ALL:
  7945. outs() << " ALL";
  7946. break;
  7947. default:
  7948. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7949. break;
  7950. }
  7951. break;
  7952. default:
  7953. outs() << format(" %7d", cputype);
  7954. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7955. break;
  7956. }
  7957. if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
  7958. outs() << " LIB64";
  7959. } else {
  7960. outs() << format(" 0x%02" PRIx32,
  7961. (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
  7962. }
  7963. switch (filetype) {
  7964. case MachO::MH_OBJECT:
  7965. outs() << " OBJECT";
  7966. break;
  7967. case MachO::MH_EXECUTE:
  7968. outs() << " EXECUTE";
  7969. break;
  7970. case MachO::MH_FVMLIB:
  7971. outs() << " FVMLIB";
  7972. break;
  7973. case MachO::MH_CORE:
  7974. outs() << " CORE";
  7975. break;
  7976. case MachO::MH_PRELOAD:
  7977. outs() << " PRELOAD";
  7978. break;
  7979. case MachO::MH_DYLIB:
  7980. outs() << " DYLIB";
  7981. break;
  7982. case MachO::MH_DYLIB_STUB:
  7983. outs() << " DYLIB_STUB";
  7984. break;
  7985. case MachO::MH_DYLINKER:
  7986. outs() << " DYLINKER";
  7987. break;
  7988. case MachO::MH_BUNDLE:
  7989. outs() << " BUNDLE";
  7990. break;
  7991. case MachO::MH_DSYM:
  7992. outs() << " DSYM";
  7993. break;
  7994. case MachO::MH_KEXT_BUNDLE:
  7995. outs() << " KEXTBUNDLE";
  7996. break;
  7997. case MachO::MH_FILESET:
  7998. outs() << " FILESET";
  7999. break;
  8000. default:
  8001. outs() << format(" %10u", filetype);
  8002. break;
  8003. }
  8004. outs() << format(" %5u", ncmds);
  8005. outs() << format(" %10u", sizeofcmds);
  8006. uint32_t f = flags;
  8007. if (f & MachO::MH_NOUNDEFS) {
  8008. outs() << " NOUNDEFS";
  8009. f &= ~MachO::MH_NOUNDEFS;
  8010. }
  8011. if (f & MachO::MH_INCRLINK) {
  8012. outs() << " INCRLINK";
  8013. f &= ~MachO::MH_INCRLINK;
  8014. }
  8015. if (f & MachO::MH_DYLDLINK) {
  8016. outs() << " DYLDLINK";
  8017. f &= ~MachO::MH_DYLDLINK;
  8018. }
  8019. if (f & MachO::MH_BINDATLOAD) {
  8020. outs() << " BINDATLOAD";
  8021. f &= ~MachO::MH_BINDATLOAD;
  8022. }
  8023. if (f & MachO::MH_PREBOUND) {
  8024. outs() << " PREBOUND";
  8025. f &= ~MachO::MH_PREBOUND;
  8026. }
  8027. if (f & MachO::MH_SPLIT_SEGS) {
  8028. outs() << " SPLIT_SEGS";
  8029. f &= ~MachO::MH_SPLIT_SEGS;
  8030. }
  8031. if (f & MachO::MH_LAZY_INIT) {
  8032. outs() << " LAZY_INIT";
  8033. f &= ~MachO::MH_LAZY_INIT;
  8034. }
  8035. if (f & MachO::MH_TWOLEVEL) {
  8036. outs() << " TWOLEVEL";
  8037. f &= ~MachO::MH_TWOLEVEL;
  8038. }
  8039. if (f & MachO::MH_FORCE_FLAT) {
  8040. outs() << " FORCE_FLAT";
  8041. f &= ~MachO::MH_FORCE_FLAT;
  8042. }
  8043. if (f & MachO::MH_NOMULTIDEFS) {
  8044. outs() << " NOMULTIDEFS";
  8045. f &= ~MachO::MH_NOMULTIDEFS;
  8046. }
  8047. if (f & MachO::MH_NOFIXPREBINDING) {
  8048. outs() << " NOFIXPREBINDING";
  8049. f &= ~MachO::MH_NOFIXPREBINDING;
  8050. }
  8051. if (f & MachO::MH_PREBINDABLE) {
  8052. outs() << " PREBINDABLE";
  8053. f &= ~MachO::MH_PREBINDABLE;
  8054. }
  8055. if (f & MachO::MH_ALLMODSBOUND) {
  8056. outs() << " ALLMODSBOUND";
  8057. f &= ~MachO::MH_ALLMODSBOUND;
  8058. }
  8059. if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
  8060. outs() << " SUBSECTIONS_VIA_SYMBOLS";
  8061. f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
  8062. }
  8063. if (f & MachO::MH_CANONICAL) {
  8064. outs() << " CANONICAL";
  8065. f &= ~MachO::MH_CANONICAL;
  8066. }
  8067. if (f & MachO::MH_WEAK_DEFINES) {
  8068. outs() << " WEAK_DEFINES";
  8069. f &= ~MachO::MH_WEAK_DEFINES;
  8070. }
  8071. if (f & MachO::MH_BINDS_TO_WEAK) {
  8072. outs() << " BINDS_TO_WEAK";
  8073. f &= ~MachO::MH_BINDS_TO_WEAK;
  8074. }
  8075. if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
  8076. outs() << " ALLOW_STACK_EXECUTION";
  8077. f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
  8078. }
  8079. if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
  8080. outs() << " DEAD_STRIPPABLE_DYLIB";
  8081. f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
  8082. }
  8083. if (f & MachO::MH_PIE) {
  8084. outs() << " PIE";
  8085. f &= ~MachO::MH_PIE;
  8086. }
  8087. if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
  8088. outs() << " NO_REEXPORTED_DYLIBS";
  8089. f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
  8090. }
  8091. if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
  8092. outs() << " MH_HAS_TLV_DESCRIPTORS";
  8093. f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
  8094. }
  8095. if (f & MachO::MH_NO_HEAP_EXECUTION) {
  8096. outs() << " MH_NO_HEAP_EXECUTION";
  8097. f &= ~MachO::MH_NO_HEAP_EXECUTION;
  8098. }
  8099. if (f & MachO::MH_APP_EXTENSION_SAFE) {
  8100. outs() << " APP_EXTENSION_SAFE";
  8101. f &= ~MachO::MH_APP_EXTENSION_SAFE;
  8102. }
  8103. if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
  8104. outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
  8105. f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
  8106. }
  8107. if (f != 0 || flags == 0)
  8108. outs() << format(" 0x%08" PRIx32, f);
  8109. } else {
  8110. outs() << format(" 0x%08" PRIx32, magic);
  8111. outs() << format(" %7d", cputype);
  8112. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  8113. outs() << format(" 0x%02" PRIx32,
  8114. (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
  8115. outs() << format(" %10u", filetype);
  8116. outs() << format(" %5u", ncmds);
  8117. outs() << format(" %10u", sizeofcmds);
  8118. outs() << format(" 0x%08" PRIx32, flags);
  8119. }
  8120. outs() << "\n";
  8121. }
  8122. static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
  8123. StringRef SegName, uint64_t vmaddr,
  8124. uint64_t vmsize, uint64_t fileoff,
  8125. uint64_t filesize, uint32_t maxprot,
  8126. uint32_t initprot, uint32_t nsects,
  8127. uint32_t flags, uint32_t object_size,
  8128. bool verbose) {
  8129. uint64_t expected_cmdsize;
  8130. if (cmd == MachO::LC_SEGMENT) {
  8131. outs() << " cmd LC_SEGMENT\n";
  8132. expected_cmdsize = nsects;
  8133. expected_cmdsize *= sizeof(struct MachO::section);
  8134. expected_cmdsize += sizeof(struct MachO::segment_command);
  8135. } else {
  8136. outs() << " cmd LC_SEGMENT_64\n";
  8137. expected_cmdsize = nsects;
  8138. expected_cmdsize *= sizeof(struct MachO::section_64);
  8139. expected_cmdsize += sizeof(struct MachO::segment_command_64);
  8140. }
  8141. outs() << " cmdsize " << cmdsize;
  8142. if (cmdsize != expected_cmdsize)
  8143. outs() << " Inconsistent size\n";
  8144. else
  8145. outs() << "\n";
  8146. outs() << " segname " << SegName << "\n";
  8147. if (cmd == MachO::LC_SEGMENT_64) {
  8148. outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
  8149. outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
  8150. } else {
  8151. outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
  8152. outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
  8153. }
  8154. outs() << " fileoff " << fileoff;
  8155. if (fileoff > object_size)
  8156. outs() << " (past end of file)\n";
  8157. else
  8158. outs() << "\n";
  8159. outs() << " filesize " << filesize;
  8160. if (fileoff + filesize > object_size)
  8161. outs() << " (past end of file)\n";
  8162. else
  8163. outs() << "\n";
  8164. if (verbose) {
  8165. if ((maxprot &
  8166. ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
  8167. MachO::VM_PROT_EXECUTE)) != 0)
  8168. outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
  8169. else {
  8170. outs() << " maxprot ";
  8171. outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
  8172. outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
  8173. outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
  8174. }
  8175. if ((initprot &
  8176. ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
  8177. MachO::VM_PROT_EXECUTE)) != 0)
  8178. outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
  8179. else {
  8180. outs() << " initprot ";
  8181. outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
  8182. outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
  8183. outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
  8184. }
  8185. } else {
  8186. outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
  8187. outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
  8188. }
  8189. outs() << " nsects " << nsects << "\n";
  8190. if (verbose) {
  8191. outs() << " flags";
  8192. if (flags == 0)
  8193. outs() << " (none)\n";
  8194. else {
  8195. if (flags & MachO::SG_HIGHVM) {
  8196. outs() << " HIGHVM";
  8197. flags &= ~MachO::SG_HIGHVM;
  8198. }
  8199. if (flags & MachO::SG_FVMLIB) {
  8200. outs() << " FVMLIB";
  8201. flags &= ~MachO::SG_FVMLIB;
  8202. }
  8203. if (flags & MachO::SG_NORELOC) {
  8204. outs() << " NORELOC";
  8205. flags &= ~MachO::SG_NORELOC;
  8206. }
  8207. if (flags & MachO::SG_PROTECTED_VERSION_1) {
  8208. outs() << " PROTECTED_VERSION_1";
  8209. flags &= ~MachO::SG_PROTECTED_VERSION_1;
  8210. }
  8211. if (flags & MachO::SG_READ_ONLY) {
  8212. // Apple's otool prints the SG_ prefix for this flag, but not for the
  8213. // others.
  8214. outs() << " SG_READ_ONLY";
  8215. flags &= ~MachO::SG_READ_ONLY;
  8216. }
  8217. if (flags)
  8218. outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
  8219. else
  8220. outs() << "\n";
  8221. }
  8222. } else {
  8223. outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
  8224. }
  8225. }
  8226. static void PrintSection(const char *sectname, const char *segname,
  8227. uint64_t addr, uint64_t size, uint32_t offset,
  8228. uint32_t align, uint32_t reloff, uint32_t nreloc,
  8229. uint32_t flags, uint32_t reserved1, uint32_t reserved2,
  8230. uint32_t cmd, const char *sg_segname,
  8231. uint32_t filetype, uint32_t object_size,
  8232. bool verbose) {
  8233. outs() << "Section\n";
  8234. outs() << " sectname " << format("%.16s\n", sectname);
  8235. outs() << " segname " << format("%.16s", segname);
  8236. if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
  8237. outs() << " (does not match segment)\n";
  8238. else
  8239. outs() << "\n";
  8240. if (cmd == MachO::LC_SEGMENT_64) {
  8241. outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
  8242. outs() << " size " << format("0x%016" PRIx64, size);
  8243. } else {
  8244. outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
  8245. outs() << " size " << format("0x%08" PRIx64, size);
  8246. }
  8247. if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
  8248. outs() << " (past end of file)\n";
  8249. else
  8250. outs() << "\n";
  8251. outs() << " offset " << offset;
  8252. if (offset > object_size)
  8253. outs() << " (past end of file)\n";
  8254. else
  8255. outs() << "\n";
  8256. uint32_t align_shifted = 1 << align;
  8257. outs() << " align 2^" << align << " (" << align_shifted << ")\n";
  8258. outs() << " reloff " << reloff;
  8259. if (reloff > object_size)
  8260. outs() << " (past end of file)\n";
  8261. else
  8262. outs() << "\n";
  8263. outs() << " nreloc " << nreloc;
  8264. if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
  8265. outs() << " (past end of file)\n";
  8266. else
  8267. outs() << "\n";
  8268. uint32_t section_type = flags & MachO::SECTION_TYPE;
  8269. if (verbose) {
  8270. outs() << " type";
  8271. if (section_type == MachO::S_REGULAR)
  8272. outs() << " S_REGULAR\n";
  8273. else if (section_type == MachO::S_ZEROFILL)
  8274. outs() << " S_ZEROFILL\n";
  8275. else if (section_type == MachO::S_CSTRING_LITERALS)
  8276. outs() << " S_CSTRING_LITERALS\n";
  8277. else if (section_type == MachO::S_4BYTE_LITERALS)
  8278. outs() << " S_4BYTE_LITERALS\n";
  8279. else if (section_type == MachO::S_8BYTE_LITERALS)
  8280. outs() << " S_8BYTE_LITERALS\n";
  8281. else if (section_type == MachO::S_16BYTE_LITERALS)
  8282. outs() << " S_16BYTE_LITERALS\n";
  8283. else if (section_type == MachO::S_LITERAL_POINTERS)
  8284. outs() << " S_LITERAL_POINTERS\n";
  8285. else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
  8286. outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
  8287. else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
  8288. outs() << " S_LAZY_SYMBOL_POINTERS\n";
  8289. else if (section_type == MachO::S_SYMBOL_STUBS)
  8290. outs() << " S_SYMBOL_STUBS\n";
  8291. else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
  8292. outs() << " S_MOD_INIT_FUNC_POINTERS\n";
  8293. else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
  8294. outs() << " S_MOD_TERM_FUNC_POINTERS\n";
  8295. else if (section_type == MachO::S_COALESCED)
  8296. outs() << " S_COALESCED\n";
  8297. else if (section_type == MachO::S_INTERPOSING)
  8298. outs() << " S_INTERPOSING\n";
  8299. else if (section_type == MachO::S_DTRACE_DOF)
  8300. outs() << " S_DTRACE_DOF\n";
  8301. else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
  8302. outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
  8303. else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
  8304. outs() << " S_THREAD_LOCAL_REGULAR\n";
  8305. else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
  8306. outs() << " S_THREAD_LOCAL_ZEROFILL\n";
  8307. else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
  8308. outs() << " S_THREAD_LOCAL_VARIABLES\n";
  8309. else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
  8310. outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
  8311. else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
  8312. outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
  8313. else if (section_type == MachO::S_INIT_FUNC_OFFSETS)
  8314. outs() << " S_INIT_FUNC_OFFSETS\n";
  8315. else
  8316. outs() << format("0x%08" PRIx32, section_type) << "\n";
  8317. outs() << "attributes";
  8318. uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
  8319. if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
  8320. outs() << " PURE_INSTRUCTIONS";
  8321. if (section_attributes & MachO::S_ATTR_NO_TOC)
  8322. outs() << " NO_TOC";
  8323. if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
  8324. outs() << " STRIP_STATIC_SYMS";
  8325. if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
  8326. outs() << " NO_DEAD_STRIP";
  8327. if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
  8328. outs() << " LIVE_SUPPORT";
  8329. if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
  8330. outs() << " SELF_MODIFYING_CODE";
  8331. if (section_attributes & MachO::S_ATTR_DEBUG)
  8332. outs() << " DEBUG";
  8333. if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
  8334. outs() << " SOME_INSTRUCTIONS";
  8335. if (section_attributes & MachO::S_ATTR_EXT_RELOC)
  8336. outs() << " EXT_RELOC";
  8337. if (section_attributes & MachO::S_ATTR_LOC_RELOC)
  8338. outs() << " LOC_RELOC";
  8339. if (section_attributes == 0)
  8340. outs() << " (none)";
  8341. outs() << "\n";
  8342. } else
  8343. outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
  8344. outs() << " reserved1 " << reserved1;
  8345. if (section_type == MachO::S_SYMBOL_STUBS ||
  8346. section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
  8347. section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
  8348. section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
  8349. section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
  8350. outs() << " (index into indirect symbol table)\n";
  8351. else
  8352. outs() << "\n";
  8353. outs() << " reserved2 " << reserved2;
  8354. if (section_type == MachO::S_SYMBOL_STUBS)
  8355. outs() << " (size of stubs)\n";
  8356. else
  8357. outs() << "\n";
  8358. }
  8359. static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
  8360. uint32_t object_size) {
  8361. outs() << " cmd LC_SYMTAB\n";
  8362. outs() << " cmdsize " << st.cmdsize;
  8363. if (st.cmdsize != sizeof(struct MachO::symtab_command))
  8364. outs() << " Incorrect size\n";
  8365. else
  8366. outs() << "\n";
  8367. outs() << " symoff " << st.symoff;
  8368. if (st.symoff > object_size)
  8369. outs() << " (past end of file)\n";
  8370. else
  8371. outs() << "\n";
  8372. outs() << " nsyms " << st.nsyms;
  8373. uint64_t big_size;
  8374. if (Is64Bit) {
  8375. big_size = st.nsyms;
  8376. big_size *= sizeof(struct MachO::nlist_64);
  8377. big_size += st.symoff;
  8378. if (big_size > object_size)
  8379. outs() << " (past end of file)\n";
  8380. else
  8381. outs() << "\n";
  8382. } else {
  8383. big_size = st.nsyms;
  8384. big_size *= sizeof(struct MachO::nlist);
  8385. big_size += st.symoff;
  8386. if (big_size > object_size)
  8387. outs() << " (past end of file)\n";
  8388. else
  8389. outs() << "\n";
  8390. }
  8391. outs() << " stroff " << st.stroff;
  8392. if (st.stroff > object_size)
  8393. outs() << " (past end of file)\n";
  8394. else
  8395. outs() << "\n";
  8396. outs() << " strsize " << st.strsize;
  8397. big_size = st.stroff;
  8398. big_size += st.strsize;
  8399. if (big_size > object_size)
  8400. outs() << " (past end of file)\n";
  8401. else
  8402. outs() << "\n";
  8403. }
  8404. static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
  8405. uint32_t nsyms, uint32_t object_size,
  8406. bool Is64Bit) {
  8407. outs() << " cmd LC_DYSYMTAB\n";
  8408. outs() << " cmdsize " << dyst.cmdsize;
  8409. if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
  8410. outs() << " Incorrect size\n";
  8411. else
  8412. outs() << "\n";
  8413. outs() << " ilocalsym " << dyst.ilocalsym;
  8414. if (dyst.ilocalsym > nsyms)
  8415. outs() << " (greater than the number of symbols)\n";
  8416. else
  8417. outs() << "\n";
  8418. outs() << " nlocalsym " << dyst.nlocalsym;
  8419. uint64_t big_size;
  8420. big_size = dyst.ilocalsym;
  8421. big_size += dyst.nlocalsym;
  8422. if (big_size > nsyms)
  8423. outs() << " (past the end of the symbol table)\n";
  8424. else
  8425. outs() << "\n";
  8426. outs() << " iextdefsym " << dyst.iextdefsym;
  8427. if (dyst.iextdefsym > nsyms)
  8428. outs() << " (greater than the number of symbols)\n";
  8429. else
  8430. outs() << "\n";
  8431. outs() << " nextdefsym " << dyst.nextdefsym;
  8432. big_size = dyst.iextdefsym;
  8433. big_size += dyst.nextdefsym;
  8434. if (big_size > nsyms)
  8435. outs() << " (past the end of the symbol table)\n";
  8436. else
  8437. outs() << "\n";
  8438. outs() << " iundefsym " << dyst.iundefsym;
  8439. if (dyst.iundefsym > nsyms)
  8440. outs() << " (greater than the number of symbols)\n";
  8441. else
  8442. outs() << "\n";
  8443. outs() << " nundefsym " << dyst.nundefsym;
  8444. big_size = dyst.iundefsym;
  8445. big_size += dyst.nundefsym;
  8446. if (big_size > nsyms)
  8447. outs() << " (past the end of the symbol table)\n";
  8448. else
  8449. outs() << "\n";
  8450. outs() << " tocoff " << dyst.tocoff;
  8451. if (dyst.tocoff > object_size)
  8452. outs() << " (past end of file)\n";
  8453. else
  8454. outs() << "\n";
  8455. outs() << " ntoc " << dyst.ntoc;
  8456. big_size = dyst.ntoc;
  8457. big_size *= sizeof(struct MachO::dylib_table_of_contents);
  8458. big_size += dyst.tocoff;
  8459. if (big_size > object_size)
  8460. outs() << " (past end of file)\n";
  8461. else
  8462. outs() << "\n";
  8463. outs() << " modtaboff " << dyst.modtaboff;
  8464. if (dyst.modtaboff > object_size)
  8465. outs() << " (past end of file)\n";
  8466. else
  8467. outs() << "\n";
  8468. outs() << " nmodtab " << dyst.nmodtab;
  8469. uint64_t modtabend;
  8470. if (Is64Bit) {
  8471. modtabend = dyst.nmodtab;
  8472. modtabend *= sizeof(struct MachO::dylib_module_64);
  8473. modtabend += dyst.modtaboff;
  8474. } else {
  8475. modtabend = dyst.nmodtab;
  8476. modtabend *= sizeof(struct MachO::dylib_module);
  8477. modtabend += dyst.modtaboff;
  8478. }
  8479. if (modtabend > object_size)
  8480. outs() << " (past end of file)\n";
  8481. else
  8482. outs() << "\n";
  8483. outs() << " extrefsymoff " << dyst.extrefsymoff;
  8484. if (dyst.extrefsymoff > object_size)
  8485. outs() << " (past end of file)\n";
  8486. else
  8487. outs() << "\n";
  8488. outs() << " nextrefsyms " << dyst.nextrefsyms;
  8489. big_size = dyst.nextrefsyms;
  8490. big_size *= sizeof(struct MachO::dylib_reference);
  8491. big_size += dyst.extrefsymoff;
  8492. if (big_size > object_size)
  8493. outs() << " (past end of file)\n";
  8494. else
  8495. outs() << "\n";
  8496. outs() << " indirectsymoff " << dyst.indirectsymoff;
  8497. if (dyst.indirectsymoff > object_size)
  8498. outs() << " (past end of file)\n";
  8499. else
  8500. outs() << "\n";
  8501. outs() << " nindirectsyms " << dyst.nindirectsyms;
  8502. big_size = dyst.nindirectsyms;
  8503. big_size *= sizeof(uint32_t);
  8504. big_size += dyst.indirectsymoff;
  8505. if (big_size > object_size)
  8506. outs() << " (past end of file)\n";
  8507. else
  8508. outs() << "\n";
  8509. outs() << " extreloff " << dyst.extreloff;
  8510. if (dyst.extreloff > object_size)
  8511. outs() << " (past end of file)\n";
  8512. else
  8513. outs() << "\n";
  8514. outs() << " nextrel " << dyst.nextrel;
  8515. big_size = dyst.nextrel;
  8516. big_size *= sizeof(struct MachO::relocation_info);
  8517. big_size += dyst.extreloff;
  8518. if (big_size > object_size)
  8519. outs() << " (past end of file)\n";
  8520. else
  8521. outs() << "\n";
  8522. outs() << " locreloff " << dyst.locreloff;
  8523. if (dyst.locreloff > object_size)
  8524. outs() << " (past end of file)\n";
  8525. else
  8526. outs() << "\n";
  8527. outs() << " nlocrel " << dyst.nlocrel;
  8528. big_size = dyst.nlocrel;
  8529. big_size *= sizeof(struct MachO::relocation_info);
  8530. big_size += dyst.locreloff;
  8531. if (big_size > object_size)
  8532. outs() << " (past end of file)\n";
  8533. else
  8534. outs() << "\n";
  8535. }
  8536. static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
  8537. uint32_t object_size) {
  8538. if (dc.cmd == MachO::LC_DYLD_INFO)
  8539. outs() << " cmd LC_DYLD_INFO\n";
  8540. else
  8541. outs() << " cmd LC_DYLD_INFO_ONLY\n";
  8542. outs() << " cmdsize " << dc.cmdsize;
  8543. if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
  8544. outs() << " Incorrect size\n";
  8545. else
  8546. outs() << "\n";
  8547. outs() << " rebase_off " << dc.rebase_off;
  8548. if (dc.rebase_off > object_size)
  8549. outs() << " (past end of file)\n";
  8550. else
  8551. outs() << "\n";
  8552. outs() << " rebase_size " << dc.rebase_size;
  8553. uint64_t big_size;
  8554. big_size = dc.rebase_off;
  8555. big_size += dc.rebase_size;
  8556. if (big_size > object_size)
  8557. outs() << " (past end of file)\n";
  8558. else
  8559. outs() << "\n";
  8560. outs() << " bind_off " << dc.bind_off;
  8561. if (dc.bind_off > object_size)
  8562. outs() << " (past end of file)\n";
  8563. else
  8564. outs() << "\n";
  8565. outs() << " bind_size " << dc.bind_size;
  8566. big_size = dc.bind_off;
  8567. big_size += dc.bind_size;
  8568. if (big_size > object_size)
  8569. outs() << " (past end of file)\n";
  8570. else
  8571. outs() << "\n";
  8572. outs() << " weak_bind_off " << dc.weak_bind_off;
  8573. if (dc.weak_bind_off > object_size)
  8574. outs() << " (past end of file)\n";
  8575. else
  8576. outs() << "\n";
  8577. outs() << " weak_bind_size " << dc.weak_bind_size;
  8578. big_size = dc.weak_bind_off;
  8579. big_size += dc.weak_bind_size;
  8580. if (big_size > object_size)
  8581. outs() << " (past end of file)\n";
  8582. else
  8583. outs() << "\n";
  8584. outs() << " lazy_bind_off " << dc.lazy_bind_off;
  8585. if (dc.lazy_bind_off > object_size)
  8586. outs() << " (past end of file)\n";
  8587. else
  8588. outs() << "\n";
  8589. outs() << " lazy_bind_size " << dc.lazy_bind_size;
  8590. big_size = dc.lazy_bind_off;
  8591. big_size += dc.lazy_bind_size;
  8592. if (big_size > object_size)
  8593. outs() << " (past end of file)\n";
  8594. else
  8595. outs() << "\n";
  8596. outs() << " export_off " << dc.export_off;
  8597. if (dc.export_off > object_size)
  8598. outs() << " (past end of file)\n";
  8599. else
  8600. outs() << "\n";
  8601. outs() << " export_size " << dc.export_size;
  8602. big_size = dc.export_off;
  8603. big_size += dc.export_size;
  8604. if (big_size > object_size)
  8605. outs() << " (past end of file)\n";
  8606. else
  8607. outs() << "\n";
  8608. }
  8609. static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
  8610. const char *Ptr) {
  8611. if (dyld.cmd == MachO::LC_ID_DYLINKER)
  8612. outs() << " cmd LC_ID_DYLINKER\n";
  8613. else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
  8614. outs() << " cmd LC_LOAD_DYLINKER\n";
  8615. else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
  8616. outs() << " cmd LC_DYLD_ENVIRONMENT\n";
  8617. else
  8618. outs() << " cmd ?(" << dyld.cmd << ")\n";
  8619. outs() << " cmdsize " << dyld.cmdsize;
  8620. if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
  8621. outs() << " Incorrect size\n";
  8622. else
  8623. outs() << "\n";
  8624. if (dyld.name >= dyld.cmdsize)
  8625. outs() << " name ?(bad offset " << dyld.name << ")\n";
  8626. else {
  8627. const char *P = (const char *)(Ptr) + dyld.name;
  8628. outs() << " name " << P << " (offset " << dyld.name << ")\n";
  8629. }
  8630. }
  8631. static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
  8632. outs() << " cmd LC_UUID\n";
  8633. outs() << " cmdsize " << uuid.cmdsize;
  8634. if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
  8635. outs() << " Incorrect size\n";
  8636. else
  8637. outs() << "\n";
  8638. outs() << " uuid ";
  8639. for (int i = 0; i < 16; ++i) {
  8640. outs() << format("%02" PRIX32, uuid.uuid[i]);
  8641. if (i == 3 || i == 5 || i == 7 || i == 9)
  8642. outs() << "-";
  8643. }
  8644. outs() << "\n";
  8645. }
  8646. static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
  8647. outs() << " cmd LC_RPATH\n";
  8648. outs() << " cmdsize " << rpath.cmdsize;
  8649. if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
  8650. outs() << " Incorrect size\n";
  8651. else
  8652. outs() << "\n";
  8653. if (rpath.path >= rpath.cmdsize)
  8654. outs() << " path ?(bad offset " << rpath.path << ")\n";
  8655. else {
  8656. const char *P = (const char *)(Ptr) + rpath.path;
  8657. outs() << " path " << P << " (offset " << rpath.path << ")\n";
  8658. }
  8659. }
  8660. static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
  8661. StringRef LoadCmdName;
  8662. switch (vd.cmd) {
  8663. case MachO::LC_VERSION_MIN_MACOSX:
  8664. LoadCmdName = "LC_VERSION_MIN_MACOSX";
  8665. break;
  8666. case MachO::LC_VERSION_MIN_IPHONEOS:
  8667. LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
  8668. break;
  8669. case MachO::LC_VERSION_MIN_TVOS:
  8670. LoadCmdName = "LC_VERSION_MIN_TVOS";
  8671. break;
  8672. case MachO::LC_VERSION_MIN_WATCHOS:
  8673. LoadCmdName = "LC_VERSION_MIN_WATCHOS";
  8674. break;
  8675. default:
  8676. llvm_unreachable("Unknown version min load command");
  8677. }
  8678. outs() << " cmd " << LoadCmdName << '\n';
  8679. outs() << " cmdsize " << vd.cmdsize;
  8680. if (vd.cmdsize != sizeof(struct MachO::version_min_command))
  8681. outs() << " Incorrect size\n";
  8682. else
  8683. outs() << "\n";
  8684. outs() << " version "
  8685. << MachOObjectFile::getVersionMinMajor(vd, false) << "."
  8686. << MachOObjectFile::getVersionMinMinor(vd, false);
  8687. uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
  8688. if (Update != 0)
  8689. outs() << "." << Update;
  8690. outs() << "\n";
  8691. if (vd.sdk == 0)
  8692. outs() << " sdk n/a";
  8693. else {
  8694. outs() << " sdk "
  8695. << MachOObjectFile::getVersionMinMajor(vd, true) << "."
  8696. << MachOObjectFile::getVersionMinMinor(vd, true);
  8697. }
  8698. Update = MachOObjectFile::getVersionMinUpdate(vd, true);
  8699. if (Update != 0)
  8700. outs() << "." << Update;
  8701. outs() << "\n";
  8702. }
  8703. static void PrintNoteLoadCommand(MachO::note_command Nt) {
  8704. outs() << " cmd LC_NOTE\n";
  8705. outs() << " cmdsize " << Nt.cmdsize;
  8706. if (Nt.cmdsize != sizeof(struct MachO::note_command))
  8707. outs() << " Incorrect size\n";
  8708. else
  8709. outs() << "\n";
  8710. const char *d = Nt.data_owner;
  8711. outs() << "data_owner " << format("%.16s\n", d);
  8712. outs() << " offset " << Nt.offset << "\n";
  8713. outs() << " size " << Nt.size << "\n";
  8714. }
  8715. static void PrintBuildToolVersion(MachO::build_tool_version bv, bool verbose) {
  8716. outs() << " tool ";
  8717. if (verbose)
  8718. outs() << MachOObjectFile::getBuildTool(bv.tool);
  8719. else
  8720. outs() << bv.tool;
  8721. outs() << "\n";
  8722. outs() << " version " << MachOObjectFile::getVersionString(bv.version)
  8723. << "\n";
  8724. }
  8725. static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
  8726. MachO::build_version_command bd,
  8727. bool verbose) {
  8728. outs() << " cmd LC_BUILD_VERSION\n";
  8729. outs() << " cmdsize " << bd.cmdsize;
  8730. if (bd.cmdsize !=
  8731. sizeof(struct MachO::build_version_command) +
  8732. bd.ntools * sizeof(struct MachO::build_tool_version))
  8733. outs() << " Incorrect size\n";
  8734. else
  8735. outs() << "\n";
  8736. outs() << " platform ";
  8737. if (verbose)
  8738. outs() << MachOObjectFile::getBuildPlatform(bd.platform);
  8739. else
  8740. outs() << bd.platform;
  8741. outs() << "\n";
  8742. if (bd.sdk)
  8743. outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
  8744. << "\n";
  8745. else
  8746. outs() << " sdk n/a\n";
  8747. outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
  8748. << "\n";
  8749. outs() << " ntools " << bd.ntools << "\n";
  8750. for (unsigned i = 0; i < bd.ntools; ++i) {
  8751. MachO::build_tool_version bv = obj->getBuildToolVersion(i);
  8752. PrintBuildToolVersion(bv, verbose);
  8753. }
  8754. }
  8755. static void PrintSourceVersionCommand(MachO::source_version_command sd) {
  8756. outs() << " cmd LC_SOURCE_VERSION\n";
  8757. outs() << " cmdsize " << sd.cmdsize;
  8758. if (sd.cmdsize != sizeof(struct MachO::source_version_command))
  8759. outs() << " Incorrect size\n";
  8760. else
  8761. outs() << "\n";
  8762. uint64_t a = (sd.version >> 40) & 0xffffff;
  8763. uint64_t b = (sd.version >> 30) & 0x3ff;
  8764. uint64_t c = (sd.version >> 20) & 0x3ff;
  8765. uint64_t d = (sd.version >> 10) & 0x3ff;
  8766. uint64_t e = sd.version & 0x3ff;
  8767. outs() << " version " << a << "." << b;
  8768. if (e != 0)
  8769. outs() << "." << c << "." << d << "." << e;
  8770. else if (d != 0)
  8771. outs() << "." << c << "." << d;
  8772. else if (c != 0)
  8773. outs() << "." << c;
  8774. outs() << "\n";
  8775. }
  8776. static void PrintEntryPointCommand(MachO::entry_point_command ep) {
  8777. outs() << " cmd LC_MAIN\n";
  8778. outs() << " cmdsize " << ep.cmdsize;
  8779. if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
  8780. outs() << " Incorrect size\n";
  8781. else
  8782. outs() << "\n";
  8783. outs() << " entryoff " << ep.entryoff << "\n";
  8784. outs() << " stacksize " << ep.stacksize << "\n";
  8785. }
  8786. static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
  8787. uint32_t object_size) {
  8788. outs() << " cmd LC_ENCRYPTION_INFO\n";
  8789. outs() << " cmdsize " << ec.cmdsize;
  8790. if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
  8791. outs() << " Incorrect size\n";
  8792. else
  8793. outs() << "\n";
  8794. outs() << " cryptoff " << ec.cryptoff;
  8795. if (ec.cryptoff > object_size)
  8796. outs() << " (past end of file)\n";
  8797. else
  8798. outs() << "\n";
  8799. outs() << " cryptsize " << ec.cryptsize;
  8800. if (ec.cryptsize > object_size)
  8801. outs() << " (past end of file)\n";
  8802. else
  8803. outs() << "\n";
  8804. outs() << " cryptid " << ec.cryptid << "\n";
  8805. }
  8806. static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
  8807. uint32_t object_size) {
  8808. outs() << " cmd LC_ENCRYPTION_INFO_64\n";
  8809. outs() << " cmdsize " << ec.cmdsize;
  8810. if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
  8811. outs() << " Incorrect size\n";
  8812. else
  8813. outs() << "\n";
  8814. outs() << " cryptoff " << ec.cryptoff;
  8815. if (ec.cryptoff > object_size)
  8816. outs() << " (past end of file)\n";
  8817. else
  8818. outs() << "\n";
  8819. outs() << " cryptsize " << ec.cryptsize;
  8820. if (ec.cryptsize > object_size)
  8821. outs() << " (past end of file)\n";
  8822. else
  8823. outs() << "\n";
  8824. outs() << " cryptid " << ec.cryptid << "\n";
  8825. outs() << " pad " << ec.pad << "\n";
  8826. }
  8827. static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
  8828. const char *Ptr) {
  8829. outs() << " cmd LC_LINKER_OPTION\n";
  8830. outs() << " cmdsize " << lo.cmdsize;
  8831. if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
  8832. outs() << " Incorrect size\n";
  8833. else
  8834. outs() << "\n";
  8835. outs() << " count " << lo.count << "\n";
  8836. const char *string = Ptr + sizeof(struct MachO::linker_option_command);
  8837. uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
  8838. uint32_t i = 0;
  8839. while (left > 0) {
  8840. while (*string == '\0' && left > 0) {
  8841. string++;
  8842. left--;
  8843. }
  8844. if (left > 0) {
  8845. i++;
  8846. outs() << " string #" << i << " " << format("%.*s\n", left, string);
  8847. uint32_t NullPos = StringRef(string, left).find('\0');
  8848. uint32_t len = std::min(NullPos, left) + 1;
  8849. string += len;
  8850. left -= len;
  8851. }
  8852. }
  8853. if (lo.count != i)
  8854. outs() << " count " << lo.count << " does not match number of strings "
  8855. << i << "\n";
  8856. }
  8857. static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
  8858. const char *Ptr) {
  8859. outs() << " cmd LC_SUB_FRAMEWORK\n";
  8860. outs() << " cmdsize " << sub.cmdsize;
  8861. if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
  8862. outs() << " Incorrect size\n";
  8863. else
  8864. outs() << "\n";
  8865. if (sub.umbrella < sub.cmdsize) {
  8866. const char *P = Ptr + sub.umbrella;
  8867. outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
  8868. } else {
  8869. outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
  8870. }
  8871. }
  8872. static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
  8873. const char *Ptr) {
  8874. outs() << " cmd LC_SUB_UMBRELLA\n";
  8875. outs() << " cmdsize " << sub.cmdsize;
  8876. if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
  8877. outs() << " Incorrect size\n";
  8878. else
  8879. outs() << "\n";
  8880. if (sub.sub_umbrella < sub.cmdsize) {
  8881. const char *P = Ptr + sub.sub_umbrella;
  8882. outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
  8883. } else {
  8884. outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
  8885. }
  8886. }
  8887. static void PrintSubLibraryCommand(MachO::sub_library_command sub,
  8888. const char *Ptr) {
  8889. outs() << " cmd LC_SUB_LIBRARY\n";
  8890. outs() << " cmdsize " << sub.cmdsize;
  8891. if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
  8892. outs() << " Incorrect size\n";
  8893. else
  8894. outs() << "\n";
  8895. if (sub.sub_library < sub.cmdsize) {
  8896. const char *P = Ptr + sub.sub_library;
  8897. outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
  8898. } else {
  8899. outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
  8900. }
  8901. }
  8902. static void PrintSubClientCommand(MachO::sub_client_command sub,
  8903. const char *Ptr) {
  8904. outs() << " cmd LC_SUB_CLIENT\n";
  8905. outs() << " cmdsize " << sub.cmdsize;
  8906. if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
  8907. outs() << " Incorrect size\n";
  8908. else
  8909. outs() << "\n";
  8910. if (sub.client < sub.cmdsize) {
  8911. const char *P = Ptr + sub.client;
  8912. outs() << " client " << P << " (offset " << sub.client << ")\n";
  8913. } else {
  8914. outs() << " client ?(bad offset " << sub.client << ")\n";
  8915. }
  8916. }
  8917. static void PrintRoutinesCommand(MachO::routines_command r) {
  8918. outs() << " cmd LC_ROUTINES\n";
  8919. outs() << " cmdsize " << r.cmdsize;
  8920. if (r.cmdsize != sizeof(struct MachO::routines_command))
  8921. outs() << " Incorrect size\n";
  8922. else
  8923. outs() << "\n";
  8924. outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
  8925. outs() << " init_module " << r.init_module << "\n";
  8926. outs() << " reserved1 " << r.reserved1 << "\n";
  8927. outs() << " reserved2 " << r.reserved2 << "\n";
  8928. outs() << " reserved3 " << r.reserved3 << "\n";
  8929. outs() << " reserved4 " << r.reserved4 << "\n";
  8930. outs() << " reserved5 " << r.reserved5 << "\n";
  8931. outs() << " reserved6 " << r.reserved6 << "\n";
  8932. }
  8933. static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
  8934. outs() << " cmd LC_ROUTINES_64\n";
  8935. outs() << " cmdsize " << r.cmdsize;
  8936. if (r.cmdsize != sizeof(struct MachO::routines_command_64))
  8937. outs() << " Incorrect size\n";
  8938. else
  8939. outs() << "\n";
  8940. outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
  8941. outs() << " init_module " << r.init_module << "\n";
  8942. outs() << " reserved1 " << r.reserved1 << "\n";
  8943. outs() << " reserved2 " << r.reserved2 << "\n";
  8944. outs() << " reserved3 " << r.reserved3 << "\n";
  8945. outs() << " reserved4 " << r.reserved4 << "\n";
  8946. outs() << " reserved5 " << r.reserved5 << "\n";
  8947. outs() << " reserved6 " << r.reserved6 << "\n";
  8948. }
  8949. static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
  8950. outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
  8951. outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
  8952. outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
  8953. outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
  8954. outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
  8955. outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
  8956. outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
  8957. outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
  8958. outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
  8959. outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
  8960. outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
  8961. outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
  8962. outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
  8963. outs() << " es " << format("0x%08" PRIx32, cpu32.es);
  8964. outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
  8965. outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
  8966. }
  8967. static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
  8968. outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
  8969. outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
  8970. outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
  8971. outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
  8972. outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
  8973. outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
  8974. outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
  8975. outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
  8976. outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
  8977. outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
  8978. outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
  8979. outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
  8980. outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
  8981. outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
  8982. outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
  8983. outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
  8984. outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
  8985. outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
  8986. outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
  8987. outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
  8988. outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
  8989. }
  8990. static void Print_mmst_reg(MachO::mmst_reg_t &r) {
  8991. uint32_t f;
  8992. outs() << "\t mmst_reg ";
  8993. for (f = 0; f < 10; f++)
  8994. outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
  8995. outs() << "\n";
  8996. outs() << "\t mmst_rsrv ";
  8997. for (f = 0; f < 6; f++)
  8998. outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
  8999. outs() << "\n";
  9000. }
  9001. static void Print_xmm_reg(MachO::xmm_reg_t &r) {
  9002. uint32_t f;
  9003. outs() << "\t xmm_reg ";
  9004. for (f = 0; f < 16; f++)
  9005. outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
  9006. outs() << "\n";
  9007. }
  9008. static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
  9009. outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
  9010. outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
  9011. outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
  9012. outs() << " denorm " << fpu.fpu_fcw.denorm;
  9013. outs() << " zdiv " << fpu.fpu_fcw.zdiv;
  9014. outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
  9015. outs() << " undfl " << fpu.fpu_fcw.undfl;
  9016. outs() << " precis " << fpu.fpu_fcw.precis << "\n";
  9017. outs() << "\t\t pc ";
  9018. if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
  9019. outs() << "FP_PREC_24B ";
  9020. else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
  9021. outs() << "FP_PREC_53B ";
  9022. else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
  9023. outs() << "FP_PREC_64B ";
  9024. else
  9025. outs() << fpu.fpu_fcw.pc << " ";
  9026. outs() << "rc ";
  9027. if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
  9028. outs() << "FP_RND_NEAR ";
  9029. else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
  9030. outs() << "FP_RND_DOWN ";
  9031. else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
  9032. outs() << "FP_RND_UP ";
  9033. else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
  9034. outs() << "FP_CHOP ";
  9035. outs() << "\n";
  9036. outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
  9037. outs() << " denorm " << fpu.fpu_fsw.denorm;
  9038. outs() << " zdiv " << fpu.fpu_fsw.zdiv;
  9039. outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
  9040. outs() << " undfl " << fpu.fpu_fsw.undfl;
  9041. outs() << " precis " << fpu.fpu_fsw.precis;
  9042. outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
  9043. outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
  9044. outs() << " c0 " << fpu.fpu_fsw.c0;
  9045. outs() << " c1 " << fpu.fpu_fsw.c1;
  9046. outs() << " c2 " << fpu.fpu_fsw.c2;
  9047. outs() << " tos " << fpu.fpu_fsw.tos;
  9048. outs() << " c3 " << fpu.fpu_fsw.c3;
  9049. outs() << " busy " << fpu.fpu_fsw.busy << "\n";
  9050. outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
  9051. outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
  9052. outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
  9053. outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
  9054. outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
  9055. outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
  9056. outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
  9057. outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
  9058. outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
  9059. outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
  9060. outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
  9061. outs() << "\n";
  9062. outs() << "\t fpu_stmm0:\n";
  9063. Print_mmst_reg(fpu.fpu_stmm0);
  9064. outs() << "\t fpu_stmm1:\n";
  9065. Print_mmst_reg(fpu.fpu_stmm1);
  9066. outs() << "\t fpu_stmm2:\n";
  9067. Print_mmst_reg(fpu.fpu_stmm2);
  9068. outs() << "\t fpu_stmm3:\n";
  9069. Print_mmst_reg(fpu.fpu_stmm3);
  9070. outs() << "\t fpu_stmm4:\n";
  9071. Print_mmst_reg(fpu.fpu_stmm4);
  9072. outs() << "\t fpu_stmm5:\n";
  9073. Print_mmst_reg(fpu.fpu_stmm5);
  9074. outs() << "\t fpu_stmm6:\n";
  9075. Print_mmst_reg(fpu.fpu_stmm6);
  9076. outs() << "\t fpu_stmm7:\n";
  9077. Print_mmst_reg(fpu.fpu_stmm7);
  9078. outs() << "\t fpu_xmm0:\n";
  9079. Print_xmm_reg(fpu.fpu_xmm0);
  9080. outs() << "\t fpu_xmm1:\n";
  9081. Print_xmm_reg(fpu.fpu_xmm1);
  9082. outs() << "\t fpu_xmm2:\n";
  9083. Print_xmm_reg(fpu.fpu_xmm2);
  9084. outs() << "\t fpu_xmm3:\n";
  9085. Print_xmm_reg(fpu.fpu_xmm3);
  9086. outs() << "\t fpu_xmm4:\n";
  9087. Print_xmm_reg(fpu.fpu_xmm4);
  9088. outs() << "\t fpu_xmm5:\n";
  9089. Print_xmm_reg(fpu.fpu_xmm5);
  9090. outs() << "\t fpu_xmm6:\n";
  9091. Print_xmm_reg(fpu.fpu_xmm6);
  9092. outs() << "\t fpu_xmm7:\n";
  9093. Print_xmm_reg(fpu.fpu_xmm7);
  9094. outs() << "\t fpu_xmm8:\n";
  9095. Print_xmm_reg(fpu.fpu_xmm8);
  9096. outs() << "\t fpu_xmm9:\n";
  9097. Print_xmm_reg(fpu.fpu_xmm9);
  9098. outs() << "\t fpu_xmm10:\n";
  9099. Print_xmm_reg(fpu.fpu_xmm10);
  9100. outs() << "\t fpu_xmm11:\n";
  9101. Print_xmm_reg(fpu.fpu_xmm11);
  9102. outs() << "\t fpu_xmm12:\n";
  9103. Print_xmm_reg(fpu.fpu_xmm12);
  9104. outs() << "\t fpu_xmm13:\n";
  9105. Print_xmm_reg(fpu.fpu_xmm13);
  9106. outs() << "\t fpu_xmm14:\n";
  9107. Print_xmm_reg(fpu.fpu_xmm14);
  9108. outs() << "\t fpu_xmm15:\n";
  9109. Print_xmm_reg(fpu.fpu_xmm15);
  9110. outs() << "\t fpu_rsrv4:\n";
  9111. for (uint32_t f = 0; f < 6; f++) {
  9112. outs() << "\t ";
  9113. for (uint32_t g = 0; g < 16; g++)
  9114. outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
  9115. outs() << "\n";
  9116. }
  9117. outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
  9118. outs() << "\n";
  9119. }
  9120. static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
  9121. outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
  9122. outs() << " err " << format("0x%08" PRIx32, exc64.err);
  9123. outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
  9124. }
  9125. static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
  9126. outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
  9127. outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
  9128. outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
  9129. outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
  9130. outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
  9131. outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
  9132. outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
  9133. outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
  9134. outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
  9135. outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
  9136. outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
  9137. outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
  9138. outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
  9139. outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
  9140. outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
  9141. outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
  9142. outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
  9143. }
  9144. static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
  9145. outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
  9146. outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
  9147. outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
  9148. outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
  9149. outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
  9150. outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
  9151. outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
  9152. outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
  9153. outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
  9154. outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
  9155. outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
  9156. outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
  9157. outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
  9158. outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
  9159. outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
  9160. outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
  9161. outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
  9162. outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
  9163. outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
  9164. outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
  9165. outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
  9166. outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
  9167. outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
  9168. outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
  9169. outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
  9170. outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
  9171. outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
  9172. outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
  9173. outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
  9174. outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
  9175. outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
  9176. outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
  9177. outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
  9178. outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
  9179. }
  9180. static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
  9181. bool isLittleEndian, uint32_t cputype) {
  9182. if (t.cmd == MachO::LC_THREAD)
  9183. outs() << " cmd LC_THREAD\n";
  9184. else if (t.cmd == MachO::LC_UNIXTHREAD)
  9185. outs() << " cmd LC_UNIXTHREAD\n";
  9186. else
  9187. outs() << " cmd " << t.cmd << " (unknown)\n";
  9188. outs() << " cmdsize " << t.cmdsize;
  9189. if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
  9190. outs() << " Incorrect size\n";
  9191. else
  9192. outs() << "\n";
  9193. const char *begin = Ptr + sizeof(struct MachO::thread_command);
  9194. const char *end = Ptr + t.cmdsize;
  9195. uint32_t flavor, count, left;
  9196. if (cputype == MachO::CPU_TYPE_I386) {
  9197. while (begin < end) {
  9198. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9199. memcpy((char *)&flavor, begin, sizeof(uint32_t));
  9200. begin += sizeof(uint32_t);
  9201. } else {
  9202. flavor = 0;
  9203. begin = end;
  9204. }
  9205. if (isLittleEndian != sys::IsLittleEndianHost)
  9206. sys::swapByteOrder(flavor);
  9207. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9208. memcpy((char *)&count, begin, sizeof(uint32_t));
  9209. begin += sizeof(uint32_t);
  9210. } else {
  9211. count = 0;
  9212. begin = end;
  9213. }
  9214. if (isLittleEndian != sys::IsLittleEndianHost)
  9215. sys::swapByteOrder(count);
  9216. if (flavor == MachO::x86_THREAD_STATE32) {
  9217. outs() << " flavor i386_THREAD_STATE\n";
  9218. if (count == MachO::x86_THREAD_STATE32_COUNT)
  9219. outs() << " count i386_THREAD_STATE_COUNT\n";
  9220. else
  9221. outs() << " count " << count
  9222. << " (not x86_THREAD_STATE32_COUNT)\n";
  9223. MachO::x86_thread_state32_t cpu32;
  9224. left = end - begin;
  9225. if (left >= sizeof(MachO::x86_thread_state32_t)) {
  9226. memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
  9227. begin += sizeof(MachO::x86_thread_state32_t);
  9228. } else {
  9229. memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
  9230. memcpy(&cpu32, begin, left);
  9231. begin += left;
  9232. }
  9233. if (isLittleEndian != sys::IsLittleEndianHost)
  9234. swapStruct(cpu32);
  9235. Print_x86_thread_state32_t(cpu32);
  9236. } else if (flavor == MachO::x86_THREAD_STATE) {
  9237. outs() << " flavor x86_THREAD_STATE\n";
  9238. if (count == MachO::x86_THREAD_STATE_COUNT)
  9239. outs() << " count x86_THREAD_STATE_COUNT\n";
  9240. else
  9241. outs() << " count " << count
  9242. << " (not x86_THREAD_STATE_COUNT)\n";
  9243. struct MachO::x86_thread_state_t ts;
  9244. left = end - begin;
  9245. if (left >= sizeof(MachO::x86_thread_state_t)) {
  9246. memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
  9247. begin += sizeof(MachO::x86_thread_state_t);
  9248. } else {
  9249. memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
  9250. memcpy(&ts, begin, left);
  9251. begin += left;
  9252. }
  9253. if (isLittleEndian != sys::IsLittleEndianHost)
  9254. swapStruct(ts);
  9255. if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
  9256. outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
  9257. if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
  9258. outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
  9259. else
  9260. outs() << "tsh.count " << ts.tsh.count
  9261. << " (not x86_THREAD_STATE32_COUNT\n";
  9262. Print_x86_thread_state32_t(ts.uts.ts32);
  9263. } else {
  9264. outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
  9265. << ts.tsh.count << "\n";
  9266. }
  9267. } else {
  9268. outs() << " flavor " << flavor << " (unknown)\n";
  9269. outs() << " count " << count << "\n";
  9270. outs() << " state (unknown)\n";
  9271. begin += count * sizeof(uint32_t);
  9272. }
  9273. }
  9274. } else if (cputype == MachO::CPU_TYPE_X86_64) {
  9275. while (begin < end) {
  9276. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9277. memcpy((char *)&flavor, begin, sizeof(uint32_t));
  9278. begin += sizeof(uint32_t);
  9279. } else {
  9280. flavor = 0;
  9281. begin = end;
  9282. }
  9283. if (isLittleEndian != sys::IsLittleEndianHost)
  9284. sys::swapByteOrder(flavor);
  9285. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9286. memcpy((char *)&count, begin, sizeof(uint32_t));
  9287. begin += sizeof(uint32_t);
  9288. } else {
  9289. count = 0;
  9290. begin = end;
  9291. }
  9292. if (isLittleEndian != sys::IsLittleEndianHost)
  9293. sys::swapByteOrder(count);
  9294. if (flavor == MachO::x86_THREAD_STATE64) {
  9295. outs() << " flavor x86_THREAD_STATE64\n";
  9296. if (count == MachO::x86_THREAD_STATE64_COUNT)
  9297. outs() << " count x86_THREAD_STATE64_COUNT\n";
  9298. else
  9299. outs() << " count " << count
  9300. << " (not x86_THREAD_STATE64_COUNT)\n";
  9301. MachO::x86_thread_state64_t cpu64;
  9302. left = end - begin;
  9303. if (left >= sizeof(MachO::x86_thread_state64_t)) {
  9304. memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
  9305. begin += sizeof(MachO::x86_thread_state64_t);
  9306. } else {
  9307. memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
  9308. memcpy(&cpu64, begin, left);
  9309. begin += left;
  9310. }
  9311. if (isLittleEndian != sys::IsLittleEndianHost)
  9312. swapStruct(cpu64);
  9313. Print_x86_thread_state64_t(cpu64);
  9314. } else if (flavor == MachO::x86_THREAD_STATE) {
  9315. outs() << " flavor x86_THREAD_STATE\n";
  9316. if (count == MachO::x86_THREAD_STATE_COUNT)
  9317. outs() << " count x86_THREAD_STATE_COUNT\n";
  9318. else
  9319. outs() << " count " << count
  9320. << " (not x86_THREAD_STATE_COUNT)\n";
  9321. struct MachO::x86_thread_state_t ts;
  9322. left = end - begin;
  9323. if (left >= sizeof(MachO::x86_thread_state_t)) {
  9324. memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
  9325. begin += sizeof(MachO::x86_thread_state_t);
  9326. } else {
  9327. memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
  9328. memcpy(&ts, begin, left);
  9329. begin += left;
  9330. }
  9331. if (isLittleEndian != sys::IsLittleEndianHost)
  9332. swapStruct(ts);
  9333. if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
  9334. outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
  9335. if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
  9336. outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
  9337. else
  9338. outs() << "tsh.count " << ts.tsh.count
  9339. << " (not x86_THREAD_STATE64_COUNT\n";
  9340. Print_x86_thread_state64_t(ts.uts.ts64);
  9341. } else {
  9342. outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
  9343. << ts.tsh.count << "\n";
  9344. }
  9345. } else if (flavor == MachO::x86_FLOAT_STATE) {
  9346. outs() << " flavor x86_FLOAT_STATE\n";
  9347. if (count == MachO::x86_FLOAT_STATE_COUNT)
  9348. outs() << " count x86_FLOAT_STATE_COUNT\n";
  9349. else
  9350. outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
  9351. struct MachO::x86_float_state_t fs;
  9352. left = end - begin;
  9353. if (left >= sizeof(MachO::x86_float_state_t)) {
  9354. memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
  9355. begin += sizeof(MachO::x86_float_state_t);
  9356. } else {
  9357. memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
  9358. memcpy(&fs, begin, left);
  9359. begin += left;
  9360. }
  9361. if (isLittleEndian != sys::IsLittleEndianHost)
  9362. swapStruct(fs);
  9363. if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
  9364. outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
  9365. if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
  9366. outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
  9367. else
  9368. outs() << "fsh.count " << fs.fsh.count
  9369. << " (not x86_FLOAT_STATE64_COUNT\n";
  9370. Print_x86_float_state_t(fs.ufs.fs64);
  9371. } else {
  9372. outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
  9373. << fs.fsh.count << "\n";
  9374. }
  9375. } else if (flavor == MachO::x86_EXCEPTION_STATE) {
  9376. outs() << " flavor x86_EXCEPTION_STATE\n";
  9377. if (count == MachO::x86_EXCEPTION_STATE_COUNT)
  9378. outs() << " count x86_EXCEPTION_STATE_COUNT\n";
  9379. else
  9380. outs() << " count " << count
  9381. << " (not x86_EXCEPTION_STATE_COUNT)\n";
  9382. struct MachO::x86_exception_state_t es;
  9383. left = end - begin;
  9384. if (left >= sizeof(MachO::x86_exception_state_t)) {
  9385. memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
  9386. begin += sizeof(MachO::x86_exception_state_t);
  9387. } else {
  9388. memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
  9389. memcpy(&es, begin, left);
  9390. begin += left;
  9391. }
  9392. if (isLittleEndian != sys::IsLittleEndianHost)
  9393. swapStruct(es);
  9394. if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
  9395. outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
  9396. if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
  9397. outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
  9398. else
  9399. outs() << "\t esh.count " << es.esh.count
  9400. << " (not x86_EXCEPTION_STATE64_COUNT\n";
  9401. Print_x86_exception_state_t(es.ues.es64);
  9402. } else {
  9403. outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
  9404. << es.esh.count << "\n";
  9405. }
  9406. } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
  9407. outs() << " flavor x86_EXCEPTION_STATE64\n";
  9408. if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
  9409. outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
  9410. else
  9411. outs() << " count " << count
  9412. << " (not x86_EXCEPTION_STATE64_COUNT)\n";
  9413. struct MachO::x86_exception_state64_t es64;
  9414. left = end - begin;
  9415. if (left >= sizeof(MachO::x86_exception_state64_t)) {
  9416. memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
  9417. begin += sizeof(MachO::x86_exception_state64_t);
  9418. } else {
  9419. memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
  9420. memcpy(&es64, begin, left);
  9421. begin += left;
  9422. }
  9423. if (isLittleEndian != sys::IsLittleEndianHost)
  9424. swapStruct(es64);
  9425. Print_x86_exception_state_t(es64);
  9426. } else {
  9427. outs() << " flavor " << flavor << " (unknown)\n";
  9428. outs() << " count " << count << "\n";
  9429. outs() << " state (unknown)\n";
  9430. begin += count * sizeof(uint32_t);
  9431. }
  9432. }
  9433. } else if (cputype == MachO::CPU_TYPE_ARM) {
  9434. while (begin < end) {
  9435. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9436. memcpy((char *)&flavor, begin, sizeof(uint32_t));
  9437. begin += sizeof(uint32_t);
  9438. } else {
  9439. flavor = 0;
  9440. begin = end;
  9441. }
  9442. if (isLittleEndian != sys::IsLittleEndianHost)
  9443. sys::swapByteOrder(flavor);
  9444. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9445. memcpy((char *)&count, begin, sizeof(uint32_t));
  9446. begin += sizeof(uint32_t);
  9447. } else {
  9448. count = 0;
  9449. begin = end;
  9450. }
  9451. if (isLittleEndian != sys::IsLittleEndianHost)
  9452. sys::swapByteOrder(count);
  9453. if (flavor == MachO::ARM_THREAD_STATE) {
  9454. outs() << " flavor ARM_THREAD_STATE\n";
  9455. if (count == MachO::ARM_THREAD_STATE_COUNT)
  9456. outs() << " count ARM_THREAD_STATE_COUNT\n";
  9457. else
  9458. outs() << " count " << count
  9459. << " (not ARM_THREAD_STATE_COUNT)\n";
  9460. MachO::arm_thread_state32_t cpu32;
  9461. left = end - begin;
  9462. if (left >= sizeof(MachO::arm_thread_state32_t)) {
  9463. memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
  9464. begin += sizeof(MachO::arm_thread_state32_t);
  9465. } else {
  9466. memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
  9467. memcpy(&cpu32, begin, left);
  9468. begin += left;
  9469. }
  9470. if (isLittleEndian != sys::IsLittleEndianHost)
  9471. swapStruct(cpu32);
  9472. Print_arm_thread_state32_t(cpu32);
  9473. } else {
  9474. outs() << " flavor " << flavor << " (unknown)\n";
  9475. outs() << " count " << count << "\n";
  9476. outs() << " state (unknown)\n";
  9477. begin += count * sizeof(uint32_t);
  9478. }
  9479. }
  9480. } else if (cputype == MachO::CPU_TYPE_ARM64 ||
  9481. cputype == MachO::CPU_TYPE_ARM64_32) {
  9482. while (begin < end) {
  9483. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9484. memcpy((char *)&flavor, begin, sizeof(uint32_t));
  9485. begin += sizeof(uint32_t);
  9486. } else {
  9487. flavor = 0;
  9488. begin = end;
  9489. }
  9490. if (isLittleEndian != sys::IsLittleEndianHost)
  9491. sys::swapByteOrder(flavor);
  9492. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9493. memcpy((char *)&count, begin, sizeof(uint32_t));
  9494. begin += sizeof(uint32_t);
  9495. } else {
  9496. count = 0;
  9497. begin = end;
  9498. }
  9499. if (isLittleEndian != sys::IsLittleEndianHost)
  9500. sys::swapByteOrder(count);
  9501. if (flavor == MachO::ARM_THREAD_STATE64) {
  9502. outs() << " flavor ARM_THREAD_STATE64\n";
  9503. if (count == MachO::ARM_THREAD_STATE64_COUNT)
  9504. outs() << " count ARM_THREAD_STATE64_COUNT\n";
  9505. else
  9506. outs() << " count " << count
  9507. << " (not ARM_THREAD_STATE64_COUNT)\n";
  9508. MachO::arm_thread_state64_t cpu64;
  9509. left = end - begin;
  9510. if (left >= sizeof(MachO::arm_thread_state64_t)) {
  9511. memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
  9512. begin += sizeof(MachO::arm_thread_state64_t);
  9513. } else {
  9514. memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
  9515. memcpy(&cpu64, begin, left);
  9516. begin += left;
  9517. }
  9518. if (isLittleEndian != sys::IsLittleEndianHost)
  9519. swapStruct(cpu64);
  9520. Print_arm_thread_state64_t(cpu64);
  9521. } else {
  9522. outs() << " flavor " << flavor << " (unknown)\n";
  9523. outs() << " count " << count << "\n";
  9524. outs() << " state (unknown)\n";
  9525. begin += count * sizeof(uint32_t);
  9526. }
  9527. }
  9528. } else {
  9529. while (begin < end) {
  9530. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9531. memcpy((char *)&flavor, begin, sizeof(uint32_t));
  9532. begin += sizeof(uint32_t);
  9533. } else {
  9534. flavor = 0;
  9535. begin = end;
  9536. }
  9537. if (isLittleEndian != sys::IsLittleEndianHost)
  9538. sys::swapByteOrder(flavor);
  9539. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9540. memcpy((char *)&count, begin, sizeof(uint32_t));
  9541. begin += sizeof(uint32_t);
  9542. } else {
  9543. count = 0;
  9544. begin = end;
  9545. }
  9546. if (isLittleEndian != sys::IsLittleEndianHost)
  9547. sys::swapByteOrder(count);
  9548. outs() << " flavor " << flavor << "\n";
  9549. outs() << " count " << count << "\n";
  9550. outs() << " state (Unknown cputype/cpusubtype)\n";
  9551. begin += count * sizeof(uint32_t);
  9552. }
  9553. }
  9554. }
  9555. static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
  9556. if (dl.cmd == MachO::LC_ID_DYLIB)
  9557. outs() << " cmd LC_ID_DYLIB\n";
  9558. else if (dl.cmd == MachO::LC_LOAD_DYLIB)
  9559. outs() << " cmd LC_LOAD_DYLIB\n";
  9560. else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
  9561. outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
  9562. else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
  9563. outs() << " cmd LC_REEXPORT_DYLIB\n";
  9564. else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
  9565. outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
  9566. else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
  9567. outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
  9568. else
  9569. outs() << " cmd " << dl.cmd << " (unknown)\n";
  9570. outs() << " cmdsize " << dl.cmdsize;
  9571. if (dl.cmdsize < sizeof(struct MachO::dylib_command))
  9572. outs() << " Incorrect size\n";
  9573. else
  9574. outs() << "\n";
  9575. if (dl.dylib.name < dl.cmdsize) {
  9576. const char *P = (const char *)(Ptr) + dl.dylib.name;
  9577. outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
  9578. } else {
  9579. outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
  9580. }
  9581. outs() << " time stamp " << dl.dylib.timestamp << " ";
  9582. time_t t = dl.dylib.timestamp;
  9583. outs() << ctime(&t);
  9584. outs() << " current version ";
  9585. if (dl.dylib.current_version == 0xffffffff)
  9586. outs() << "n/a\n";
  9587. else
  9588. outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
  9589. << ((dl.dylib.current_version >> 8) & 0xff) << "."
  9590. << (dl.dylib.current_version & 0xff) << "\n";
  9591. outs() << "compatibility version ";
  9592. if (dl.dylib.compatibility_version == 0xffffffff)
  9593. outs() << "n/a\n";
  9594. else
  9595. outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
  9596. << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
  9597. << (dl.dylib.compatibility_version & 0xff) << "\n";
  9598. }
  9599. static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
  9600. uint32_t object_size) {
  9601. if (ld.cmd == MachO::LC_CODE_SIGNATURE)
  9602. outs() << " cmd LC_CODE_SIGNATURE\n";
  9603. else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
  9604. outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
  9605. else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
  9606. outs() << " cmd LC_FUNCTION_STARTS\n";
  9607. else if (ld.cmd == MachO::LC_DATA_IN_CODE)
  9608. outs() << " cmd LC_DATA_IN_CODE\n";
  9609. else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
  9610. outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
  9611. else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
  9612. outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
  9613. else if (ld.cmd == MachO::LC_DYLD_EXPORTS_TRIE)
  9614. outs() << " cmd LC_DYLD_EXPORTS_TRIE\n";
  9615. else if (ld.cmd == MachO::LC_DYLD_CHAINED_FIXUPS)
  9616. outs() << " cmd LC_DYLD_CHAINED_FIXUPS\n";
  9617. else
  9618. outs() << " cmd " << ld.cmd << " (?)\n";
  9619. outs() << " cmdsize " << ld.cmdsize;
  9620. if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
  9621. outs() << " Incorrect size\n";
  9622. else
  9623. outs() << "\n";
  9624. outs() << " dataoff " << ld.dataoff;
  9625. if (ld.dataoff > object_size)
  9626. outs() << " (past end of file)\n";
  9627. else
  9628. outs() << "\n";
  9629. outs() << " datasize " << ld.datasize;
  9630. uint64_t big_size = ld.dataoff;
  9631. big_size += ld.datasize;
  9632. if (big_size > object_size)
  9633. outs() << " (past end of file)\n";
  9634. else
  9635. outs() << "\n";
  9636. }
  9637. static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
  9638. uint32_t cputype, bool verbose) {
  9639. StringRef Buf = Obj->getData();
  9640. unsigned Index = 0;
  9641. for (const auto &Command : Obj->load_commands()) {
  9642. outs() << "Load command " << Index++ << "\n";
  9643. if (Command.C.cmd == MachO::LC_SEGMENT) {
  9644. MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
  9645. const char *sg_segname = SLC.segname;
  9646. PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
  9647. SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
  9648. SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
  9649. verbose);
  9650. for (unsigned j = 0; j < SLC.nsects; j++) {
  9651. MachO::section S = Obj->getSection(Command, j);
  9652. PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
  9653. S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
  9654. SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
  9655. }
  9656. } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
  9657. MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
  9658. const char *sg_segname = SLC_64.segname;
  9659. PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
  9660. SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
  9661. SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
  9662. SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
  9663. for (unsigned j = 0; j < SLC_64.nsects; j++) {
  9664. MachO::section_64 S_64 = Obj->getSection64(Command, j);
  9665. PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
  9666. S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
  9667. S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
  9668. sg_segname, filetype, Buf.size(), verbose);
  9669. }
  9670. } else if (Command.C.cmd == MachO::LC_SYMTAB) {
  9671. MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
  9672. PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
  9673. } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
  9674. MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
  9675. MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
  9676. PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
  9677. Obj->is64Bit());
  9678. } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
  9679. Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
  9680. MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
  9681. PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
  9682. } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
  9683. Command.C.cmd == MachO::LC_ID_DYLINKER ||
  9684. Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
  9685. MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
  9686. PrintDyldLoadCommand(Dyld, Command.Ptr);
  9687. } else if (Command.C.cmd == MachO::LC_UUID) {
  9688. MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
  9689. PrintUuidLoadCommand(Uuid);
  9690. } else if (Command.C.cmd == MachO::LC_RPATH) {
  9691. MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
  9692. PrintRpathLoadCommand(Rpath, Command.Ptr);
  9693. } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
  9694. Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
  9695. Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
  9696. Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
  9697. MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
  9698. PrintVersionMinLoadCommand(Vd);
  9699. } else if (Command.C.cmd == MachO::LC_NOTE) {
  9700. MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
  9701. PrintNoteLoadCommand(Nt);
  9702. } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
  9703. MachO::build_version_command Bv =
  9704. Obj->getBuildVersionLoadCommand(Command);
  9705. PrintBuildVersionLoadCommand(Obj, Bv, verbose);
  9706. } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
  9707. MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
  9708. PrintSourceVersionCommand(Sd);
  9709. } else if (Command.C.cmd == MachO::LC_MAIN) {
  9710. MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
  9711. PrintEntryPointCommand(Ep);
  9712. } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
  9713. MachO::encryption_info_command Ei =
  9714. Obj->getEncryptionInfoCommand(Command);
  9715. PrintEncryptionInfoCommand(Ei, Buf.size());
  9716. } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
  9717. MachO::encryption_info_command_64 Ei =
  9718. Obj->getEncryptionInfoCommand64(Command);
  9719. PrintEncryptionInfoCommand64(Ei, Buf.size());
  9720. } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
  9721. MachO::linker_option_command Lo =
  9722. Obj->getLinkerOptionLoadCommand(Command);
  9723. PrintLinkerOptionCommand(Lo, Command.Ptr);
  9724. } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
  9725. MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
  9726. PrintSubFrameworkCommand(Sf, Command.Ptr);
  9727. } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
  9728. MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
  9729. PrintSubUmbrellaCommand(Sf, Command.Ptr);
  9730. } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
  9731. MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
  9732. PrintSubLibraryCommand(Sl, Command.Ptr);
  9733. } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
  9734. MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
  9735. PrintSubClientCommand(Sc, Command.Ptr);
  9736. } else if (Command.C.cmd == MachO::LC_ROUTINES) {
  9737. MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
  9738. PrintRoutinesCommand(Rc);
  9739. } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
  9740. MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
  9741. PrintRoutinesCommand64(Rc);
  9742. } else if (Command.C.cmd == MachO::LC_THREAD ||
  9743. Command.C.cmd == MachO::LC_UNIXTHREAD) {
  9744. MachO::thread_command Tc = Obj->getThreadCommand(Command);
  9745. PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
  9746. } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
  9747. Command.C.cmd == MachO::LC_ID_DYLIB ||
  9748. Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
  9749. Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
  9750. Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
  9751. Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
  9752. MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
  9753. PrintDylibCommand(Dl, Command.Ptr);
  9754. } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
  9755. Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
  9756. Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
  9757. Command.C.cmd == MachO::LC_DATA_IN_CODE ||
  9758. Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
  9759. Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT ||
  9760. Command.C.cmd == MachO::LC_DYLD_EXPORTS_TRIE ||
  9761. Command.C.cmd == MachO::LC_DYLD_CHAINED_FIXUPS) {
  9762. MachO::linkedit_data_command Ld =
  9763. Obj->getLinkeditDataLoadCommand(Command);
  9764. PrintLinkEditDataCommand(Ld, Buf.size());
  9765. } else {
  9766. outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
  9767. << ")\n";
  9768. outs() << " cmdsize " << Command.C.cmdsize << "\n";
  9769. // TODO: get and print the raw bytes of the load command.
  9770. }
  9771. // TODO: print all the other kinds of load commands.
  9772. }
  9773. }
  9774. static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
  9775. if (Obj->is64Bit()) {
  9776. MachO::mach_header_64 H_64;
  9777. H_64 = Obj->getHeader64();
  9778. PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
  9779. H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
  9780. } else {
  9781. MachO::mach_header H;
  9782. H = Obj->getHeader();
  9783. PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
  9784. H.sizeofcmds, H.flags, verbose);
  9785. }
  9786. }
  9787. void objdump::printMachOFileHeader(const object::ObjectFile *Obj) {
  9788. const MachOObjectFile *file = cast<const MachOObjectFile>(Obj);
  9789. PrintMachHeader(file, Verbose);
  9790. }
  9791. void objdump::printMachOLoadCommands(const object::ObjectFile *Obj) {
  9792. const MachOObjectFile *file = cast<const MachOObjectFile>(Obj);
  9793. uint32_t filetype = 0;
  9794. uint32_t cputype = 0;
  9795. if (file->is64Bit()) {
  9796. MachO::mach_header_64 H_64;
  9797. H_64 = file->getHeader64();
  9798. filetype = H_64.filetype;
  9799. cputype = H_64.cputype;
  9800. } else {
  9801. MachO::mach_header H;
  9802. H = file->getHeader();
  9803. filetype = H.filetype;
  9804. cputype = H.cputype;
  9805. }
  9806. PrintLoadCommands(file, filetype, cputype, Verbose);
  9807. }
  9808. //===----------------------------------------------------------------------===//
  9809. // export trie dumping
  9810. //===----------------------------------------------------------------------===//
  9811. static void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
  9812. uint64_t BaseSegmentAddress = 0;
  9813. for (const auto &Command : Obj->load_commands()) {
  9814. if (Command.C.cmd == MachO::LC_SEGMENT) {
  9815. MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
  9816. if (Seg.fileoff == 0 && Seg.filesize != 0) {
  9817. BaseSegmentAddress = Seg.vmaddr;
  9818. break;
  9819. }
  9820. } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
  9821. MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
  9822. if (Seg.fileoff == 0 && Seg.filesize != 0) {
  9823. BaseSegmentAddress = Seg.vmaddr;
  9824. break;
  9825. }
  9826. }
  9827. }
  9828. Error Err = Error::success();
  9829. for (const object::ExportEntry &Entry : Obj->exports(Err)) {
  9830. uint64_t Flags = Entry.flags();
  9831. bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
  9832. bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
  9833. bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
  9834. MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
  9835. bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
  9836. MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
  9837. bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
  9838. if (ReExport)
  9839. outs() << "[re-export] ";
  9840. else
  9841. outs() << format("0x%08llX ",
  9842. Entry.address() + BaseSegmentAddress);
  9843. outs() << Entry.name();
  9844. if (WeakDef || ThreadLocal || Resolver || Abs) {
  9845. ListSeparator LS;
  9846. outs() << " [";
  9847. if (WeakDef)
  9848. outs() << LS << "weak_def";
  9849. if (ThreadLocal)
  9850. outs() << LS << "per-thread";
  9851. if (Abs)
  9852. outs() << LS << "absolute";
  9853. if (Resolver)
  9854. outs() << LS << format("resolver=0x%08llX", Entry.other());
  9855. outs() << "]";
  9856. }
  9857. if (ReExport) {
  9858. StringRef DylibName = "unknown";
  9859. int Ordinal = Entry.other() - 1;
  9860. Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
  9861. if (Entry.otherName().empty())
  9862. outs() << " (from " << DylibName << ")";
  9863. else
  9864. outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
  9865. }
  9866. outs() << "\n";
  9867. }
  9868. if (Err)
  9869. reportError(std::move(Err), Obj->getFileName());
  9870. }
  9871. //===----------------------------------------------------------------------===//
  9872. // rebase table dumping
  9873. //===----------------------------------------------------------------------===//
  9874. static void printMachORebaseTable(object::MachOObjectFile *Obj) {
  9875. outs() << "segment section address type\n";
  9876. Error Err = Error::success();
  9877. for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
  9878. StringRef SegmentName = Entry.segmentName();
  9879. StringRef SectionName = Entry.sectionName();
  9880. uint64_t Address = Entry.address();
  9881. // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
  9882. outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
  9883. SegmentName.str().c_str(), SectionName.str().c_str(),
  9884. Address, Entry.typeName().str().c_str());
  9885. }
  9886. if (Err)
  9887. reportError(std::move(Err), Obj->getFileName());
  9888. }
  9889. static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
  9890. StringRef DylibName;
  9891. switch (Ordinal) {
  9892. case MachO::BIND_SPECIAL_DYLIB_SELF:
  9893. return "this-image";
  9894. case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
  9895. return "main-executable";
  9896. case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
  9897. return "flat-namespace";
  9898. case MachO::BIND_SPECIAL_DYLIB_WEAK_LOOKUP:
  9899. return "weak";
  9900. default:
  9901. if (Ordinal > 0) {
  9902. std::error_code EC =
  9903. Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
  9904. if (EC)
  9905. return "<<bad library ordinal>>";
  9906. return DylibName;
  9907. }
  9908. }
  9909. return "<<unknown special ordinal>>";
  9910. }
  9911. //===----------------------------------------------------------------------===//
  9912. // bind table dumping
  9913. //===----------------------------------------------------------------------===//
  9914. static void printMachOBindTable(object::MachOObjectFile *Obj) {
  9915. // Build table of sections so names can used in final output.
  9916. outs() << "segment section address type "
  9917. "addend dylib symbol\n";
  9918. Error Err = Error::success();
  9919. for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
  9920. StringRef SegmentName = Entry.segmentName();
  9921. StringRef SectionName = Entry.sectionName();
  9922. uint64_t Address = Entry.address();
  9923. // Table lines look like:
  9924. // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
  9925. StringRef Attr;
  9926. if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
  9927. Attr = " (weak_import)";
  9928. outs() << left_justify(SegmentName, 8) << " "
  9929. << left_justify(SectionName, 18) << " "
  9930. << format_hex(Address, 10, true) << " "
  9931. << left_justify(Entry.typeName(), 8) << " "
  9932. << format_decimal(Entry.addend(), 8) << " "
  9933. << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
  9934. << Entry.symbolName() << Attr << "\n";
  9935. }
  9936. if (Err)
  9937. reportError(std::move(Err), Obj->getFileName());
  9938. }
  9939. //===----------------------------------------------------------------------===//
  9940. // lazy bind table dumping
  9941. //===----------------------------------------------------------------------===//
  9942. static void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
  9943. outs() << "segment section address "
  9944. "dylib symbol\n";
  9945. Error Err = Error::success();
  9946. for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
  9947. StringRef SegmentName = Entry.segmentName();
  9948. StringRef SectionName = Entry.sectionName();
  9949. uint64_t Address = Entry.address();
  9950. // Table lines look like:
  9951. // __DATA __got 0x00012010 libSystem ___stack_chk_guard
  9952. outs() << left_justify(SegmentName, 8) << " "
  9953. << left_justify(SectionName, 18) << " "
  9954. << format_hex(Address, 10, true) << " "
  9955. << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
  9956. << Entry.symbolName() << "\n";
  9957. }
  9958. if (Err)
  9959. reportError(std::move(Err), Obj->getFileName());
  9960. }
  9961. //===----------------------------------------------------------------------===//
  9962. // weak bind table dumping
  9963. //===----------------------------------------------------------------------===//
  9964. static void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
  9965. outs() << "segment section address "
  9966. "type addend symbol\n";
  9967. Error Err = Error::success();
  9968. for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
  9969. // Strong symbols don't have a location to update.
  9970. if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
  9971. outs() << " strong "
  9972. << Entry.symbolName() << "\n";
  9973. continue;
  9974. }
  9975. StringRef SegmentName = Entry.segmentName();
  9976. StringRef SectionName = Entry.sectionName();
  9977. uint64_t Address = Entry.address();
  9978. // Table lines look like:
  9979. // __DATA __data 0x00001000 pointer 0 _foo
  9980. outs() << left_justify(SegmentName, 8) << " "
  9981. << left_justify(SectionName, 18) << " "
  9982. << format_hex(Address, 10, true) << " "
  9983. << left_justify(Entry.typeName(), 8) << " "
  9984. << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
  9985. << "\n";
  9986. }
  9987. if (Err)
  9988. reportError(std::move(Err), Obj->getFileName());
  9989. }
  9990. // get_dyld_bind_info_symbolname() is used for disassembly and passed an
  9991. // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
  9992. // information for that address. If the address is found its binding symbol
  9993. // name is returned. If not nullptr is returned.
  9994. static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
  9995. struct DisassembleInfo *info) {
  9996. if (info->bindtable == nullptr) {
  9997. info->bindtable = std::make_unique<SymbolAddressMap>();
  9998. Error Err = Error::success();
  9999. for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
  10000. uint64_t Address = Entry.address();
  10001. StringRef name = Entry.symbolName();
  10002. if (!name.empty())
  10003. (*info->bindtable)[Address] = name;
  10004. }
  10005. if (Err)
  10006. reportError(std::move(Err), info->O->getFileName());
  10007. }
  10008. auto name = info->bindtable->lookup(ReferenceValue);
  10009. return !name.empty() ? name.data() : nullptr;
  10010. }
  10011. void objdump::printLazyBindTable(ObjectFile *o) {
  10012. outs() << "\nLazy bind table:\n";
  10013. if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  10014. printMachOLazyBindTable(MachO);
  10015. else
  10016. WithColor::error()
  10017. << "This operation is only currently supported "
  10018. "for Mach-O executable files.\n";
  10019. }
  10020. void objdump::printWeakBindTable(ObjectFile *o) {
  10021. outs() << "\nWeak bind table:\n";
  10022. if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  10023. printMachOWeakBindTable(MachO);
  10024. else
  10025. WithColor::error()
  10026. << "This operation is only currently supported "
  10027. "for Mach-O executable files.\n";
  10028. }
  10029. void objdump::printExportsTrie(const ObjectFile *o) {
  10030. outs() << "\nExports trie:\n";
  10031. if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  10032. printMachOExportsTrie(MachO);
  10033. else
  10034. WithColor::error()
  10035. << "This operation is only currently supported "
  10036. "for Mach-O executable files.\n";
  10037. }
  10038. void objdump::printRebaseTable(ObjectFile *o) {
  10039. outs() << "\nRebase table:\n";
  10040. if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  10041. printMachORebaseTable(MachO);
  10042. else
  10043. WithColor::error()
  10044. << "This operation is only currently supported "
  10045. "for Mach-O executable files.\n";
  10046. }
  10047. void objdump::printBindTable(ObjectFile *o) {
  10048. outs() << "\nBind table:\n";
  10049. if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  10050. printMachOBindTable(MachO);
  10051. else
  10052. WithColor::error()
  10053. << "This operation is only currently supported "
  10054. "for Mach-O executable files.\n";
  10055. }