MachODump.cpp 381 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521
  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. bool objdump::FunctionStarts;
  77. bool objdump::LinkOptHints;
  78. bool objdump::InfoPlist;
  79. bool objdump::DylibsUsed;
  80. bool objdump::DylibId;
  81. bool objdump::Verbose;
  82. bool objdump::ObjcMetaData;
  83. std::string objdump::DisSymName;
  84. bool objdump::SymbolicOperands;
  85. static std::vector<std::string> ArchFlags;
  86. static bool ArchAll = false;
  87. static std::string ThumbTripleName;
  88. void objdump::parseMachOOptions(const llvm::opt::InputArgList &InputArgs) {
  89. FirstPrivateHeader = InputArgs.hasArg(OBJDUMP_private_header);
  90. ExportsTrie = InputArgs.hasArg(OBJDUMP_exports_trie);
  91. Rebase = InputArgs.hasArg(OBJDUMP_rebase);
  92. Rpaths = InputArgs.hasArg(OBJDUMP_rpaths);
  93. Bind = InputArgs.hasArg(OBJDUMP_bind);
  94. LazyBind = InputArgs.hasArg(OBJDUMP_lazy_bind);
  95. WeakBind = InputArgs.hasArg(OBJDUMP_weak_bind);
  96. UseDbg = InputArgs.hasArg(OBJDUMP_g);
  97. DSYMFile = InputArgs.getLastArgValue(OBJDUMP_dsym_EQ).str();
  98. FullLeadingAddr = InputArgs.hasArg(OBJDUMP_full_leading_addr);
  99. LeadingHeaders = !InputArgs.hasArg(OBJDUMP_no_leading_headers);
  100. UniversalHeaders = InputArgs.hasArg(OBJDUMP_universal_headers);
  101. ArchiveMemberOffsets = InputArgs.hasArg(OBJDUMP_archive_member_offsets);
  102. IndirectSymbols = InputArgs.hasArg(OBJDUMP_indirect_symbols);
  103. DataInCode = InputArgs.hasArg(OBJDUMP_data_in_code);
  104. FunctionStarts = InputArgs.hasArg(OBJDUMP_function_starts);
  105. LinkOptHints = InputArgs.hasArg(OBJDUMP_link_opt_hints);
  106. InfoPlist = InputArgs.hasArg(OBJDUMP_info_plist);
  107. DylibsUsed = InputArgs.hasArg(OBJDUMP_dylibs_used);
  108. DylibId = InputArgs.hasArg(OBJDUMP_dylib_id);
  109. Verbose = !InputArgs.hasArg(OBJDUMP_non_verbose);
  110. ObjcMetaData = InputArgs.hasArg(OBJDUMP_objc_meta_data);
  111. DisSymName = InputArgs.getLastArgValue(OBJDUMP_dis_symname).str();
  112. SymbolicOperands = !InputArgs.hasArg(OBJDUMP_no_symbolic_operands);
  113. ArchFlags = InputArgs.getAllArgValues(OBJDUMP_arch_EQ);
  114. }
  115. static const Target *GetTarget(const MachOObjectFile *MachOObj,
  116. const char **McpuDefault,
  117. const Target **ThumbTarget) {
  118. // Figure out the target triple.
  119. Triple TT(TripleName);
  120. if (TripleName.empty()) {
  121. TT = MachOObj->getArchTriple(McpuDefault);
  122. TripleName = TT.str();
  123. }
  124. if (TT.getArch() == Triple::arm) {
  125. // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
  126. // that support ARM are also capable of Thumb mode.
  127. Triple ThumbTriple = TT;
  128. std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
  129. ThumbTriple.setArchName(ThumbName);
  130. ThumbTripleName = ThumbTriple.str();
  131. }
  132. // Get the target specific parser.
  133. std::string Error;
  134. const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
  135. if (TheTarget && ThumbTripleName.empty())
  136. return TheTarget;
  137. *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
  138. if (*ThumbTarget)
  139. return TheTarget;
  140. WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
  141. if (!TheTarget)
  142. errs() << TripleName;
  143. else
  144. errs() << ThumbTripleName;
  145. errs() << "', see --version and --triple.\n";
  146. return nullptr;
  147. }
  148. namespace {
  149. struct SymbolSorter {
  150. bool operator()(const SymbolRef &A, const SymbolRef &B) {
  151. Expected<SymbolRef::Type> ATypeOrErr = A.getType();
  152. if (!ATypeOrErr)
  153. reportError(ATypeOrErr.takeError(), A.getObject()->getFileName());
  154. SymbolRef::Type AType = *ATypeOrErr;
  155. Expected<SymbolRef::Type> BTypeOrErr = B.getType();
  156. if (!BTypeOrErr)
  157. reportError(BTypeOrErr.takeError(), B.getObject()->getFileName());
  158. SymbolRef::Type BType = *BTypeOrErr;
  159. uint64_t AAddr =
  160. (AType != SymbolRef::ST_Function) ? 0 : cantFail(A.getValue());
  161. uint64_t BAddr =
  162. (BType != SymbolRef::ST_Function) ? 0 : cantFail(B.getValue());
  163. return AAddr < BAddr;
  164. }
  165. };
  166. } // namespace
  167. // Types for the storted data in code table that is built before disassembly
  168. // and the predicate function to sort them.
  169. typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
  170. typedef std::vector<DiceTableEntry> DiceTable;
  171. typedef DiceTable::iterator dice_table_iterator;
  172. #ifdef LLVM_HAVE_LIBXAR
  173. namespace {
  174. struct ScopedXarFile {
  175. xar_t xar;
  176. ScopedXarFile(const char *filename, int32_t flags)
  177. : xar(xar_open(filename, flags)) {}
  178. ~ScopedXarFile() {
  179. if (xar)
  180. xar_close(xar);
  181. }
  182. ScopedXarFile(const ScopedXarFile &) = delete;
  183. ScopedXarFile &operator=(const ScopedXarFile &) = delete;
  184. operator xar_t() { return xar; }
  185. };
  186. struct ScopedXarIter {
  187. xar_iter_t iter;
  188. ScopedXarIter() : iter(xar_iter_new()) {}
  189. ~ScopedXarIter() {
  190. if (iter)
  191. xar_iter_free(iter);
  192. }
  193. ScopedXarIter(const ScopedXarIter &) = delete;
  194. ScopedXarIter &operator=(const ScopedXarIter &) = delete;
  195. operator xar_iter_t() { return iter; }
  196. };
  197. } // namespace
  198. #endif // defined(LLVM_HAVE_LIBXAR)
  199. // This is used to search for a data in code table entry for the PC being
  200. // disassembled. The j parameter has the PC in j.first. A single data in code
  201. // table entry can cover many bytes for each of its Kind's. So if the offset,
  202. // aka the i.first value, of the data in code table entry plus its Length
  203. // covers the PC being searched for this will return true. If not it will
  204. // return false.
  205. static bool compareDiceTableEntries(const DiceTableEntry &i,
  206. const DiceTableEntry &j) {
  207. uint16_t Length;
  208. i.second.getLength(Length);
  209. return j.first >= i.first && j.first < i.first + Length;
  210. }
  211. static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
  212. unsigned short Kind) {
  213. uint32_t Value, Size = 1;
  214. switch (Kind) {
  215. default:
  216. case MachO::DICE_KIND_DATA:
  217. if (Length >= 4) {
  218. if (ShowRawInsn)
  219. dumpBytes(makeArrayRef(bytes, 4), outs());
  220. Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
  221. outs() << "\t.long " << Value;
  222. Size = 4;
  223. } else if (Length >= 2) {
  224. if (ShowRawInsn)
  225. dumpBytes(makeArrayRef(bytes, 2), outs());
  226. Value = bytes[1] << 8 | bytes[0];
  227. outs() << "\t.short " << Value;
  228. Size = 2;
  229. } else {
  230. if (ShowRawInsn)
  231. dumpBytes(makeArrayRef(bytes, 2), outs());
  232. Value = bytes[0];
  233. outs() << "\t.byte " << Value;
  234. Size = 1;
  235. }
  236. if (Kind == MachO::DICE_KIND_DATA)
  237. outs() << "\t@ KIND_DATA\n";
  238. else
  239. outs() << "\t@ data in code kind = " << Kind << "\n";
  240. break;
  241. case MachO::DICE_KIND_JUMP_TABLE8:
  242. if (ShowRawInsn)
  243. dumpBytes(makeArrayRef(bytes, 1), outs());
  244. Value = bytes[0];
  245. outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
  246. Size = 1;
  247. break;
  248. case MachO::DICE_KIND_JUMP_TABLE16:
  249. if (ShowRawInsn)
  250. dumpBytes(makeArrayRef(bytes, 2), outs());
  251. Value = bytes[1] << 8 | bytes[0];
  252. outs() << "\t.short " << format("%5u", Value & 0xffff)
  253. << "\t@ KIND_JUMP_TABLE16\n";
  254. Size = 2;
  255. break;
  256. case MachO::DICE_KIND_JUMP_TABLE32:
  257. case MachO::DICE_KIND_ABS_JUMP_TABLE32:
  258. if (ShowRawInsn)
  259. dumpBytes(makeArrayRef(bytes, 4), outs());
  260. Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
  261. outs() << "\t.long " << Value;
  262. if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
  263. outs() << "\t@ KIND_JUMP_TABLE32\n";
  264. else
  265. outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
  266. Size = 4;
  267. break;
  268. }
  269. return Size;
  270. }
  271. static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
  272. std::vector<SectionRef> &Sections,
  273. std::vector<SymbolRef> &Symbols,
  274. SmallVectorImpl<uint64_t> &FoundFns,
  275. uint64_t &BaseSegmentAddress) {
  276. const StringRef FileName = MachOObj->getFileName();
  277. for (const SymbolRef &Symbol : MachOObj->symbols()) {
  278. StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
  279. if (!SymName.startswith("ltmp"))
  280. Symbols.push_back(Symbol);
  281. }
  282. append_range(Sections, MachOObj->sections());
  283. bool BaseSegmentAddressSet = false;
  284. for (const auto &Command : MachOObj->load_commands()) {
  285. if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
  286. // We found a function starts segment, parse the addresses for later
  287. // consumption.
  288. MachO::linkedit_data_command LLC =
  289. MachOObj->getLinkeditDataLoadCommand(Command);
  290. MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
  291. } else if (Command.C.cmd == MachO::LC_SEGMENT) {
  292. MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
  293. StringRef SegName = SLC.segname;
  294. if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
  295. BaseSegmentAddressSet = true;
  296. BaseSegmentAddress = SLC.vmaddr;
  297. }
  298. } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
  299. MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(Command);
  300. StringRef SegName = SLC.segname;
  301. if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
  302. BaseSegmentAddressSet = true;
  303. BaseSegmentAddress = SLC.vmaddr;
  304. }
  305. }
  306. }
  307. }
  308. static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes,
  309. DiceTable &Dices, uint64_t &InstSize) {
  310. // Check the data in code table here to see if this is data not an
  311. // instruction to be disassembled.
  312. DiceTable Dice;
  313. Dice.push_back(std::make_pair(PC, DiceRef()));
  314. dice_table_iterator DTI =
  315. std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
  316. compareDiceTableEntries);
  317. if (DTI != Dices.end()) {
  318. uint16_t Length;
  319. DTI->second.getLength(Length);
  320. uint16_t Kind;
  321. DTI->second.getKind(Kind);
  322. InstSize = DumpDataInCode(bytes, Length, Kind);
  323. if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
  324. (PC == (DTI->first + Length - 1)) && (Length & 1))
  325. InstSize++;
  326. return true;
  327. }
  328. return false;
  329. }
  330. static void printRelocationTargetName(const MachOObjectFile *O,
  331. const MachO::any_relocation_info &RE,
  332. raw_string_ostream &Fmt) {
  333. // Target of a scattered relocation is an address. In the interest of
  334. // generating pretty output, scan through the symbol table looking for a
  335. // symbol that aligns with that address. If we find one, print it.
  336. // Otherwise, we just print the hex address of the target.
  337. const StringRef FileName = O->getFileName();
  338. if (O->isRelocationScattered(RE)) {
  339. uint32_t Val = O->getPlainRelocationSymbolNum(RE);
  340. for (const SymbolRef &Symbol : O->symbols()) {
  341. uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
  342. if (Addr != Val)
  343. continue;
  344. Fmt << unwrapOrError(Symbol.getName(), FileName);
  345. return;
  346. }
  347. // If we couldn't find a symbol that this relocation refers to, try
  348. // to find a section beginning instead.
  349. for (const SectionRef &Section : ToolSectionFilter(*O)) {
  350. uint64_t Addr = Section.getAddress();
  351. if (Addr != Val)
  352. continue;
  353. StringRef NameOrErr = unwrapOrError(Section.getName(), O->getFileName());
  354. Fmt << NameOrErr;
  355. return;
  356. }
  357. Fmt << format("0x%x", Val);
  358. return;
  359. }
  360. StringRef S;
  361. bool isExtern = O->getPlainRelocationExternal(RE);
  362. uint64_t Val = O->getPlainRelocationSymbolNum(RE);
  363. if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND &&
  364. (O->getArch() == Triple::aarch64 || O->getArch() == Triple::aarch64_be)) {
  365. Fmt << format("0x%0" PRIx64, Val);
  366. return;
  367. }
  368. if (isExtern) {
  369. symbol_iterator SI = O->symbol_begin();
  370. std::advance(SI, Val);
  371. S = unwrapOrError(SI->getName(), FileName);
  372. } else {
  373. section_iterator SI = O->section_begin();
  374. // Adjust for the fact that sections are 1-indexed.
  375. if (Val == 0) {
  376. Fmt << "0 (?,?)";
  377. return;
  378. }
  379. uint32_t I = Val - 1;
  380. while (I != 0 && SI != O->section_end()) {
  381. --I;
  382. std::advance(SI, 1);
  383. }
  384. if (SI == O->section_end()) {
  385. Fmt << Val << " (?,?)";
  386. } else {
  387. if (Expected<StringRef> NameOrErr = SI->getName())
  388. S = *NameOrErr;
  389. else
  390. consumeError(NameOrErr.takeError());
  391. }
  392. }
  393. Fmt << S;
  394. }
  395. Error objdump::getMachORelocationValueString(const MachOObjectFile *Obj,
  396. const RelocationRef &RelRef,
  397. SmallVectorImpl<char> &Result) {
  398. DataRefImpl Rel = RelRef.getRawDataRefImpl();
  399. MachO::any_relocation_info RE = Obj->getRelocation(Rel);
  400. unsigned Arch = Obj->getArch();
  401. std::string FmtBuf;
  402. raw_string_ostream Fmt(FmtBuf);
  403. unsigned Type = Obj->getAnyRelocationType(RE);
  404. bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
  405. // Determine any addends that should be displayed with the relocation.
  406. // These require decoding the relocation type, which is triple-specific.
  407. // X86_64 has entirely custom relocation types.
  408. if (Arch == Triple::x86_64) {
  409. switch (Type) {
  410. case MachO::X86_64_RELOC_GOT_LOAD:
  411. case MachO::X86_64_RELOC_GOT: {
  412. printRelocationTargetName(Obj, RE, Fmt);
  413. Fmt << "@GOT";
  414. if (IsPCRel)
  415. Fmt << "PCREL";
  416. break;
  417. }
  418. case MachO::X86_64_RELOC_SUBTRACTOR: {
  419. DataRefImpl RelNext = Rel;
  420. Obj->moveRelocationNext(RelNext);
  421. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  422. // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
  423. // X86_64_RELOC_UNSIGNED.
  424. // NOTE: Scattered relocations don't exist on x86_64.
  425. unsigned RType = Obj->getAnyRelocationType(RENext);
  426. if (RType != MachO::X86_64_RELOC_UNSIGNED)
  427. reportError(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
  428. "X86_64_RELOC_SUBTRACTOR.");
  429. // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
  430. // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
  431. printRelocationTargetName(Obj, RENext, Fmt);
  432. Fmt << "-";
  433. printRelocationTargetName(Obj, RE, Fmt);
  434. break;
  435. }
  436. case MachO::X86_64_RELOC_TLV:
  437. printRelocationTargetName(Obj, RE, Fmt);
  438. Fmt << "@TLV";
  439. if (IsPCRel)
  440. Fmt << "P";
  441. break;
  442. case MachO::X86_64_RELOC_SIGNED_1:
  443. printRelocationTargetName(Obj, RE, Fmt);
  444. Fmt << "-1";
  445. break;
  446. case MachO::X86_64_RELOC_SIGNED_2:
  447. printRelocationTargetName(Obj, RE, Fmt);
  448. Fmt << "-2";
  449. break;
  450. case MachO::X86_64_RELOC_SIGNED_4:
  451. printRelocationTargetName(Obj, RE, Fmt);
  452. Fmt << "-4";
  453. break;
  454. default:
  455. printRelocationTargetName(Obj, RE, Fmt);
  456. break;
  457. }
  458. // X86 and ARM share some relocation types in common.
  459. } else if (Arch == Triple::x86 || Arch == Triple::arm ||
  460. Arch == Triple::ppc) {
  461. // Generic relocation types...
  462. switch (Type) {
  463. case MachO::GENERIC_RELOC_PAIR: // prints no info
  464. return Error::success();
  465. case MachO::GENERIC_RELOC_SECTDIFF: {
  466. DataRefImpl RelNext = Rel;
  467. Obj->moveRelocationNext(RelNext);
  468. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  469. // X86 sect diff's must be followed by a relocation of type
  470. // GENERIC_RELOC_PAIR.
  471. unsigned RType = Obj->getAnyRelocationType(RENext);
  472. if (RType != MachO::GENERIC_RELOC_PAIR)
  473. reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
  474. "GENERIC_RELOC_SECTDIFF.");
  475. printRelocationTargetName(Obj, RE, Fmt);
  476. Fmt << "-";
  477. printRelocationTargetName(Obj, RENext, Fmt);
  478. break;
  479. }
  480. }
  481. if (Arch == Triple::x86 || Arch == Triple::ppc) {
  482. switch (Type) {
  483. case MachO::GENERIC_RELOC_LOCAL_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_LOCAL_SECTDIFF.");
  493. printRelocationTargetName(Obj, RE, Fmt);
  494. Fmt << "-";
  495. printRelocationTargetName(Obj, RENext, Fmt);
  496. break;
  497. }
  498. case MachO::GENERIC_RELOC_TLV: {
  499. printRelocationTargetName(Obj, RE, Fmt);
  500. Fmt << "@TLV";
  501. if (IsPCRel)
  502. Fmt << "P";
  503. break;
  504. }
  505. default:
  506. printRelocationTargetName(Obj, RE, Fmt);
  507. }
  508. } else { // ARM-specific relocations
  509. switch (Type) {
  510. case MachO::ARM_RELOC_HALF:
  511. case MachO::ARM_RELOC_HALF_SECTDIFF: {
  512. // Half relocations steal a bit from the length field to encode
  513. // whether this is an upper16 or a lower16 relocation.
  514. bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
  515. if (isUpper)
  516. Fmt << ":upper16:(";
  517. else
  518. Fmt << ":lower16:(";
  519. printRelocationTargetName(Obj, RE, Fmt);
  520. DataRefImpl RelNext = Rel;
  521. Obj->moveRelocationNext(RelNext);
  522. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  523. // ARM half relocs must be followed by a relocation of type
  524. // ARM_RELOC_PAIR.
  525. unsigned RType = Obj->getAnyRelocationType(RENext);
  526. if (RType != MachO::ARM_RELOC_PAIR)
  527. reportError(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
  528. "ARM_RELOC_HALF");
  529. // NOTE: The half of the target virtual address is stashed in the
  530. // address field of the secondary relocation, but we can't reverse
  531. // engineer the constant offset from it without decoding the movw/movt
  532. // instruction to find the other half in its immediate field.
  533. // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
  534. // symbol/section pointer of the follow-on relocation.
  535. if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
  536. Fmt << "-";
  537. printRelocationTargetName(Obj, RENext, Fmt);
  538. }
  539. Fmt << ")";
  540. break;
  541. }
  542. default: {
  543. printRelocationTargetName(Obj, RE, Fmt);
  544. }
  545. }
  546. }
  547. } else
  548. printRelocationTargetName(Obj, RE, Fmt);
  549. Fmt.flush();
  550. Result.append(FmtBuf.begin(), FmtBuf.end());
  551. return Error::success();
  552. }
  553. static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
  554. uint32_t n, uint32_t count,
  555. uint32_t stride, uint64_t addr) {
  556. MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
  557. uint32_t nindirectsyms = Dysymtab.nindirectsyms;
  558. if (n > nindirectsyms)
  559. outs() << " (entries start past the end of the indirect symbol "
  560. "table) (reserved1 field greater than the table size)";
  561. else if (n + count > nindirectsyms)
  562. outs() << " (entries extends past the end of the indirect symbol "
  563. "table)";
  564. outs() << "\n";
  565. uint32_t cputype = O->getHeader().cputype;
  566. if (cputype & MachO::CPU_ARCH_ABI64)
  567. outs() << "address index";
  568. else
  569. outs() << "address index";
  570. if (verbose)
  571. outs() << " name\n";
  572. else
  573. outs() << "\n";
  574. for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
  575. if (cputype & MachO::CPU_ARCH_ABI64)
  576. outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
  577. else
  578. outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
  579. MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
  580. uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
  581. if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
  582. outs() << "LOCAL\n";
  583. continue;
  584. }
  585. if (indirect_symbol ==
  586. (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
  587. outs() << "LOCAL ABSOLUTE\n";
  588. continue;
  589. }
  590. if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
  591. outs() << "ABSOLUTE\n";
  592. continue;
  593. }
  594. outs() << format("%5u ", indirect_symbol);
  595. if (verbose) {
  596. MachO::symtab_command Symtab = O->getSymtabLoadCommand();
  597. if (indirect_symbol < Symtab.nsyms) {
  598. symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
  599. SymbolRef Symbol = *Sym;
  600. outs() << unwrapOrError(Symbol.getName(), O->getFileName());
  601. } else {
  602. outs() << "?";
  603. }
  604. }
  605. outs() << "\n";
  606. }
  607. }
  608. static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
  609. for (const auto &Load : O->load_commands()) {
  610. if (Load.C.cmd == MachO::LC_SEGMENT_64) {
  611. MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
  612. for (unsigned J = 0; J < Seg.nsects; ++J) {
  613. MachO::section_64 Sec = O->getSection64(Load, J);
  614. uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
  615. if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
  616. section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
  617. section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
  618. section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
  619. section_type == MachO::S_SYMBOL_STUBS) {
  620. uint32_t stride;
  621. if (section_type == MachO::S_SYMBOL_STUBS)
  622. stride = Sec.reserved2;
  623. else
  624. stride = 8;
  625. if (stride == 0) {
  626. outs() << "Can't print indirect symbols for (" << Sec.segname << ","
  627. << Sec.sectname << ") "
  628. << "(size of stubs in reserved2 field is zero)\n";
  629. continue;
  630. }
  631. uint32_t count = Sec.size / stride;
  632. outs() << "Indirect symbols for (" << Sec.segname << ","
  633. << Sec.sectname << ") " << count << " entries";
  634. uint32_t n = Sec.reserved1;
  635. PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
  636. }
  637. }
  638. } else if (Load.C.cmd == MachO::LC_SEGMENT) {
  639. MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
  640. for (unsigned J = 0; J < Seg.nsects; ++J) {
  641. MachO::section Sec = O->getSection(Load, J);
  642. uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
  643. if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
  644. section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
  645. section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
  646. section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
  647. section_type == MachO::S_SYMBOL_STUBS) {
  648. uint32_t stride;
  649. if (section_type == MachO::S_SYMBOL_STUBS)
  650. stride = Sec.reserved2;
  651. else
  652. stride = 4;
  653. if (stride == 0) {
  654. outs() << "Can't print indirect symbols for (" << Sec.segname << ","
  655. << Sec.sectname << ") "
  656. << "(size of stubs in reserved2 field is zero)\n";
  657. continue;
  658. }
  659. uint32_t count = Sec.size / stride;
  660. outs() << "Indirect symbols for (" << Sec.segname << ","
  661. << Sec.sectname << ") " << count << " entries";
  662. uint32_t n = Sec.reserved1;
  663. PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
  664. }
  665. }
  666. }
  667. }
  668. }
  669. static void PrintRType(const uint64_t cputype, const unsigned r_type) {
  670. static char const *generic_r_types[] = {
  671. "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
  672. " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
  673. " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
  674. };
  675. static char const *x86_64_r_types[] = {
  676. "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
  677. "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
  678. " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
  679. };
  680. static char const *arm_r_types[] = {
  681. "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
  682. "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
  683. " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
  684. };
  685. static char const *arm64_r_types[] = {
  686. "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
  687. "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
  688. "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
  689. };
  690. if (r_type > 0xf){
  691. outs() << format("%-7u", r_type) << " ";
  692. return;
  693. }
  694. switch (cputype) {
  695. case MachO::CPU_TYPE_I386:
  696. outs() << generic_r_types[r_type];
  697. break;
  698. case MachO::CPU_TYPE_X86_64:
  699. outs() << x86_64_r_types[r_type];
  700. break;
  701. case MachO::CPU_TYPE_ARM:
  702. outs() << arm_r_types[r_type];
  703. break;
  704. case MachO::CPU_TYPE_ARM64:
  705. case MachO::CPU_TYPE_ARM64_32:
  706. outs() << arm64_r_types[r_type];
  707. break;
  708. default:
  709. outs() << format("%-7u ", r_type);
  710. }
  711. }
  712. static void PrintRLength(const uint64_t cputype, const unsigned r_type,
  713. const unsigned r_length, const bool previous_arm_half){
  714. if (cputype == MachO::CPU_TYPE_ARM &&
  715. (r_type == MachO::ARM_RELOC_HALF ||
  716. r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
  717. if ((r_length & 0x1) == 0)
  718. outs() << "lo/";
  719. else
  720. outs() << "hi/";
  721. if ((r_length & 0x1) == 0)
  722. outs() << "arm ";
  723. else
  724. outs() << "thm ";
  725. } else {
  726. switch (r_length) {
  727. case 0:
  728. outs() << "byte ";
  729. break;
  730. case 1:
  731. outs() << "word ";
  732. break;
  733. case 2:
  734. outs() << "long ";
  735. break;
  736. case 3:
  737. if (cputype == MachO::CPU_TYPE_X86_64)
  738. outs() << "quad ";
  739. else
  740. outs() << format("?(%2d) ", r_length);
  741. break;
  742. default:
  743. outs() << format("?(%2d) ", r_length);
  744. }
  745. }
  746. }
  747. static void PrintRelocationEntries(const MachOObjectFile *O,
  748. const relocation_iterator Begin,
  749. const relocation_iterator End,
  750. const uint64_t cputype,
  751. const bool verbose) {
  752. const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
  753. bool previous_arm_half = false;
  754. bool previous_sectdiff = false;
  755. uint32_t sectdiff_r_type = 0;
  756. for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
  757. const DataRefImpl Rel = Reloc->getRawDataRefImpl();
  758. const MachO::any_relocation_info RE = O->getRelocation(Rel);
  759. const unsigned r_type = O->getAnyRelocationType(RE);
  760. const bool r_scattered = O->isRelocationScattered(RE);
  761. const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
  762. const unsigned r_length = O->getAnyRelocationLength(RE);
  763. const unsigned r_address = O->getAnyRelocationAddress(RE);
  764. const bool r_extern = (r_scattered ? false :
  765. O->getPlainRelocationExternal(RE));
  766. const uint32_t r_value = (r_scattered ?
  767. O->getScatteredRelocationValue(RE) : 0);
  768. const unsigned r_symbolnum = (r_scattered ? 0 :
  769. O->getPlainRelocationSymbolNum(RE));
  770. if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
  771. if (verbose) {
  772. // scattered: address
  773. if ((cputype == MachO::CPU_TYPE_I386 &&
  774. r_type == MachO::GENERIC_RELOC_PAIR) ||
  775. (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
  776. outs() << " ";
  777. else
  778. outs() << format("%08x ", (unsigned int)r_address);
  779. // scattered: pcrel
  780. if (r_pcrel)
  781. outs() << "True ";
  782. else
  783. outs() << "False ";
  784. // scattered: length
  785. PrintRLength(cputype, r_type, r_length, previous_arm_half);
  786. // scattered: extern & type
  787. outs() << "n/a ";
  788. PrintRType(cputype, r_type);
  789. // scattered: scattered & value
  790. outs() << format("True 0x%08x", (unsigned int)r_value);
  791. if (previous_sectdiff == false) {
  792. if ((cputype == MachO::CPU_TYPE_ARM &&
  793. r_type == MachO::ARM_RELOC_PAIR))
  794. outs() << format(" half = 0x%04x ", (unsigned int)r_address);
  795. } else if (cputype == MachO::CPU_TYPE_ARM &&
  796. sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
  797. outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
  798. if ((cputype == MachO::CPU_TYPE_I386 &&
  799. (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
  800. r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
  801. (cputype == MachO::CPU_TYPE_ARM &&
  802. (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
  803. sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
  804. sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
  805. previous_sectdiff = true;
  806. sectdiff_r_type = r_type;
  807. } else {
  808. previous_sectdiff = false;
  809. sectdiff_r_type = 0;
  810. }
  811. if (cputype == MachO::CPU_TYPE_ARM &&
  812. (r_type == MachO::ARM_RELOC_HALF ||
  813. r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
  814. previous_arm_half = true;
  815. else
  816. previous_arm_half = false;
  817. outs() << "\n";
  818. }
  819. else {
  820. // scattered: address pcrel length extern type scattered value
  821. outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
  822. (unsigned int)r_address, r_pcrel, r_length, r_type,
  823. (unsigned int)r_value);
  824. }
  825. }
  826. else {
  827. if (verbose) {
  828. // plain: address
  829. if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
  830. outs() << " ";
  831. else
  832. outs() << format("%08x ", (unsigned int)r_address);
  833. // plain: pcrel
  834. if (r_pcrel)
  835. outs() << "True ";
  836. else
  837. outs() << "False ";
  838. // plain: length
  839. PrintRLength(cputype, r_type, r_length, previous_arm_half);
  840. if (r_extern) {
  841. // plain: extern & type & scattered
  842. outs() << "True ";
  843. PrintRType(cputype, r_type);
  844. outs() << "False ";
  845. // plain: symbolnum/value
  846. if (r_symbolnum > Symtab.nsyms)
  847. outs() << format("?(%d)\n", r_symbolnum);
  848. else {
  849. SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
  850. Expected<StringRef> SymNameNext = Symbol.getName();
  851. const char *name = nullptr;
  852. if (SymNameNext)
  853. name = SymNameNext->data();
  854. if (name == nullptr)
  855. outs() << format("?(%d)\n", r_symbolnum);
  856. else
  857. outs() << name << "\n";
  858. }
  859. }
  860. else {
  861. // plain: extern & type & scattered
  862. outs() << "False ";
  863. PrintRType(cputype, r_type);
  864. outs() << "False ";
  865. // plain: symbolnum/value
  866. if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
  867. outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
  868. else if ((cputype == MachO::CPU_TYPE_ARM64 ||
  869. cputype == MachO::CPU_TYPE_ARM64_32) &&
  870. r_type == MachO::ARM64_RELOC_ADDEND)
  871. outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
  872. else {
  873. outs() << format("%d ", r_symbolnum);
  874. if (r_symbolnum == MachO::R_ABS)
  875. outs() << "R_ABS\n";
  876. else {
  877. // in this case, r_symbolnum is actually a 1-based section number
  878. uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
  879. if (r_symbolnum > 0 && r_symbolnum <= nsects) {
  880. object::DataRefImpl DRI;
  881. DRI.d.a = r_symbolnum-1;
  882. StringRef SegName = O->getSectionFinalSegmentName(DRI);
  883. if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
  884. outs() << "(" << SegName << "," << *NameOrErr << ")\n";
  885. else
  886. outs() << "(?,?)\n";
  887. }
  888. else {
  889. outs() << "(?,?)\n";
  890. }
  891. }
  892. }
  893. }
  894. if (cputype == MachO::CPU_TYPE_ARM &&
  895. (r_type == MachO::ARM_RELOC_HALF ||
  896. r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
  897. previous_arm_half = true;
  898. else
  899. previous_arm_half = false;
  900. }
  901. else {
  902. // plain: address pcrel length extern type scattered symbolnum/section
  903. outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
  904. (unsigned int)r_address, r_pcrel, r_length, r_extern,
  905. r_type, r_symbolnum);
  906. }
  907. }
  908. }
  909. }
  910. static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
  911. const uint64_t cputype = O->getHeader().cputype;
  912. const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
  913. if (Dysymtab.nextrel != 0) {
  914. outs() << "External relocation information " << Dysymtab.nextrel
  915. << " entries";
  916. outs() << "\naddress pcrel length extern type scattered "
  917. "symbolnum/value\n";
  918. PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
  919. verbose);
  920. }
  921. if (Dysymtab.nlocrel != 0) {
  922. outs() << format("Local relocation information %u entries",
  923. Dysymtab.nlocrel);
  924. outs() << "\naddress pcrel length extern type scattered "
  925. "symbolnum/value\n";
  926. PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
  927. verbose);
  928. }
  929. for (const auto &Load : O->load_commands()) {
  930. if (Load.C.cmd == MachO::LC_SEGMENT_64) {
  931. const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
  932. for (unsigned J = 0; J < Seg.nsects; ++J) {
  933. const MachO::section_64 Sec = O->getSection64(Load, J);
  934. if (Sec.nreloc != 0) {
  935. DataRefImpl DRI;
  936. DRI.d.a = J;
  937. const StringRef SegName = O->getSectionFinalSegmentName(DRI);
  938. if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
  939. outs() << "Relocation information (" << SegName << "," << *NameOrErr
  940. << format(") %u entries", Sec.nreloc);
  941. else
  942. outs() << "Relocation information (" << SegName << ",?) "
  943. << format("%u entries", Sec.nreloc);
  944. outs() << "\naddress pcrel length extern type scattered "
  945. "symbolnum/value\n";
  946. PrintRelocationEntries(O, O->section_rel_begin(DRI),
  947. O->section_rel_end(DRI), cputype, verbose);
  948. }
  949. }
  950. } else if (Load.C.cmd == MachO::LC_SEGMENT) {
  951. const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
  952. for (unsigned J = 0; J < Seg.nsects; ++J) {
  953. const MachO::section Sec = O->getSection(Load, J);
  954. if (Sec.nreloc != 0) {
  955. DataRefImpl DRI;
  956. DRI.d.a = J;
  957. const StringRef SegName = O->getSectionFinalSegmentName(DRI);
  958. if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
  959. outs() << "Relocation information (" << SegName << "," << *NameOrErr
  960. << format(") %u entries", Sec.nreloc);
  961. else
  962. outs() << "Relocation information (" << SegName << ",?) "
  963. << format("%u entries", Sec.nreloc);
  964. outs() << "\naddress pcrel length extern type scattered "
  965. "symbolnum/value\n";
  966. PrintRelocationEntries(O, O->section_rel_begin(DRI),
  967. O->section_rel_end(DRI), cputype, verbose);
  968. }
  969. }
  970. }
  971. }
  972. }
  973. static void PrintFunctionStarts(MachOObjectFile *O) {
  974. uint64_t BaseSegmentAddress = 0;
  975. for (const MachOObjectFile::LoadCommandInfo &Command : O->load_commands()) {
  976. if (Command.C.cmd == MachO::LC_SEGMENT) {
  977. MachO::segment_command SLC = O->getSegmentLoadCommand(Command);
  978. if (StringRef(SLC.segname) == "__TEXT") {
  979. BaseSegmentAddress = SLC.vmaddr;
  980. break;
  981. }
  982. } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
  983. MachO::segment_command_64 SLC = O->getSegment64LoadCommand(Command);
  984. if (StringRef(SLC.segname) == "__TEXT") {
  985. BaseSegmentAddress = SLC.vmaddr;
  986. break;
  987. }
  988. }
  989. }
  990. SmallVector<uint64_t, 8> FunctionStarts;
  991. for (const MachOObjectFile::LoadCommandInfo &LC : O->load_commands()) {
  992. if (LC.C.cmd == MachO::LC_FUNCTION_STARTS) {
  993. MachO::linkedit_data_command FunctionStartsLC =
  994. O->getLinkeditDataLoadCommand(LC);
  995. O->ReadULEB128s(FunctionStartsLC.dataoff, FunctionStarts);
  996. break;
  997. }
  998. }
  999. for (uint64_t S : FunctionStarts) {
  1000. uint64_t Addr = BaseSegmentAddress + S;
  1001. if (O->is64Bit())
  1002. outs() << format("%016" PRIx64, Addr) << "\n";
  1003. else
  1004. outs() << format("%08" PRIx32, static_cast<uint32_t>(Addr)) << "\n";
  1005. }
  1006. }
  1007. static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
  1008. MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
  1009. uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
  1010. outs() << "Data in code table (" << nentries << " entries)\n";
  1011. outs() << "offset length kind\n";
  1012. for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
  1013. ++DI) {
  1014. uint32_t Offset;
  1015. DI->getOffset(Offset);
  1016. outs() << format("0x%08" PRIx32, Offset) << " ";
  1017. uint16_t Length;
  1018. DI->getLength(Length);
  1019. outs() << format("%6u", Length) << " ";
  1020. uint16_t Kind;
  1021. DI->getKind(Kind);
  1022. if (verbose) {
  1023. switch (Kind) {
  1024. case MachO::DICE_KIND_DATA:
  1025. outs() << "DATA";
  1026. break;
  1027. case MachO::DICE_KIND_JUMP_TABLE8:
  1028. outs() << "JUMP_TABLE8";
  1029. break;
  1030. case MachO::DICE_KIND_JUMP_TABLE16:
  1031. outs() << "JUMP_TABLE16";
  1032. break;
  1033. case MachO::DICE_KIND_JUMP_TABLE32:
  1034. outs() << "JUMP_TABLE32";
  1035. break;
  1036. case MachO::DICE_KIND_ABS_JUMP_TABLE32:
  1037. outs() << "ABS_JUMP_TABLE32";
  1038. break;
  1039. default:
  1040. outs() << format("0x%04" PRIx32, Kind);
  1041. break;
  1042. }
  1043. } else
  1044. outs() << format("0x%04" PRIx32, Kind);
  1045. outs() << "\n";
  1046. }
  1047. }
  1048. static void PrintLinkOptHints(MachOObjectFile *O) {
  1049. MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
  1050. const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
  1051. uint32_t nloh = LohLC.datasize;
  1052. outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
  1053. for (uint32_t i = 0; i < nloh;) {
  1054. unsigned n;
  1055. uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
  1056. i += n;
  1057. outs() << " identifier " << identifier << " ";
  1058. if (i >= nloh)
  1059. return;
  1060. switch (identifier) {
  1061. case 1:
  1062. outs() << "AdrpAdrp\n";
  1063. break;
  1064. case 2:
  1065. outs() << "AdrpLdr\n";
  1066. break;
  1067. case 3:
  1068. outs() << "AdrpAddLdr\n";
  1069. break;
  1070. case 4:
  1071. outs() << "AdrpLdrGotLdr\n";
  1072. break;
  1073. case 5:
  1074. outs() << "AdrpAddStr\n";
  1075. break;
  1076. case 6:
  1077. outs() << "AdrpLdrGotStr\n";
  1078. break;
  1079. case 7:
  1080. outs() << "AdrpAdd\n";
  1081. break;
  1082. case 8:
  1083. outs() << "AdrpLdrGot\n";
  1084. break;
  1085. default:
  1086. outs() << "Unknown identifier value\n";
  1087. break;
  1088. }
  1089. uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
  1090. i += n;
  1091. outs() << " narguments " << narguments << "\n";
  1092. if (i >= nloh)
  1093. return;
  1094. for (uint32_t j = 0; j < narguments; j++) {
  1095. uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
  1096. i += n;
  1097. outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
  1098. if (i >= nloh)
  1099. return;
  1100. }
  1101. }
  1102. }
  1103. static void PrintDylibs(MachOObjectFile *O, bool JustId) {
  1104. unsigned Index = 0;
  1105. for (const auto &Load : O->load_commands()) {
  1106. if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
  1107. (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
  1108. Load.C.cmd == MachO::LC_LOAD_DYLIB ||
  1109. Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
  1110. Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
  1111. Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
  1112. Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
  1113. MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
  1114. if (dl.dylib.name < dl.cmdsize) {
  1115. const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
  1116. if (JustId)
  1117. outs() << p << "\n";
  1118. else {
  1119. outs() << "\t" << p;
  1120. outs() << " (compatibility version "
  1121. << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
  1122. << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
  1123. << (dl.dylib.compatibility_version & 0xff) << ",";
  1124. outs() << " current version "
  1125. << ((dl.dylib.current_version >> 16) & 0xffff) << "."
  1126. << ((dl.dylib.current_version >> 8) & 0xff) << "."
  1127. << (dl.dylib.current_version & 0xff);
  1128. if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
  1129. outs() << ", weak";
  1130. if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
  1131. outs() << ", reexport";
  1132. if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
  1133. outs() << ", upward";
  1134. if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
  1135. outs() << ", lazy";
  1136. outs() << ")\n";
  1137. }
  1138. } else {
  1139. outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
  1140. if (Load.C.cmd == MachO::LC_ID_DYLIB)
  1141. outs() << "LC_ID_DYLIB ";
  1142. else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
  1143. outs() << "LC_LOAD_DYLIB ";
  1144. else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
  1145. outs() << "LC_LOAD_WEAK_DYLIB ";
  1146. else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
  1147. outs() << "LC_LAZY_LOAD_DYLIB ";
  1148. else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
  1149. outs() << "LC_REEXPORT_DYLIB ";
  1150. else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
  1151. outs() << "LC_LOAD_UPWARD_DYLIB ";
  1152. else
  1153. outs() << "LC_??? ";
  1154. outs() << "command " << Index++ << "\n";
  1155. }
  1156. }
  1157. }
  1158. }
  1159. static void printRpaths(MachOObjectFile *O) {
  1160. for (const auto &Command : O->load_commands()) {
  1161. if (Command.C.cmd == MachO::LC_RPATH) {
  1162. auto Rpath = O->getRpathCommand(Command);
  1163. const char *P = (const char *)(Command.Ptr) + Rpath.path;
  1164. outs() << P << "\n";
  1165. }
  1166. }
  1167. }
  1168. typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
  1169. static void CreateSymbolAddressMap(MachOObjectFile *O,
  1170. SymbolAddressMap *AddrMap) {
  1171. // Create a map of symbol addresses to symbol names.
  1172. const StringRef FileName = O->getFileName();
  1173. for (const SymbolRef &Symbol : O->symbols()) {
  1174. SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
  1175. if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
  1176. ST == SymbolRef::ST_Other) {
  1177. uint64_t Address = cantFail(Symbol.getValue());
  1178. StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
  1179. if (!SymName.startswith(".objc"))
  1180. (*AddrMap)[Address] = SymName;
  1181. }
  1182. }
  1183. }
  1184. // GuessSymbolName is passed the address of what might be a symbol and a
  1185. // pointer to the SymbolAddressMap. It returns the name of a symbol
  1186. // with that address or nullptr if no symbol is found with that address.
  1187. static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
  1188. const char *SymbolName = nullptr;
  1189. // A DenseMap can't lookup up some values.
  1190. if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
  1191. StringRef name = AddrMap->lookup(value);
  1192. if (!name.empty())
  1193. SymbolName = name.data();
  1194. }
  1195. return SymbolName;
  1196. }
  1197. static void DumpCstringChar(const char c) {
  1198. char p[2];
  1199. p[0] = c;
  1200. p[1] = '\0';
  1201. outs().write_escaped(p);
  1202. }
  1203. static void DumpCstringSection(MachOObjectFile *O, const char *sect,
  1204. uint32_t sect_size, uint64_t sect_addr,
  1205. bool print_addresses) {
  1206. for (uint32_t i = 0; i < sect_size; i++) {
  1207. if (print_addresses) {
  1208. if (O->is64Bit())
  1209. outs() << format("%016" PRIx64, sect_addr + i) << " ";
  1210. else
  1211. outs() << format("%08" PRIx64, sect_addr + i) << " ";
  1212. }
  1213. for (; i < sect_size && sect[i] != '\0'; i++)
  1214. DumpCstringChar(sect[i]);
  1215. if (i < sect_size && sect[i] == '\0')
  1216. outs() << "\n";
  1217. }
  1218. }
  1219. static void DumpLiteral4(uint32_t l, float f) {
  1220. outs() << format("0x%08" PRIx32, l);
  1221. if ((l & 0x7f800000) != 0x7f800000)
  1222. outs() << format(" (%.16e)\n", f);
  1223. else {
  1224. if (l == 0x7f800000)
  1225. outs() << " (+Infinity)\n";
  1226. else if (l == 0xff800000)
  1227. outs() << " (-Infinity)\n";
  1228. else if ((l & 0x00400000) == 0x00400000)
  1229. outs() << " (non-signaling Not-a-Number)\n";
  1230. else
  1231. outs() << " (signaling Not-a-Number)\n";
  1232. }
  1233. }
  1234. static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
  1235. uint32_t sect_size, uint64_t sect_addr,
  1236. bool print_addresses) {
  1237. for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
  1238. if (print_addresses) {
  1239. if (O->is64Bit())
  1240. outs() << format("%016" PRIx64, sect_addr + i) << " ";
  1241. else
  1242. outs() << format("%08" PRIx64, sect_addr + i) << " ";
  1243. }
  1244. float f;
  1245. memcpy(&f, sect + i, sizeof(float));
  1246. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1247. sys::swapByteOrder(f);
  1248. uint32_t l;
  1249. memcpy(&l, sect + i, sizeof(uint32_t));
  1250. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1251. sys::swapByteOrder(l);
  1252. DumpLiteral4(l, f);
  1253. }
  1254. }
  1255. static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
  1256. double d) {
  1257. outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
  1258. uint32_t Hi, Lo;
  1259. Hi = (O->isLittleEndian()) ? l1 : l0;
  1260. Lo = (O->isLittleEndian()) ? l0 : l1;
  1261. // Hi is the high word, so this is equivalent to if(isfinite(d))
  1262. if ((Hi & 0x7ff00000) != 0x7ff00000)
  1263. outs() << format(" (%.16e)\n", d);
  1264. else {
  1265. if (Hi == 0x7ff00000 && Lo == 0)
  1266. outs() << " (+Infinity)\n";
  1267. else if (Hi == 0xfff00000 && Lo == 0)
  1268. outs() << " (-Infinity)\n";
  1269. else if ((Hi & 0x00080000) == 0x00080000)
  1270. outs() << " (non-signaling Not-a-Number)\n";
  1271. else
  1272. outs() << " (signaling Not-a-Number)\n";
  1273. }
  1274. }
  1275. static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
  1276. uint32_t sect_size, uint64_t sect_addr,
  1277. bool print_addresses) {
  1278. for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
  1279. if (print_addresses) {
  1280. if (O->is64Bit())
  1281. outs() << format("%016" PRIx64, sect_addr + i) << " ";
  1282. else
  1283. outs() << format("%08" PRIx64, sect_addr + i) << " ";
  1284. }
  1285. double d;
  1286. memcpy(&d, sect + i, sizeof(double));
  1287. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1288. sys::swapByteOrder(d);
  1289. uint32_t l0, l1;
  1290. memcpy(&l0, sect + i, sizeof(uint32_t));
  1291. memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
  1292. if (O->isLittleEndian() != sys::IsLittleEndianHost) {
  1293. sys::swapByteOrder(l0);
  1294. sys::swapByteOrder(l1);
  1295. }
  1296. DumpLiteral8(O, l0, l1, d);
  1297. }
  1298. }
  1299. static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
  1300. outs() << format("0x%08" PRIx32, l0) << " ";
  1301. outs() << format("0x%08" PRIx32, l1) << " ";
  1302. outs() << format("0x%08" PRIx32, l2) << " ";
  1303. outs() << format("0x%08" PRIx32, l3) << "\n";
  1304. }
  1305. static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
  1306. uint32_t sect_size, uint64_t sect_addr,
  1307. bool print_addresses) {
  1308. for (uint32_t i = 0; i < sect_size; i += 16) {
  1309. if (print_addresses) {
  1310. if (O->is64Bit())
  1311. outs() << format("%016" PRIx64, sect_addr + i) << " ";
  1312. else
  1313. outs() << format("%08" PRIx64, sect_addr + i) << " ";
  1314. }
  1315. uint32_t l0, l1, l2, l3;
  1316. memcpy(&l0, sect + i, sizeof(uint32_t));
  1317. memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
  1318. memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
  1319. memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
  1320. if (O->isLittleEndian() != sys::IsLittleEndianHost) {
  1321. sys::swapByteOrder(l0);
  1322. sys::swapByteOrder(l1);
  1323. sys::swapByteOrder(l2);
  1324. sys::swapByteOrder(l3);
  1325. }
  1326. DumpLiteral16(l0, l1, l2, l3);
  1327. }
  1328. }
  1329. static void DumpLiteralPointerSection(MachOObjectFile *O,
  1330. const SectionRef &Section,
  1331. const char *sect, uint32_t sect_size,
  1332. uint64_t sect_addr,
  1333. bool print_addresses) {
  1334. // Collect the literal sections in this Mach-O file.
  1335. std::vector<SectionRef> LiteralSections;
  1336. for (const SectionRef &Section : O->sections()) {
  1337. DataRefImpl Ref = Section.getRawDataRefImpl();
  1338. uint32_t section_type;
  1339. if (O->is64Bit()) {
  1340. const MachO::section_64 Sec = O->getSection64(Ref);
  1341. section_type = Sec.flags & MachO::SECTION_TYPE;
  1342. } else {
  1343. const MachO::section Sec = O->getSection(Ref);
  1344. section_type = Sec.flags & MachO::SECTION_TYPE;
  1345. }
  1346. if (section_type == MachO::S_CSTRING_LITERALS ||
  1347. section_type == MachO::S_4BYTE_LITERALS ||
  1348. section_type == MachO::S_8BYTE_LITERALS ||
  1349. section_type == MachO::S_16BYTE_LITERALS)
  1350. LiteralSections.push_back(Section);
  1351. }
  1352. // Set the size of the literal pointer.
  1353. uint32_t lp_size = O->is64Bit() ? 8 : 4;
  1354. // Collect the external relocation symbols for the literal pointers.
  1355. std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
  1356. for (const RelocationRef &Reloc : Section.relocations()) {
  1357. DataRefImpl Rel;
  1358. MachO::any_relocation_info RE;
  1359. bool isExtern = false;
  1360. Rel = Reloc.getRawDataRefImpl();
  1361. RE = O->getRelocation(Rel);
  1362. isExtern = O->getPlainRelocationExternal(RE);
  1363. if (isExtern) {
  1364. uint64_t RelocOffset = Reloc.getOffset();
  1365. symbol_iterator RelocSym = Reloc.getSymbol();
  1366. Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
  1367. }
  1368. }
  1369. array_pod_sort(Relocs.begin(), Relocs.end());
  1370. // Dump each literal pointer.
  1371. for (uint32_t i = 0; i < sect_size; i += lp_size) {
  1372. if (print_addresses) {
  1373. if (O->is64Bit())
  1374. outs() << format("%016" PRIx64, sect_addr + i) << " ";
  1375. else
  1376. outs() << format("%08" PRIx64, sect_addr + i) << " ";
  1377. }
  1378. uint64_t lp;
  1379. if (O->is64Bit()) {
  1380. memcpy(&lp, sect + i, sizeof(uint64_t));
  1381. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1382. sys::swapByteOrder(lp);
  1383. } else {
  1384. uint32_t li;
  1385. memcpy(&li, sect + i, sizeof(uint32_t));
  1386. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1387. sys::swapByteOrder(li);
  1388. lp = li;
  1389. }
  1390. // First look for an external relocation entry for this literal pointer.
  1391. auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
  1392. return P.first == i;
  1393. });
  1394. if (Reloc != Relocs.end()) {
  1395. symbol_iterator RelocSym = Reloc->second;
  1396. StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
  1397. outs() << "external relocation entry for symbol:" << SymName << "\n";
  1398. continue;
  1399. }
  1400. // For local references see what the section the literal pointer points to.
  1401. auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
  1402. return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
  1403. });
  1404. if (Sect == LiteralSections.end()) {
  1405. outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
  1406. continue;
  1407. }
  1408. uint64_t SectAddress = Sect->getAddress();
  1409. uint64_t SectSize = Sect->getSize();
  1410. StringRef SectName;
  1411. Expected<StringRef> SectNameOrErr = Sect->getName();
  1412. if (SectNameOrErr)
  1413. SectName = *SectNameOrErr;
  1414. else
  1415. consumeError(SectNameOrErr.takeError());
  1416. DataRefImpl Ref = Sect->getRawDataRefImpl();
  1417. StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
  1418. outs() << SegmentName << ":" << SectName << ":";
  1419. uint32_t section_type;
  1420. if (O->is64Bit()) {
  1421. const MachO::section_64 Sec = O->getSection64(Ref);
  1422. section_type = Sec.flags & MachO::SECTION_TYPE;
  1423. } else {
  1424. const MachO::section Sec = O->getSection(Ref);
  1425. section_type = Sec.flags & MachO::SECTION_TYPE;
  1426. }
  1427. StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName());
  1428. const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
  1429. switch (section_type) {
  1430. case MachO::S_CSTRING_LITERALS:
  1431. for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
  1432. i++) {
  1433. DumpCstringChar(Contents[i]);
  1434. }
  1435. outs() << "\n";
  1436. break;
  1437. case MachO::S_4BYTE_LITERALS:
  1438. float f;
  1439. memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
  1440. uint32_t l;
  1441. memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
  1442. if (O->isLittleEndian() != sys::IsLittleEndianHost) {
  1443. sys::swapByteOrder(f);
  1444. sys::swapByteOrder(l);
  1445. }
  1446. DumpLiteral4(l, f);
  1447. break;
  1448. case MachO::S_8BYTE_LITERALS: {
  1449. double d;
  1450. memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
  1451. uint32_t l0, l1;
  1452. memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
  1453. memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
  1454. sizeof(uint32_t));
  1455. if (O->isLittleEndian() != sys::IsLittleEndianHost) {
  1456. sys::swapByteOrder(f);
  1457. sys::swapByteOrder(l0);
  1458. sys::swapByteOrder(l1);
  1459. }
  1460. DumpLiteral8(O, l0, l1, d);
  1461. break;
  1462. }
  1463. case MachO::S_16BYTE_LITERALS: {
  1464. uint32_t l0, l1, l2, l3;
  1465. memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
  1466. memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
  1467. sizeof(uint32_t));
  1468. memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
  1469. sizeof(uint32_t));
  1470. memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
  1471. sizeof(uint32_t));
  1472. if (O->isLittleEndian() != sys::IsLittleEndianHost) {
  1473. sys::swapByteOrder(l0);
  1474. sys::swapByteOrder(l1);
  1475. sys::swapByteOrder(l2);
  1476. sys::swapByteOrder(l3);
  1477. }
  1478. DumpLiteral16(l0, l1, l2, l3);
  1479. break;
  1480. }
  1481. }
  1482. }
  1483. }
  1484. static void DumpInitTermPointerSection(MachOObjectFile *O,
  1485. const SectionRef &Section,
  1486. const char *sect,
  1487. uint32_t sect_size, uint64_t sect_addr,
  1488. SymbolAddressMap *AddrMap,
  1489. bool verbose) {
  1490. uint32_t stride;
  1491. stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
  1492. // Collect the external relocation symbols for the pointers.
  1493. std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
  1494. for (const RelocationRef &Reloc : Section.relocations()) {
  1495. DataRefImpl Rel;
  1496. MachO::any_relocation_info RE;
  1497. bool isExtern = false;
  1498. Rel = Reloc.getRawDataRefImpl();
  1499. RE = O->getRelocation(Rel);
  1500. isExtern = O->getPlainRelocationExternal(RE);
  1501. if (isExtern) {
  1502. uint64_t RelocOffset = Reloc.getOffset();
  1503. symbol_iterator RelocSym = Reloc.getSymbol();
  1504. Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
  1505. }
  1506. }
  1507. array_pod_sort(Relocs.begin(), Relocs.end());
  1508. for (uint32_t i = 0; i < sect_size; i += stride) {
  1509. const char *SymbolName = nullptr;
  1510. uint64_t p;
  1511. if (O->is64Bit()) {
  1512. outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
  1513. uint64_t pointer_value;
  1514. memcpy(&pointer_value, sect + i, stride);
  1515. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1516. sys::swapByteOrder(pointer_value);
  1517. outs() << format("0x%016" PRIx64, pointer_value);
  1518. p = pointer_value;
  1519. } else {
  1520. outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
  1521. uint32_t pointer_value;
  1522. memcpy(&pointer_value, sect + i, stride);
  1523. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1524. sys::swapByteOrder(pointer_value);
  1525. outs() << format("0x%08" PRIx32, pointer_value);
  1526. p = pointer_value;
  1527. }
  1528. if (verbose) {
  1529. // First look for an external relocation entry for this pointer.
  1530. auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
  1531. return P.first == i;
  1532. });
  1533. if (Reloc != Relocs.end()) {
  1534. symbol_iterator RelocSym = Reloc->second;
  1535. outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
  1536. } else {
  1537. SymbolName = GuessSymbolName(p, AddrMap);
  1538. if (SymbolName)
  1539. outs() << " " << SymbolName;
  1540. }
  1541. }
  1542. outs() << "\n";
  1543. }
  1544. }
  1545. static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
  1546. uint32_t size, uint64_t addr) {
  1547. uint32_t cputype = O->getHeader().cputype;
  1548. if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
  1549. uint32_t j;
  1550. for (uint32_t i = 0; i < size; i += j, addr += j) {
  1551. if (O->is64Bit())
  1552. outs() << format("%016" PRIx64, addr) << "\t";
  1553. else
  1554. outs() << format("%08" PRIx64, addr) << "\t";
  1555. for (j = 0; j < 16 && i + j < size; j++) {
  1556. uint8_t byte_word = *(sect + i + j);
  1557. outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
  1558. }
  1559. outs() << "\n";
  1560. }
  1561. } else {
  1562. uint32_t j;
  1563. for (uint32_t i = 0; i < size; i += j, addr += j) {
  1564. if (O->is64Bit())
  1565. outs() << format("%016" PRIx64, addr) << "\t";
  1566. else
  1567. outs() << format("%08" PRIx64, addr) << "\t";
  1568. for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
  1569. j += sizeof(int32_t)) {
  1570. if (i + j + sizeof(int32_t) <= size) {
  1571. uint32_t long_word;
  1572. memcpy(&long_word, sect + i + j, sizeof(int32_t));
  1573. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1574. sys::swapByteOrder(long_word);
  1575. outs() << format("%08" PRIx32, long_word) << " ";
  1576. } else {
  1577. for (uint32_t k = 0; i + j + k < size; k++) {
  1578. uint8_t byte_word = *(sect + i + j + k);
  1579. outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
  1580. }
  1581. }
  1582. }
  1583. outs() << "\n";
  1584. }
  1585. }
  1586. }
  1587. static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
  1588. StringRef DisSegName, StringRef DisSectName);
  1589. static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
  1590. uint32_t size, uint32_t addr);
  1591. #ifdef LLVM_HAVE_LIBXAR
  1592. static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
  1593. uint32_t size, bool verbose,
  1594. bool PrintXarHeader, bool PrintXarFileHeaders,
  1595. std::string XarMemberName);
  1596. #endif // defined(LLVM_HAVE_LIBXAR)
  1597. static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
  1598. bool verbose) {
  1599. SymbolAddressMap AddrMap;
  1600. if (verbose)
  1601. CreateSymbolAddressMap(O, &AddrMap);
  1602. for (unsigned i = 0; i < FilterSections.size(); ++i) {
  1603. StringRef DumpSection = FilterSections[i];
  1604. std::pair<StringRef, StringRef> DumpSegSectName;
  1605. DumpSegSectName = DumpSection.split(',');
  1606. StringRef DumpSegName, DumpSectName;
  1607. if (!DumpSegSectName.second.empty()) {
  1608. DumpSegName = DumpSegSectName.first;
  1609. DumpSectName = DumpSegSectName.second;
  1610. } else {
  1611. DumpSegName = "";
  1612. DumpSectName = DumpSegSectName.first;
  1613. }
  1614. for (const SectionRef &Section : O->sections()) {
  1615. StringRef SectName;
  1616. Expected<StringRef> SecNameOrErr = Section.getName();
  1617. if (SecNameOrErr)
  1618. SectName = *SecNameOrErr;
  1619. else
  1620. consumeError(SecNameOrErr.takeError());
  1621. if (!DumpSection.empty())
  1622. FoundSectionSet.insert(DumpSection);
  1623. DataRefImpl Ref = Section.getRawDataRefImpl();
  1624. StringRef SegName = O->getSectionFinalSegmentName(Ref);
  1625. if ((DumpSegName.empty() || SegName == DumpSegName) &&
  1626. (SectName == DumpSectName)) {
  1627. uint32_t section_flags;
  1628. if (O->is64Bit()) {
  1629. const MachO::section_64 Sec = O->getSection64(Ref);
  1630. section_flags = Sec.flags;
  1631. } else {
  1632. const MachO::section Sec = O->getSection(Ref);
  1633. section_flags = Sec.flags;
  1634. }
  1635. uint32_t section_type = section_flags & MachO::SECTION_TYPE;
  1636. StringRef BytesStr =
  1637. unwrapOrError(Section.getContents(), O->getFileName());
  1638. const char *sect = reinterpret_cast<const char *>(BytesStr.data());
  1639. uint32_t sect_size = BytesStr.size();
  1640. uint64_t sect_addr = Section.getAddress();
  1641. if (LeadingHeaders)
  1642. outs() << "Contents of (" << SegName << "," << SectName
  1643. << ") section\n";
  1644. if (verbose) {
  1645. if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
  1646. (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
  1647. DisassembleMachO(Filename, O, SegName, SectName);
  1648. continue;
  1649. }
  1650. if (SegName == "__TEXT" && SectName == "__info_plist") {
  1651. outs() << sect;
  1652. continue;
  1653. }
  1654. if (SegName == "__OBJC" && SectName == "__protocol") {
  1655. DumpProtocolSection(O, sect, sect_size, sect_addr);
  1656. continue;
  1657. }
  1658. #ifdef LLVM_HAVE_LIBXAR
  1659. if (SegName == "__LLVM" && SectName == "__bundle") {
  1660. DumpBitcodeSection(O, sect, sect_size, verbose, SymbolicOperands,
  1661. ArchiveHeaders, "");
  1662. continue;
  1663. }
  1664. #endif // defined(LLVM_HAVE_LIBXAR)
  1665. switch (section_type) {
  1666. case MachO::S_REGULAR:
  1667. DumpRawSectionContents(O, sect, sect_size, sect_addr);
  1668. break;
  1669. case MachO::S_ZEROFILL:
  1670. outs() << "zerofill section and has no contents in the file\n";
  1671. break;
  1672. case MachO::S_CSTRING_LITERALS:
  1673. DumpCstringSection(O, sect, sect_size, sect_addr, LeadingAddr);
  1674. break;
  1675. case MachO::S_4BYTE_LITERALS:
  1676. DumpLiteral4Section(O, sect, sect_size, sect_addr, LeadingAddr);
  1677. break;
  1678. case MachO::S_8BYTE_LITERALS:
  1679. DumpLiteral8Section(O, sect, sect_size, sect_addr, LeadingAddr);
  1680. break;
  1681. case MachO::S_16BYTE_LITERALS:
  1682. DumpLiteral16Section(O, sect, sect_size, sect_addr, LeadingAddr);
  1683. break;
  1684. case MachO::S_LITERAL_POINTERS:
  1685. DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
  1686. LeadingAddr);
  1687. break;
  1688. case MachO::S_MOD_INIT_FUNC_POINTERS:
  1689. case MachO::S_MOD_TERM_FUNC_POINTERS:
  1690. DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
  1691. &AddrMap, verbose);
  1692. break;
  1693. default:
  1694. outs() << "Unknown section type ("
  1695. << format("0x%08" PRIx32, section_type) << ")\n";
  1696. DumpRawSectionContents(O, sect, sect_size, sect_addr);
  1697. break;
  1698. }
  1699. } else {
  1700. if (section_type == MachO::S_ZEROFILL)
  1701. outs() << "zerofill section and has no contents in the file\n";
  1702. else
  1703. DumpRawSectionContents(O, sect, sect_size, sect_addr);
  1704. }
  1705. }
  1706. }
  1707. }
  1708. }
  1709. static void DumpInfoPlistSectionContents(StringRef Filename,
  1710. MachOObjectFile *O) {
  1711. for (const SectionRef &Section : O->sections()) {
  1712. StringRef SectName;
  1713. Expected<StringRef> SecNameOrErr = Section.getName();
  1714. if (SecNameOrErr)
  1715. SectName = *SecNameOrErr;
  1716. else
  1717. consumeError(SecNameOrErr.takeError());
  1718. DataRefImpl Ref = Section.getRawDataRefImpl();
  1719. StringRef SegName = O->getSectionFinalSegmentName(Ref);
  1720. if (SegName == "__TEXT" && SectName == "__info_plist") {
  1721. if (LeadingHeaders)
  1722. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  1723. StringRef BytesStr =
  1724. unwrapOrError(Section.getContents(), O->getFileName());
  1725. const char *sect = reinterpret_cast<const char *>(BytesStr.data());
  1726. outs() << format("%.*s", BytesStr.size(), sect) << "\n";
  1727. return;
  1728. }
  1729. }
  1730. }
  1731. // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
  1732. // and if it is and there is a list of architecture flags is specified then
  1733. // check to make sure this Mach-O file is one of those architectures or all
  1734. // architectures were specified. If not then an error is generated and this
  1735. // routine returns false. Else it returns true.
  1736. static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
  1737. auto *MachO = dyn_cast<MachOObjectFile>(O);
  1738. if (!MachO || ArchAll || ArchFlags.empty())
  1739. return true;
  1740. MachO::mach_header H;
  1741. MachO::mach_header_64 H_64;
  1742. Triple T;
  1743. const char *McpuDefault, *ArchFlag;
  1744. if (MachO->is64Bit()) {
  1745. H_64 = MachO->MachOObjectFile::getHeader64();
  1746. T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
  1747. &McpuDefault, &ArchFlag);
  1748. } else {
  1749. H = MachO->MachOObjectFile::getHeader();
  1750. T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
  1751. &McpuDefault, &ArchFlag);
  1752. }
  1753. const std::string ArchFlagName(ArchFlag);
  1754. if (!llvm::is_contained(ArchFlags, ArchFlagName)) {
  1755. WithColor::error(errs(), "llvm-objdump")
  1756. << Filename << ": no architecture specified.\n";
  1757. return false;
  1758. }
  1759. return true;
  1760. }
  1761. static void printObjcMetaData(MachOObjectFile *O, bool verbose);
  1762. // ProcessMachO() is passed a single opened Mach-O file, which may be an
  1763. // archive member and or in a slice of a universal file. It prints the
  1764. // the file name and header info and then processes it according to the
  1765. // command line options.
  1766. static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
  1767. StringRef ArchiveMemberName = StringRef(),
  1768. StringRef ArchitectureName = StringRef()) {
  1769. // If we are doing some processing here on the Mach-O file print the header
  1770. // info. And don't print it otherwise like in the case of printing the
  1771. // UniversalHeaders or ArchiveHeaders.
  1772. if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
  1773. Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
  1774. DataInCode || FunctionStarts || LinkOptHints || DylibsUsed || DylibId ||
  1775. Rpaths || ObjcMetaData || (!FilterSections.empty())) {
  1776. if (LeadingHeaders) {
  1777. outs() << Name;
  1778. if (!ArchiveMemberName.empty())
  1779. outs() << '(' << ArchiveMemberName << ')';
  1780. if (!ArchitectureName.empty())
  1781. outs() << " (architecture " << ArchitectureName << ")";
  1782. outs() << ":\n";
  1783. }
  1784. }
  1785. // To use the report_error() form with an ArchiveName and FileName set
  1786. // these up based on what is passed for Name and ArchiveMemberName.
  1787. StringRef ArchiveName;
  1788. StringRef FileName;
  1789. if (!ArchiveMemberName.empty()) {
  1790. ArchiveName = Name;
  1791. FileName = ArchiveMemberName;
  1792. } else {
  1793. ArchiveName = StringRef();
  1794. FileName = Name;
  1795. }
  1796. // If we need the symbol table to do the operation then check it here to
  1797. // produce a good error message as to where the Mach-O file comes from in
  1798. // the error message.
  1799. if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
  1800. if (Error Err = MachOOF->checkSymbolTable())
  1801. reportError(std::move(Err), FileName, ArchiveName, ArchitectureName);
  1802. if (DisassembleAll) {
  1803. for (const SectionRef &Section : MachOOF->sections()) {
  1804. StringRef SectName;
  1805. if (Expected<StringRef> NameOrErr = Section.getName())
  1806. SectName = *NameOrErr;
  1807. else
  1808. consumeError(NameOrErr.takeError());
  1809. if (SectName.equals("__text")) {
  1810. DataRefImpl Ref = Section.getRawDataRefImpl();
  1811. StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
  1812. DisassembleMachO(FileName, MachOOF, SegName, SectName);
  1813. }
  1814. }
  1815. }
  1816. else if (Disassemble) {
  1817. if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
  1818. MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
  1819. DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
  1820. else
  1821. DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
  1822. }
  1823. if (IndirectSymbols)
  1824. PrintIndirectSymbols(MachOOF, Verbose);
  1825. if (DataInCode)
  1826. PrintDataInCodeTable(MachOOF, Verbose);
  1827. if (FunctionStarts)
  1828. PrintFunctionStarts(MachOOF);
  1829. if (LinkOptHints)
  1830. PrintLinkOptHints(MachOOF);
  1831. if (Relocations)
  1832. PrintRelocations(MachOOF, Verbose);
  1833. if (SectionHeaders)
  1834. printSectionHeaders(MachOOF);
  1835. if (SectionContents)
  1836. printSectionContents(MachOOF);
  1837. if (!FilterSections.empty())
  1838. DumpSectionContents(FileName, MachOOF, Verbose);
  1839. if (InfoPlist)
  1840. DumpInfoPlistSectionContents(FileName, MachOOF);
  1841. if (DylibsUsed)
  1842. PrintDylibs(MachOOF, false);
  1843. if (DylibId)
  1844. PrintDylibs(MachOOF, true);
  1845. if (SymbolTable)
  1846. printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
  1847. if (UnwindInfo)
  1848. printMachOUnwindInfo(MachOOF);
  1849. if (PrivateHeaders) {
  1850. printMachOFileHeader(MachOOF);
  1851. printMachOLoadCommands(MachOOF);
  1852. }
  1853. if (FirstPrivateHeader)
  1854. printMachOFileHeader(MachOOF);
  1855. if (ObjcMetaData)
  1856. printObjcMetaData(MachOOF, Verbose);
  1857. if (ExportsTrie)
  1858. printExportsTrie(MachOOF);
  1859. if (Rebase)
  1860. printRebaseTable(MachOOF);
  1861. if (Rpaths)
  1862. printRpaths(MachOOF);
  1863. if (Bind)
  1864. printBindTable(MachOOF);
  1865. if (LazyBind)
  1866. printLazyBindTable(MachOOF);
  1867. if (WeakBind)
  1868. printWeakBindTable(MachOOF);
  1869. if (DwarfDumpType != DIDT_Null) {
  1870. std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
  1871. // Dump the complete DWARF structure.
  1872. DIDumpOptions DumpOpts;
  1873. DumpOpts.DumpType = DwarfDumpType;
  1874. DICtx->dump(outs(), DumpOpts);
  1875. }
  1876. }
  1877. // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
  1878. static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
  1879. outs() << " cputype (" << cputype << ")\n";
  1880. outs() << " cpusubtype (" << cpusubtype << ")\n";
  1881. }
  1882. // printCPUType() helps print_fat_headers by printing the cputype and
  1883. // pusubtype (symbolically for the one's it knows about).
  1884. static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
  1885. switch (cputype) {
  1886. case MachO::CPU_TYPE_I386:
  1887. switch (cpusubtype) {
  1888. case MachO::CPU_SUBTYPE_I386_ALL:
  1889. outs() << " cputype CPU_TYPE_I386\n";
  1890. outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
  1891. break;
  1892. default:
  1893. printUnknownCPUType(cputype, cpusubtype);
  1894. break;
  1895. }
  1896. break;
  1897. case MachO::CPU_TYPE_X86_64:
  1898. switch (cpusubtype) {
  1899. case MachO::CPU_SUBTYPE_X86_64_ALL:
  1900. outs() << " cputype CPU_TYPE_X86_64\n";
  1901. outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
  1902. break;
  1903. case MachO::CPU_SUBTYPE_X86_64_H:
  1904. outs() << " cputype CPU_TYPE_X86_64\n";
  1905. outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
  1906. break;
  1907. default:
  1908. printUnknownCPUType(cputype, cpusubtype);
  1909. break;
  1910. }
  1911. break;
  1912. case MachO::CPU_TYPE_ARM:
  1913. switch (cpusubtype) {
  1914. case MachO::CPU_SUBTYPE_ARM_ALL:
  1915. outs() << " cputype CPU_TYPE_ARM\n";
  1916. outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
  1917. break;
  1918. case MachO::CPU_SUBTYPE_ARM_V4T:
  1919. outs() << " cputype CPU_TYPE_ARM\n";
  1920. outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
  1921. break;
  1922. case MachO::CPU_SUBTYPE_ARM_V5TEJ:
  1923. outs() << " cputype CPU_TYPE_ARM\n";
  1924. outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
  1925. break;
  1926. case MachO::CPU_SUBTYPE_ARM_XSCALE:
  1927. outs() << " cputype CPU_TYPE_ARM\n";
  1928. outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
  1929. break;
  1930. case MachO::CPU_SUBTYPE_ARM_V6:
  1931. outs() << " cputype CPU_TYPE_ARM\n";
  1932. outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
  1933. break;
  1934. case MachO::CPU_SUBTYPE_ARM_V6M:
  1935. outs() << " cputype CPU_TYPE_ARM\n";
  1936. outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
  1937. break;
  1938. case MachO::CPU_SUBTYPE_ARM_V7:
  1939. outs() << " cputype CPU_TYPE_ARM\n";
  1940. outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
  1941. break;
  1942. case MachO::CPU_SUBTYPE_ARM_V7EM:
  1943. outs() << " cputype CPU_TYPE_ARM\n";
  1944. outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
  1945. break;
  1946. case MachO::CPU_SUBTYPE_ARM_V7K:
  1947. outs() << " cputype CPU_TYPE_ARM\n";
  1948. outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
  1949. break;
  1950. case MachO::CPU_SUBTYPE_ARM_V7M:
  1951. outs() << " cputype CPU_TYPE_ARM\n";
  1952. outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
  1953. break;
  1954. case MachO::CPU_SUBTYPE_ARM_V7S:
  1955. outs() << " cputype CPU_TYPE_ARM\n";
  1956. outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
  1957. break;
  1958. default:
  1959. printUnknownCPUType(cputype, cpusubtype);
  1960. break;
  1961. }
  1962. break;
  1963. case MachO::CPU_TYPE_ARM64:
  1964. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  1965. case MachO::CPU_SUBTYPE_ARM64_ALL:
  1966. outs() << " cputype CPU_TYPE_ARM64\n";
  1967. outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
  1968. break;
  1969. case MachO::CPU_SUBTYPE_ARM64_V8:
  1970. outs() << " cputype CPU_TYPE_ARM64\n";
  1971. outs() << " cpusubtype CPU_SUBTYPE_ARM64_V8\n";
  1972. break;
  1973. case MachO::CPU_SUBTYPE_ARM64E:
  1974. outs() << " cputype CPU_TYPE_ARM64\n";
  1975. outs() << " cpusubtype CPU_SUBTYPE_ARM64E\n";
  1976. break;
  1977. default:
  1978. printUnknownCPUType(cputype, cpusubtype);
  1979. break;
  1980. }
  1981. break;
  1982. case MachO::CPU_TYPE_ARM64_32:
  1983. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  1984. case MachO::CPU_SUBTYPE_ARM64_32_V8:
  1985. outs() << " cputype CPU_TYPE_ARM64_32\n";
  1986. outs() << " cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
  1987. break;
  1988. default:
  1989. printUnknownCPUType(cputype, cpusubtype);
  1990. break;
  1991. }
  1992. break;
  1993. default:
  1994. printUnknownCPUType(cputype, cpusubtype);
  1995. break;
  1996. }
  1997. }
  1998. static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
  1999. bool verbose) {
  2000. outs() << "Fat headers\n";
  2001. if (verbose) {
  2002. if (UB->getMagic() == MachO::FAT_MAGIC)
  2003. outs() << "fat_magic FAT_MAGIC\n";
  2004. else // UB->getMagic() == MachO::FAT_MAGIC_64
  2005. outs() << "fat_magic FAT_MAGIC_64\n";
  2006. } else
  2007. outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
  2008. uint32_t nfat_arch = UB->getNumberOfObjects();
  2009. StringRef Buf = UB->getData();
  2010. uint64_t size = Buf.size();
  2011. uint64_t big_size = sizeof(struct MachO::fat_header) +
  2012. nfat_arch * sizeof(struct MachO::fat_arch);
  2013. outs() << "nfat_arch " << UB->getNumberOfObjects();
  2014. if (nfat_arch == 0)
  2015. outs() << " (malformed, contains zero architecture types)\n";
  2016. else if (big_size > size)
  2017. outs() << " (malformed, architectures past end of file)\n";
  2018. else
  2019. outs() << "\n";
  2020. for (uint32_t i = 0; i < nfat_arch; ++i) {
  2021. MachOUniversalBinary::ObjectForArch OFA(UB, i);
  2022. uint32_t cputype = OFA.getCPUType();
  2023. uint32_t cpusubtype = OFA.getCPUSubType();
  2024. outs() << "architecture ";
  2025. for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
  2026. MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
  2027. uint32_t other_cputype = other_OFA.getCPUType();
  2028. uint32_t other_cpusubtype = other_OFA.getCPUSubType();
  2029. if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
  2030. (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
  2031. (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
  2032. outs() << "(illegal duplicate architecture) ";
  2033. break;
  2034. }
  2035. }
  2036. if (verbose) {
  2037. outs() << OFA.getArchFlagName() << "\n";
  2038. printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  2039. } else {
  2040. outs() << i << "\n";
  2041. outs() << " cputype " << cputype << "\n";
  2042. outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
  2043. << "\n";
  2044. }
  2045. if (verbose &&
  2046. (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
  2047. outs() << " capabilities CPU_SUBTYPE_LIB64\n";
  2048. else
  2049. outs() << " capabilities "
  2050. << format("0x%" PRIx32,
  2051. (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
  2052. outs() << " offset " << OFA.getOffset();
  2053. if (OFA.getOffset() > size)
  2054. outs() << " (past end of file)";
  2055. if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0)
  2056. outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
  2057. outs() << "\n";
  2058. outs() << " size " << OFA.getSize();
  2059. big_size = OFA.getOffset() + OFA.getSize();
  2060. if (big_size > size)
  2061. outs() << " (past end of file)";
  2062. outs() << "\n";
  2063. outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
  2064. << ")\n";
  2065. }
  2066. }
  2067. static void printArchiveChild(StringRef Filename, const Archive::Child &C,
  2068. size_t ChildIndex, bool verbose,
  2069. bool print_offset,
  2070. StringRef ArchitectureName = StringRef()) {
  2071. if (print_offset)
  2072. outs() << C.getChildOffset() << "\t";
  2073. sys::fs::perms Mode =
  2074. unwrapOrError(C.getAccessMode(), getFileNameForError(C, ChildIndex),
  2075. Filename, ArchitectureName);
  2076. if (verbose) {
  2077. // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
  2078. // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
  2079. outs() << "-";
  2080. outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
  2081. outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
  2082. outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
  2083. outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
  2084. outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
  2085. outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
  2086. outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
  2087. outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
  2088. outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
  2089. } else {
  2090. outs() << format("0%o ", Mode);
  2091. }
  2092. outs() << format("%3d/%-3d %5" PRId64 " ",
  2093. unwrapOrError(C.getUID(), getFileNameForError(C, ChildIndex),
  2094. Filename, ArchitectureName),
  2095. unwrapOrError(C.getGID(), getFileNameForError(C, ChildIndex),
  2096. Filename, ArchitectureName),
  2097. unwrapOrError(C.getRawSize(),
  2098. getFileNameForError(C, ChildIndex), Filename,
  2099. ArchitectureName));
  2100. StringRef RawLastModified = C.getRawLastModified();
  2101. if (verbose) {
  2102. unsigned Seconds;
  2103. if (RawLastModified.getAsInteger(10, Seconds))
  2104. outs() << "(date: \"" << RawLastModified
  2105. << "\" contains non-decimal chars) ";
  2106. else {
  2107. // Since cime(3) returns a 26 character string of the form:
  2108. // "Sun Sep 16 01:03:52 1973\n\0"
  2109. // just print 24 characters.
  2110. time_t t = Seconds;
  2111. outs() << format("%.24s ", ctime(&t));
  2112. }
  2113. } else {
  2114. outs() << RawLastModified << " ";
  2115. }
  2116. if (verbose) {
  2117. Expected<StringRef> NameOrErr = C.getName();
  2118. if (!NameOrErr) {
  2119. consumeError(NameOrErr.takeError());
  2120. outs() << unwrapOrError(C.getRawName(),
  2121. getFileNameForError(C, ChildIndex), Filename,
  2122. ArchitectureName)
  2123. << "\n";
  2124. } else {
  2125. StringRef Name = NameOrErr.get();
  2126. outs() << Name << "\n";
  2127. }
  2128. } else {
  2129. outs() << unwrapOrError(C.getRawName(), getFileNameForError(C, ChildIndex),
  2130. Filename, ArchitectureName)
  2131. << "\n";
  2132. }
  2133. }
  2134. static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
  2135. bool print_offset,
  2136. StringRef ArchitectureName = StringRef()) {
  2137. Error Err = Error::success();
  2138. size_t I = 0;
  2139. for (const auto &C : A->children(Err, false))
  2140. printArchiveChild(Filename, C, I++, verbose, print_offset,
  2141. ArchitectureName);
  2142. if (Err)
  2143. reportError(std::move(Err), Filename, "", ArchitectureName);
  2144. }
  2145. static bool ValidateArchFlags() {
  2146. // Check for -arch all and verifiy the -arch flags are valid.
  2147. for (unsigned i = 0; i < ArchFlags.size(); ++i) {
  2148. if (ArchFlags[i] == "all") {
  2149. ArchAll = true;
  2150. } else {
  2151. if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
  2152. WithColor::error(errs(), "llvm-objdump")
  2153. << "unknown architecture named '" + ArchFlags[i] +
  2154. "'for the -arch option\n";
  2155. return false;
  2156. }
  2157. }
  2158. }
  2159. return true;
  2160. }
  2161. // ParseInputMachO() parses the named Mach-O file in Filename and handles the
  2162. // -arch flags selecting just those slices as specified by them and also parses
  2163. // archive files. Then for each individual Mach-O file ProcessMachO() is
  2164. // called to process the file based on the command line options.
  2165. void objdump::parseInputMachO(StringRef Filename) {
  2166. if (!ValidateArchFlags())
  2167. return;
  2168. // Attempt to open the binary.
  2169. Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
  2170. if (!BinaryOrErr) {
  2171. if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
  2172. reportError(std::move(E), Filename);
  2173. else
  2174. outs() << Filename << ": is not an object file\n";
  2175. return;
  2176. }
  2177. Binary &Bin = *BinaryOrErr.get().getBinary();
  2178. if (Archive *A = dyn_cast<Archive>(&Bin)) {
  2179. outs() << "Archive : " << Filename << "\n";
  2180. if (ArchiveHeaders)
  2181. printArchiveHeaders(Filename, A, Verbose, ArchiveMemberOffsets);
  2182. Error Err = Error::success();
  2183. unsigned I = -1;
  2184. for (auto &C : A->children(Err)) {
  2185. ++I;
  2186. Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
  2187. if (!ChildOrErr) {
  2188. if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
  2189. reportError(std::move(E), getFileNameForError(C, I), Filename);
  2190. continue;
  2191. }
  2192. if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
  2193. if (!checkMachOAndArchFlags(O, Filename))
  2194. return;
  2195. ProcessMachO(Filename, O, O->getFileName());
  2196. }
  2197. }
  2198. if (Err)
  2199. reportError(std::move(Err), Filename);
  2200. return;
  2201. }
  2202. if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
  2203. parseInputMachO(UB);
  2204. return;
  2205. }
  2206. if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
  2207. if (!checkMachOAndArchFlags(O, Filename))
  2208. return;
  2209. if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
  2210. ProcessMachO(Filename, MachOOF);
  2211. else
  2212. WithColor::error(errs(), "llvm-objdump")
  2213. << Filename << "': "
  2214. << "object is not a Mach-O file type.\n";
  2215. return;
  2216. }
  2217. llvm_unreachable("Input object can't be invalid at this point");
  2218. }
  2219. void objdump::parseInputMachO(MachOUniversalBinary *UB) {
  2220. if (!ValidateArchFlags())
  2221. return;
  2222. auto Filename = UB->getFileName();
  2223. if (UniversalHeaders)
  2224. printMachOUniversalHeaders(UB, Verbose);
  2225. // If we have a list of architecture flags specified dump only those.
  2226. if (!ArchAll && !ArchFlags.empty()) {
  2227. // Look for a slice in the universal binary that matches each ArchFlag.
  2228. bool ArchFound;
  2229. for (unsigned i = 0; i < ArchFlags.size(); ++i) {
  2230. ArchFound = false;
  2231. for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
  2232. E = UB->end_objects();
  2233. I != E; ++I) {
  2234. if (ArchFlags[i] == I->getArchFlagName()) {
  2235. ArchFound = true;
  2236. Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
  2237. I->getAsObjectFile();
  2238. std::string ArchitectureName;
  2239. if (ArchFlags.size() > 1)
  2240. ArchitectureName = I->getArchFlagName();
  2241. if (ObjOrErr) {
  2242. ObjectFile &O = *ObjOrErr.get();
  2243. if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
  2244. ProcessMachO(Filename, MachOOF, "", ArchitectureName);
  2245. } else if (Error E = isNotObjectErrorInvalidFileType(
  2246. ObjOrErr.takeError())) {
  2247. reportError(std::move(E), "", Filename, ArchitectureName);
  2248. continue;
  2249. } else if (Expected<std::unique_ptr<Archive>> AOrErr =
  2250. I->getAsArchive()) {
  2251. std::unique_ptr<Archive> &A = *AOrErr;
  2252. outs() << "Archive : " << Filename;
  2253. if (!ArchitectureName.empty())
  2254. outs() << " (architecture " << ArchitectureName << ")";
  2255. outs() << "\n";
  2256. if (ArchiveHeaders)
  2257. printArchiveHeaders(Filename, A.get(), Verbose,
  2258. ArchiveMemberOffsets, ArchitectureName);
  2259. Error Err = Error::success();
  2260. unsigned I = -1;
  2261. for (auto &C : A->children(Err)) {
  2262. ++I;
  2263. Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
  2264. if (!ChildOrErr) {
  2265. if (Error E =
  2266. isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
  2267. reportError(std::move(E), getFileNameForError(C, I), Filename,
  2268. ArchitectureName);
  2269. continue;
  2270. }
  2271. if (MachOObjectFile *O =
  2272. dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
  2273. ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
  2274. }
  2275. if (Err)
  2276. reportError(std::move(Err), Filename);
  2277. } else {
  2278. consumeError(AOrErr.takeError());
  2279. reportError(Filename,
  2280. "Mach-O universal file for architecture " +
  2281. StringRef(I->getArchFlagName()) +
  2282. " is not a Mach-O file or an archive file");
  2283. }
  2284. }
  2285. }
  2286. if (!ArchFound) {
  2287. WithColor::error(errs(), "llvm-objdump")
  2288. << "file: " + Filename + " does not contain "
  2289. << "architecture: " + ArchFlags[i] + "\n";
  2290. return;
  2291. }
  2292. }
  2293. return;
  2294. }
  2295. // No architecture flags were specified so if this contains a slice that
  2296. // matches the host architecture dump only that.
  2297. if (!ArchAll) {
  2298. for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
  2299. E = UB->end_objects();
  2300. I != E; ++I) {
  2301. if (MachOObjectFile::getHostArch().getArchName() ==
  2302. I->getArchFlagName()) {
  2303. Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
  2304. std::string ArchiveName;
  2305. ArchiveName.clear();
  2306. if (ObjOrErr) {
  2307. ObjectFile &O = *ObjOrErr.get();
  2308. if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
  2309. ProcessMachO(Filename, MachOOF);
  2310. } else if (Error E =
  2311. isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
  2312. reportError(std::move(E), Filename);
  2313. } else if (Expected<std::unique_ptr<Archive>> AOrErr =
  2314. I->getAsArchive()) {
  2315. std::unique_ptr<Archive> &A = *AOrErr;
  2316. outs() << "Archive : " << Filename << "\n";
  2317. if (ArchiveHeaders)
  2318. printArchiveHeaders(Filename, A.get(), Verbose,
  2319. ArchiveMemberOffsets);
  2320. Error Err = Error::success();
  2321. unsigned I = -1;
  2322. for (auto &C : A->children(Err)) {
  2323. ++I;
  2324. Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
  2325. if (!ChildOrErr) {
  2326. if (Error E =
  2327. isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
  2328. reportError(std::move(E), getFileNameForError(C, I), Filename);
  2329. continue;
  2330. }
  2331. if (MachOObjectFile *O =
  2332. dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
  2333. ProcessMachO(Filename, O, O->getFileName());
  2334. }
  2335. if (Err)
  2336. reportError(std::move(Err), Filename);
  2337. } else {
  2338. consumeError(AOrErr.takeError());
  2339. reportError(Filename, "Mach-O universal file for architecture " +
  2340. StringRef(I->getArchFlagName()) +
  2341. " is not a Mach-O file or an archive file");
  2342. }
  2343. return;
  2344. }
  2345. }
  2346. }
  2347. // Either all architectures have been specified or none have been specified
  2348. // and this does not contain the host architecture so dump all the slices.
  2349. bool moreThanOneArch = UB->getNumberOfObjects() > 1;
  2350. for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
  2351. E = UB->end_objects();
  2352. I != E; ++I) {
  2353. Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
  2354. std::string ArchitectureName;
  2355. if (moreThanOneArch)
  2356. ArchitectureName = I->getArchFlagName();
  2357. if (ObjOrErr) {
  2358. ObjectFile &Obj = *ObjOrErr.get();
  2359. if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
  2360. ProcessMachO(Filename, MachOOF, "", ArchitectureName);
  2361. } else if (Error E =
  2362. isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
  2363. reportError(std::move(E), Filename, "", ArchitectureName);
  2364. } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
  2365. std::unique_ptr<Archive> &A = *AOrErr;
  2366. outs() << "Archive : " << Filename;
  2367. if (!ArchitectureName.empty())
  2368. outs() << " (architecture " << ArchitectureName << ")";
  2369. outs() << "\n";
  2370. if (ArchiveHeaders)
  2371. printArchiveHeaders(Filename, A.get(), Verbose, ArchiveMemberOffsets,
  2372. ArchitectureName);
  2373. Error Err = Error::success();
  2374. unsigned I = -1;
  2375. for (auto &C : A->children(Err)) {
  2376. ++I;
  2377. Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
  2378. if (!ChildOrErr) {
  2379. if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
  2380. reportError(std::move(E), getFileNameForError(C, I), Filename,
  2381. ArchitectureName);
  2382. continue;
  2383. }
  2384. if (MachOObjectFile *O =
  2385. dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
  2386. if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
  2387. ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
  2388. ArchitectureName);
  2389. }
  2390. }
  2391. if (Err)
  2392. reportError(std::move(Err), Filename);
  2393. } else {
  2394. consumeError(AOrErr.takeError());
  2395. reportError(Filename, "Mach-O universal file for architecture " +
  2396. StringRef(I->getArchFlagName()) +
  2397. " is not a Mach-O file or an archive file");
  2398. }
  2399. }
  2400. }
  2401. namespace {
  2402. // The block of info used by the Symbolizer call backs.
  2403. struct DisassembleInfo {
  2404. DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
  2405. std::vector<SectionRef> *Sections, bool verbose)
  2406. : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
  2407. bool verbose;
  2408. MachOObjectFile *O;
  2409. SectionRef S;
  2410. SymbolAddressMap *AddrMap;
  2411. std::vector<SectionRef> *Sections;
  2412. const char *class_name = nullptr;
  2413. const char *selector_name = nullptr;
  2414. std::unique_ptr<char[]> method = nullptr;
  2415. char *demangled_name = nullptr;
  2416. uint64_t adrp_addr = 0;
  2417. uint32_t adrp_inst = 0;
  2418. std::unique_ptr<SymbolAddressMap> bindtable;
  2419. uint32_t depth = 0;
  2420. };
  2421. } // namespace
  2422. // SymbolizerGetOpInfo() is the operand information call back function.
  2423. // This is called to get the symbolic information for operand(s) of an
  2424. // instruction when it is being done. This routine does this from
  2425. // the relocation information, symbol table, etc. That block of information
  2426. // is a pointer to the struct DisassembleInfo that was passed when the
  2427. // disassembler context was created and passed to back to here when
  2428. // called back by the disassembler for instruction operands that could have
  2429. // relocation information. The address of the instruction containing operand is
  2430. // at the Pc parameter. The immediate value the operand has is passed in
  2431. // op_info->Value and is at Offset past the start of the instruction and has a
  2432. // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
  2433. // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
  2434. // names and addends of the symbolic expression to add for the operand. The
  2435. // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
  2436. // information is returned then this function returns 1 else it returns 0.
  2437. static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
  2438. uint64_t Size, int TagType, void *TagBuf) {
  2439. struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
  2440. struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
  2441. uint64_t value = op_info->Value;
  2442. // Make sure all fields returned are zero if we don't set them.
  2443. memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
  2444. op_info->Value = value;
  2445. // If the TagType is not the value 1 which it code knows about or if no
  2446. // verbose symbolic information is wanted then just return 0, indicating no
  2447. // information is being returned.
  2448. if (TagType != 1 || !info->verbose)
  2449. return 0;
  2450. unsigned int Arch = info->O->getArch();
  2451. if (Arch == Triple::x86) {
  2452. if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
  2453. return 0;
  2454. if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
  2455. // TODO:
  2456. // Search the external relocation entries of a fully linked image
  2457. // (if any) for an entry that matches this segment offset.
  2458. // uint32_t seg_offset = (Pc + Offset);
  2459. return 0;
  2460. }
  2461. // In MH_OBJECT filetypes search the section's relocation entries (if any)
  2462. // for an entry for this section offset.
  2463. uint32_t sect_addr = info->S.getAddress();
  2464. uint32_t sect_offset = (Pc + Offset) - sect_addr;
  2465. bool reloc_found = false;
  2466. DataRefImpl Rel;
  2467. MachO::any_relocation_info RE;
  2468. bool isExtern = false;
  2469. SymbolRef Symbol;
  2470. bool r_scattered = false;
  2471. uint32_t r_value, pair_r_value, r_type;
  2472. for (const RelocationRef &Reloc : info->S.relocations()) {
  2473. uint64_t RelocOffset = Reloc.getOffset();
  2474. if (RelocOffset == sect_offset) {
  2475. Rel = Reloc.getRawDataRefImpl();
  2476. RE = info->O->getRelocation(Rel);
  2477. r_type = info->O->getAnyRelocationType(RE);
  2478. r_scattered = info->O->isRelocationScattered(RE);
  2479. if (r_scattered) {
  2480. r_value = info->O->getScatteredRelocationValue(RE);
  2481. if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
  2482. r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
  2483. DataRefImpl RelNext = Rel;
  2484. info->O->moveRelocationNext(RelNext);
  2485. MachO::any_relocation_info RENext;
  2486. RENext = info->O->getRelocation(RelNext);
  2487. if (info->O->isRelocationScattered(RENext))
  2488. pair_r_value = info->O->getScatteredRelocationValue(RENext);
  2489. else
  2490. return 0;
  2491. }
  2492. } else {
  2493. isExtern = info->O->getPlainRelocationExternal(RE);
  2494. if (isExtern) {
  2495. symbol_iterator RelocSym = Reloc.getSymbol();
  2496. Symbol = *RelocSym;
  2497. }
  2498. }
  2499. reloc_found = true;
  2500. break;
  2501. }
  2502. }
  2503. if (reloc_found && isExtern) {
  2504. op_info->AddSymbol.Present = 1;
  2505. op_info->AddSymbol.Name =
  2506. unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
  2507. // For i386 extern relocation entries the value in the instruction is
  2508. // the offset from the symbol, and value is already set in op_info->Value.
  2509. return 1;
  2510. }
  2511. if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
  2512. r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
  2513. const char *add = GuessSymbolName(r_value, info->AddrMap);
  2514. const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
  2515. uint32_t offset = value - (r_value - pair_r_value);
  2516. op_info->AddSymbol.Present = 1;
  2517. if (add != nullptr)
  2518. op_info->AddSymbol.Name = add;
  2519. else
  2520. op_info->AddSymbol.Value = r_value;
  2521. op_info->SubtractSymbol.Present = 1;
  2522. if (sub != nullptr)
  2523. op_info->SubtractSymbol.Name = sub;
  2524. else
  2525. op_info->SubtractSymbol.Value = pair_r_value;
  2526. op_info->Value = offset;
  2527. return 1;
  2528. }
  2529. return 0;
  2530. }
  2531. if (Arch == Triple::x86_64) {
  2532. if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
  2533. return 0;
  2534. // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
  2535. // relocation entries of a linked image (if any) for an entry that matches
  2536. // this segment offset.
  2537. if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
  2538. uint64_t seg_offset = Pc + Offset;
  2539. bool reloc_found = false;
  2540. DataRefImpl Rel;
  2541. MachO::any_relocation_info RE;
  2542. bool isExtern = false;
  2543. SymbolRef Symbol;
  2544. for (const RelocationRef &Reloc : info->O->external_relocations()) {
  2545. uint64_t RelocOffset = Reloc.getOffset();
  2546. if (RelocOffset == seg_offset) {
  2547. Rel = Reloc.getRawDataRefImpl();
  2548. RE = info->O->getRelocation(Rel);
  2549. // external relocation entries should always be external.
  2550. isExtern = info->O->getPlainRelocationExternal(RE);
  2551. if (isExtern) {
  2552. symbol_iterator RelocSym = Reloc.getSymbol();
  2553. Symbol = *RelocSym;
  2554. }
  2555. reloc_found = true;
  2556. break;
  2557. }
  2558. }
  2559. if (reloc_found && isExtern) {
  2560. // The Value passed in will be adjusted by the Pc if the instruction
  2561. // adds the Pc. But for x86_64 external relocation entries the Value
  2562. // is the offset from the external symbol.
  2563. if (info->O->getAnyRelocationPCRel(RE))
  2564. op_info->Value -= Pc + Offset + Size;
  2565. const char *name =
  2566. unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
  2567. op_info->AddSymbol.Present = 1;
  2568. op_info->AddSymbol.Name = name;
  2569. return 1;
  2570. }
  2571. return 0;
  2572. }
  2573. // In MH_OBJECT filetypes search the section's relocation entries (if any)
  2574. // for an entry for this section offset.
  2575. uint64_t sect_addr = info->S.getAddress();
  2576. uint64_t sect_offset = (Pc + Offset) - sect_addr;
  2577. bool reloc_found = false;
  2578. DataRefImpl Rel;
  2579. MachO::any_relocation_info RE;
  2580. bool isExtern = false;
  2581. SymbolRef Symbol;
  2582. for (const RelocationRef &Reloc : info->S.relocations()) {
  2583. uint64_t RelocOffset = Reloc.getOffset();
  2584. if (RelocOffset == sect_offset) {
  2585. Rel = Reloc.getRawDataRefImpl();
  2586. RE = info->O->getRelocation(Rel);
  2587. // NOTE: Scattered relocations don't exist on x86_64.
  2588. isExtern = info->O->getPlainRelocationExternal(RE);
  2589. if (isExtern) {
  2590. symbol_iterator RelocSym = Reloc.getSymbol();
  2591. Symbol = *RelocSym;
  2592. }
  2593. reloc_found = true;
  2594. break;
  2595. }
  2596. }
  2597. if (reloc_found && isExtern) {
  2598. // The Value passed in will be adjusted by the Pc if the instruction
  2599. // adds the Pc. But for x86_64 external relocation entries the Value
  2600. // is the offset from the external symbol.
  2601. if (info->O->getAnyRelocationPCRel(RE))
  2602. op_info->Value -= Pc + Offset + Size;
  2603. const char *name =
  2604. unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
  2605. unsigned Type = info->O->getAnyRelocationType(RE);
  2606. if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
  2607. DataRefImpl RelNext = Rel;
  2608. info->O->moveRelocationNext(RelNext);
  2609. MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
  2610. unsigned TypeNext = info->O->getAnyRelocationType(RENext);
  2611. bool isExternNext = info->O->getPlainRelocationExternal(RENext);
  2612. unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
  2613. if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
  2614. op_info->SubtractSymbol.Present = 1;
  2615. op_info->SubtractSymbol.Name = name;
  2616. symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
  2617. Symbol = *RelocSymNext;
  2618. name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
  2619. }
  2620. }
  2621. // TODO: add the VariantKinds to op_info->VariantKind for relocation types
  2622. // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
  2623. op_info->AddSymbol.Present = 1;
  2624. op_info->AddSymbol.Name = name;
  2625. return 1;
  2626. }
  2627. return 0;
  2628. }
  2629. if (Arch == Triple::arm) {
  2630. if (Offset != 0 || (Size != 4 && Size != 2))
  2631. return 0;
  2632. if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
  2633. // TODO:
  2634. // Search the external relocation entries of a fully linked image
  2635. // (if any) for an entry that matches this segment offset.
  2636. // uint32_t seg_offset = (Pc + Offset);
  2637. return 0;
  2638. }
  2639. // In MH_OBJECT filetypes search the section's relocation entries (if any)
  2640. // for an entry for this section offset.
  2641. uint32_t sect_addr = info->S.getAddress();
  2642. uint32_t sect_offset = (Pc + Offset) - sect_addr;
  2643. DataRefImpl Rel;
  2644. MachO::any_relocation_info RE;
  2645. bool isExtern = false;
  2646. SymbolRef Symbol;
  2647. bool r_scattered = false;
  2648. uint32_t r_value, pair_r_value, r_type, r_length, other_half;
  2649. auto Reloc =
  2650. find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
  2651. uint64_t RelocOffset = Reloc.getOffset();
  2652. return RelocOffset == sect_offset;
  2653. });
  2654. if (Reloc == info->S.relocations().end())
  2655. return 0;
  2656. Rel = Reloc->getRawDataRefImpl();
  2657. RE = info->O->getRelocation(Rel);
  2658. r_length = info->O->getAnyRelocationLength(RE);
  2659. r_scattered = info->O->isRelocationScattered(RE);
  2660. if (r_scattered) {
  2661. r_value = info->O->getScatteredRelocationValue(RE);
  2662. r_type = info->O->getScatteredRelocationType(RE);
  2663. } else {
  2664. r_type = info->O->getAnyRelocationType(RE);
  2665. isExtern = info->O->getPlainRelocationExternal(RE);
  2666. if (isExtern) {
  2667. symbol_iterator RelocSym = Reloc->getSymbol();
  2668. Symbol = *RelocSym;
  2669. }
  2670. }
  2671. if (r_type == MachO::ARM_RELOC_HALF ||
  2672. r_type == MachO::ARM_RELOC_SECTDIFF ||
  2673. r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
  2674. r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
  2675. DataRefImpl RelNext = Rel;
  2676. info->O->moveRelocationNext(RelNext);
  2677. MachO::any_relocation_info RENext;
  2678. RENext = info->O->getRelocation(RelNext);
  2679. other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
  2680. if (info->O->isRelocationScattered(RENext))
  2681. pair_r_value = info->O->getScatteredRelocationValue(RENext);
  2682. }
  2683. if (isExtern) {
  2684. const char *name =
  2685. unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
  2686. op_info->AddSymbol.Present = 1;
  2687. op_info->AddSymbol.Name = name;
  2688. switch (r_type) {
  2689. case MachO::ARM_RELOC_HALF:
  2690. if ((r_length & 0x1) == 1) {
  2691. op_info->Value = value << 16 | other_half;
  2692. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
  2693. } else {
  2694. op_info->Value = other_half << 16 | value;
  2695. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
  2696. }
  2697. break;
  2698. default:
  2699. break;
  2700. }
  2701. return 1;
  2702. }
  2703. // If we have a branch that is not an external relocation entry then
  2704. // return 0 so the code in tryAddingSymbolicOperand() can use the
  2705. // SymbolLookUp call back with the branch target address to look up the
  2706. // symbol and possibility add an annotation for a symbol stub.
  2707. if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
  2708. r_type == MachO::ARM_THUMB_RELOC_BR22))
  2709. return 0;
  2710. uint32_t offset = 0;
  2711. if (r_type == MachO::ARM_RELOC_HALF ||
  2712. r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
  2713. if ((r_length & 0x1) == 1)
  2714. value = value << 16 | other_half;
  2715. else
  2716. value = other_half << 16 | value;
  2717. }
  2718. if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
  2719. r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
  2720. offset = value - r_value;
  2721. value = r_value;
  2722. }
  2723. if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
  2724. if ((r_length & 0x1) == 1)
  2725. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
  2726. else
  2727. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
  2728. const char *add = GuessSymbolName(r_value, info->AddrMap);
  2729. const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
  2730. int32_t offset = value - (r_value - pair_r_value);
  2731. op_info->AddSymbol.Present = 1;
  2732. if (add != nullptr)
  2733. op_info->AddSymbol.Name = add;
  2734. else
  2735. op_info->AddSymbol.Value = r_value;
  2736. op_info->SubtractSymbol.Present = 1;
  2737. if (sub != nullptr)
  2738. op_info->SubtractSymbol.Name = sub;
  2739. else
  2740. op_info->SubtractSymbol.Value = pair_r_value;
  2741. op_info->Value = offset;
  2742. return 1;
  2743. }
  2744. op_info->AddSymbol.Present = 1;
  2745. op_info->Value = offset;
  2746. if (r_type == MachO::ARM_RELOC_HALF) {
  2747. if ((r_length & 0x1) == 1)
  2748. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
  2749. else
  2750. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
  2751. }
  2752. const char *add = GuessSymbolName(value, info->AddrMap);
  2753. if (add != nullptr) {
  2754. op_info->AddSymbol.Name = add;
  2755. return 1;
  2756. }
  2757. op_info->AddSymbol.Value = value;
  2758. return 1;
  2759. }
  2760. if (Arch == Triple::aarch64) {
  2761. if (Offset != 0 || Size != 4)
  2762. return 0;
  2763. if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
  2764. // TODO:
  2765. // Search the external relocation entries of a fully linked image
  2766. // (if any) for an entry that matches this segment offset.
  2767. // uint64_t seg_offset = (Pc + Offset);
  2768. return 0;
  2769. }
  2770. // In MH_OBJECT filetypes search the section's relocation entries (if any)
  2771. // for an entry for this section offset.
  2772. uint64_t sect_addr = info->S.getAddress();
  2773. uint64_t sect_offset = (Pc + Offset) - sect_addr;
  2774. auto Reloc =
  2775. find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
  2776. uint64_t RelocOffset = Reloc.getOffset();
  2777. return RelocOffset == sect_offset;
  2778. });
  2779. if (Reloc == info->S.relocations().end())
  2780. return 0;
  2781. DataRefImpl Rel = Reloc->getRawDataRefImpl();
  2782. MachO::any_relocation_info RE = info->O->getRelocation(Rel);
  2783. uint32_t r_type = info->O->getAnyRelocationType(RE);
  2784. if (r_type == MachO::ARM64_RELOC_ADDEND) {
  2785. DataRefImpl RelNext = Rel;
  2786. info->O->moveRelocationNext(RelNext);
  2787. MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
  2788. if (value == 0) {
  2789. value = info->O->getPlainRelocationSymbolNum(RENext);
  2790. op_info->Value = value;
  2791. }
  2792. }
  2793. // NOTE: Scattered relocations don't exist on arm64.
  2794. if (!info->O->getPlainRelocationExternal(RE))
  2795. return 0;
  2796. const char *name =
  2797. unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
  2798. .data();
  2799. op_info->AddSymbol.Present = 1;
  2800. op_info->AddSymbol.Name = name;
  2801. switch (r_type) {
  2802. case MachO::ARM64_RELOC_PAGE21:
  2803. /* @page */
  2804. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
  2805. break;
  2806. case MachO::ARM64_RELOC_PAGEOFF12:
  2807. /* @pageoff */
  2808. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
  2809. break;
  2810. case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
  2811. /* @gotpage */
  2812. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
  2813. break;
  2814. case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
  2815. /* @gotpageoff */
  2816. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
  2817. break;
  2818. case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
  2819. /* @tvlppage is not implemented in llvm-mc */
  2820. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
  2821. break;
  2822. case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
  2823. /* @tvlppageoff is not implemented in llvm-mc */
  2824. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
  2825. break;
  2826. default:
  2827. case MachO::ARM64_RELOC_BRANCH26:
  2828. op_info->VariantKind = LLVMDisassembler_VariantKind_None;
  2829. break;
  2830. }
  2831. return 1;
  2832. }
  2833. return 0;
  2834. }
  2835. // GuessCstringPointer is passed the address of what might be a pointer to a
  2836. // literal string in a cstring section. If that address is in a cstring section
  2837. // it returns a pointer to that string. Else it returns nullptr.
  2838. static const char *GuessCstringPointer(uint64_t ReferenceValue,
  2839. struct DisassembleInfo *info) {
  2840. for (const auto &Load : info->O->load_commands()) {
  2841. if (Load.C.cmd == MachO::LC_SEGMENT_64) {
  2842. MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
  2843. for (unsigned J = 0; J < Seg.nsects; ++J) {
  2844. MachO::section_64 Sec = info->O->getSection64(Load, J);
  2845. uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
  2846. if (section_type == MachO::S_CSTRING_LITERALS &&
  2847. ReferenceValue >= Sec.addr &&
  2848. ReferenceValue < Sec.addr + Sec.size) {
  2849. uint64_t sect_offset = ReferenceValue - Sec.addr;
  2850. uint64_t object_offset = Sec.offset + sect_offset;
  2851. StringRef MachOContents = info->O->getData();
  2852. uint64_t object_size = MachOContents.size();
  2853. const char *object_addr = (const char *)MachOContents.data();
  2854. if (object_offset < object_size) {
  2855. const char *name = object_addr + object_offset;
  2856. return name;
  2857. } else {
  2858. return nullptr;
  2859. }
  2860. }
  2861. }
  2862. } else if (Load.C.cmd == MachO::LC_SEGMENT) {
  2863. MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
  2864. for (unsigned J = 0; J < Seg.nsects; ++J) {
  2865. MachO::section Sec = info->O->getSection(Load, J);
  2866. uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
  2867. if (section_type == MachO::S_CSTRING_LITERALS &&
  2868. ReferenceValue >= Sec.addr &&
  2869. ReferenceValue < Sec.addr + Sec.size) {
  2870. uint64_t sect_offset = ReferenceValue - Sec.addr;
  2871. uint64_t object_offset = Sec.offset + sect_offset;
  2872. StringRef MachOContents = info->O->getData();
  2873. uint64_t object_size = MachOContents.size();
  2874. const char *object_addr = (const char *)MachOContents.data();
  2875. if (object_offset < object_size) {
  2876. const char *name = object_addr + object_offset;
  2877. return name;
  2878. } else {
  2879. return nullptr;
  2880. }
  2881. }
  2882. }
  2883. }
  2884. }
  2885. return nullptr;
  2886. }
  2887. // GuessIndirectSymbol returns the name of the indirect symbol for the
  2888. // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
  2889. // an address of a symbol stub or a lazy or non-lazy pointer to associate the
  2890. // symbol name being referenced by the stub or pointer.
  2891. static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
  2892. struct DisassembleInfo *info) {
  2893. MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
  2894. MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
  2895. for (const auto &Load : info->O->load_commands()) {
  2896. if (Load.C.cmd == MachO::LC_SEGMENT_64) {
  2897. MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
  2898. for (unsigned J = 0; J < Seg.nsects; ++J) {
  2899. MachO::section_64 Sec = info->O->getSection64(Load, J);
  2900. uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
  2901. if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
  2902. section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
  2903. section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
  2904. section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
  2905. section_type == MachO::S_SYMBOL_STUBS) &&
  2906. ReferenceValue >= Sec.addr &&
  2907. ReferenceValue < Sec.addr + Sec.size) {
  2908. uint32_t stride;
  2909. if (section_type == MachO::S_SYMBOL_STUBS)
  2910. stride = Sec.reserved2;
  2911. else
  2912. stride = 8;
  2913. if (stride == 0)
  2914. return nullptr;
  2915. uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
  2916. if (index < Dysymtab.nindirectsyms) {
  2917. uint32_t indirect_symbol =
  2918. info->O->getIndirectSymbolTableEntry(Dysymtab, index);
  2919. if (indirect_symbol < Symtab.nsyms) {
  2920. symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
  2921. return unwrapOrError(Sym->getName(), info->O->getFileName())
  2922. .data();
  2923. }
  2924. }
  2925. }
  2926. }
  2927. } else if (Load.C.cmd == MachO::LC_SEGMENT) {
  2928. MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
  2929. for (unsigned J = 0; J < Seg.nsects; ++J) {
  2930. MachO::section Sec = info->O->getSection(Load, J);
  2931. uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
  2932. if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
  2933. section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
  2934. section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
  2935. section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
  2936. section_type == MachO::S_SYMBOL_STUBS) &&
  2937. ReferenceValue >= Sec.addr &&
  2938. ReferenceValue < Sec.addr + Sec.size) {
  2939. uint32_t stride;
  2940. if (section_type == MachO::S_SYMBOL_STUBS)
  2941. stride = Sec.reserved2;
  2942. else
  2943. stride = 4;
  2944. if (stride == 0)
  2945. return nullptr;
  2946. uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
  2947. if (index < Dysymtab.nindirectsyms) {
  2948. uint32_t indirect_symbol =
  2949. info->O->getIndirectSymbolTableEntry(Dysymtab, index);
  2950. if (indirect_symbol < Symtab.nsyms) {
  2951. symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
  2952. return unwrapOrError(Sym->getName(), info->O->getFileName())
  2953. .data();
  2954. }
  2955. }
  2956. }
  2957. }
  2958. }
  2959. }
  2960. return nullptr;
  2961. }
  2962. // method_reference() is called passing it the ReferenceName that might be
  2963. // a reference it to an Objective-C method call. If so then it allocates and
  2964. // assembles a method call string with the values last seen and saved in
  2965. // the DisassembleInfo's class_name and selector_name fields. This is saved
  2966. // into the method field of the info and any previous string is free'ed.
  2967. // Then the class_name field in the info is set to nullptr. The method call
  2968. // string is set into ReferenceName and ReferenceType is set to
  2969. // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
  2970. // then both ReferenceType and ReferenceName are left unchanged.
  2971. static void method_reference(struct DisassembleInfo *info,
  2972. uint64_t *ReferenceType,
  2973. const char **ReferenceName) {
  2974. unsigned int Arch = info->O->getArch();
  2975. if (*ReferenceName != nullptr) {
  2976. if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
  2977. if (info->selector_name != nullptr) {
  2978. if (info->class_name != nullptr) {
  2979. info->method = std::make_unique<char[]>(
  2980. 5 + strlen(info->class_name) + strlen(info->selector_name));
  2981. char *method = info->method.get();
  2982. if (method != nullptr) {
  2983. strcpy(method, "+[");
  2984. strcat(method, info->class_name);
  2985. strcat(method, " ");
  2986. strcat(method, info->selector_name);
  2987. strcat(method, "]");
  2988. *ReferenceName = method;
  2989. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
  2990. }
  2991. } else {
  2992. info->method =
  2993. std::make_unique<char[]>(9 + strlen(info->selector_name));
  2994. char *method = info->method.get();
  2995. if (method != nullptr) {
  2996. if (Arch == Triple::x86_64)
  2997. strcpy(method, "-[%rdi ");
  2998. else if (Arch == Triple::aarch64)
  2999. strcpy(method, "-[x0 ");
  3000. else
  3001. strcpy(method, "-[r? ");
  3002. strcat(method, info->selector_name);
  3003. strcat(method, "]");
  3004. *ReferenceName = method;
  3005. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
  3006. }
  3007. }
  3008. info->class_name = nullptr;
  3009. }
  3010. } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
  3011. if (info->selector_name != nullptr) {
  3012. info->method =
  3013. std::make_unique<char[]>(17 + strlen(info->selector_name));
  3014. char *method = info->method.get();
  3015. if (method != nullptr) {
  3016. if (Arch == Triple::x86_64)
  3017. strcpy(method, "-[[%rdi super] ");
  3018. else if (Arch == Triple::aarch64)
  3019. strcpy(method, "-[[x0 super] ");
  3020. else
  3021. strcpy(method, "-[[r? super] ");
  3022. strcat(method, info->selector_name);
  3023. strcat(method, "]");
  3024. *ReferenceName = method;
  3025. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
  3026. }
  3027. info->class_name = nullptr;
  3028. }
  3029. }
  3030. }
  3031. }
  3032. // GuessPointerPointer() is passed the address of what might be a pointer to
  3033. // a reference to an Objective-C class, selector, message ref or cfstring.
  3034. // If so the value of the pointer is returned and one of the booleans are set
  3035. // to true. If not zero is returned and all the booleans are set to false.
  3036. static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
  3037. struct DisassembleInfo *info,
  3038. bool &classref, bool &selref, bool &msgref,
  3039. bool &cfstring) {
  3040. classref = false;
  3041. selref = false;
  3042. msgref = false;
  3043. cfstring = false;
  3044. for (const auto &Load : info->O->load_commands()) {
  3045. if (Load.C.cmd == MachO::LC_SEGMENT_64) {
  3046. MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
  3047. for (unsigned J = 0; J < Seg.nsects; ++J) {
  3048. MachO::section_64 Sec = info->O->getSection64(Load, J);
  3049. if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
  3050. strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
  3051. strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
  3052. strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
  3053. strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
  3054. ReferenceValue >= Sec.addr &&
  3055. ReferenceValue < Sec.addr + Sec.size) {
  3056. uint64_t sect_offset = ReferenceValue - Sec.addr;
  3057. uint64_t object_offset = Sec.offset + sect_offset;
  3058. StringRef MachOContents = info->O->getData();
  3059. uint64_t object_size = MachOContents.size();
  3060. const char *object_addr = (const char *)MachOContents.data();
  3061. if (object_offset < object_size) {
  3062. uint64_t pointer_value;
  3063. memcpy(&pointer_value, object_addr + object_offset,
  3064. sizeof(uint64_t));
  3065. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3066. sys::swapByteOrder(pointer_value);
  3067. if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
  3068. selref = true;
  3069. else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
  3070. strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
  3071. classref = true;
  3072. else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
  3073. ReferenceValue + 8 < Sec.addr + Sec.size) {
  3074. msgref = true;
  3075. memcpy(&pointer_value, object_addr + object_offset + 8,
  3076. sizeof(uint64_t));
  3077. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3078. sys::swapByteOrder(pointer_value);
  3079. } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
  3080. cfstring = true;
  3081. return pointer_value;
  3082. } else {
  3083. return 0;
  3084. }
  3085. }
  3086. }
  3087. }
  3088. // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
  3089. }
  3090. return 0;
  3091. }
  3092. // get_pointer_64 returns a pointer to the bytes in the object file at the
  3093. // Address from a section in the Mach-O file. And indirectly returns the
  3094. // offset into the section, number of bytes left in the section past the offset
  3095. // and which section is was being referenced. If the Address is not in a
  3096. // section nullptr is returned.
  3097. static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
  3098. uint32_t &left, SectionRef &S,
  3099. DisassembleInfo *info,
  3100. bool objc_only = false) {
  3101. offset = 0;
  3102. left = 0;
  3103. S = SectionRef();
  3104. for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
  3105. uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
  3106. uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
  3107. if (SectSize == 0)
  3108. continue;
  3109. if (objc_only) {
  3110. StringRef SectName;
  3111. Expected<StringRef> SecNameOrErr =
  3112. ((*(info->Sections))[SectIdx]).getName();
  3113. if (SecNameOrErr)
  3114. SectName = *SecNameOrErr;
  3115. else
  3116. consumeError(SecNameOrErr.takeError());
  3117. DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
  3118. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  3119. if (SegName != "__OBJC" && SectName != "__cstring")
  3120. continue;
  3121. }
  3122. if (Address >= SectAddress && Address < SectAddress + SectSize) {
  3123. S = (*(info->Sections))[SectIdx];
  3124. offset = Address - SectAddress;
  3125. left = SectSize - offset;
  3126. StringRef SectContents = unwrapOrError(
  3127. ((*(info->Sections))[SectIdx]).getContents(), info->O->getFileName());
  3128. return SectContents.data() + offset;
  3129. }
  3130. }
  3131. return nullptr;
  3132. }
  3133. static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
  3134. uint32_t &left, SectionRef &S,
  3135. DisassembleInfo *info,
  3136. bool objc_only = false) {
  3137. return get_pointer_64(Address, offset, left, S, info, objc_only);
  3138. }
  3139. // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
  3140. // the symbol indirectly through n_value. Based on the relocation information
  3141. // for the specified section offset in the specified section reference.
  3142. // If no relocation information is found and a non-zero ReferenceValue for the
  3143. // symbol is passed, look up that address in the info's AddrMap.
  3144. static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
  3145. DisassembleInfo *info, uint64_t &n_value,
  3146. uint64_t ReferenceValue = 0) {
  3147. n_value = 0;
  3148. if (!info->verbose)
  3149. return nullptr;
  3150. // See if there is an external relocation entry at the sect_offset.
  3151. bool reloc_found = false;
  3152. DataRefImpl Rel;
  3153. MachO::any_relocation_info RE;
  3154. bool isExtern = false;
  3155. SymbolRef Symbol;
  3156. for (const RelocationRef &Reloc : S.relocations()) {
  3157. uint64_t RelocOffset = Reloc.getOffset();
  3158. if (RelocOffset == sect_offset) {
  3159. Rel = Reloc.getRawDataRefImpl();
  3160. RE = info->O->getRelocation(Rel);
  3161. if (info->O->isRelocationScattered(RE))
  3162. continue;
  3163. isExtern = info->O->getPlainRelocationExternal(RE);
  3164. if (isExtern) {
  3165. symbol_iterator RelocSym = Reloc.getSymbol();
  3166. Symbol = *RelocSym;
  3167. }
  3168. reloc_found = true;
  3169. break;
  3170. }
  3171. }
  3172. // If there is an external relocation entry for a symbol in this section
  3173. // at this section_offset then use that symbol's value for the n_value
  3174. // and return its name.
  3175. const char *SymbolName = nullptr;
  3176. if (reloc_found && isExtern) {
  3177. n_value = cantFail(Symbol.getValue());
  3178. StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
  3179. if (!Name.empty()) {
  3180. SymbolName = Name.data();
  3181. return SymbolName;
  3182. }
  3183. }
  3184. // TODO: For fully linked images, look through the external relocation
  3185. // entries off the dynamic symtab command. For these the r_offset is from the
  3186. // start of the first writeable segment in the Mach-O file. So the offset
  3187. // to this section from that segment is passed to this routine by the caller,
  3188. // as the database_offset. Which is the difference of the section's starting
  3189. // address and the first writable segment.
  3190. //
  3191. // NOTE: need add passing the database_offset to this routine.
  3192. // We did not find an external relocation entry so look up the ReferenceValue
  3193. // as an address of a symbol and if found return that symbol's name.
  3194. SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
  3195. return SymbolName;
  3196. }
  3197. static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
  3198. DisassembleInfo *info,
  3199. uint32_t ReferenceValue) {
  3200. uint64_t n_value64;
  3201. return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
  3202. }
  3203. namespace {
  3204. // These are structs in the Objective-C meta data and read to produce the
  3205. // comments for disassembly. While these are part of the ABI they are no
  3206. // public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
  3207. // .
  3208. // The cfstring object in a 64-bit Mach-O file.
  3209. struct cfstring64_t {
  3210. uint64_t isa; // class64_t * (64-bit pointer)
  3211. uint64_t flags; // flag bits
  3212. uint64_t characters; // char * (64-bit pointer)
  3213. uint64_t length; // number of non-NULL characters in above
  3214. };
  3215. // The class object in a 64-bit Mach-O file.
  3216. struct class64_t {
  3217. uint64_t isa; // class64_t * (64-bit pointer)
  3218. uint64_t superclass; // class64_t * (64-bit pointer)
  3219. uint64_t cache; // Cache (64-bit pointer)
  3220. uint64_t vtable; // IMP * (64-bit pointer)
  3221. uint64_t data; // class_ro64_t * (64-bit pointer)
  3222. };
  3223. struct class32_t {
  3224. uint32_t isa; /* class32_t * (32-bit pointer) */
  3225. uint32_t superclass; /* class32_t * (32-bit pointer) */
  3226. uint32_t cache; /* Cache (32-bit pointer) */
  3227. uint32_t vtable; /* IMP * (32-bit pointer) */
  3228. uint32_t data; /* class_ro32_t * (32-bit pointer) */
  3229. };
  3230. struct class_ro64_t {
  3231. uint32_t flags;
  3232. uint32_t instanceStart;
  3233. uint32_t instanceSize;
  3234. uint32_t reserved;
  3235. uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
  3236. uint64_t name; // const char * (64-bit pointer)
  3237. uint64_t baseMethods; // const method_list_t * (64-bit pointer)
  3238. uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
  3239. uint64_t ivars; // const ivar_list_t * (64-bit pointer)
  3240. uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
  3241. uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
  3242. };
  3243. struct class_ro32_t {
  3244. uint32_t flags;
  3245. uint32_t instanceStart;
  3246. uint32_t instanceSize;
  3247. uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
  3248. uint32_t name; /* const char * (32-bit pointer) */
  3249. uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
  3250. uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
  3251. uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
  3252. uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
  3253. uint32_t baseProperties; /* const struct objc_property_list *
  3254. (32-bit pointer) */
  3255. };
  3256. /* Values for class_ro{64,32}_t->flags */
  3257. #define RO_META (1 << 0)
  3258. #define RO_ROOT (1 << 1)
  3259. #define RO_HAS_CXX_STRUCTORS (1 << 2)
  3260. struct method_list64_t {
  3261. uint32_t entsize;
  3262. uint32_t count;
  3263. /* struct method64_t first; These structures follow inline */
  3264. };
  3265. struct method_list32_t {
  3266. uint32_t entsize;
  3267. uint32_t count;
  3268. /* struct method32_t first; These structures follow inline */
  3269. };
  3270. struct method64_t {
  3271. uint64_t name; /* SEL (64-bit pointer) */
  3272. uint64_t types; /* const char * (64-bit pointer) */
  3273. uint64_t imp; /* IMP (64-bit pointer) */
  3274. };
  3275. struct method32_t {
  3276. uint32_t name; /* SEL (32-bit pointer) */
  3277. uint32_t types; /* const char * (32-bit pointer) */
  3278. uint32_t imp; /* IMP (32-bit pointer) */
  3279. };
  3280. struct protocol_list64_t {
  3281. uint64_t count; /* uintptr_t (a 64-bit value) */
  3282. /* struct protocol64_t * list[0]; These pointers follow inline */
  3283. };
  3284. struct protocol_list32_t {
  3285. uint32_t count; /* uintptr_t (a 32-bit value) */
  3286. /* struct protocol32_t * list[0]; These pointers follow inline */
  3287. };
  3288. struct protocol64_t {
  3289. uint64_t isa; /* id * (64-bit pointer) */
  3290. uint64_t name; /* const char * (64-bit pointer) */
  3291. uint64_t protocols; /* struct protocol_list64_t *
  3292. (64-bit pointer) */
  3293. uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
  3294. uint64_t classMethods; /* method_list_t * (64-bit pointer) */
  3295. uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
  3296. uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
  3297. uint64_t instanceProperties; /* struct objc_property_list *
  3298. (64-bit pointer) */
  3299. };
  3300. struct protocol32_t {
  3301. uint32_t isa; /* id * (32-bit pointer) */
  3302. uint32_t name; /* const char * (32-bit pointer) */
  3303. uint32_t protocols; /* struct protocol_list_t *
  3304. (32-bit pointer) */
  3305. uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
  3306. uint32_t classMethods; /* method_list_t * (32-bit pointer) */
  3307. uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
  3308. uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
  3309. uint32_t instanceProperties; /* struct objc_property_list *
  3310. (32-bit pointer) */
  3311. };
  3312. struct ivar_list64_t {
  3313. uint32_t entsize;
  3314. uint32_t count;
  3315. /* struct ivar64_t first; These structures follow inline */
  3316. };
  3317. struct ivar_list32_t {
  3318. uint32_t entsize;
  3319. uint32_t count;
  3320. /* struct ivar32_t first; These structures follow inline */
  3321. };
  3322. struct ivar64_t {
  3323. uint64_t offset; /* uintptr_t * (64-bit pointer) */
  3324. uint64_t name; /* const char * (64-bit pointer) */
  3325. uint64_t type; /* const char * (64-bit pointer) */
  3326. uint32_t alignment;
  3327. uint32_t size;
  3328. };
  3329. struct ivar32_t {
  3330. uint32_t offset; /* uintptr_t * (32-bit pointer) */
  3331. uint32_t name; /* const char * (32-bit pointer) */
  3332. uint32_t type; /* const char * (32-bit pointer) */
  3333. uint32_t alignment;
  3334. uint32_t size;
  3335. };
  3336. struct objc_property_list64 {
  3337. uint32_t entsize;
  3338. uint32_t count;
  3339. /* struct objc_property64 first; These structures follow inline */
  3340. };
  3341. struct objc_property_list32 {
  3342. uint32_t entsize;
  3343. uint32_t count;
  3344. /* struct objc_property32 first; These structures follow inline */
  3345. };
  3346. struct objc_property64 {
  3347. uint64_t name; /* const char * (64-bit pointer) */
  3348. uint64_t attributes; /* const char * (64-bit pointer) */
  3349. };
  3350. struct objc_property32 {
  3351. uint32_t name; /* const char * (32-bit pointer) */
  3352. uint32_t attributes; /* const char * (32-bit pointer) */
  3353. };
  3354. struct category64_t {
  3355. uint64_t name; /* const char * (64-bit pointer) */
  3356. uint64_t cls; /* struct class_t * (64-bit pointer) */
  3357. uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
  3358. uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
  3359. uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
  3360. uint64_t instanceProperties; /* struct objc_property_list *
  3361. (64-bit pointer) */
  3362. };
  3363. struct category32_t {
  3364. uint32_t name; /* const char * (32-bit pointer) */
  3365. uint32_t cls; /* struct class_t * (32-bit pointer) */
  3366. uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
  3367. uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
  3368. uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
  3369. uint32_t instanceProperties; /* struct objc_property_list *
  3370. (32-bit pointer) */
  3371. };
  3372. struct objc_image_info64 {
  3373. uint32_t version;
  3374. uint32_t flags;
  3375. };
  3376. struct objc_image_info32 {
  3377. uint32_t version;
  3378. uint32_t flags;
  3379. };
  3380. struct imageInfo_t {
  3381. uint32_t version;
  3382. uint32_t flags;
  3383. };
  3384. /* masks for objc_image_info.flags */
  3385. #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
  3386. #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
  3387. #define OBJC_IMAGE_IS_SIMULATED (1 << 5)
  3388. #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
  3389. struct message_ref64 {
  3390. uint64_t imp; /* IMP (64-bit pointer) */
  3391. uint64_t sel; /* SEL (64-bit pointer) */
  3392. };
  3393. struct message_ref32 {
  3394. uint32_t imp; /* IMP (32-bit pointer) */
  3395. uint32_t sel; /* SEL (32-bit pointer) */
  3396. };
  3397. // Objective-C 1 (32-bit only) meta data structs.
  3398. struct objc_module_t {
  3399. uint32_t version;
  3400. uint32_t size;
  3401. uint32_t name; /* char * (32-bit pointer) */
  3402. uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
  3403. };
  3404. struct objc_symtab_t {
  3405. uint32_t sel_ref_cnt;
  3406. uint32_t refs; /* SEL * (32-bit pointer) */
  3407. uint16_t cls_def_cnt;
  3408. uint16_t cat_def_cnt;
  3409. // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
  3410. };
  3411. struct objc_class_t {
  3412. uint32_t isa; /* struct objc_class * (32-bit pointer) */
  3413. uint32_t super_class; /* struct objc_class * (32-bit pointer) */
  3414. uint32_t name; /* const char * (32-bit pointer) */
  3415. int32_t version;
  3416. int32_t info;
  3417. int32_t instance_size;
  3418. uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
  3419. uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
  3420. uint32_t cache; /* struct objc_cache * (32-bit pointer) */
  3421. uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
  3422. };
  3423. #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
  3424. // class is not a metaclass
  3425. #define CLS_CLASS 0x1
  3426. // class is a metaclass
  3427. #define CLS_META 0x2
  3428. struct objc_category_t {
  3429. uint32_t category_name; /* char * (32-bit pointer) */
  3430. uint32_t class_name; /* char * (32-bit pointer) */
  3431. uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
  3432. uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
  3433. uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
  3434. };
  3435. struct objc_ivar_t {
  3436. uint32_t ivar_name; /* char * (32-bit pointer) */
  3437. uint32_t ivar_type; /* char * (32-bit pointer) */
  3438. int32_t ivar_offset;
  3439. };
  3440. struct objc_ivar_list_t {
  3441. int32_t ivar_count;
  3442. // struct objc_ivar_t ivar_list[1]; /* variable length structure */
  3443. };
  3444. struct objc_method_list_t {
  3445. uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
  3446. int32_t method_count;
  3447. // struct objc_method_t method_list[1]; /* variable length structure */
  3448. };
  3449. struct objc_method_t {
  3450. uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
  3451. uint32_t method_types; /* char * (32-bit pointer) */
  3452. uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
  3453. (32-bit pointer) */
  3454. };
  3455. struct objc_protocol_list_t {
  3456. uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
  3457. int32_t count;
  3458. // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
  3459. // (32-bit pointer) */
  3460. };
  3461. struct objc_protocol_t {
  3462. uint32_t isa; /* struct objc_class * (32-bit pointer) */
  3463. uint32_t protocol_name; /* char * (32-bit pointer) */
  3464. uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
  3465. uint32_t instance_methods; /* struct objc_method_description_list *
  3466. (32-bit pointer) */
  3467. uint32_t class_methods; /* struct objc_method_description_list *
  3468. (32-bit pointer) */
  3469. };
  3470. struct objc_method_description_list_t {
  3471. int32_t count;
  3472. // struct objc_method_description_t list[1];
  3473. };
  3474. struct objc_method_description_t {
  3475. uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
  3476. uint32_t types; /* char * (32-bit pointer) */
  3477. };
  3478. inline void swapStruct(struct cfstring64_t &cfs) {
  3479. sys::swapByteOrder(cfs.isa);
  3480. sys::swapByteOrder(cfs.flags);
  3481. sys::swapByteOrder(cfs.characters);
  3482. sys::swapByteOrder(cfs.length);
  3483. }
  3484. inline void swapStruct(struct class64_t &c) {
  3485. sys::swapByteOrder(c.isa);
  3486. sys::swapByteOrder(c.superclass);
  3487. sys::swapByteOrder(c.cache);
  3488. sys::swapByteOrder(c.vtable);
  3489. sys::swapByteOrder(c.data);
  3490. }
  3491. inline void swapStruct(struct class32_t &c) {
  3492. sys::swapByteOrder(c.isa);
  3493. sys::swapByteOrder(c.superclass);
  3494. sys::swapByteOrder(c.cache);
  3495. sys::swapByteOrder(c.vtable);
  3496. sys::swapByteOrder(c.data);
  3497. }
  3498. inline void swapStruct(struct class_ro64_t &cro) {
  3499. sys::swapByteOrder(cro.flags);
  3500. sys::swapByteOrder(cro.instanceStart);
  3501. sys::swapByteOrder(cro.instanceSize);
  3502. sys::swapByteOrder(cro.reserved);
  3503. sys::swapByteOrder(cro.ivarLayout);
  3504. sys::swapByteOrder(cro.name);
  3505. sys::swapByteOrder(cro.baseMethods);
  3506. sys::swapByteOrder(cro.baseProtocols);
  3507. sys::swapByteOrder(cro.ivars);
  3508. sys::swapByteOrder(cro.weakIvarLayout);
  3509. sys::swapByteOrder(cro.baseProperties);
  3510. }
  3511. inline void swapStruct(struct class_ro32_t &cro) {
  3512. sys::swapByteOrder(cro.flags);
  3513. sys::swapByteOrder(cro.instanceStart);
  3514. sys::swapByteOrder(cro.instanceSize);
  3515. sys::swapByteOrder(cro.ivarLayout);
  3516. sys::swapByteOrder(cro.name);
  3517. sys::swapByteOrder(cro.baseMethods);
  3518. sys::swapByteOrder(cro.baseProtocols);
  3519. sys::swapByteOrder(cro.ivars);
  3520. sys::swapByteOrder(cro.weakIvarLayout);
  3521. sys::swapByteOrder(cro.baseProperties);
  3522. }
  3523. inline void swapStruct(struct method_list64_t &ml) {
  3524. sys::swapByteOrder(ml.entsize);
  3525. sys::swapByteOrder(ml.count);
  3526. }
  3527. inline void swapStruct(struct method_list32_t &ml) {
  3528. sys::swapByteOrder(ml.entsize);
  3529. sys::swapByteOrder(ml.count);
  3530. }
  3531. inline void swapStruct(struct method64_t &m) {
  3532. sys::swapByteOrder(m.name);
  3533. sys::swapByteOrder(m.types);
  3534. sys::swapByteOrder(m.imp);
  3535. }
  3536. inline void swapStruct(struct method32_t &m) {
  3537. sys::swapByteOrder(m.name);
  3538. sys::swapByteOrder(m.types);
  3539. sys::swapByteOrder(m.imp);
  3540. }
  3541. inline void swapStruct(struct protocol_list64_t &pl) {
  3542. sys::swapByteOrder(pl.count);
  3543. }
  3544. inline void swapStruct(struct protocol_list32_t &pl) {
  3545. sys::swapByteOrder(pl.count);
  3546. }
  3547. inline void swapStruct(struct protocol64_t &p) {
  3548. sys::swapByteOrder(p.isa);
  3549. sys::swapByteOrder(p.name);
  3550. sys::swapByteOrder(p.protocols);
  3551. sys::swapByteOrder(p.instanceMethods);
  3552. sys::swapByteOrder(p.classMethods);
  3553. sys::swapByteOrder(p.optionalInstanceMethods);
  3554. sys::swapByteOrder(p.optionalClassMethods);
  3555. sys::swapByteOrder(p.instanceProperties);
  3556. }
  3557. inline void swapStruct(struct protocol32_t &p) {
  3558. sys::swapByteOrder(p.isa);
  3559. sys::swapByteOrder(p.name);
  3560. sys::swapByteOrder(p.protocols);
  3561. sys::swapByteOrder(p.instanceMethods);
  3562. sys::swapByteOrder(p.classMethods);
  3563. sys::swapByteOrder(p.optionalInstanceMethods);
  3564. sys::swapByteOrder(p.optionalClassMethods);
  3565. sys::swapByteOrder(p.instanceProperties);
  3566. }
  3567. inline void swapStruct(struct ivar_list64_t &il) {
  3568. sys::swapByteOrder(il.entsize);
  3569. sys::swapByteOrder(il.count);
  3570. }
  3571. inline void swapStruct(struct ivar_list32_t &il) {
  3572. sys::swapByteOrder(il.entsize);
  3573. sys::swapByteOrder(il.count);
  3574. }
  3575. inline void swapStruct(struct ivar64_t &i) {
  3576. sys::swapByteOrder(i.offset);
  3577. sys::swapByteOrder(i.name);
  3578. sys::swapByteOrder(i.type);
  3579. sys::swapByteOrder(i.alignment);
  3580. sys::swapByteOrder(i.size);
  3581. }
  3582. inline void swapStruct(struct ivar32_t &i) {
  3583. sys::swapByteOrder(i.offset);
  3584. sys::swapByteOrder(i.name);
  3585. sys::swapByteOrder(i.type);
  3586. sys::swapByteOrder(i.alignment);
  3587. sys::swapByteOrder(i.size);
  3588. }
  3589. inline void swapStruct(struct objc_property_list64 &pl) {
  3590. sys::swapByteOrder(pl.entsize);
  3591. sys::swapByteOrder(pl.count);
  3592. }
  3593. inline void swapStruct(struct objc_property_list32 &pl) {
  3594. sys::swapByteOrder(pl.entsize);
  3595. sys::swapByteOrder(pl.count);
  3596. }
  3597. inline void swapStruct(struct objc_property64 &op) {
  3598. sys::swapByteOrder(op.name);
  3599. sys::swapByteOrder(op.attributes);
  3600. }
  3601. inline void swapStruct(struct objc_property32 &op) {
  3602. sys::swapByteOrder(op.name);
  3603. sys::swapByteOrder(op.attributes);
  3604. }
  3605. inline void swapStruct(struct category64_t &c) {
  3606. sys::swapByteOrder(c.name);
  3607. sys::swapByteOrder(c.cls);
  3608. sys::swapByteOrder(c.instanceMethods);
  3609. sys::swapByteOrder(c.classMethods);
  3610. sys::swapByteOrder(c.protocols);
  3611. sys::swapByteOrder(c.instanceProperties);
  3612. }
  3613. inline void swapStruct(struct category32_t &c) {
  3614. sys::swapByteOrder(c.name);
  3615. sys::swapByteOrder(c.cls);
  3616. sys::swapByteOrder(c.instanceMethods);
  3617. sys::swapByteOrder(c.classMethods);
  3618. sys::swapByteOrder(c.protocols);
  3619. sys::swapByteOrder(c.instanceProperties);
  3620. }
  3621. inline void swapStruct(struct objc_image_info64 &o) {
  3622. sys::swapByteOrder(o.version);
  3623. sys::swapByteOrder(o.flags);
  3624. }
  3625. inline void swapStruct(struct objc_image_info32 &o) {
  3626. sys::swapByteOrder(o.version);
  3627. sys::swapByteOrder(o.flags);
  3628. }
  3629. inline void swapStruct(struct imageInfo_t &o) {
  3630. sys::swapByteOrder(o.version);
  3631. sys::swapByteOrder(o.flags);
  3632. }
  3633. inline void swapStruct(struct message_ref64 &mr) {
  3634. sys::swapByteOrder(mr.imp);
  3635. sys::swapByteOrder(mr.sel);
  3636. }
  3637. inline void swapStruct(struct message_ref32 &mr) {
  3638. sys::swapByteOrder(mr.imp);
  3639. sys::swapByteOrder(mr.sel);
  3640. }
  3641. inline void swapStruct(struct objc_module_t &module) {
  3642. sys::swapByteOrder(module.version);
  3643. sys::swapByteOrder(module.size);
  3644. sys::swapByteOrder(module.name);
  3645. sys::swapByteOrder(module.symtab);
  3646. }
  3647. inline void swapStruct(struct objc_symtab_t &symtab) {
  3648. sys::swapByteOrder(symtab.sel_ref_cnt);
  3649. sys::swapByteOrder(symtab.refs);
  3650. sys::swapByteOrder(symtab.cls_def_cnt);
  3651. sys::swapByteOrder(symtab.cat_def_cnt);
  3652. }
  3653. inline void swapStruct(struct objc_class_t &objc_class) {
  3654. sys::swapByteOrder(objc_class.isa);
  3655. sys::swapByteOrder(objc_class.super_class);
  3656. sys::swapByteOrder(objc_class.name);
  3657. sys::swapByteOrder(objc_class.version);
  3658. sys::swapByteOrder(objc_class.info);
  3659. sys::swapByteOrder(objc_class.instance_size);
  3660. sys::swapByteOrder(objc_class.ivars);
  3661. sys::swapByteOrder(objc_class.methodLists);
  3662. sys::swapByteOrder(objc_class.cache);
  3663. sys::swapByteOrder(objc_class.protocols);
  3664. }
  3665. inline void swapStruct(struct objc_category_t &objc_category) {
  3666. sys::swapByteOrder(objc_category.category_name);
  3667. sys::swapByteOrder(objc_category.class_name);
  3668. sys::swapByteOrder(objc_category.instance_methods);
  3669. sys::swapByteOrder(objc_category.class_methods);
  3670. sys::swapByteOrder(objc_category.protocols);
  3671. }
  3672. inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
  3673. sys::swapByteOrder(objc_ivar_list.ivar_count);
  3674. }
  3675. inline void swapStruct(struct objc_ivar_t &objc_ivar) {
  3676. sys::swapByteOrder(objc_ivar.ivar_name);
  3677. sys::swapByteOrder(objc_ivar.ivar_type);
  3678. sys::swapByteOrder(objc_ivar.ivar_offset);
  3679. }
  3680. inline void swapStruct(struct objc_method_list_t &method_list) {
  3681. sys::swapByteOrder(method_list.obsolete);
  3682. sys::swapByteOrder(method_list.method_count);
  3683. }
  3684. inline void swapStruct(struct objc_method_t &method) {
  3685. sys::swapByteOrder(method.method_name);
  3686. sys::swapByteOrder(method.method_types);
  3687. sys::swapByteOrder(method.method_imp);
  3688. }
  3689. inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
  3690. sys::swapByteOrder(protocol_list.next);
  3691. sys::swapByteOrder(protocol_list.count);
  3692. }
  3693. inline void swapStruct(struct objc_protocol_t &protocol) {
  3694. sys::swapByteOrder(protocol.isa);
  3695. sys::swapByteOrder(protocol.protocol_name);
  3696. sys::swapByteOrder(protocol.protocol_list);
  3697. sys::swapByteOrder(protocol.instance_methods);
  3698. sys::swapByteOrder(protocol.class_methods);
  3699. }
  3700. inline void swapStruct(struct objc_method_description_list_t &mdl) {
  3701. sys::swapByteOrder(mdl.count);
  3702. }
  3703. inline void swapStruct(struct objc_method_description_t &md) {
  3704. sys::swapByteOrder(md.name);
  3705. sys::swapByteOrder(md.types);
  3706. }
  3707. } // namespace
  3708. static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
  3709. struct DisassembleInfo *info);
  3710. // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
  3711. // to an Objective-C class and returns the class name. It is also passed the
  3712. // address of the pointer, so when the pointer is zero as it can be in an .o
  3713. // file, that is used to look for an external relocation entry with a symbol
  3714. // name.
  3715. static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
  3716. uint64_t ReferenceValue,
  3717. struct DisassembleInfo *info) {
  3718. const char *r;
  3719. uint32_t offset, left;
  3720. SectionRef S;
  3721. // The pointer_value can be 0 in an object file and have a relocation
  3722. // entry for the class symbol at the ReferenceValue (the address of the
  3723. // pointer).
  3724. if (pointer_value == 0) {
  3725. r = get_pointer_64(ReferenceValue, offset, left, S, info);
  3726. if (r == nullptr || left < sizeof(uint64_t))
  3727. return nullptr;
  3728. uint64_t n_value;
  3729. const char *symbol_name = get_symbol_64(offset, S, info, n_value);
  3730. if (symbol_name == nullptr)
  3731. return nullptr;
  3732. const char *class_name = strrchr(symbol_name, '$');
  3733. if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
  3734. return class_name + 2;
  3735. else
  3736. return nullptr;
  3737. }
  3738. // The case were the pointer_value is non-zero and points to a class defined
  3739. // in this Mach-O file.
  3740. r = get_pointer_64(pointer_value, offset, left, S, info);
  3741. if (r == nullptr || left < sizeof(struct class64_t))
  3742. return nullptr;
  3743. struct class64_t c;
  3744. memcpy(&c, r, sizeof(struct class64_t));
  3745. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3746. swapStruct(c);
  3747. if (c.data == 0)
  3748. return nullptr;
  3749. r = get_pointer_64(c.data, offset, left, S, info);
  3750. if (r == nullptr || left < sizeof(struct class_ro64_t))
  3751. return nullptr;
  3752. struct class_ro64_t cro;
  3753. memcpy(&cro, r, sizeof(struct class_ro64_t));
  3754. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3755. swapStruct(cro);
  3756. if (cro.name == 0)
  3757. return nullptr;
  3758. const char *name = get_pointer_64(cro.name, offset, left, S, info);
  3759. return name;
  3760. }
  3761. // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
  3762. // pointer to a cfstring and returns its name or nullptr.
  3763. static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
  3764. struct DisassembleInfo *info) {
  3765. const char *r, *name;
  3766. uint32_t offset, left;
  3767. SectionRef S;
  3768. struct cfstring64_t cfs;
  3769. uint64_t cfs_characters;
  3770. r = get_pointer_64(ReferenceValue, offset, left, S, info);
  3771. if (r == nullptr || left < sizeof(struct cfstring64_t))
  3772. return nullptr;
  3773. memcpy(&cfs, r, sizeof(struct cfstring64_t));
  3774. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3775. swapStruct(cfs);
  3776. if (cfs.characters == 0) {
  3777. uint64_t n_value;
  3778. const char *symbol_name = get_symbol_64(
  3779. offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
  3780. if (symbol_name == nullptr)
  3781. return nullptr;
  3782. cfs_characters = n_value;
  3783. } else
  3784. cfs_characters = cfs.characters;
  3785. name = get_pointer_64(cfs_characters, offset, left, S, info);
  3786. return name;
  3787. }
  3788. // get_objc2_64bit_selref() is used for disassembly and is passed a the address
  3789. // of a pointer to an Objective-C selector reference when the pointer value is
  3790. // zero as in a .o file and is likely to have a external relocation entry with
  3791. // who's symbol's n_value is the real pointer to the selector name. If that is
  3792. // the case the real pointer to the selector name is returned else 0 is
  3793. // returned
  3794. static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
  3795. struct DisassembleInfo *info) {
  3796. uint32_t offset, left;
  3797. SectionRef S;
  3798. const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
  3799. if (r == nullptr || left < sizeof(uint64_t))
  3800. return 0;
  3801. uint64_t n_value;
  3802. const char *symbol_name = get_symbol_64(offset, S, info, n_value);
  3803. if (symbol_name == nullptr)
  3804. return 0;
  3805. return n_value;
  3806. }
  3807. static const SectionRef get_section(MachOObjectFile *O, const char *segname,
  3808. const char *sectname) {
  3809. for (const SectionRef &Section : O->sections()) {
  3810. StringRef SectName;
  3811. Expected<StringRef> SecNameOrErr = Section.getName();
  3812. if (SecNameOrErr)
  3813. SectName = *SecNameOrErr;
  3814. else
  3815. consumeError(SecNameOrErr.takeError());
  3816. DataRefImpl Ref = Section.getRawDataRefImpl();
  3817. StringRef SegName = O->getSectionFinalSegmentName(Ref);
  3818. if (SegName == segname && SectName == sectname)
  3819. return Section;
  3820. }
  3821. return SectionRef();
  3822. }
  3823. static void
  3824. walk_pointer_list_64(const char *listname, const SectionRef S,
  3825. MachOObjectFile *O, struct DisassembleInfo *info,
  3826. void (*func)(uint64_t, struct DisassembleInfo *info)) {
  3827. if (S == SectionRef())
  3828. return;
  3829. StringRef SectName;
  3830. Expected<StringRef> SecNameOrErr = S.getName();
  3831. if (SecNameOrErr)
  3832. SectName = *SecNameOrErr;
  3833. else
  3834. consumeError(SecNameOrErr.takeError());
  3835. DataRefImpl Ref = S.getRawDataRefImpl();
  3836. StringRef SegName = O->getSectionFinalSegmentName(Ref);
  3837. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  3838. StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
  3839. const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
  3840. for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
  3841. uint32_t left = S.getSize() - i;
  3842. uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
  3843. uint64_t p = 0;
  3844. memcpy(&p, Contents + i, size);
  3845. if (i + sizeof(uint64_t) > S.getSize())
  3846. outs() << listname << " list pointer extends past end of (" << SegName
  3847. << "," << SectName << ") section\n";
  3848. outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
  3849. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  3850. sys::swapByteOrder(p);
  3851. uint64_t n_value = 0;
  3852. const char *name = get_symbol_64(i, S, info, n_value, p);
  3853. if (name == nullptr)
  3854. name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
  3855. if (n_value != 0) {
  3856. outs() << format("0x%" PRIx64, n_value);
  3857. if (p != 0)
  3858. outs() << " + " << format("0x%" PRIx64, p);
  3859. } else
  3860. outs() << format("0x%" PRIx64, p);
  3861. if (name != nullptr)
  3862. outs() << " " << name;
  3863. outs() << "\n";
  3864. p += n_value;
  3865. if (func)
  3866. func(p, info);
  3867. }
  3868. }
  3869. static void
  3870. walk_pointer_list_32(const char *listname, const SectionRef S,
  3871. MachOObjectFile *O, struct DisassembleInfo *info,
  3872. void (*func)(uint32_t, struct DisassembleInfo *info)) {
  3873. if (S == SectionRef())
  3874. return;
  3875. StringRef SectName = unwrapOrError(S.getName(), O->getFileName());
  3876. DataRefImpl Ref = S.getRawDataRefImpl();
  3877. StringRef SegName = O->getSectionFinalSegmentName(Ref);
  3878. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  3879. StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
  3880. const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
  3881. for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
  3882. uint32_t left = S.getSize() - i;
  3883. uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
  3884. uint32_t p = 0;
  3885. memcpy(&p, Contents + i, size);
  3886. if (i + sizeof(uint32_t) > S.getSize())
  3887. outs() << listname << " list pointer extends past end of (" << SegName
  3888. << "," << SectName << ") section\n";
  3889. uint32_t Address = S.getAddress() + i;
  3890. outs() << format("%08" PRIx32, Address) << " ";
  3891. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  3892. sys::swapByteOrder(p);
  3893. outs() << format("0x%" PRIx32, p);
  3894. const char *name = get_symbol_32(i, S, info, p);
  3895. if (name != nullptr)
  3896. outs() << " " << name;
  3897. outs() << "\n";
  3898. if (func)
  3899. func(p, info);
  3900. }
  3901. }
  3902. static void print_layout_map(const char *layout_map, uint32_t left) {
  3903. if (layout_map == nullptr)
  3904. return;
  3905. outs() << " layout map: ";
  3906. do {
  3907. outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
  3908. left--;
  3909. layout_map++;
  3910. } while (*layout_map != '\0' && left != 0);
  3911. outs() << "\n";
  3912. }
  3913. static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
  3914. uint32_t offset, left;
  3915. SectionRef S;
  3916. const char *layout_map;
  3917. if (p == 0)
  3918. return;
  3919. layout_map = get_pointer_64(p, offset, left, S, info);
  3920. print_layout_map(layout_map, left);
  3921. }
  3922. static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
  3923. uint32_t offset, left;
  3924. SectionRef S;
  3925. const char *layout_map;
  3926. if (p == 0)
  3927. return;
  3928. layout_map = get_pointer_32(p, offset, left, S, info);
  3929. print_layout_map(layout_map, left);
  3930. }
  3931. static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
  3932. const char *indent) {
  3933. struct method_list64_t ml;
  3934. struct method64_t m;
  3935. const char *r;
  3936. uint32_t offset, xoffset, left, i;
  3937. SectionRef S, xS;
  3938. const char *name, *sym_name;
  3939. uint64_t n_value;
  3940. r = get_pointer_64(p, offset, left, S, info);
  3941. if (r == nullptr)
  3942. return;
  3943. memset(&ml, '\0', sizeof(struct method_list64_t));
  3944. if (left < sizeof(struct method_list64_t)) {
  3945. memcpy(&ml, r, left);
  3946. outs() << " (method_list_t entends past the end of the section)\n";
  3947. } else
  3948. memcpy(&ml, r, sizeof(struct method_list64_t));
  3949. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3950. swapStruct(ml);
  3951. outs() << indent << "\t\t entsize " << ml.entsize << "\n";
  3952. outs() << indent << "\t\t count " << ml.count << "\n";
  3953. p += sizeof(struct method_list64_t);
  3954. offset += sizeof(struct method_list64_t);
  3955. for (i = 0; i < ml.count; i++) {
  3956. r = get_pointer_64(p, offset, left, S, info);
  3957. if (r == nullptr)
  3958. return;
  3959. memset(&m, '\0', sizeof(struct method64_t));
  3960. if (left < sizeof(struct method64_t)) {
  3961. memcpy(&m, r, left);
  3962. outs() << indent << " (method_t extends past the end of the section)\n";
  3963. } else
  3964. memcpy(&m, r, sizeof(struct method64_t));
  3965. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3966. swapStruct(m);
  3967. outs() << indent << "\t\t name ";
  3968. sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
  3969. info, n_value, m.name);
  3970. if (n_value != 0) {
  3971. if (info->verbose && sym_name != nullptr)
  3972. outs() << sym_name;
  3973. else
  3974. outs() << format("0x%" PRIx64, n_value);
  3975. if (m.name != 0)
  3976. outs() << " + " << format("0x%" PRIx64, m.name);
  3977. } else
  3978. outs() << format("0x%" PRIx64, m.name);
  3979. name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
  3980. if (name != nullptr)
  3981. outs() << format(" %.*s", left, name);
  3982. outs() << "\n";
  3983. outs() << indent << "\t\t types ";
  3984. sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
  3985. info, n_value, m.types);
  3986. if (n_value != 0) {
  3987. if (info->verbose && sym_name != nullptr)
  3988. outs() << sym_name;
  3989. else
  3990. outs() << format("0x%" PRIx64, n_value);
  3991. if (m.types != 0)
  3992. outs() << " + " << format("0x%" PRIx64, m.types);
  3993. } else
  3994. outs() << format("0x%" PRIx64, m.types);
  3995. name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
  3996. if (name != nullptr)
  3997. outs() << format(" %.*s", left, name);
  3998. outs() << "\n";
  3999. outs() << indent << "\t\t imp ";
  4000. name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
  4001. n_value, m.imp);
  4002. if (info->verbose && name == nullptr) {
  4003. if (n_value != 0) {
  4004. outs() << format("0x%" PRIx64, n_value) << " ";
  4005. if (m.imp != 0)
  4006. outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
  4007. } else
  4008. outs() << format("0x%" PRIx64, m.imp) << " ";
  4009. }
  4010. if (name != nullptr)
  4011. outs() << name;
  4012. outs() << "\n";
  4013. p += sizeof(struct method64_t);
  4014. offset += sizeof(struct method64_t);
  4015. }
  4016. }
  4017. static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
  4018. const char *indent) {
  4019. struct method_list32_t ml;
  4020. struct method32_t m;
  4021. const char *r, *name;
  4022. uint32_t offset, xoffset, left, i;
  4023. SectionRef S, xS;
  4024. r = get_pointer_32(p, offset, left, S, info);
  4025. if (r == nullptr)
  4026. return;
  4027. memset(&ml, '\0', sizeof(struct method_list32_t));
  4028. if (left < sizeof(struct method_list32_t)) {
  4029. memcpy(&ml, r, left);
  4030. outs() << " (method_list_t entends past the end of the section)\n";
  4031. } else
  4032. memcpy(&ml, r, sizeof(struct method_list32_t));
  4033. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4034. swapStruct(ml);
  4035. outs() << indent << "\t\t entsize " << ml.entsize << "\n";
  4036. outs() << indent << "\t\t count " << ml.count << "\n";
  4037. p += sizeof(struct method_list32_t);
  4038. offset += sizeof(struct method_list32_t);
  4039. for (i = 0; i < ml.count; i++) {
  4040. r = get_pointer_32(p, offset, left, S, info);
  4041. if (r == nullptr)
  4042. return;
  4043. memset(&m, '\0', sizeof(struct method32_t));
  4044. if (left < sizeof(struct method32_t)) {
  4045. memcpy(&ml, r, left);
  4046. outs() << indent << " (method_t entends past the end of the section)\n";
  4047. } else
  4048. memcpy(&m, r, sizeof(struct method32_t));
  4049. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4050. swapStruct(m);
  4051. outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
  4052. name = get_pointer_32(m.name, xoffset, left, xS, info);
  4053. if (name != nullptr)
  4054. outs() << format(" %.*s", left, name);
  4055. outs() << "\n";
  4056. outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
  4057. name = get_pointer_32(m.types, xoffset, left, xS, info);
  4058. if (name != nullptr)
  4059. outs() << format(" %.*s", left, name);
  4060. outs() << "\n";
  4061. outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
  4062. name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
  4063. m.imp);
  4064. if (name != nullptr)
  4065. outs() << " " << name;
  4066. outs() << "\n";
  4067. p += sizeof(struct method32_t);
  4068. offset += sizeof(struct method32_t);
  4069. }
  4070. }
  4071. static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
  4072. uint32_t offset, left, xleft;
  4073. SectionRef S;
  4074. struct objc_method_list_t method_list;
  4075. struct objc_method_t method;
  4076. const char *r, *methods, *name, *SymbolName;
  4077. int32_t i;
  4078. r = get_pointer_32(p, offset, left, S, info, true);
  4079. if (r == nullptr)
  4080. return true;
  4081. outs() << "\n";
  4082. if (left > sizeof(struct objc_method_list_t)) {
  4083. memcpy(&method_list, r, sizeof(struct objc_method_list_t));
  4084. } else {
  4085. outs() << "\t\t objc_method_list extends past end of the section\n";
  4086. memset(&method_list, '\0', sizeof(struct objc_method_list_t));
  4087. memcpy(&method_list, r, left);
  4088. }
  4089. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4090. swapStruct(method_list);
  4091. outs() << "\t\t obsolete "
  4092. << format("0x%08" PRIx32, method_list.obsolete) << "\n";
  4093. outs() << "\t\t method_count " << method_list.method_count << "\n";
  4094. methods = r + sizeof(struct objc_method_list_t);
  4095. for (i = 0; i < method_list.method_count; i++) {
  4096. if ((i + 1) * sizeof(struct objc_method_t) > left) {
  4097. outs() << "\t\t remaining method's extend past the of the section\n";
  4098. break;
  4099. }
  4100. memcpy(&method, methods + i * sizeof(struct objc_method_t),
  4101. sizeof(struct objc_method_t));
  4102. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4103. swapStruct(method);
  4104. outs() << "\t\t method_name "
  4105. << format("0x%08" PRIx32, method.method_name);
  4106. if (info->verbose) {
  4107. name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
  4108. if (name != nullptr)
  4109. outs() << format(" %.*s", xleft, name);
  4110. else
  4111. outs() << " (not in an __OBJC section)";
  4112. }
  4113. outs() << "\n";
  4114. outs() << "\t\t method_types "
  4115. << format("0x%08" PRIx32, method.method_types);
  4116. if (info->verbose) {
  4117. name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
  4118. if (name != nullptr)
  4119. outs() << format(" %.*s", xleft, name);
  4120. else
  4121. outs() << " (not in an __OBJC section)";
  4122. }
  4123. outs() << "\n";
  4124. outs() << "\t\t method_imp "
  4125. << format("0x%08" PRIx32, method.method_imp) << " ";
  4126. if (info->verbose) {
  4127. SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
  4128. if (SymbolName != nullptr)
  4129. outs() << SymbolName;
  4130. }
  4131. outs() << "\n";
  4132. }
  4133. return false;
  4134. }
  4135. static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
  4136. struct protocol_list64_t pl;
  4137. uint64_t q, n_value;
  4138. struct protocol64_t pc;
  4139. const char *r;
  4140. uint32_t offset, xoffset, left, i;
  4141. SectionRef S, xS;
  4142. const char *name, *sym_name;
  4143. r = get_pointer_64(p, offset, left, S, info);
  4144. if (r == nullptr)
  4145. return;
  4146. memset(&pl, '\0', sizeof(struct protocol_list64_t));
  4147. if (left < sizeof(struct protocol_list64_t)) {
  4148. memcpy(&pl, r, left);
  4149. outs() << " (protocol_list_t entends past the end of the section)\n";
  4150. } else
  4151. memcpy(&pl, r, sizeof(struct protocol_list64_t));
  4152. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4153. swapStruct(pl);
  4154. outs() << " count " << pl.count << "\n";
  4155. p += sizeof(struct protocol_list64_t);
  4156. offset += sizeof(struct protocol_list64_t);
  4157. for (i = 0; i < pl.count; i++) {
  4158. r = get_pointer_64(p, offset, left, S, info);
  4159. if (r == nullptr)
  4160. return;
  4161. q = 0;
  4162. if (left < sizeof(uint64_t)) {
  4163. memcpy(&q, r, left);
  4164. outs() << " (protocol_t * entends past the end of the section)\n";
  4165. } else
  4166. memcpy(&q, r, sizeof(uint64_t));
  4167. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4168. sys::swapByteOrder(q);
  4169. outs() << "\t\t list[" << i << "] ";
  4170. sym_name = get_symbol_64(offset, S, info, n_value, q);
  4171. if (n_value != 0) {
  4172. if (info->verbose && sym_name != nullptr)
  4173. outs() << sym_name;
  4174. else
  4175. outs() << format("0x%" PRIx64, n_value);
  4176. if (q != 0)
  4177. outs() << " + " << format("0x%" PRIx64, q);
  4178. } else
  4179. outs() << format("0x%" PRIx64, q);
  4180. outs() << " (struct protocol_t *)\n";
  4181. r = get_pointer_64(q + n_value, offset, left, S, info);
  4182. if (r == nullptr)
  4183. return;
  4184. memset(&pc, '\0', sizeof(struct protocol64_t));
  4185. if (left < sizeof(struct protocol64_t)) {
  4186. memcpy(&pc, r, left);
  4187. outs() << " (protocol_t entends past the end of the section)\n";
  4188. } else
  4189. memcpy(&pc, r, sizeof(struct protocol64_t));
  4190. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4191. swapStruct(pc);
  4192. outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
  4193. outs() << "\t\t\t name ";
  4194. sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
  4195. info, n_value, pc.name);
  4196. if (n_value != 0) {
  4197. if (info->verbose && sym_name != nullptr)
  4198. outs() << sym_name;
  4199. else
  4200. outs() << format("0x%" PRIx64, n_value);
  4201. if (pc.name != 0)
  4202. outs() << " + " << format("0x%" PRIx64, pc.name);
  4203. } else
  4204. outs() << format("0x%" PRIx64, pc.name);
  4205. name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
  4206. if (name != nullptr)
  4207. outs() << format(" %.*s", left, name);
  4208. outs() << "\n";
  4209. outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
  4210. outs() << "\t\t instanceMethods ";
  4211. sym_name =
  4212. get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
  4213. S, info, n_value, pc.instanceMethods);
  4214. if (n_value != 0) {
  4215. if (info->verbose && sym_name != nullptr)
  4216. outs() << sym_name;
  4217. else
  4218. outs() << format("0x%" PRIx64, n_value);
  4219. if (pc.instanceMethods != 0)
  4220. outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
  4221. } else
  4222. outs() << format("0x%" PRIx64, pc.instanceMethods);
  4223. outs() << " (struct method_list_t *)\n";
  4224. if (pc.instanceMethods + n_value != 0)
  4225. print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
  4226. outs() << "\t\t classMethods ";
  4227. sym_name =
  4228. get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
  4229. info, n_value, pc.classMethods);
  4230. if (n_value != 0) {
  4231. if (info->verbose && sym_name != nullptr)
  4232. outs() << sym_name;
  4233. else
  4234. outs() << format("0x%" PRIx64, n_value);
  4235. if (pc.classMethods != 0)
  4236. outs() << " + " << format("0x%" PRIx64, pc.classMethods);
  4237. } else
  4238. outs() << format("0x%" PRIx64, pc.classMethods);
  4239. outs() << " (struct method_list_t *)\n";
  4240. if (pc.classMethods + n_value != 0)
  4241. print_method_list64_t(pc.classMethods + n_value, info, "\t");
  4242. outs() << "\t optionalInstanceMethods "
  4243. << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
  4244. outs() << "\t optionalClassMethods "
  4245. << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
  4246. outs() << "\t instanceProperties "
  4247. << format("0x%" PRIx64, pc.instanceProperties) << "\n";
  4248. p += sizeof(uint64_t);
  4249. offset += sizeof(uint64_t);
  4250. }
  4251. }
  4252. static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
  4253. struct protocol_list32_t pl;
  4254. uint32_t q;
  4255. struct protocol32_t pc;
  4256. const char *r;
  4257. uint32_t offset, xoffset, left, i;
  4258. SectionRef S, xS;
  4259. const char *name;
  4260. r = get_pointer_32(p, offset, left, S, info);
  4261. if (r == nullptr)
  4262. return;
  4263. memset(&pl, '\0', sizeof(struct protocol_list32_t));
  4264. if (left < sizeof(struct protocol_list32_t)) {
  4265. memcpy(&pl, r, left);
  4266. outs() << " (protocol_list_t entends past the end of the section)\n";
  4267. } else
  4268. memcpy(&pl, r, sizeof(struct protocol_list32_t));
  4269. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4270. swapStruct(pl);
  4271. outs() << " count " << pl.count << "\n";
  4272. p += sizeof(struct protocol_list32_t);
  4273. offset += sizeof(struct protocol_list32_t);
  4274. for (i = 0; i < pl.count; i++) {
  4275. r = get_pointer_32(p, offset, left, S, info);
  4276. if (r == nullptr)
  4277. return;
  4278. q = 0;
  4279. if (left < sizeof(uint32_t)) {
  4280. memcpy(&q, r, left);
  4281. outs() << " (protocol_t * entends past the end of the section)\n";
  4282. } else
  4283. memcpy(&q, r, sizeof(uint32_t));
  4284. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4285. sys::swapByteOrder(q);
  4286. outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
  4287. << " (struct protocol_t *)\n";
  4288. r = get_pointer_32(q, offset, left, S, info);
  4289. if (r == nullptr)
  4290. return;
  4291. memset(&pc, '\0', sizeof(struct protocol32_t));
  4292. if (left < sizeof(struct protocol32_t)) {
  4293. memcpy(&pc, r, left);
  4294. outs() << " (protocol_t entends past the end of the section)\n";
  4295. } else
  4296. memcpy(&pc, r, sizeof(struct protocol32_t));
  4297. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4298. swapStruct(pc);
  4299. outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
  4300. outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
  4301. name = get_pointer_32(pc.name, xoffset, left, xS, info);
  4302. if (name != nullptr)
  4303. outs() << format(" %.*s", left, name);
  4304. outs() << "\n";
  4305. outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
  4306. outs() << "\t\t instanceMethods "
  4307. << format("0x%" PRIx32, pc.instanceMethods)
  4308. << " (struct method_list_t *)\n";
  4309. if (pc.instanceMethods != 0)
  4310. print_method_list32_t(pc.instanceMethods, info, "\t");
  4311. outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
  4312. << " (struct method_list_t *)\n";
  4313. if (pc.classMethods != 0)
  4314. print_method_list32_t(pc.classMethods, info, "\t");
  4315. outs() << "\t optionalInstanceMethods "
  4316. << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
  4317. outs() << "\t optionalClassMethods "
  4318. << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
  4319. outs() << "\t instanceProperties "
  4320. << format("0x%" PRIx32, pc.instanceProperties) << "\n";
  4321. p += sizeof(uint32_t);
  4322. offset += sizeof(uint32_t);
  4323. }
  4324. }
  4325. static void print_indent(uint32_t indent) {
  4326. for (uint32_t i = 0; i < indent;) {
  4327. if (indent - i >= 8) {
  4328. outs() << "\t";
  4329. i += 8;
  4330. } else {
  4331. for (uint32_t j = i; j < indent; j++)
  4332. outs() << " ";
  4333. return;
  4334. }
  4335. }
  4336. }
  4337. static bool print_method_description_list(uint32_t p, uint32_t indent,
  4338. struct DisassembleInfo *info) {
  4339. uint32_t offset, left, xleft;
  4340. SectionRef S;
  4341. struct objc_method_description_list_t mdl;
  4342. struct objc_method_description_t md;
  4343. const char *r, *list, *name;
  4344. int32_t i;
  4345. r = get_pointer_32(p, offset, left, S, info, true);
  4346. if (r == nullptr)
  4347. return true;
  4348. outs() << "\n";
  4349. if (left > sizeof(struct objc_method_description_list_t)) {
  4350. memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
  4351. } else {
  4352. print_indent(indent);
  4353. outs() << " objc_method_description_list extends past end of the section\n";
  4354. memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
  4355. memcpy(&mdl, r, left);
  4356. }
  4357. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4358. swapStruct(mdl);
  4359. print_indent(indent);
  4360. outs() << " count " << mdl.count << "\n";
  4361. list = r + sizeof(struct objc_method_description_list_t);
  4362. for (i = 0; i < mdl.count; i++) {
  4363. if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
  4364. print_indent(indent);
  4365. outs() << " remaining list entries extend past the of the section\n";
  4366. break;
  4367. }
  4368. print_indent(indent);
  4369. outs() << " list[" << i << "]\n";
  4370. memcpy(&md, list + i * sizeof(struct objc_method_description_t),
  4371. sizeof(struct objc_method_description_t));
  4372. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4373. swapStruct(md);
  4374. print_indent(indent);
  4375. outs() << " name " << format("0x%08" PRIx32, md.name);
  4376. if (info->verbose) {
  4377. name = get_pointer_32(md.name, offset, xleft, S, info, true);
  4378. if (name != nullptr)
  4379. outs() << format(" %.*s", xleft, name);
  4380. else
  4381. outs() << " (not in an __OBJC section)";
  4382. }
  4383. outs() << "\n";
  4384. print_indent(indent);
  4385. outs() << " types " << format("0x%08" PRIx32, md.types);
  4386. if (info->verbose) {
  4387. name = get_pointer_32(md.types, offset, xleft, S, info, true);
  4388. if (name != nullptr)
  4389. outs() << format(" %.*s", xleft, name);
  4390. else
  4391. outs() << " (not in an __OBJC section)";
  4392. }
  4393. outs() << "\n";
  4394. }
  4395. return false;
  4396. }
  4397. static bool print_protocol_list(uint32_t p, uint32_t indent,
  4398. struct DisassembleInfo *info);
  4399. static bool print_protocol(uint32_t p, uint32_t indent,
  4400. struct DisassembleInfo *info) {
  4401. uint32_t offset, left;
  4402. SectionRef S;
  4403. struct objc_protocol_t protocol;
  4404. const char *r, *name;
  4405. r = get_pointer_32(p, offset, left, S, info, true);
  4406. if (r == nullptr)
  4407. return true;
  4408. outs() << "\n";
  4409. if (left >= sizeof(struct objc_protocol_t)) {
  4410. memcpy(&protocol, r, sizeof(struct objc_protocol_t));
  4411. } else {
  4412. print_indent(indent);
  4413. outs() << " Protocol extends past end of the section\n";
  4414. memset(&protocol, '\0', sizeof(struct objc_protocol_t));
  4415. memcpy(&protocol, r, left);
  4416. }
  4417. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4418. swapStruct(protocol);
  4419. print_indent(indent);
  4420. outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
  4421. << "\n";
  4422. print_indent(indent);
  4423. outs() << " protocol_name "
  4424. << format("0x%08" PRIx32, protocol.protocol_name);
  4425. if (info->verbose) {
  4426. name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
  4427. if (name != nullptr)
  4428. outs() << format(" %.*s", left, name);
  4429. else
  4430. outs() << " (not in an __OBJC section)";
  4431. }
  4432. outs() << "\n";
  4433. print_indent(indent);
  4434. outs() << " protocol_list "
  4435. << format("0x%08" PRIx32, protocol.protocol_list);
  4436. if (print_protocol_list(protocol.protocol_list, indent + 4, info))
  4437. outs() << " (not in an __OBJC section)\n";
  4438. print_indent(indent);
  4439. outs() << " instance_methods "
  4440. << format("0x%08" PRIx32, protocol.instance_methods);
  4441. if (print_method_description_list(protocol.instance_methods, indent, info))
  4442. outs() << " (not in an __OBJC section)\n";
  4443. print_indent(indent);
  4444. outs() << " class_methods "
  4445. << format("0x%08" PRIx32, protocol.class_methods);
  4446. if (print_method_description_list(protocol.class_methods, indent, info))
  4447. outs() << " (not in an __OBJC section)\n";
  4448. return false;
  4449. }
  4450. static bool print_protocol_list(uint32_t p, uint32_t indent,
  4451. struct DisassembleInfo *info) {
  4452. uint32_t offset, left, l;
  4453. SectionRef S;
  4454. struct objc_protocol_list_t protocol_list;
  4455. const char *r, *list;
  4456. int32_t i;
  4457. r = get_pointer_32(p, offset, left, S, info, true);
  4458. if (r == nullptr)
  4459. return true;
  4460. outs() << "\n";
  4461. if (left > sizeof(struct objc_protocol_list_t)) {
  4462. memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
  4463. } else {
  4464. outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
  4465. memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
  4466. memcpy(&protocol_list, r, left);
  4467. }
  4468. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4469. swapStruct(protocol_list);
  4470. print_indent(indent);
  4471. outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
  4472. << "\n";
  4473. print_indent(indent);
  4474. outs() << " count " << protocol_list.count << "\n";
  4475. list = r + sizeof(struct objc_protocol_list_t);
  4476. for (i = 0; i < protocol_list.count; i++) {
  4477. if ((i + 1) * sizeof(uint32_t) > left) {
  4478. outs() << "\t\t remaining list entries extend past the of the section\n";
  4479. break;
  4480. }
  4481. memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
  4482. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4483. sys::swapByteOrder(l);
  4484. print_indent(indent);
  4485. outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
  4486. if (print_protocol(l, indent, info))
  4487. outs() << "(not in an __OBJC section)\n";
  4488. }
  4489. return false;
  4490. }
  4491. static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
  4492. struct ivar_list64_t il;
  4493. struct ivar64_t i;
  4494. const char *r;
  4495. uint32_t offset, xoffset, left, j;
  4496. SectionRef S, xS;
  4497. const char *name, *sym_name, *ivar_offset_p;
  4498. uint64_t ivar_offset, n_value;
  4499. r = get_pointer_64(p, offset, left, S, info);
  4500. if (r == nullptr)
  4501. return;
  4502. memset(&il, '\0', sizeof(struct ivar_list64_t));
  4503. if (left < sizeof(struct ivar_list64_t)) {
  4504. memcpy(&il, r, left);
  4505. outs() << " (ivar_list_t entends past the end of the section)\n";
  4506. } else
  4507. memcpy(&il, r, sizeof(struct ivar_list64_t));
  4508. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4509. swapStruct(il);
  4510. outs() << " entsize " << il.entsize << "\n";
  4511. outs() << " count " << il.count << "\n";
  4512. p += sizeof(struct ivar_list64_t);
  4513. offset += sizeof(struct ivar_list64_t);
  4514. for (j = 0; j < il.count; j++) {
  4515. r = get_pointer_64(p, offset, left, S, info);
  4516. if (r == nullptr)
  4517. return;
  4518. memset(&i, '\0', sizeof(struct ivar64_t));
  4519. if (left < sizeof(struct ivar64_t)) {
  4520. memcpy(&i, r, left);
  4521. outs() << " (ivar_t entends past the end of the section)\n";
  4522. } else
  4523. memcpy(&i, r, sizeof(struct ivar64_t));
  4524. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4525. swapStruct(i);
  4526. outs() << "\t\t\t offset ";
  4527. sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
  4528. info, n_value, i.offset);
  4529. if (n_value != 0) {
  4530. if (info->verbose && sym_name != nullptr)
  4531. outs() << sym_name;
  4532. else
  4533. outs() << format("0x%" PRIx64, n_value);
  4534. if (i.offset != 0)
  4535. outs() << " + " << format("0x%" PRIx64, i.offset);
  4536. } else
  4537. outs() << format("0x%" PRIx64, i.offset);
  4538. ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
  4539. if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
  4540. memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
  4541. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4542. sys::swapByteOrder(ivar_offset);
  4543. outs() << " " << ivar_offset << "\n";
  4544. } else
  4545. outs() << "\n";
  4546. outs() << "\t\t\t name ";
  4547. sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
  4548. n_value, i.name);
  4549. if (n_value != 0) {
  4550. if (info->verbose && sym_name != nullptr)
  4551. outs() << sym_name;
  4552. else
  4553. outs() << format("0x%" PRIx64, n_value);
  4554. if (i.name != 0)
  4555. outs() << " + " << format("0x%" PRIx64, i.name);
  4556. } else
  4557. outs() << format("0x%" PRIx64, i.name);
  4558. name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
  4559. if (name != nullptr)
  4560. outs() << format(" %.*s", left, name);
  4561. outs() << "\n";
  4562. outs() << "\t\t\t type ";
  4563. sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
  4564. n_value, i.name);
  4565. name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
  4566. if (n_value != 0) {
  4567. if (info->verbose && sym_name != nullptr)
  4568. outs() << sym_name;
  4569. else
  4570. outs() << format("0x%" PRIx64, n_value);
  4571. if (i.type != 0)
  4572. outs() << " + " << format("0x%" PRIx64, i.type);
  4573. } else
  4574. outs() << format("0x%" PRIx64, i.type);
  4575. if (name != nullptr)
  4576. outs() << format(" %.*s", left, name);
  4577. outs() << "\n";
  4578. outs() << "\t\t\talignment " << i.alignment << "\n";
  4579. outs() << "\t\t\t size " << i.size << "\n";
  4580. p += sizeof(struct ivar64_t);
  4581. offset += sizeof(struct ivar64_t);
  4582. }
  4583. }
  4584. static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
  4585. struct ivar_list32_t il;
  4586. struct ivar32_t i;
  4587. const char *r;
  4588. uint32_t offset, xoffset, left, j;
  4589. SectionRef S, xS;
  4590. const char *name, *ivar_offset_p;
  4591. uint32_t ivar_offset;
  4592. r = get_pointer_32(p, offset, left, S, info);
  4593. if (r == nullptr)
  4594. return;
  4595. memset(&il, '\0', sizeof(struct ivar_list32_t));
  4596. if (left < sizeof(struct ivar_list32_t)) {
  4597. memcpy(&il, r, left);
  4598. outs() << " (ivar_list_t entends past the end of the section)\n";
  4599. } else
  4600. memcpy(&il, r, sizeof(struct ivar_list32_t));
  4601. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4602. swapStruct(il);
  4603. outs() << " entsize " << il.entsize << "\n";
  4604. outs() << " count " << il.count << "\n";
  4605. p += sizeof(struct ivar_list32_t);
  4606. offset += sizeof(struct ivar_list32_t);
  4607. for (j = 0; j < il.count; j++) {
  4608. r = get_pointer_32(p, offset, left, S, info);
  4609. if (r == nullptr)
  4610. return;
  4611. memset(&i, '\0', sizeof(struct ivar32_t));
  4612. if (left < sizeof(struct ivar32_t)) {
  4613. memcpy(&i, r, left);
  4614. outs() << " (ivar_t entends past the end of the section)\n";
  4615. } else
  4616. memcpy(&i, r, sizeof(struct ivar32_t));
  4617. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4618. swapStruct(i);
  4619. outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
  4620. ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
  4621. if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
  4622. memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
  4623. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4624. sys::swapByteOrder(ivar_offset);
  4625. outs() << " " << ivar_offset << "\n";
  4626. } else
  4627. outs() << "\n";
  4628. outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
  4629. name = get_pointer_32(i.name, xoffset, left, xS, info);
  4630. if (name != nullptr)
  4631. outs() << format(" %.*s", left, name);
  4632. outs() << "\n";
  4633. outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
  4634. name = get_pointer_32(i.type, xoffset, left, xS, info);
  4635. if (name != nullptr)
  4636. outs() << format(" %.*s", left, name);
  4637. outs() << "\n";
  4638. outs() << "\t\t\talignment " << i.alignment << "\n";
  4639. outs() << "\t\t\t size " << i.size << "\n";
  4640. p += sizeof(struct ivar32_t);
  4641. offset += sizeof(struct ivar32_t);
  4642. }
  4643. }
  4644. static void print_objc_property_list64(uint64_t p,
  4645. struct DisassembleInfo *info) {
  4646. struct objc_property_list64 opl;
  4647. struct objc_property64 op;
  4648. const char *r;
  4649. uint32_t offset, xoffset, left, j;
  4650. SectionRef S, xS;
  4651. const char *name, *sym_name;
  4652. uint64_t n_value;
  4653. r = get_pointer_64(p, offset, left, S, info);
  4654. if (r == nullptr)
  4655. return;
  4656. memset(&opl, '\0', sizeof(struct objc_property_list64));
  4657. if (left < sizeof(struct objc_property_list64)) {
  4658. memcpy(&opl, r, left);
  4659. outs() << " (objc_property_list entends past the end of the section)\n";
  4660. } else
  4661. memcpy(&opl, r, sizeof(struct objc_property_list64));
  4662. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4663. swapStruct(opl);
  4664. outs() << " entsize " << opl.entsize << "\n";
  4665. outs() << " count " << opl.count << "\n";
  4666. p += sizeof(struct objc_property_list64);
  4667. offset += sizeof(struct objc_property_list64);
  4668. for (j = 0; j < opl.count; j++) {
  4669. r = get_pointer_64(p, offset, left, S, info);
  4670. if (r == nullptr)
  4671. return;
  4672. memset(&op, '\0', sizeof(struct objc_property64));
  4673. if (left < sizeof(struct objc_property64)) {
  4674. memcpy(&op, r, left);
  4675. outs() << " (objc_property entends past the end of the section)\n";
  4676. } else
  4677. memcpy(&op, r, sizeof(struct objc_property64));
  4678. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4679. swapStruct(op);
  4680. outs() << "\t\t\t name ";
  4681. sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
  4682. info, n_value, op.name);
  4683. if (n_value != 0) {
  4684. if (info->verbose && sym_name != nullptr)
  4685. outs() << sym_name;
  4686. else
  4687. outs() << format("0x%" PRIx64, n_value);
  4688. if (op.name != 0)
  4689. outs() << " + " << format("0x%" PRIx64, op.name);
  4690. } else
  4691. outs() << format("0x%" PRIx64, op.name);
  4692. name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
  4693. if (name != nullptr)
  4694. outs() << format(" %.*s", left, name);
  4695. outs() << "\n";
  4696. outs() << "\t\t\tattributes ";
  4697. sym_name =
  4698. get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
  4699. info, n_value, op.attributes);
  4700. if (n_value != 0) {
  4701. if (info->verbose && sym_name != nullptr)
  4702. outs() << sym_name;
  4703. else
  4704. outs() << format("0x%" PRIx64, n_value);
  4705. if (op.attributes != 0)
  4706. outs() << " + " << format("0x%" PRIx64, op.attributes);
  4707. } else
  4708. outs() << format("0x%" PRIx64, op.attributes);
  4709. name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
  4710. if (name != nullptr)
  4711. outs() << format(" %.*s", left, name);
  4712. outs() << "\n";
  4713. p += sizeof(struct objc_property64);
  4714. offset += sizeof(struct objc_property64);
  4715. }
  4716. }
  4717. static void print_objc_property_list32(uint32_t p,
  4718. struct DisassembleInfo *info) {
  4719. struct objc_property_list32 opl;
  4720. struct objc_property32 op;
  4721. const char *r;
  4722. uint32_t offset, xoffset, left, j;
  4723. SectionRef S, xS;
  4724. const char *name;
  4725. r = get_pointer_32(p, offset, left, S, info);
  4726. if (r == nullptr)
  4727. return;
  4728. memset(&opl, '\0', sizeof(struct objc_property_list32));
  4729. if (left < sizeof(struct objc_property_list32)) {
  4730. memcpy(&opl, r, left);
  4731. outs() << " (objc_property_list entends past the end of the section)\n";
  4732. } else
  4733. memcpy(&opl, r, sizeof(struct objc_property_list32));
  4734. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4735. swapStruct(opl);
  4736. outs() << " entsize " << opl.entsize << "\n";
  4737. outs() << " count " << opl.count << "\n";
  4738. p += sizeof(struct objc_property_list32);
  4739. offset += sizeof(struct objc_property_list32);
  4740. for (j = 0; j < opl.count; j++) {
  4741. r = get_pointer_32(p, offset, left, S, info);
  4742. if (r == nullptr)
  4743. return;
  4744. memset(&op, '\0', sizeof(struct objc_property32));
  4745. if (left < sizeof(struct objc_property32)) {
  4746. memcpy(&op, r, left);
  4747. outs() << " (objc_property entends past the end of the section)\n";
  4748. } else
  4749. memcpy(&op, r, sizeof(struct objc_property32));
  4750. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4751. swapStruct(op);
  4752. outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
  4753. name = get_pointer_32(op.name, xoffset, left, xS, info);
  4754. if (name != nullptr)
  4755. outs() << format(" %.*s", left, name);
  4756. outs() << "\n";
  4757. outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
  4758. name = get_pointer_32(op.attributes, xoffset, left, xS, info);
  4759. if (name != nullptr)
  4760. outs() << format(" %.*s", left, name);
  4761. outs() << "\n";
  4762. p += sizeof(struct objc_property32);
  4763. offset += sizeof(struct objc_property32);
  4764. }
  4765. }
  4766. static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
  4767. bool &is_meta_class) {
  4768. struct class_ro64_t cro;
  4769. const char *r;
  4770. uint32_t offset, xoffset, left;
  4771. SectionRef S, xS;
  4772. const char *name, *sym_name;
  4773. uint64_t n_value;
  4774. r = get_pointer_64(p, offset, left, S, info);
  4775. if (r == nullptr || left < sizeof(struct class_ro64_t))
  4776. return false;
  4777. memcpy(&cro, r, sizeof(struct class_ro64_t));
  4778. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4779. swapStruct(cro);
  4780. outs() << " flags " << format("0x%" PRIx32, cro.flags);
  4781. if (cro.flags & RO_META)
  4782. outs() << " RO_META";
  4783. if (cro.flags & RO_ROOT)
  4784. outs() << " RO_ROOT";
  4785. if (cro.flags & RO_HAS_CXX_STRUCTORS)
  4786. outs() << " RO_HAS_CXX_STRUCTORS";
  4787. outs() << "\n";
  4788. outs() << " instanceStart " << cro.instanceStart << "\n";
  4789. outs() << " instanceSize " << cro.instanceSize << "\n";
  4790. outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
  4791. << "\n";
  4792. outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
  4793. << "\n";
  4794. print_layout_map64(cro.ivarLayout, info);
  4795. outs() << " name ";
  4796. sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
  4797. info, n_value, cro.name);
  4798. if (n_value != 0) {
  4799. if (info->verbose && sym_name != nullptr)
  4800. outs() << sym_name;
  4801. else
  4802. outs() << format("0x%" PRIx64, n_value);
  4803. if (cro.name != 0)
  4804. outs() << " + " << format("0x%" PRIx64, cro.name);
  4805. } else
  4806. outs() << format("0x%" PRIx64, cro.name);
  4807. name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
  4808. if (name != nullptr)
  4809. outs() << format(" %.*s", left, name);
  4810. outs() << "\n";
  4811. outs() << " baseMethods ";
  4812. sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
  4813. S, info, n_value, cro.baseMethods);
  4814. if (n_value != 0) {
  4815. if (info->verbose && sym_name != nullptr)
  4816. outs() << sym_name;
  4817. else
  4818. outs() << format("0x%" PRIx64, n_value);
  4819. if (cro.baseMethods != 0)
  4820. outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
  4821. } else
  4822. outs() << format("0x%" PRIx64, cro.baseMethods);
  4823. outs() << " (struct method_list_t *)\n";
  4824. if (cro.baseMethods + n_value != 0)
  4825. print_method_list64_t(cro.baseMethods + n_value, info, "");
  4826. outs() << " baseProtocols ";
  4827. sym_name =
  4828. get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
  4829. info, n_value, cro.baseProtocols);
  4830. if (n_value != 0) {
  4831. if (info->verbose && sym_name != nullptr)
  4832. outs() << sym_name;
  4833. else
  4834. outs() << format("0x%" PRIx64, n_value);
  4835. if (cro.baseProtocols != 0)
  4836. outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
  4837. } else
  4838. outs() << format("0x%" PRIx64, cro.baseProtocols);
  4839. outs() << "\n";
  4840. if (cro.baseProtocols + n_value != 0)
  4841. print_protocol_list64_t(cro.baseProtocols + n_value, info);
  4842. outs() << " ivars ";
  4843. sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
  4844. info, n_value, cro.ivars);
  4845. if (n_value != 0) {
  4846. if (info->verbose && sym_name != nullptr)
  4847. outs() << sym_name;
  4848. else
  4849. outs() << format("0x%" PRIx64, n_value);
  4850. if (cro.ivars != 0)
  4851. outs() << " + " << format("0x%" PRIx64, cro.ivars);
  4852. } else
  4853. outs() << format("0x%" PRIx64, cro.ivars);
  4854. outs() << "\n";
  4855. if (cro.ivars + n_value != 0)
  4856. print_ivar_list64_t(cro.ivars + n_value, info);
  4857. outs() << " weakIvarLayout ";
  4858. sym_name =
  4859. get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
  4860. info, n_value, cro.weakIvarLayout);
  4861. if (n_value != 0) {
  4862. if (info->verbose && sym_name != nullptr)
  4863. outs() << sym_name;
  4864. else
  4865. outs() << format("0x%" PRIx64, n_value);
  4866. if (cro.weakIvarLayout != 0)
  4867. outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
  4868. } else
  4869. outs() << format("0x%" PRIx64, cro.weakIvarLayout);
  4870. outs() << "\n";
  4871. print_layout_map64(cro.weakIvarLayout + n_value, info);
  4872. outs() << " baseProperties ";
  4873. sym_name =
  4874. get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
  4875. info, n_value, cro.baseProperties);
  4876. if (n_value != 0) {
  4877. if (info->verbose && sym_name != nullptr)
  4878. outs() << sym_name;
  4879. else
  4880. outs() << format("0x%" PRIx64, n_value);
  4881. if (cro.baseProperties != 0)
  4882. outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
  4883. } else
  4884. outs() << format("0x%" PRIx64, cro.baseProperties);
  4885. outs() << "\n";
  4886. if (cro.baseProperties + n_value != 0)
  4887. print_objc_property_list64(cro.baseProperties + n_value, info);
  4888. is_meta_class = (cro.flags & RO_META) != 0;
  4889. return true;
  4890. }
  4891. static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
  4892. bool &is_meta_class) {
  4893. struct class_ro32_t cro;
  4894. const char *r;
  4895. uint32_t offset, xoffset, left;
  4896. SectionRef S, xS;
  4897. const char *name;
  4898. r = get_pointer_32(p, offset, left, S, info);
  4899. if (r == nullptr)
  4900. return false;
  4901. memset(&cro, '\0', sizeof(struct class_ro32_t));
  4902. if (left < sizeof(struct class_ro32_t)) {
  4903. memcpy(&cro, r, left);
  4904. outs() << " (class_ro_t entends past the end of the section)\n";
  4905. } else
  4906. memcpy(&cro, r, sizeof(struct class_ro32_t));
  4907. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4908. swapStruct(cro);
  4909. outs() << " flags " << format("0x%" PRIx32, cro.flags);
  4910. if (cro.flags & RO_META)
  4911. outs() << " RO_META";
  4912. if (cro.flags & RO_ROOT)
  4913. outs() << " RO_ROOT";
  4914. if (cro.flags & RO_HAS_CXX_STRUCTORS)
  4915. outs() << " RO_HAS_CXX_STRUCTORS";
  4916. outs() << "\n";
  4917. outs() << " instanceStart " << cro.instanceStart << "\n";
  4918. outs() << " instanceSize " << cro.instanceSize << "\n";
  4919. outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
  4920. << "\n";
  4921. print_layout_map32(cro.ivarLayout, info);
  4922. outs() << " name " << format("0x%" PRIx32, cro.name);
  4923. name = get_pointer_32(cro.name, xoffset, left, xS, info);
  4924. if (name != nullptr)
  4925. outs() << format(" %.*s", left, name);
  4926. outs() << "\n";
  4927. outs() << " baseMethods "
  4928. << format("0x%" PRIx32, cro.baseMethods)
  4929. << " (struct method_list_t *)\n";
  4930. if (cro.baseMethods != 0)
  4931. print_method_list32_t(cro.baseMethods, info, "");
  4932. outs() << " baseProtocols "
  4933. << format("0x%" PRIx32, cro.baseProtocols) << "\n";
  4934. if (cro.baseProtocols != 0)
  4935. print_protocol_list32_t(cro.baseProtocols, info);
  4936. outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
  4937. << "\n";
  4938. if (cro.ivars != 0)
  4939. print_ivar_list32_t(cro.ivars, info);
  4940. outs() << " weakIvarLayout "
  4941. << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
  4942. print_layout_map32(cro.weakIvarLayout, info);
  4943. outs() << " baseProperties "
  4944. << format("0x%" PRIx32, cro.baseProperties) << "\n";
  4945. if (cro.baseProperties != 0)
  4946. print_objc_property_list32(cro.baseProperties, info);
  4947. is_meta_class = (cro.flags & RO_META) != 0;
  4948. return true;
  4949. }
  4950. static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
  4951. struct class64_t c;
  4952. const char *r;
  4953. uint32_t offset, left;
  4954. SectionRef S;
  4955. const char *name;
  4956. uint64_t isa_n_value, n_value;
  4957. r = get_pointer_64(p, offset, left, S, info);
  4958. if (r == nullptr || left < sizeof(struct class64_t))
  4959. return;
  4960. memcpy(&c, r, sizeof(struct class64_t));
  4961. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4962. swapStruct(c);
  4963. outs() << " isa " << format("0x%" PRIx64, c.isa);
  4964. name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
  4965. isa_n_value, c.isa);
  4966. if (name != nullptr)
  4967. outs() << " " << name;
  4968. outs() << "\n";
  4969. outs() << " superclass " << format("0x%" PRIx64, c.superclass);
  4970. name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
  4971. n_value, c.superclass);
  4972. if (name != nullptr)
  4973. outs() << " " << name;
  4974. else {
  4975. name = get_dyld_bind_info_symbolname(S.getAddress() +
  4976. offset + offsetof(struct class64_t, superclass), info);
  4977. if (name != nullptr)
  4978. outs() << " " << name;
  4979. }
  4980. outs() << "\n";
  4981. outs() << " cache " << format("0x%" PRIx64, c.cache);
  4982. name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
  4983. n_value, c.cache);
  4984. if (name != nullptr)
  4985. outs() << " " << name;
  4986. outs() << "\n";
  4987. outs() << " vtable " << format("0x%" PRIx64, c.vtable);
  4988. name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
  4989. n_value, c.vtable);
  4990. if (name != nullptr)
  4991. outs() << " " << name;
  4992. outs() << "\n";
  4993. name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
  4994. n_value, c.data);
  4995. outs() << " data ";
  4996. if (n_value != 0) {
  4997. if (info->verbose && name != nullptr)
  4998. outs() << name;
  4999. else
  5000. outs() << format("0x%" PRIx64, n_value);
  5001. if (c.data != 0)
  5002. outs() << " + " << format("0x%" PRIx64, c.data);
  5003. } else
  5004. outs() << format("0x%" PRIx64, c.data);
  5005. outs() << " (struct class_ro_t *)";
  5006. // This is a Swift class if some of the low bits of the pointer are set.
  5007. if ((c.data + n_value) & 0x7)
  5008. outs() << " Swift class";
  5009. outs() << "\n";
  5010. bool is_meta_class;
  5011. if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
  5012. return;
  5013. if (!is_meta_class &&
  5014. c.isa + isa_n_value != p &&
  5015. c.isa + isa_n_value != 0 &&
  5016. info->depth < 100) {
  5017. info->depth++;
  5018. outs() << "Meta Class\n";
  5019. print_class64_t(c.isa + isa_n_value, info);
  5020. }
  5021. }
  5022. static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
  5023. struct class32_t c;
  5024. const char *r;
  5025. uint32_t offset, left;
  5026. SectionRef S;
  5027. const char *name;
  5028. r = get_pointer_32(p, offset, left, S, info);
  5029. if (r == nullptr)
  5030. return;
  5031. memset(&c, '\0', sizeof(struct class32_t));
  5032. if (left < sizeof(struct class32_t)) {
  5033. memcpy(&c, r, left);
  5034. outs() << " (class_t entends past the end of the section)\n";
  5035. } else
  5036. memcpy(&c, r, sizeof(struct class32_t));
  5037. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5038. swapStruct(c);
  5039. outs() << " isa " << format("0x%" PRIx32, c.isa);
  5040. name =
  5041. get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
  5042. if (name != nullptr)
  5043. outs() << " " << name;
  5044. outs() << "\n";
  5045. outs() << " superclass " << format("0x%" PRIx32, c.superclass);
  5046. name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
  5047. c.superclass);
  5048. if (name != nullptr)
  5049. outs() << " " << name;
  5050. outs() << "\n";
  5051. outs() << " cache " << format("0x%" PRIx32, c.cache);
  5052. name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
  5053. c.cache);
  5054. if (name != nullptr)
  5055. outs() << " " << name;
  5056. outs() << "\n";
  5057. outs() << " vtable " << format("0x%" PRIx32, c.vtable);
  5058. name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
  5059. c.vtable);
  5060. if (name != nullptr)
  5061. outs() << " " << name;
  5062. outs() << "\n";
  5063. name =
  5064. get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
  5065. outs() << " data " << format("0x%" PRIx32, c.data)
  5066. << " (struct class_ro_t *)";
  5067. // This is a Swift class if some of the low bits of the pointer are set.
  5068. if (c.data & 0x3)
  5069. outs() << " Swift class";
  5070. outs() << "\n";
  5071. bool is_meta_class;
  5072. if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
  5073. return;
  5074. if (!is_meta_class) {
  5075. outs() << "Meta Class\n";
  5076. print_class32_t(c.isa, info);
  5077. }
  5078. }
  5079. static void print_objc_class_t(struct objc_class_t *objc_class,
  5080. struct DisassembleInfo *info) {
  5081. uint32_t offset, left, xleft;
  5082. const char *name, *p, *ivar_list;
  5083. SectionRef S;
  5084. int32_t i;
  5085. struct objc_ivar_list_t objc_ivar_list;
  5086. struct objc_ivar_t ivar;
  5087. outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
  5088. if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
  5089. name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
  5090. if (name != nullptr)
  5091. outs() << format(" %.*s", left, name);
  5092. else
  5093. outs() << " (not in an __OBJC section)";
  5094. }
  5095. outs() << "\n";
  5096. outs() << "\t super_class "
  5097. << format("0x%08" PRIx32, objc_class->super_class);
  5098. if (info->verbose) {
  5099. name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
  5100. if (name != nullptr)
  5101. outs() << format(" %.*s", left, name);
  5102. else
  5103. outs() << " (not in an __OBJC section)";
  5104. }
  5105. outs() << "\n";
  5106. outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
  5107. if (info->verbose) {
  5108. name = get_pointer_32(objc_class->name, offset, left, S, info, true);
  5109. if (name != nullptr)
  5110. outs() << format(" %.*s", left, name);
  5111. else
  5112. outs() << " (not in an __OBJC section)";
  5113. }
  5114. outs() << "\n";
  5115. outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
  5116. << "\n";
  5117. outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
  5118. if (info->verbose) {
  5119. if (CLS_GETINFO(objc_class, CLS_CLASS))
  5120. outs() << " CLS_CLASS";
  5121. else if (CLS_GETINFO(objc_class, CLS_META))
  5122. outs() << " CLS_META";
  5123. }
  5124. outs() << "\n";
  5125. outs() << "\t instance_size "
  5126. << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
  5127. p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
  5128. outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
  5129. if (p != nullptr) {
  5130. if (left > sizeof(struct objc_ivar_list_t)) {
  5131. outs() << "\n";
  5132. memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
  5133. } else {
  5134. outs() << " (entends past the end of the section)\n";
  5135. memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
  5136. memcpy(&objc_ivar_list, p, left);
  5137. }
  5138. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5139. swapStruct(objc_ivar_list);
  5140. outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
  5141. ivar_list = p + sizeof(struct objc_ivar_list_t);
  5142. for (i = 0; i < objc_ivar_list.ivar_count; i++) {
  5143. if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
  5144. outs() << "\t\t remaining ivar's extend past the of the section\n";
  5145. break;
  5146. }
  5147. memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
  5148. sizeof(struct objc_ivar_t));
  5149. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5150. swapStruct(ivar);
  5151. outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
  5152. if (info->verbose) {
  5153. name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
  5154. if (name != nullptr)
  5155. outs() << format(" %.*s", xleft, name);
  5156. else
  5157. outs() << " (not in an __OBJC section)";
  5158. }
  5159. outs() << "\n";
  5160. outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
  5161. if (info->verbose) {
  5162. name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
  5163. if (name != nullptr)
  5164. outs() << format(" %.*s", xleft, name);
  5165. else
  5166. outs() << " (not in an __OBJC section)";
  5167. }
  5168. outs() << "\n";
  5169. outs() << "\t\t ivar_offset "
  5170. << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
  5171. }
  5172. } else {
  5173. outs() << " (not in an __OBJC section)\n";
  5174. }
  5175. outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
  5176. if (print_method_list(objc_class->methodLists, info))
  5177. outs() << " (not in an __OBJC section)\n";
  5178. outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
  5179. << "\n";
  5180. outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
  5181. if (print_protocol_list(objc_class->protocols, 16, info))
  5182. outs() << " (not in an __OBJC section)\n";
  5183. }
  5184. static void print_objc_objc_category_t(struct objc_category_t *objc_category,
  5185. struct DisassembleInfo *info) {
  5186. uint32_t offset, left;
  5187. const char *name;
  5188. SectionRef S;
  5189. outs() << "\t category name "
  5190. << format("0x%08" PRIx32, objc_category->category_name);
  5191. if (info->verbose) {
  5192. name = get_pointer_32(objc_category->category_name, offset, left, S, info,
  5193. true);
  5194. if (name != nullptr)
  5195. outs() << format(" %.*s", left, name);
  5196. else
  5197. outs() << " (not in an __OBJC section)";
  5198. }
  5199. outs() << "\n";
  5200. outs() << "\t\t class name "
  5201. << format("0x%08" PRIx32, objc_category->class_name);
  5202. if (info->verbose) {
  5203. name =
  5204. get_pointer_32(objc_category->class_name, offset, left, S, info, true);
  5205. if (name != nullptr)
  5206. outs() << format(" %.*s", left, name);
  5207. else
  5208. outs() << " (not in an __OBJC section)";
  5209. }
  5210. outs() << "\n";
  5211. outs() << "\t instance methods "
  5212. << format("0x%08" PRIx32, objc_category->instance_methods);
  5213. if (print_method_list(objc_category->instance_methods, info))
  5214. outs() << " (not in an __OBJC section)\n";
  5215. outs() << "\t class methods "
  5216. << format("0x%08" PRIx32, objc_category->class_methods);
  5217. if (print_method_list(objc_category->class_methods, info))
  5218. outs() << " (not in an __OBJC section)\n";
  5219. }
  5220. static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
  5221. struct category64_t c;
  5222. const char *r;
  5223. uint32_t offset, xoffset, left;
  5224. SectionRef S, xS;
  5225. const char *name, *sym_name;
  5226. uint64_t n_value;
  5227. r = get_pointer_64(p, offset, left, S, info);
  5228. if (r == nullptr)
  5229. return;
  5230. memset(&c, '\0', sizeof(struct category64_t));
  5231. if (left < sizeof(struct category64_t)) {
  5232. memcpy(&c, r, left);
  5233. outs() << " (category_t entends past the end of the section)\n";
  5234. } else
  5235. memcpy(&c, r, sizeof(struct category64_t));
  5236. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5237. swapStruct(c);
  5238. outs() << " name ";
  5239. sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
  5240. info, n_value, c.name);
  5241. if (n_value != 0) {
  5242. if (info->verbose && sym_name != nullptr)
  5243. outs() << sym_name;
  5244. else
  5245. outs() << format("0x%" PRIx64, n_value);
  5246. if (c.name != 0)
  5247. outs() << " + " << format("0x%" PRIx64, c.name);
  5248. } else
  5249. outs() << format("0x%" PRIx64, c.name);
  5250. name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
  5251. if (name != nullptr)
  5252. outs() << format(" %.*s", left, name);
  5253. outs() << "\n";
  5254. outs() << " cls ";
  5255. sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
  5256. n_value, c.cls);
  5257. if (n_value != 0) {
  5258. if (info->verbose && sym_name != nullptr)
  5259. outs() << sym_name;
  5260. else
  5261. outs() << format("0x%" PRIx64, n_value);
  5262. if (c.cls != 0)
  5263. outs() << " + " << format("0x%" PRIx64, c.cls);
  5264. } else
  5265. outs() << format("0x%" PRIx64, c.cls);
  5266. outs() << "\n";
  5267. if (c.cls + n_value != 0)
  5268. print_class64_t(c.cls + n_value, info);
  5269. outs() << " instanceMethods ";
  5270. sym_name =
  5271. get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
  5272. info, n_value, c.instanceMethods);
  5273. if (n_value != 0) {
  5274. if (info->verbose && sym_name != nullptr)
  5275. outs() << sym_name;
  5276. else
  5277. outs() << format("0x%" PRIx64, n_value);
  5278. if (c.instanceMethods != 0)
  5279. outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
  5280. } else
  5281. outs() << format("0x%" PRIx64, c.instanceMethods);
  5282. outs() << "\n";
  5283. if (c.instanceMethods + n_value != 0)
  5284. print_method_list64_t(c.instanceMethods + n_value, info, "");
  5285. outs() << " classMethods ";
  5286. sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
  5287. S, info, n_value, c.classMethods);
  5288. if (n_value != 0) {
  5289. if (info->verbose && sym_name != nullptr)
  5290. outs() << sym_name;
  5291. else
  5292. outs() << format("0x%" PRIx64, n_value);
  5293. if (c.classMethods != 0)
  5294. outs() << " + " << format("0x%" PRIx64, c.classMethods);
  5295. } else
  5296. outs() << format("0x%" PRIx64, c.classMethods);
  5297. outs() << "\n";
  5298. if (c.classMethods + n_value != 0)
  5299. print_method_list64_t(c.classMethods + n_value, info, "");
  5300. outs() << " protocols ";
  5301. sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
  5302. info, n_value, c.protocols);
  5303. if (n_value != 0) {
  5304. if (info->verbose && sym_name != nullptr)
  5305. outs() << sym_name;
  5306. else
  5307. outs() << format("0x%" PRIx64, n_value);
  5308. if (c.protocols != 0)
  5309. outs() << " + " << format("0x%" PRIx64, c.protocols);
  5310. } else
  5311. outs() << format("0x%" PRIx64, c.protocols);
  5312. outs() << "\n";
  5313. if (c.protocols + n_value != 0)
  5314. print_protocol_list64_t(c.protocols + n_value, info);
  5315. outs() << "instanceProperties ";
  5316. sym_name =
  5317. get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
  5318. S, info, n_value, c.instanceProperties);
  5319. if (n_value != 0) {
  5320. if (info->verbose && sym_name != nullptr)
  5321. outs() << sym_name;
  5322. else
  5323. outs() << format("0x%" PRIx64, n_value);
  5324. if (c.instanceProperties != 0)
  5325. outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
  5326. } else
  5327. outs() << format("0x%" PRIx64, c.instanceProperties);
  5328. outs() << "\n";
  5329. if (c.instanceProperties + n_value != 0)
  5330. print_objc_property_list64(c.instanceProperties + n_value, info);
  5331. }
  5332. static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
  5333. struct category32_t c;
  5334. const char *r;
  5335. uint32_t offset, left;
  5336. SectionRef S, xS;
  5337. const char *name;
  5338. r = get_pointer_32(p, offset, left, S, info);
  5339. if (r == nullptr)
  5340. return;
  5341. memset(&c, '\0', sizeof(struct category32_t));
  5342. if (left < sizeof(struct category32_t)) {
  5343. memcpy(&c, r, left);
  5344. outs() << " (category_t entends past the end of the section)\n";
  5345. } else
  5346. memcpy(&c, r, sizeof(struct category32_t));
  5347. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5348. swapStruct(c);
  5349. outs() << " name " << format("0x%" PRIx32, c.name);
  5350. name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
  5351. c.name);
  5352. if (name)
  5353. outs() << " " << name;
  5354. outs() << "\n";
  5355. outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
  5356. if (c.cls != 0)
  5357. print_class32_t(c.cls, info);
  5358. outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
  5359. << "\n";
  5360. if (c.instanceMethods != 0)
  5361. print_method_list32_t(c.instanceMethods, info, "");
  5362. outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
  5363. << "\n";
  5364. if (c.classMethods != 0)
  5365. print_method_list32_t(c.classMethods, info, "");
  5366. outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
  5367. if (c.protocols != 0)
  5368. print_protocol_list32_t(c.protocols, info);
  5369. outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
  5370. << "\n";
  5371. if (c.instanceProperties != 0)
  5372. print_objc_property_list32(c.instanceProperties, info);
  5373. }
  5374. static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
  5375. uint32_t i, left, offset, xoffset;
  5376. uint64_t p, n_value;
  5377. struct message_ref64 mr;
  5378. const char *name, *sym_name;
  5379. const char *r;
  5380. SectionRef xS;
  5381. if (S == SectionRef())
  5382. return;
  5383. StringRef SectName;
  5384. Expected<StringRef> SecNameOrErr = S.getName();
  5385. if (SecNameOrErr)
  5386. SectName = *SecNameOrErr;
  5387. else
  5388. consumeError(SecNameOrErr.takeError());
  5389. DataRefImpl Ref = S.getRawDataRefImpl();
  5390. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  5391. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  5392. offset = 0;
  5393. for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
  5394. p = S.getAddress() + i;
  5395. r = get_pointer_64(p, offset, left, S, info);
  5396. if (r == nullptr)
  5397. return;
  5398. memset(&mr, '\0', sizeof(struct message_ref64));
  5399. if (left < sizeof(struct message_ref64)) {
  5400. memcpy(&mr, r, left);
  5401. outs() << " (message_ref entends past the end of the section)\n";
  5402. } else
  5403. memcpy(&mr, r, sizeof(struct message_ref64));
  5404. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5405. swapStruct(mr);
  5406. outs() << " imp ";
  5407. name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
  5408. n_value, mr.imp);
  5409. if (n_value != 0) {
  5410. outs() << format("0x%" PRIx64, n_value) << " ";
  5411. if (mr.imp != 0)
  5412. outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
  5413. } else
  5414. outs() << format("0x%" PRIx64, mr.imp) << " ";
  5415. if (name != nullptr)
  5416. outs() << " " << name;
  5417. outs() << "\n";
  5418. outs() << " sel ";
  5419. sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
  5420. info, n_value, mr.sel);
  5421. if (n_value != 0) {
  5422. if (info->verbose && sym_name != nullptr)
  5423. outs() << sym_name;
  5424. else
  5425. outs() << format("0x%" PRIx64, n_value);
  5426. if (mr.sel != 0)
  5427. outs() << " + " << format("0x%" PRIx64, mr.sel);
  5428. } else
  5429. outs() << format("0x%" PRIx64, mr.sel);
  5430. name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
  5431. if (name != nullptr)
  5432. outs() << format(" %.*s", left, name);
  5433. outs() << "\n";
  5434. offset += sizeof(struct message_ref64);
  5435. }
  5436. }
  5437. static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
  5438. uint32_t i, left, offset, xoffset, p;
  5439. struct message_ref32 mr;
  5440. const char *name, *r;
  5441. SectionRef xS;
  5442. if (S == SectionRef())
  5443. return;
  5444. StringRef SectName;
  5445. Expected<StringRef> SecNameOrErr = S.getName();
  5446. if (SecNameOrErr)
  5447. SectName = *SecNameOrErr;
  5448. else
  5449. consumeError(SecNameOrErr.takeError());
  5450. DataRefImpl Ref = S.getRawDataRefImpl();
  5451. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  5452. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  5453. offset = 0;
  5454. for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
  5455. p = S.getAddress() + i;
  5456. r = get_pointer_32(p, offset, left, S, info);
  5457. if (r == nullptr)
  5458. return;
  5459. memset(&mr, '\0', sizeof(struct message_ref32));
  5460. if (left < sizeof(struct message_ref32)) {
  5461. memcpy(&mr, r, left);
  5462. outs() << " (message_ref entends past the end of the section)\n";
  5463. } else
  5464. memcpy(&mr, r, sizeof(struct message_ref32));
  5465. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5466. swapStruct(mr);
  5467. outs() << " imp " << format("0x%" PRIx32, mr.imp);
  5468. name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
  5469. mr.imp);
  5470. if (name != nullptr)
  5471. outs() << " " << name;
  5472. outs() << "\n";
  5473. outs() << " sel " << format("0x%" PRIx32, mr.sel);
  5474. name = get_pointer_32(mr.sel, xoffset, left, xS, info);
  5475. if (name != nullptr)
  5476. outs() << " " << name;
  5477. outs() << "\n";
  5478. offset += sizeof(struct message_ref32);
  5479. }
  5480. }
  5481. static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
  5482. uint32_t left, offset, swift_version;
  5483. uint64_t p;
  5484. struct objc_image_info64 o;
  5485. const char *r;
  5486. if (S == SectionRef())
  5487. return;
  5488. StringRef SectName;
  5489. Expected<StringRef> SecNameOrErr = S.getName();
  5490. if (SecNameOrErr)
  5491. SectName = *SecNameOrErr;
  5492. else
  5493. consumeError(SecNameOrErr.takeError());
  5494. DataRefImpl Ref = S.getRawDataRefImpl();
  5495. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  5496. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  5497. p = S.getAddress();
  5498. r = get_pointer_64(p, offset, left, S, info);
  5499. if (r == nullptr)
  5500. return;
  5501. memset(&o, '\0', sizeof(struct objc_image_info64));
  5502. if (left < sizeof(struct objc_image_info64)) {
  5503. memcpy(&o, r, left);
  5504. outs() << " (objc_image_info entends past the end of the section)\n";
  5505. } else
  5506. memcpy(&o, r, sizeof(struct objc_image_info64));
  5507. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5508. swapStruct(o);
  5509. outs() << " version " << o.version << "\n";
  5510. outs() << " flags " << format("0x%" PRIx32, o.flags);
  5511. if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
  5512. outs() << " OBJC_IMAGE_IS_REPLACEMENT";
  5513. if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
  5514. outs() << " OBJC_IMAGE_SUPPORTS_GC";
  5515. if (o.flags & OBJC_IMAGE_IS_SIMULATED)
  5516. outs() << " OBJC_IMAGE_IS_SIMULATED";
  5517. if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
  5518. outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
  5519. swift_version = (o.flags >> 8) & 0xff;
  5520. if (swift_version != 0) {
  5521. if (swift_version == 1)
  5522. outs() << " Swift 1.0";
  5523. else if (swift_version == 2)
  5524. outs() << " Swift 1.1";
  5525. else if(swift_version == 3)
  5526. outs() << " Swift 2.0";
  5527. else if(swift_version == 4)
  5528. outs() << " Swift 3.0";
  5529. else if(swift_version == 5)
  5530. outs() << " Swift 4.0";
  5531. else if(swift_version == 6)
  5532. outs() << " Swift 4.1/Swift 4.2";
  5533. else if(swift_version == 7)
  5534. outs() << " Swift 5 or later";
  5535. else
  5536. outs() << " unknown future Swift version (" << swift_version << ")";
  5537. }
  5538. outs() << "\n";
  5539. }
  5540. static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
  5541. uint32_t left, offset, swift_version, p;
  5542. struct objc_image_info32 o;
  5543. const char *r;
  5544. if (S == SectionRef())
  5545. return;
  5546. StringRef SectName;
  5547. Expected<StringRef> SecNameOrErr = S.getName();
  5548. if (SecNameOrErr)
  5549. SectName = *SecNameOrErr;
  5550. else
  5551. consumeError(SecNameOrErr.takeError());
  5552. DataRefImpl Ref = S.getRawDataRefImpl();
  5553. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  5554. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  5555. p = S.getAddress();
  5556. r = get_pointer_32(p, offset, left, S, info);
  5557. if (r == nullptr)
  5558. return;
  5559. memset(&o, '\0', sizeof(struct objc_image_info32));
  5560. if (left < sizeof(struct objc_image_info32)) {
  5561. memcpy(&o, r, left);
  5562. outs() << " (objc_image_info entends past the end of the section)\n";
  5563. } else
  5564. memcpy(&o, r, sizeof(struct objc_image_info32));
  5565. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5566. swapStruct(o);
  5567. outs() << " version " << o.version << "\n";
  5568. outs() << " flags " << format("0x%" PRIx32, o.flags);
  5569. if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
  5570. outs() << " OBJC_IMAGE_IS_REPLACEMENT";
  5571. if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
  5572. outs() << " OBJC_IMAGE_SUPPORTS_GC";
  5573. swift_version = (o.flags >> 8) & 0xff;
  5574. if (swift_version != 0) {
  5575. if (swift_version == 1)
  5576. outs() << " Swift 1.0";
  5577. else if (swift_version == 2)
  5578. outs() << " Swift 1.1";
  5579. else if(swift_version == 3)
  5580. outs() << " Swift 2.0";
  5581. else if(swift_version == 4)
  5582. outs() << " Swift 3.0";
  5583. else if(swift_version == 5)
  5584. outs() << " Swift 4.0";
  5585. else if(swift_version == 6)
  5586. outs() << " Swift 4.1/Swift 4.2";
  5587. else if(swift_version == 7)
  5588. outs() << " Swift 5 or later";
  5589. else
  5590. outs() << " unknown future Swift version (" << swift_version << ")";
  5591. }
  5592. outs() << "\n";
  5593. }
  5594. static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
  5595. uint32_t left, offset, p;
  5596. struct imageInfo_t o;
  5597. const char *r;
  5598. StringRef SectName;
  5599. Expected<StringRef> SecNameOrErr = S.getName();
  5600. if (SecNameOrErr)
  5601. SectName = *SecNameOrErr;
  5602. else
  5603. consumeError(SecNameOrErr.takeError());
  5604. DataRefImpl Ref = S.getRawDataRefImpl();
  5605. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  5606. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  5607. p = S.getAddress();
  5608. r = get_pointer_32(p, offset, left, S, info);
  5609. if (r == nullptr)
  5610. return;
  5611. memset(&o, '\0', sizeof(struct imageInfo_t));
  5612. if (left < sizeof(struct imageInfo_t)) {
  5613. memcpy(&o, r, left);
  5614. outs() << " (imageInfo entends past the end of the section)\n";
  5615. } else
  5616. memcpy(&o, r, sizeof(struct imageInfo_t));
  5617. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5618. swapStruct(o);
  5619. outs() << " version " << o.version << "\n";
  5620. outs() << " flags " << format("0x%" PRIx32, o.flags);
  5621. if (o.flags & 0x1)
  5622. outs() << " F&C";
  5623. if (o.flags & 0x2)
  5624. outs() << " GC";
  5625. if (o.flags & 0x4)
  5626. outs() << " GC-only";
  5627. else
  5628. outs() << " RR";
  5629. outs() << "\n";
  5630. }
  5631. static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
  5632. SymbolAddressMap AddrMap;
  5633. if (verbose)
  5634. CreateSymbolAddressMap(O, &AddrMap);
  5635. std::vector<SectionRef> Sections;
  5636. append_range(Sections, O->sections());
  5637. struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
  5638. SectionRef CL = get_section(O, "__OBJC2", "__class_list");
  5639. if (CL == SectionRef())
  5640. CL = get_section(O, "__DATA", "__objc_classlist");
  5641. if (CL == SectionRef())
  5642. CL = get_section(O, "__DATA_CONST", "__objc_classlist");
  5643. if (CL == SectionRef())
  5644. CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
  5645. info.S = CL;
  5646. walk_pointer_list_64("class", CL, O, &info, print_class64_t);
  5647. SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
  5648. if (CR == SectionRef())
  5649. CR = get_section(O, "__DATA", "__objc_classrefs");
  5650. if (CR == SectionRef())
  5651. CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
  5652. if (CR == SectionRef())
  5653. CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
  5654. info.S = CR;
  5655. walk_pointer_list_64("class refs", CR, O, &info, nullptr);
  5656. SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
  5657. if (SR == SectionRef())
  5658. SR = get_section(O, "__DATA", "__objc_superrefs");
  5659. if (SR == SectionRef())
  5660. SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
  5661. if (SR == SectionRef())
  5662. SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
  5663. info.S = SR;
  5664. walk_pointer_list_64("super refs", SR, O, &info, nullptr);
  5665. SectionRef CA = get_section(O, "__OBJC2", "__category_list");
  5666. if (CA == SectionRef())
  5667. CA = get_section(O, "__DATA", "__objc_catlist");
  5668. if (CA == SectionRef())
  5669. CA = get_section(O, "__DATA_CONST", "__objc_catlist");
  5670. if (CA == SectionRef())
  5671. CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
  5672. info.S = CA;
  5673. walk_pointer_list_64("category", CA, O, &info, print_category64_t);
  5674. SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
  5675. if (PL == SectionRef())
  5676. PL = get_section(O, "__DATA", "__objc_protolist");
  5677. if (PL == SectionRef())
  5678. PL = get_section(O, "__DATA_CONST", "__objc_protolist");
  5679. if (PL == SectionRef())
  5680. PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
  5681. info.S = PL;
  5682. walk_pointer_list_64("protocol", PL, O, &info, nullptr);
  5683. SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
  5684. if (MR == SectionRef())
  5685. MR = get_section(O, "__DATA", "__objc_msgrefs");
  5686. if (MR == SectionRef())
  5687. MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
  5688. if (MR == SectionRef())
  5689. MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
  5690. info.S = MR;
  5691. print_message_refs64(MR, &info);
  5692. SectionRef II = get_section(O, "__OBJC2", "__image_info");
  5693. if (II == SectionRef())
  5694. II = get_section(O, "__DATA", "__objc_imageinfo");
  5695. if (II == SectionRef())
  5696. II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
  5697. if (II == SectionRef())
  5698. II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
  5699. info.S = II;
  5700. print_image_info64(II, &info);
  5701. }
  5702. static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
  5703. SymbolAddressMap AddrMap;
  5704. if (verbose)
  5705. CreateSymbolAddressMap(O, &AddrMap);
  5706. std::vector<SectionRef> Sections;
  5707. append_range(Sections, O->sections());
  5708. struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
  5709. SectionRef CL = get_section(O, "__OBJC2", "__class_list");
  5710. if (CL == SectionRef())
  5711. CL = get_section(O, "__DATA", "__objc_classlist");
  5712. if (CL == SectionRef())
  5713. CL = get_section(O, "__DATA_CONST", "__objc_classlist");
  5714. if (CL == SectionRef())
  5715. CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
  5716. info.S = CL;
  5717. walk_pointer_list_32("class", CL, O, &info, print_class32_t);
  5718. SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
  5719. if (CR == SectionRef())
  5720. CR = get_section(O, "__DATA", "__objc_classrefs");
  5721. if (CR == SectionRef())
  5722. CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
  5723. if (CR == SectionRef())
  5724. CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
  5725. info.S = CR;
  5726. walk_pointer_list_32("class refs", CR, O, &info, nullptr);
  5727. SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
  5728. if (SR == SectionRef())
  5729. SR = get_section(O, "__DATA", "__objc_superrefs");
  5730. if (SR == SectionRef())
  5731. SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
  5732. if (SR == SectionRef())
  5733. SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
  5734. info.S = SR;
  5735. walk_pointer_list_32("super refs", SR, O, &info, nullptr);
  5736. SectionRef CA = get_section(O, "__OBJC2", "__category_list");
  5737. if (CA == SectionRef())
  5738. CA = get_section(O, "__DATA", "__objc_catlist");
  5739. if (CA == SectionRef())
  5740. CA = get_section(O, "__DATA_CONST", "__objc_catlist");
  5741. if (CA == SectionRef())
  5742. CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
  5743. info.S = CA;
  5744. walk_pointer_list_32("category", CA, O, &info, print_category32_t);
  5745. SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
  5746. if (PL == SectionRef())
  5747. PL = get_section(O, "__DATA", "__objc_protolist");
  5748. if (PL == SectionRef())
  5749. PL = get_section(O, "__DATA_CONST", "__objc_protolist");
  5750. if (PL == SectionRef())
  5751. PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
  5752. info.S = PL;
  5753. walk_pointer_list_32("protocol", PL, O, &info, nullptr);
  5754. SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
  5755. if (MR == SectionRef())
  5756. MR = get_section(O, "__DATA", "__objc_msgrefs");
  5757. if (MR == SectionRef())
  5758. MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
  5759. if (MR == SectionRef())
  5760. MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
  5761. info.S = MR;
  5762. print_message_refs32(MR, &info);
  5763. SectionRef II = get_section(O, "__OBJC2", "__image_info");
  5764. if (II == SectionRef())
  5765. II = get_section(O, "__DATA", "__objc_imageinfo");
  5766. if (II == SectionRef())
  5767. II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
  5768. if (II == SectionRef())
  5769. II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
  5770. info.S = II;
  5771. print_image_info32(II, &info);
  5772. }
  5773. static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
  5774. uint32_t i, j, p, offset, xoffset, left, defs_left, def;
  5775. const char *r, *name, *defs;
  5776. struct objc_module_t module;
  5777. SectionRef S, xS;
  5778. struct objc_symtab_t symtab;
  5779. struct objc_class_t objc_class;
  5780. struct objc_category_t objc_category;
  5781. outs() << "Objective-C segment\n";
  5782. S = get_section(O, "__OBJC", "__module_info");
  5783. if (S == SectionRef())
  5784. return false;
  5785. SymbolAddressMap AddrMap;
  5786. if (verbose)
  5787. CreateSymbolAddressMap(O, &AddrMap);
  5788. std::vector<SectionRef> Sections;
  5789. append_range(Sections, O->sections());
  5790. struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
  5791. for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
  5792. p = S.getAddress() + i;
  5793. r = get_pointer_32(p, offset, left, S, &info, true);
  5794. if (r == nullptr)
  5795. return true;
  5796. memset(&module, '\0', sizeof(struct objc_module_t));
  5797. if (left < sizeof(struct objc_module_t)) {
  5798. memcpy(&module, r, left);
  5799. outs() << " (module extends past end of __module_info section)\n";
  5800. } else
  5801. memcpy(&module, r, sizeof(struct objc_module_t));
  5802. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5803. swapStruct(module);
  5804. outs() << "Module " << format("0x%" PRIx32, p) << "\n";
  5805. outs() << " version " << module.version << "\n";
  5806. outs() << " size " << module.size << "\n";
  5807. outs() << " name ";
  5808. name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
  5809. if (name != nullptr)
  5810. outs() << format("%.*s", left, name);
  5811. else
  5812. outs() << format("0x%08" PRIx32, module.name)
  5813. << "(not in an __OBJC section)";
  5814. outs() << "\n";
  5815. r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
  5816. if (module.symtab == 0 || r == nullptr) {
  5817. outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
  5818. << " (not in an __OBJC section)\n";
  5819. continue;
  5820. }
  5821. outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
  5822. memset(&symtab, '\0', sizeof(struct objc_symtab_t));
  5823. defs_left = 0;
  5824. defs = nullptr;
  5825. if (left < sizeof(struct objc_symtab_t)) {
  5826. memcpy(&symtab, r, left);
  5827. outs() << "\tsymtab extends past end of an __OBJC section)\n";
  5828. } else {
  5829. memcpy(&symtab, r, sizeof(struct objc_symtab_t));
  5830. if (left > sizeof(struct objc_symtab_t)) {
  5831. defs_left = left - sizeof(struct objc_symtab_t);
  5832. defs = r + sizeof(struct objc_symtab_t);
  5833. }
  5834. }
  5835. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5836. swapStruct(symtab);
  5837. outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
  5838. r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
  5839. outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
  5840. if (r == nullptr)
  5841. outs() << " (not in an __OBJC section)";
  5842. outs() << "\n";
  5843. outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
  5844. outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
  5845. if (symtab.cls_def_cnt > 0)
  5846. outs() << "\tClass Definitions\n";
  5847. for (j = 0; j < symtab.cls_def_cnt; j++) {
  5848. if ((j + 1) * sizeof(uint32_t) > defs_left) {
  5849. outs() << "\t(remaining class defs entries entends past the end of the "
  5850. << "section)\n";
  5851. break;
  5852. }
  5853. memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
  5854. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5855. sys::swapByteOrder(def);
  5856. r = get_pointer_32(def, xoffset, left, xS, &info, true);
  5857. outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
  5858. if (r != nullptr) {
  5859. if (left > sizeof(struct objc_class_t)) {
  5860. outs() << "\n";
  5861. memcpy(&objc_class, r, sizeof(struct objc_class_t));
  5862. } else {
  5863. outs() << " (entends past the end of the section)\n";
  5864. memset(&objc_class, '\0', sizeof(struct objc_class_t));
  5865. memcpy(&objc_class, r, left);
  5866. }
  5867. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5868. swapStruct(objc_class);
  5869. print_objc_class_t(&objc_class, &info);
  5870. } else {
  5871. outs() << "(not in an __OBJC section)\n";
  5872. }
  5873. if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
  5874. outs() << "\tMeta Class";
  5875. r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
  5876. if (r != nullptr) {
  5877. if (left > sizeof(struct objc_class_t)) {
  5878. outs() << "\n";
  5879. memcpy(&objc_class, r, sizeof(struct objc_class_t));
  5880. } else {
  5881. outs() << " (entends past the end of the section)\n";
  5882. memset(&objc_class, '\0', sizeof(struct objc_class_t));
  5883. memcpy(&objc_class, r, left);
  5884. }
  5885. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5886. swapStruct(objc_class);
  5887. print_objc_class_t(&objc_class, &info);
  5888. } else {
  5889. outs() << "(not in an __OBJC section)\n";
  5890. }
  5891. }
  5892. }
  5893. if (symtab.cat_def_cnt > 0)
  5894. outs() << "\tCategory Definitions\n";
  5895. for (j = 0; j < symtab.cat_def_cnt; j++) {
  5896. if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
  5897. outs() << "\t(remaining category defs entries entends past the end of "
  5898. << "the section)\n";
  5899. break;
  5900. }
  5901. memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
  5902. sizeof(uint32_t));
  5903. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5904. sys::swapByteOrder(def);
  5905. r = get_pointer_32(def, xoffset, left, xS, &info, true);
  5906. outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
  5907. << format("0x%08" PRIx32, def);
  5908. if (r != nullptr) {
  5909. if (left > sizeof(struct objc_category_t)) {
  5910. outs() << "\n";
  5911. memcpy(&objc_category, r, sizeof(struct objc_category_t));
  5912. } else {
  5913. outs() << " (entends past the end of the section)\n";
  5914. memset(&objc_category, '\0', sizeof(struct objc_category_t));
  5915. memcpy(&objc_category, r, left);
  5916. }
  5917. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5918. swapStruct(objc_category);
  5919. print_objc_objc_category_t(&objc_category, &info);
  5920. } else {
  5921. outs() << "(not in an __OBJC section)\n";
  5922. }
  5923. }
  5924. }
  5925. const SectionRef II = get_section(O, "__OBJC", "__image_info");
  5926. if (II != SectionRef())
  5927. print_image_info(II, &info);
  5928. return true;
  5929. }
  5930. static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
  5931. uint32_t size, uint32_t addr) {
  5932. SymbolAddressMap AddrMap;
  5933. CreateSymbolAddressMap(O, &AddrMap);
  5934. std::vector<SectionRef> Sections;
  5935. append_range(Sections, O->sections());
  5936. struct DisassembleInfo info(O, &AddrMap, &Sections, true);
  5937. const char *p;
  5938. struct objc_protocol_t protocol;
  5939. uint32_t left, paddr;
  5940. for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
  5941. memset(&protocol, '\0', sizeof(struct objc_protocol_t));
  5942. left = size - (p - sect);
  5943. if (left < sizeof(struct objc_protocol_t)) {
  5944. outs() << "Protocol extends past end of __protocol section\n";
  5945. memcpy(&protocol, p, left);
  5946. } else
  5947. memcpy(&protocol, p, sizeof(struct objc_protocol_t));
  5948. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5949. swapStruct(protocol);
  5950. paddr = addr + (p - sect);
  5951. outs() << "Protocol " << format("0x%" PRIx32, paddr);
  5952. if (print_protocol(paddr, 0, &info))
  5953. outs() << "(not in an __OBJC section)\n";
  5954. }
  5955. }
  5956. #ifdef LLVM_HAVE_LIBXAR
  5957. static inline void swapStruct(struct xar_header &xar) {
  5958. sys::swapByteOrder(xar.magic);
  5959. sys::swapByteOrder(xar.size);
  5960. sys::swapByteOrder(xar.version);
  5961. sys::swapByteOrder(xar.toc_length_compressed);
  5962. sys::swapByteOrder(xar.toc_length_uncompressed);
  5963. sys::swapByteOrder(xar.cksum_alg);
  5964. }
  5965. static void PrintModeVerbose(uint32_t mode) {
  5966. switch(mode & S_IFMT){
  5967. case S_IFDIR:
  5968. outs() << "d";
  5969. break;
  5970. case S_IFCHR:
  5971. outs() << "c";
  5972. break;
  5973. case S_IFBLK:
  5974. outs() << "b";
  5975. break;
  5976. case S_IFREG:
  5977. outs() << "-";
  5978. break;
  5979. case S_IFLNK:
  5980. outs() << "l";
  5981. break;
  5982. case S_IFSOCK:
  5983. outs() << "s";
  5984. break;
  5985. default:
  5986. outs() << "?";
  5987. break;
  5988. }
  5989. /* owner permissions */
  5990. if(mode & S_IREAD)
  5991. outs() << "r";
  5992. else
  5993. outs() << "-";
  5994. if(mode & S_IWRITE)
  5995. outs() << "w";
  5996. else
  5997. outs() << "-";
  5998. if(mode & S_ISUID)
  5999. outs() << "s";
  6000. else if(mode & S_IEXEC)
  6001. outs() << "x";
  6002. else
  6003. outs() << "-";
  6004. /* group permissions */
  6005. if(mode & (S_IREAD >> 3))
  6006. outs() << "r";
  6007. else
  6008. outs() << "-";
  6009. if(mode & (S_IWRITE >> 3))
  6010. outs() << "w";
  6011. else
  6012. outs() << "-";
  6013. if(mode & S_ISGID)
  6014. outs() << "s";
  6015. else if(mode & (S_IEXEC >> 3))
  6016. outs() << "x";
  6017. else
  6018. outs() << "-";
  6019. /* other permissions */
  6020. if(mode & (S_IREAD >> 6))
  6021. outs() << "r";
  6022. else
  6023. outs() << "-";
  6024. if(mode & (S_IWRITE >> 6))
  6025. outs() << "w";
  6026. else
  6027. outs() << "-";
  6028. if(mode & S_ISVTX)
  6029. outs() << "t";
  6030. else if(mode & (S_IEXEC >> 6))
  6031. outs() << "x";
  6032. else
  6033. outs() << "-";
  6034. }
  6035. static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
  6036. xar_file_t xf;
  6037. const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
  6038. char *endp;
  6039. uint32_t mode_value;
  6040. ScopedXarIter xi;
  6041. if (!xi) {
  6042. WithColor::error(errs(), "llvm-objdump")
  6043. << "can't obtain an xar iterator for xar archive " << XarFilename
  6044. << "\n";
  6045. return;
  6046. }
  6047. // Go through the xar's files.
  6048. for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
  6049. ScopedXarIter xp;
  6050. if(!xp){
  6051. WithColor::error(errs(), "llvm-objdump")
  6052. << "can't obtain an xar iterator for xar archive " << XarFilename
  6053. << "\n";
  6054. return;
  6055. }
  6056. type = nullptr;
  6057. mode = nullptr;
  6058. user = nullptr;
  6059. group = nullptr;
  6060. size = nullptr;
  6061. mtime = nullptr;
  6062. name = nullptr;
  6063. for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
  6064. const char *val = nullptr;
  6065. xar_prop_get(xf, key, &val);
  6066. #if 0 // Useful for debugging.
  6067. outs() << "key: " << key << " value: " << val << "\n";
  6068. #endif
  6069. if(strcmp(key, "type") == 0)
  6070. type = val;
  6071. if(strcmp(key, "mode") == 0)
  6072. mode = val;
  6073. if(strcmp(key, "user") == 0)
  6074. user = val;
  6075. if(strcmp(key, "group") == 0)
  6076. group = val;
  6077. if(strcmp(key, "data/size") == 0)
  6078. size = val;
  6079. if(strcmp(key, "mtime") == 0)
  6080. mtime = val;
  6081. if(strcmp(key, "name") == 0)
  6082. name = val;
  6083. }
  6084. if(mode != nullptr){
  6085. mode_value = strtoul(mode, &endp, 8);
  6086. if(*endp != '\0')
  6087. outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
  6088. if(strcmp(type, "file") == 0)
  6089. mode_value |= S_IFREG;
  6090. PrintModeVerbose(mode_value);
  6091. outs() << " ";
  6092. }
  6093. if(user != nullptr)
  6094. outs() << format("%10s/", user);
  6095. if(group != nullptr)
  6096. outs() << format("%-10s ", group);
  6097. if(size != nullptr)
  6098. outs() << format("%7s ", size);
  6099. if(mtime != nullptr){
  6100. for(m = mtime; *m != 'T' && *m != '\0'; m++)
  6101. outs() << *m;
  6102. if(*m == 'T')
  6103. m++;
  6104. outs() << " ";
  6105. for( ; *m != 'Z' && *m != '\0'; m++)
  6106. outs() << *m;
  6107. outs() << " ";
  6108. }
  6109. if(name != nullptr)
  6110. outs() << name;
  6111. outs() << "\n";
  6112. }
  6113. }
  6114. static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
  6115. uint32_t size, bool verbose,
  6116. bool PrintXarHeader, bool PrintXarFileHeaders,
  6117. std::string XarMemberName) {
  6118. if(size < sizeof(struct xar_header)) {
  6119. outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
  6120. "of struct xar_header)\n";
  6121. return;
  6122. }
  6123. struct xar_header XarHeader;
  6124. memcpy(&XarHeader, sect, sizeof(struct xar_header));
  6125. if (sys::IsLittleEndianHost)
  6126. swapStruct(XarHeader);
  6127. if (PrintXarHeader) {
  6128. if (!XarMemberName.empty())
  6129. outs() << "In xar member " << XarMemberName << ": ";
  6130. else
  6131. outs() << "For (__LLVM,__bundle) section: ";
  6132. outs() << "xar header\n";
  6133. if (XarHeader.magic == XAR_HEADER_MAGIC)
  6134. outs() << " magic XAR_HEADER_MAGIC\n";
  6135. else
  6136. outs() << " magic "
  6137. << format_hex(XarHeader.magic, 10, true)
  6138. << " (not XAR_HEADER_MAGIC)\n";
  6139. outs() << " size " << XarHeader.size << "\n";
  6140. outs() << " version " << XarHeader.version << "\n";
  6141. outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
  6142. << "\n";
  6143. outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
  6144. << "\n";
  6145. outs() << " cksum_alg ";
  6146. switch (XarHeader.cksum_alg) {
  6147. case XAR_CKSUM_NONE:
  6148. outs() << "XAR_CKSUM_NONE\n";
  6149. break;
  6150. case XAR_CKSUM_SHA1:
  6151. outs() << "XAR_CKSUM_SHA1\n";
  6152. break;
  6153. case XAR_CKSUM_MD5:
  6154. outs() << "XAR_CKSUM_MD5\n";
  6155. break;
  6156. #ifdef XAR_CKSUM_SHA256
  6157. case XAR_CKSUM_SHA256:
  6158. outs() << "XAR_CKSUM_SHA256\n";
  6159. break;
  6160. #endif
  6161. #ifdef XAR_CKSUM_SHA512
  6162. case XAR_CKSUM_SHA512:
  6163. outs() << "XAR_CKSUM_SHA512\n";
  6164. break;
  6165. #endif
  6166. default:
  6167. outs() << XarHeader.cksum_alg << "\n";
  6168. }
  6169. }
  6170. SmallString<128> XarFilename;
  6171. int FD;
  6172. std::error_code XarEC =
  6173. sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
  6174. if (XarEC) {
  6175. WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
  6176. return;
  6177. }
  6178. ToolOutputFile XarFile(XarFilename, FD);
  6179. raw_fd_ostream &XarOut = XarFile.os();
  6180. StringRef XarContents(sect, size);
  6181. XarOut << XarContents;
  6182. XarOut.close();
  6183. if (XarOut.has_error())
  6184. return;
  6185. ScopedXarFile xar(XarFilename.c_str(), READ);
  6186. if (!xar) {
  6187. WithColor::error(errs(), "llvm-objdump")
  6188. << "can't create temporary xar archive " << XarFilename << "\n";
  6189. return;
  6190. }
  6191. SmallString<128> TocFilename;
  6192. std::error_code TocEC =
  6193. sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
  6194. if (TocEC) {
  6195. WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
  6196. return;
  6197. }
  6198. xar_serialize(xar, TocFilename.c_str());
  6199. if (PrintXarFileHeaders) {
  6200. if (!XarMemberName.empty())
  6201. outs() << "In xar member " << XarMemberName << ": ";
  6202. else
  6203. outs() << "For (__LLVM,__bundle) section: ";
  6204. outs() << "xar archive files:\n";
  6205. PrintXarFilesSummary(XarFilename.c_str(), xar);
  6206. }
  6207. ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
  6208. MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
  6209. if (std::error_code EC = FileOrErr.getError()) {
  6210. WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
  6211. return;
  6212. }
  6213. std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
  6214. if (!XarMemberName.empty())
  6215. outs() << "In xar member " << XarMemberName << ": ";
  6216. else
  6217. outs() << "For (__LLVM,__bundle) section: ";
  6218. outs() << "xar table of contents:\n";
  6219. outs() << Buffer->getBuffer() << "\n";
  6220. // TODO: Go through the xar's files.
  6221. ScopedXarIter xi;
  6222. if(!xi){
  6223. WithColor::error(errs(), "llvm-objdump")
  6224. << "can't obtain an xar iterator for xar archive "
  6225. << XarFilename.c_str() << "\n";
  6226. return;
  6227. }
  6228. for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
  6229. const char *key;
  6230. const char *member_name, *member_type, *member_size_string;
  6231. size_t member_size;
  6232. ScopedXarIter xp;
  6233. if(!xp){
  6234. WithColor::error(errs(), "llvm-objdump")
  6235. << "can't obtain an xar iterator for xar archive "
  6236. << XarFilename.c_str() << "\n";
  6237. return;
  6238. }
  6239. member_name = NULL;
  6240. member_type = NULL;
  6241. member_size_string = NULL;
  6242. for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
  6243. const char *val = nullptr;
  6244. xar_prop_get(xf, key, &val);
  6245. #if 0 // Useful for debugging.
  6246. outs() << "key: " << key << " value: " << val << "\n";
  6247. #endif
  6248. if (strcmp(key, "name") == 0)
  6249. member_name = val;
  6250. if (strcmp(key, "type") == 0)
  6251. member_type = val;
  6252. if (strcmp(key, "data/size") == 0)
  6253. member_size_string = val;
  6254. }
  6255. /*
  6256. * If we find a file with a name, date/size and type properties
  6257. * and with the type being "file" see if that is a xar file.
  6258. */
  6259. if (member_name != NULL && member_type != NULL &&
  6260. strcmp(member_type, "file") == 0 &&
  6261. member_size_string != NULL){
  6262. // Extract the file into a buffer.
  6263. char *endptr;
  6264. member_size = strtoul(member_size_string, &endptr, 10);
  6265. if (*endptr == '\0' && member_size != 0) {
  6266. char *buffer;
  6267. if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
  6268. #if 0 // Useful for debugging.
  6269. outs() << "xar member: " << member_name << " extracted\n";
  6270. #endif
  6271. // Set the XarMemberName we want to see printed in the header.
  6272. std::string OldXarMemberName;
  6273. // If XarMemberName is already set this is nested. So
  6274. // save the old name and create the nested name.
  6275. if (!XarMemberName.empty()) {
  6276. OldXarMemberName = XarMemberName;
  6277. XarMemberName =
  6278. (Twine("[") + XarMemberName + "]" + member_name).str();
  6279. } else {
  6280. OldXarMemberName = "";
  6281. XarMemberName = member_name;
  6282. }
  6283. // See if this is could be a xar file (nested).
  6284. if (member_size >= sizeof(struct xar_header)) {
  6285. #if 0 // Useful for debugging.
  6286. outs() << "could be a xar file: " << member_name << "\n";
  6287. #endif
  6288. memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
  6289. if (sys::IsLittleEndianHost)
  6290. swapStruct(XarHeader);
  6291. if (XarHeader.magic == XAR_HEADER_MAGIC)
  6292. DumpBitcodeSection(O, buffer, member_size, verbose,
  6293. PrintXarHeader, PrintXarFileHeaders,
  6294. XarMemberName);
  6295. }
  6296. XarMemberName = OldXarMemberName;
  6297. delete buffer;
  6298. }
  6299. }
  6300. }
  6301. }
  6302. }
  6303. #endif // defined(LLVM_HAVE_LIBXAR)
  6304. static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
  6305. if (O->is64Bit())
  6306. printObjc2_64bit_MetaData(O, verbose);
  6307. else {
  6308. MachO::mach_header H;
  6309. H = O->getHeader();
  6310. if (H.cputype == MachO::CPU_TYPE_ARM)
  6311. printObjc2_32bit_MetaData(O, verbose);
  6312. else {
  6313. // This is the 32-bit non-arm cputype case. Which is normally
  6314. // the first Objective-C ABI. But it may be the case of a
  6315. // binary for the iOS simulator which is the second Objective-C
  6316. // ABI. In that case printObjc1_32bit_MetaData() will determine that
  6317. // and return false.
  6318. if (!printObjc1_32bit_MetaData(O, verbose))
  6319. printObjc2_32bit_MetaData(O, verbose);
  6320. }
  6321. }
  6322. }
  6323. // GuessLiteralPointer returns a string which for the item in the Mach-O file
  6324. // for the address passed in as ReferenceValue for printing as a comment with
  6325. // the instruction and also returns the corresponding type of that item
  6326. // indirectly through ReferenceType.
  6327. //
  6328. // If ReferenceValue is an address of literal cstring then a pointer to the
  6329. // cstring is returned and ReferenceType is set to
  6330. // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
  6331. //
  6332. // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
  6333. // Class ref that name is returned and the ReferenceType is set accordingly.
  6334. //
  6335. // Lastly, literals which are Symbol address in a literal pool are looked for
  6336. // and if found the symbol name is returned and ReferenceType is set to
  6337. // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
  6338. //
  6339. // If there is no item in the Mach-O file for the address passed in as
  6340. // ReferenceValue nullptr is returned and ReferenceType is unchanged.
  6341. static const char *GuessLiteralPointer(uint64_t ReferenceValue,
  6342. uint64_t ReferencePC,
  6343. uint64_t *ReferenceType,
  6344. struct DisassembleInfo *info) {
  6345. // First see if there is an external relocation entry at the ReferencePC.
  6346. if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
  6347. uint64_t sect_addr = info->S.getAddress();
  6348. uint64_t sect_offset = ReferencePC - sect_addr;
  6349. bool reloc_found = false;
  6350. DataRefImpl Rel;
  6351. MachO::any_relocation_info RE;
  6352. bool isExtern = false;
  6353. SymbolRef Symbol;
  6354. for (const RelocationRef &Reloc : info->S.relocations()) {
  6355. uint64_t RelocOffset = Reloc.getOffset();
  6356. if (RelocOffset == sect_offset) {
  6357. Rel = Reloc.getRawDataRefImpl();
  6358. RE = info->O->getRelocation(Rel);
  6359. if (info->O->isRelocationScattered(RE))
  6360. continue;
  6361. isExtern = info->O->getPlainRelocationExternal(RE);
  6362. if (isExtern) {
  6363. symbol_iterator RelocSym = Reloc.getSymbol();
  6364. Symbol = *RelocSym;
  6365. }
  6366. reloc_found = true;
  6367. break;
  6368. }
  6369. }
  6370. // If there is an external relocation entry for a symbol in a section
  6371. // then used that symbol's value for the value of the reference.
  6372. if (reloc_found && isExtern) {
  6373. if (info->O->getAnyRelocationPCRel(RE)) {
  6374. unsigned Type = info->O->getAnyRelocationType(RE);
  6375. if (Type == MachO::X86_64_RELOC_SIGNED) {
  6376. ReferenceValue = cantFail(Symbol.getValue());
  6377. }
  6378. }
  6379. }
  6380. }
  6381. // Look for literals such as Objective-C CFStrings refs, Selector refs,
  6382. // Message refs and Class refs.
  6383. bool classref, selref, msgref, cfstring;
  6384. uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
  6385. selref, msgref, cfstring);
  6386. if (classref && pointer_value == 0) {
  6387. // Note the ReferenceValue is a pointer into the __objc_classrefs section.
  6388. // And the pointer_value in that section is typically zero as it will be
  6389. // set by dyld as part of the "bind information".
  6390. const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
  6391. if (name != nullptr) {
  6392. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
  6393. const char *class_name = strrchr(name, '$');
  6394. if (class_name != nullptr && class_name[1] == '_' &&
  6395. class_name[2] != '\0') {
  6396. info->class_name = class_name + 2;
  6397. return name;
  6398. }
  6399. }
  6400. }
  6401. if (classref) {
  6402. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
  6403. const char *name =
  6404. get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
  6405. if (name != nullptr)
  6406. info->class_name = name;
  6407. else
  6408. name = "bad class ref";
  6409. return name;
  6410. }
  6411. if (cfstring) {
  6412. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
  6413. const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
  6414. return name;
  6415. }
  6416. if (selref && pointer_value == 0)
  6417. pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
  6418. if (pointer_value != 0)
  6419. ReferenceValue = pointer_value;
  6420. const char *name = GuessCstringPointer(ReferenceValue, info);
  6421. if (name) {
  6422. if (pointer_value != 0 && selref) {
  6423. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
  6424. info->selector_name = name;
  6425. } else if (pointer_value != 0 && msgref) {
  6426. info->class_name = nullptr;
  6427. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
  6428. info->selector_name = name;
  6429. } else
  6430. *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
  6431. return name;
  6432. }
  6433. // Lastly look for an indirect symbol with this ReferenceValue which is in
  6434. // a literal pool. If found return that symbol name.
  6435. name = GuessIndirectSymbol(ReferenceValue, info);
  6436. if (name) {
  6437. *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
  6438. return name;
  6439. }
  6440. return nullptr;
  6441. }
  6442. // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
  6443. // the Symbolizer. It looks up the ReferenceValue using the info passed via the
  6444. // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
  6445. // is created and returns the symbol name that matches the ReferenceValue or
  6446. // nullptr if none. The ReferenceType is passed in for the IN type of
  6447. // reference the instruction is making from the values in defined in the header
  6448. // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
  6449. // Out type and the ReferenceName will also be set which is added as a comment
  6450. // to the disassembled instruction.
  6451. //
  6452. // If the symbol name is a C++ mangled name then the demangled name is
  6453. // returned through ReferenceName and ReferenceType is set to
  6454. // LLVMDisassembler_ReferenceType_DeMangled_Name .
  6455. //
  6456. // When this is called to get a symbol name for a branch target then the
  6457. // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
  6458. // SymbolValue will be looked for in the indirect symbol table to determine if
  6459. // it is an address for a symbol stub. If so then the symbol name for that
  6460. // stub is returned indirectly through ReferenceName and then ReferenceType is
  6461. // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
  6462. //
  6463. // When this is called with an value loaded via a PC relative load then
  6464. // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
  6465. // SymbolValue is checked to be an address of literal pointer, symbol pointer,
  6466. // or an Objective-C meta data reference. If so the output ReferenceType is
  6467. // set to correspond to that as well as setting the ReferenceName.
  6468. static const char *SymbolizerSymbolLookUp(void *DisInfo,
  6469. uint64_t ReferenceValue,
  6470. uint64_t *ReferenceType,
  6471. uint64_t ReferencePC,
  6472. const char **ReferenceName) {
  6473. struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
  6474. // If no verbose symbolic information is wanted then just return nullptr.
  6475. if (!info->verbose) {
  6476. *ReferenceName = nullptr;
  6477. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6478. return nullptr;
  6479. }
  6480. const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
  6481. if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
  6482. *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
  6483. if (*ReferenceName != nullptr) {
  6484. method_reference(info, ReferenceType, ReferenceName);
  6485. if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
  6486. *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
  6487. } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
  6488. if (info->demangled_name != nullptr)
  6489. free(info->demangled_name);
  6490. int status;
  6491. info->demangled_name =
  6492. itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
  6493. if (info->demangled_name != nullptr) {
  6494. *ReferenceName = info->demangled_name;
  6495. *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
  6496. } else
  6497. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6498. } else
  6499. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6500. } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
  6501. *ReferenceName =
  6502. GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
  6503. if (*ReferenceName)
  6504. method_reference(info, ReferenceType, ReferenceName);
  6505. else
  6506. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6507. // If this is arm64 and the reference is an adrp instruction save the
  6508. // instruction, passed in ReferenceValue and the address of the instruction
  6509. // for use later if we see and add immediate instruction.
  6510. } else if (info->O->getArch() == Triple::aarch64 &&
  6511. *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
  6512. info->adrp_inst = ReferenceValue;
  6513. info->adrp_addr = ReferencePC;
  6514. SymbolName = nullptr;
  6515. *ReferenceName = nullptr;
  6516. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6517. // If this is arm64 and reference is an add immediate instruction and we
  6518. // have
  6519. // seen an adrp instruction just before it and the adrp's Xd register
  6520. // matches
  6521. // this add's Xn register reconstruct the value being referenced and look to
  6522. // see if it is a literal pointer. Note the add immediate instruction is
  6523. // passed in ReferenceValue.
  6524. } else if (info->O->getArch() == Triple::aarch64 &&
  6525. *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
  6526. ReferencePC - 4 == info->adrp_addr &&
  6527. (info->adrp_inst & 0x9f000000) == 0x90000000 &&
  6528. (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
  6529. uint32_t addxri_inst;
  6530. uint64_t adrp_imm, addxri_imm;
  6531. adrp_imm =
  6532. ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
  6533. if (info->adrp_inst & 0x0200000)
  6534. adrp_imm |= 0xfffffffffc000000LL;
  6535. addxri_inst = ReferenceValue;
  6536. addxri_imm = (addxri_inst >> 10) & 0xfff;
  6537. if (((addxri_inst >> 22) & 0x3) == 1)
  6538. addxri_imm <<= 12;
  6539. ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
  6540. (adrp_imm << 12) + addxri_imm;
  6541. *ReferenceName =
  6542. GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
  6543. if (*ReferenceName == nullptr)
  6544. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6545. // If this is arm64 and the reference is a load register instruction and we
  6546. // have seen an adrp instruction just before it and the adrp's Xd register
  6547. // matches this add's Xn register reconstruct the value being referenced and
  6548. // look to see if it is a literal pointer. Note the load register
  6549. // instruction is passed in ReferenceValue.
  6550. } else if (info->O->getArch() == Triple::aarch64 &&
  6551. *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
  6552. ReferencePC - 4 == info->adrp_addr &&
  6553. (info->adrp_inst & 0x9f000000) == 0x90000000 &&
  6554. (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
  6555. uint32_t ldrxui_inst;
  6556. uint64_t adrp_imm, ldrxui_imm;
  6557. adrp_imm =
  6558. ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
  6559. if (info->adrp_inst & 0x0200000)
  6560. adrp_imm |= 0xfffffffffc000000LL;
  6561. ldrxui_inst = ReferenceValue;
  6562. ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
  6563. ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
  6564. (adrp_imm << 12) + (ldrxui_imm << 3);
  6565. *ReferenceName =
  6566. GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
  6567. if (*ReferenceName == nullptr)
  6568. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6569. }
  6570. // If this arm64 and is an load register (PC-relative) instruction the
  6571. // ReferenceValue is the PC plus the immediate value.
  6572. else if (info->O->getArch() == Triple::aarch64 &&
  6573. (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
  6574. *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
  6575. *ReferenceName =
  6576. GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
  6577. if (*ReferenceName == nullptr)
  6578. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6579. } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
  6580. if (info->demangled_name != nullptr)
  6581. free(info->demangled_name);
  6582. int status;
  6583. info->demangled_name =
  6584. itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
  6585. if (info->demangled_name != nullptr) {
  6586. *ReferenceName = info->demangled_name;
  6587. *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
  6588. }
  6589. }
  6590. else {
  6591. *ReferenceName = nullptr;
  6592. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6593. }
  6594. return SymbolName;
  6595. }
  6596. /// Emits the comments that are stored in the CommentStream.
  6597. /// Each comment in the CommentStream must end with a newline.
  6598. static void emitComments(raw_svector_ostream &CommentStream,
  6599. SmallString<128> &CommentsToEmit,
  6600. formatted_raw_ostream &FormattedOS,
  6601. const MCAsmInfo &MAI) {
  6602. // Flush the stream before taking its content.
  6603. StringRef Comments = CommentsToEmit.str();
  6604. // Get the default information for printing a comment.
  6605. StringRef CommentBegin = MAI.getCommentString();
  6606. unsigned CommentColumn = MAI.getCommentColumn();
  6607. ListSeparator LS("\n");
  6608. while (!Comments.empty()) {
  6609. FormattedOS << LS;
  6610. // Emit a line of comments.
  6611. FormattedOS.PadToColumn(CommentColumn);
  6612. size_t Position = Comments.find('\n');
  6613. FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
  6614. // Move after the newline character.
  6615. Comments = Comments.substr(Position + 1);
  6616. }
  6617. FormattedOS.flush();
  6618. // Tell the comment stream that the vector changed underneath it.
  6619. CommentsToEmit.clear();
  6620. }
  6621. static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
  6622. StringRef DisSegName, StringRef DisSectName) {
  6623. const char *McpuDefault = nullptr;
  6624. const Target *ThumbTarget = nullptr;
  6625. const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
  6626. if (!TheTarget) {
  6627. // GetTarget prints out stuff.
  6628. return;
  6629. }
  6630. std::string MachOMCPU;
  6631. if (MCPU.empty() && McpuDefault)
  6632. MachOMCPU = McpuDefault;
  6633. else
  6634. MachOMCPU = MCPU;
  6635. #define CHECK_TARGET_INFO_CREATION(NAME) \
  6636. do { \
  6637. if (!NAME) { \
  6638. WithColor::error(errs(), "llvm-objdump") \
  6639. << "couldn't initialize disassembler for target " << TripleName \
  6640. << '\n'; \
  6641. return; \
  6642. } \
  6643. } while (false)
  6644. #define CHECK_THUMB_TARGET_INFO_CREATION(NAME) \
  6645. do { \
  6646. if (!NAME) { \
  6647. WithColor::error(errs(), "llvm-objdump") \
  6648. << "couldn't initialize disassembler for target " << ThumbTripleName \
  6649. << '\n'; \
  6650. return; \
  6651. } \
  6652. } while (false)
  6653. std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
  6654. CHECK_TARGET_INFO_CREATION(InstrInfo);
  6655. std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
  6656. if (ThumbTarget) {
  6657. ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
  6658. CHECK_THUMB_TARGET_INFO_CREATION(ThumbInstrInfo);
  6659. }
  6660. // Package up features to be passed to target/subtarget
  6661. std::string FeaturesStr;
  6662. if (!MAttrs.empty()) {
  6663. SubtargetFeatures Features;
  6664. for (unsigned i = 0; i != MAttrs.size(); ++i)
  6665. Features.AddFeature(MAttrs[i]);
  6666. FeaturesStr = Features.getString();
  6667. }
  6668. MCTargetOptions MCOptions;
  6669. // Set up disassembler.
  6670. std::unique_ptr<const MCRegisterInfo> MRI(
  6671. TheTarget->createMCRegInfo(TripleName));
  6672. CHECK_TARGET_INFO_CREATION(MRI);
  6673. std::unique_ptr<const MCAsmInfo> AsmInfo(
  6674. TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
  6675. CHECK_TARGET_INFO_CREATION(AsmInfo);
  6676. std::unique_ptr<const MCSubtargetInfo> STI(
  6677. TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
  6678. CHECK_TARGET_INFO_CREATION(STI);
  6679. MCContext Ctx(Triple(TripleName), AsmInfo.get(), MRI.get(), STI.get());
  6680. std::unique_ptr<MCDisassembler> DisAsm(
  6681. TheTarget->createMCDisassembler(*STI, Ctx));
  6682. CHECK_TARGET_INFO_CREATION(DisAsm);
  6683. std::unique_ptr<MCSymbolizer> Symbolizer;
  6684. struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
  6685. std::unique_ptr<MCRelocationInfo> RelInfo(
  6686. TheTarget->createMCRelocationInfo(TripleName, Ctx));
  6687. if (RelInfo) {
  6688. Symbolizer.reset(TheTarget->createMCSymbolizer(
  6689. TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
  6690. &SymbolizerInfo, &Ctx, std::move(RelInfo)));
  6691. DisAsm->setSymbolizer(std::move(Symbolizer));
  6692. }
  6693. int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
  6694. std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
  6695. Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
  6696. CHECK_TARGET_INFO_CREATION(IP);
  6697. // Set the display preference for hex vs. decimal immediates.
  6698. IP->setPrintImmHex(PrintImmHex);
  6699. // Comment stream and backing vector.
  6700. SmallString<128> CommentsToEmit;
  6701. raw_svector_ostream CommentStream(CommentsToEmit);
  6702. // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
  6703. // if it is done then arm64 comments for string literals don't get printed
  6704. // and some constant get printed instead and not setting it causes intel
  6705. // (32-bit and 64-bit) comments printed with different spacing before the
  6706. // comment causing different diffs with the 'C' disassembler library API.
  6707. // IP->setCommentStream(CommentStream);
  6708. // Set up separate thumb disassembler if needed.
  6709. std::unique_ptr<const MCRegisterInfo> ThumbMRI;
  6710. std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
  6711. std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
  6712. std::unique_ptr<MCDisassembler> ThumbDisAsm;
  6713. std::unique_ptr<MCInstPrinter> ThumbIP;
  6714. std::unique_ptr<MCContext> ThumbCtx;
  6715. std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
  6716. struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
  6717. std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
  6718. if (ThumbTarget) {
  6719. ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
  6720. CHECK_THUMB_TARGET_INFO_CREATION(ThumbMRI);
  6721. ThumbAsmInfo.reset(
  6722. ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName, MCOptions));
  6723. CHECK_THUMB_TARGET_INFO_CREATION(ThumbAsmInfo);
  6724. ThumbSTI.reset(
  6725. ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
  6726. FeaturesStr));
  6727. CHECK_THUMB_TARGET_INFO_CREATION(ThumbSTI);
  6728. ThumbCtx.reset(new MCContext(Triple(ThumbTripleName), ThumbAsmInfo.get(),
  6729. ThumbMRI.get(), ThumbSTI.get()));
  6730. ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
  6731. CHECK_THUMB_TARGET_INFO_CREATION(ThumbDisAsm);
  6732. MCContext *PtrThumbCtx = ThumbCtx.get();
  6733. ThumbRelInfo.reset(
  6734. ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
  6735. if (ThumbRelInfo) {
  6736. ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
  6737. ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
  6738. &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
  6739. ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
  6740. }
  6741. int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
  6742. ThumbIP.reset(ThumbTarget->createMCInstPrinter(
  6743. Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
  6744. *ThumbInstrInfo, *ThumbMRI));
  6745. CHECK_THUMB_TARGET_INFO_CREATION(ThumbIP);
  6746. // Set the display preference for hex vs. decimal immediates.
  6747. ThumbIP->setPrintImmHex(PrintImmHex);
  6748. }
  6749. #undef CHECK_TARGET_INFO_CREATION
  6750. #undef CHECK_THUMB_TARGET_INFO_CREATION
  6751. MachO::mach_header Header = MachOOF->getHeader();
  6752. // FIXME: Using the -cfg command line option, this code used to be able to
  6753. // annotate relocations with the referenced symbol's name, and if this was
  6754. // inside a __[cf]string section, the data it points to. This is now replaced
  6755. // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
  6756. std::vector<SectionRef> Sections;
  6757. std::vector<SymbolRef> Symbols;
  6758. SmallVector<uint64_t, 8> FoundFns;
  6759. uint64_t BaseSegmentAddress = 0;
  6760. getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
  6761. BaseSegmentAddress);
  6762. // Sort the symbols by address, just in case they didn't come in that way.
  6763. llvm::stable_sort(Symbols, SymbolSorter());
  6764. // Build a data in code table that is sorted on by the address of each entry.
  6765. uint64_t BaseAddress = 0;
  6766. if (Header.filetype == MachO::MH_OBJECT)
  6767. BaseAddress = Sections[0].getAddress();
  6768. else
  6769. BaseAddress = BaseSegmentAddress;
  6770. DiceTable Dices;
  6771. for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
  6772. DI != DE; ++DI) {
  6773. uint32_t Offset;
  6774. DI->getOffset(Offset);
  6775. Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
  6776. }
  6777. array_pod_sort(Dices.begin(), Dices.end());
  6778. // Try to find debug info and set up the DIContext for it.
  6779. std::unique_ptr<DIContext> diContext;
  6780. std::unique_ptr<Binary> DSYMBinary;
  6781. std::unique_ptr<MemoryBuffer> DSYMBuf;
  6782. if (UseDbg) {
  6783. ObjectFile *DbgObj = MachOOF;
  6784. // A separate DSym file path was specified, parse it as a macho file,
  6785. // get the sections and supply it to the section name parsing machinery.
  6786. if (!DSYMFile.empty()) {
  6787. std::string DSYMPath(DSYMFile);
  6788. // If DSYMPath is a .dSYM directory, append the Mach-O file.
  6789. if (llvm::sys::fs::is_directory(DSYMPath) &&
  6790. llvm::sys::path::extension(DSYMPath) == ".dSYM") {
  6791. SmallString<128> ShortName(llvm::sys::path::filename(DSYMPath));
  6792. llvm::sys::path::replace_extension(ShortName, "");
  6793. SmallString<1024> FullPath(DSYMPath);
  6794. llvm::sys::path::append(FullPath, "Contents", "Resources", "DWARF",
  6795. ShortName);
  6796. DSYMPath = std::string(FullPath.str());
  6797. }
  6798. // Load the file.
  6799. ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
  6800. MemoryBuffer::getFileOrSTDIN(DSYMPath);
  6801. if (std::error_code EC = BufOrErr.getError()) {
  6802. reportError(errorCodeToError(EC), DSYMPath);
  6803. return;
  6804. }
  6805. // We need to keep the file alive, because we're replacing DbgObj with it.
  6806. DSYMBuf = std::move(BufOrErr.get());
  6807. Expected<std::unique_ptr<Binary>> BinaryOrErr =
  6808. createBinary(DSYMBuf.get()->getMemBufferRef());
  6809. if (!BinaryOrErr) {
  6810. reportError(BinaryOrErr.takeError(), DSYMPath);
  6811. return;
  6812. }
  6813. // We need to keep the Binary alive with the buffer
  6814. DSYMBinary = std::move(BinaryOrErr.get());
  6815. if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) {
  6816. // this is a Mach-O object file, use it
  6817. if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) {
  6818. DbgObj = MachDSYM;
  6819. }
  6820. else {
  6821. WithColor::error(errs(), "llvm-objdump")
  6822. << DSYMPath << " is not a Mach-O file type.\n";
  6823. return;
  6824. }
  6825. }
  6826. else if (auto UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())){
  6827. // this is a Universal Binary, find a Mach-O for this architecture
  6828. uint32_t CPUType, CPUSubType;
  6829. const char *ArchFlag;
  6830. if (MachOOF->is64Bit()) {
  6831. const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
  6832. CPUType = H_64.cputype;
  6833. CPUSubType = H_64.cpusubtype;
  6834. } else {
  6835. const MachO::mach_header H = MachOOF->getHeader();
  6836. CPUType = H.cputype;
  6837. CPUSubType = H.cpusubtype;
  6838. }
  6839. Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr,
  6840. &ArchFlag);
  6841. Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
  6842. UB->getMachOObjectForArch(ArchFlag);
  6843. if (!MachDSYM) {
  6844. reportError(MachDSYM.takeError(), DSYMPath);
  6845. return;
  6846. }
  6847. // We need to keep the Binary alive with the buffer
  6848. DbgObj = &*MachDSYM.get();
  6849. DSYMBinary = std::move(*MachDSYM);
  6850. }
  6851. else {
  6852. WithColor::error(errs(), "llvm-objdump")
  6853. << DSYMPath << " is not a Mach-O or Universal file type.\n";
  6854. return;
  6855. }
  6856. }
  6857. // Setup the DIContext
  6858. diContext = DWARFContext::create(*DbgObj);
  6859. }
  6860. if (FilterSections.empty())
  6861. outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
  6862. for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
  6863. Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName();
  6864. if (!SecNameOrErr) {
  6865. consumeError(SecNameOrErr.takeError());
  6866. continue;
  6867. }
  6868. if (*SecNameOrErr != DisSectName)
  6869. continue;
  6870. DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
  6871. StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
  6872. if (SegmentName != DisSegName)
  6873. continue;
  6874. StringRef BytesStr =
  6875. unwrapOrError(Sections[SectIdx].getContents(), Filename);
  6876. ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
  6877. uint64_t SectAddress = Sections[SectIdx].getAddress();
  6878. bool symbolTableWorked = false;
  6879. // Create a map of symbol addresses to symbol names for use by
  6880. // the SymbolizerSymbolLookUp() routine.
  6881. SymbolAddressMap AddrMap;
  6882. bool DisSymNameFound = false;
  6883. for (const SymbolRef &Symbol : MachOOF->symbols()) {
  6884. SymbolRef::Type ST =
  6885. unwrapOrError(Symbol.getType(), MachOOF->getFileName());
  6886. if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
  6887. ST == SymbolRef::ST_Other) {
  6888. uint64_t Address = cantFail(Symbol.getValue());
  6889. StringRef SymName =
  6890. unwrapOrError(Symbol.getName(), MachOOF->getFileName());
  6891. AddrMap[Address] = SymName;
  6892. if (!DisSymName.empty() && DisSymName == SymName)
  6893. DisSymNameFound = true;
  6894. }
  6895. }
  6896. if (!DisSymName.empty() && !DisSymNameFound) {
  6897. outs() << "Can't find -dis-symname: " << DisSymName << "\n";
  6898. return;
  6899. }
  6900. // Set up the block of info used by the Symbolizer call backs.
  6901. SymbolizerInfo.verbose = SymbolicOperands;
  6902. SymbolizerInfo.O = MachOOF;
  6903. SymbolizerInfo.S = Sections[SectIdx];
  6904. SymbolizerInfo.AddrMap = &AddrMap;
  6905. SymbolizerInfo.Sections = &Sections;
  6906. // Same for the ThumbSymbolizer
  6907. ThumbSymbolizerInfo.verbose = SymbolicOperands;
  6908. ThumbSymbolizerInfo.O = MachOOF;
  6909. ThumbSymbolizerInfo.S = Sections[SectIdx];
  6910. ThumbSymbolizerInfo.AddrMap = &AddrMap;
  6911. ThumbSymbolizerInfo.Sections = &Sections;
  6912. unsigned int Arch = MachOOF->getArch();
  6913. // Skip all symbols if this is a stubs file.
  6914. if (Bytes.empty())
  6915. return;
  6916. // If the section has symbols but no symbol at the start of the section
  6917. // these are used to make sure the bytes before the first symbol are
  6918. // disassembled.
  6919. bool FirstSymbol = true;
  6920. bool FirstSymbolAtSectionStart = true;
  6921. // Disassemble symbol by symbol.
  6922. for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
  6923. StringRef SymName =
  6924. unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
  6925. SymbolRef::Type ST =
  6926. unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
  6927. if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
  6928. continue;
  6929. // Make sure the symbol is defined in this section.
  6930. bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
  6931. if (!containsSym) {
  6932. if (!DisSymName.empty() && DisSymName == SymName) {
  6933. outs() << "-dis-symname: " << DisSymName << " not in the section\n";
  6934. return;
  6935. }
  6936. continue;
  6937. }
  6938. // The __mh_execute_header is special and we need to deal with that fact
  6939. // this symbol is before the start of the (__TEXT,__text) section and at the
  6940. // address of the start of the __TEXT segment. This is because this symbol
  6941. // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
  6942. // start of the section in a standard MH_EXECUTE filetype.
  6943. if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
  6944. outs() << "-dis-symname: __mh_execute_header not in any section\n";
  6945. return;
  6946. }
  6947. // When this code is trying to disassemble a symbol at a time and in the
  6948. // case there is only the __mh_execute_header symbol left as in a stripped
  6949. // executable, we need to deal with this by ignoring this symbol so the
  6950. // whole section is disassembled and this symbol is then not displayed.
  6951. if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
  6952. SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
  6953. SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
  6954. continue;
  6955. // If we are only disassembling one symbol see if this is that symbol.
  6956. if (!DisSymName.empty() && DisSymName != SymName)
  6957. continue;
  6958. // Start at the address of the symbol relative to the section's address.
  6959. uint64_t SectSize = Sections[SectIdx].getSize();
  6960. uint64_t Start = cantFail(Symbols[SymIdx].getValue());
  6961. uint64_t SectionAddress = Sections[SectIdx].getAddress();
  6962. Start -= SectionAddress;
  6963. if (Start > SectSize) {
  6964. outs() << "section data ends, " << SymName
  6965. << " lies outside valid range\n";
  6966. return;
  6967. }
  6968. // Stop disassembling either at the beginning of the next symbol or at
  6969. // the end of the section.
  6970. bool containsNextSym = false;
  6971. uint64_t NextSym = 0;
  6972. uint64_t NextSymIdx = SymIdx + 1;
  6973. while (Symbols.size() > NextSymIdx) {
  6974. SymbolRef::Type NextSymType = unwrapOrError(
  6975. Symbols[NextSymIdx].getType(), MachOOF->getFileName());
  6976. if (NextSymType == SymbolRef::ST_Function) {
  6977. containsNextSym =
  6978. Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
  6979. NextSym = cantFail(Symbols[NextSymIdx].getValue());
  6980. NextSym -= SectionAddress;
  6981. break;
  6982. }
  6983. ++NextSymIdx;
  6984. }
  6985. uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
  6986. uint64_t Size;
  6987. symbolTableWorked = true;
  6988. DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
  6989. uint32_t SymbolFlags = cantFail(MachOOF->getSymbolFlags(Symb));
  6990. bool IsThumb = SymbolFlags & SymbolRef::SF_Thumb;
  6991. // We only need the dedicated Thumb target if there's a real choice
  6992. // (i.e. we're not targeting M-class) and the function is Thumb.
  6993. bool UseThumbTarget = IsThumb && ThumbTarget;
  6994. // If we are not specifying a symbol to start disassembly with and this
  6995. // is the first symbol in the section but not at the start of the section
  6996. // then move the disassembly index to the start of the section and
  6997. // don't print the symbol name just yet. This is so the bytes before the
  6998. // first symbol are disassembled.
  6999. uint64_t SymbolStart = Start;
  7000. if (DisSymName.empty() && FirstSymbol && Start != 0) {
  7001. FirstSymbolAtSectionStart = false;
  7002. Start = 0;
  7003. }
  7004. else
  7005. outs() << SymName << ":\n";
  7006. DILineInfo lastLine;
  7007. for (uint64_t Index = Start; Index < End; Index += Size) {
  7008. MCInst Inst;
  7009. // If this is the first symbol in the section and it was not at the
  7010. // start of the section, see if we are at its Index now and if so print
  7011. // the symbol name.
  7012. if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
  7013. outs() << SymName << ":\n";
  7014. uint64_t PC = SectAddress + Index;
  7015. if (LeadingAddr) {
  7016. if (FullLeadingAddr) {
  7017. if (MachOOF->is64Bit())
  7018. outs() << format("%016" PRIx64, PC);
  7019. else
  7020. outs() << format("%08" PRIx64, PC);
  7021. } else {
  7022. outs() << format("%8" PRIx64 ":", PC);
  7023. }
  7024. }
  7025. if (ShowRawInsn || Arch == Triple::arm)
  7026. outs() << "\t";
  7027. if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, Size))
  7028. continue;
  7029. SmallVector<char, 64> AnnotationsBytes;
  7030. raw_svector_ostream Annotations(AnnotationsBytes);
  7031. bool gotInst;
  7032. if (UseThumbTarget)
  7033. gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
  7034. PC, Annotations);
  7035. else
  7036. gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
  7037. Annotations);
  7038. if (gotInst) {
  7039. if (ShowRawInsn || Arch == Triple::arm) {
  7040. dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
  7041. }
  7042. formatted_raw_ostream FormattedOS(outs());
  7043. StringRef AnnotationsStr = Annotations.str();
  7044. if (UseThumbTarget)
  7045. ThumbIP->printInst(&Inst, PC, AnnotationsStr, *ThumbSTI,
  7046. FormattedOS);
  7047. else
  7048. IP->printInst(&Inst, PC, AnnotationsStr, *STI, FormattedOS);
  7049. emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
  7050. // Print debug info.
  7051. if (diContext) {
  7052. DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
  7053. // Print valid line info if it changed.
  7054. if (dli != lastLine && dli.Line != 0)
  7055. outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
  7056. << dli.Column;
  7057. lastLine = dli;
  7058. }
  7059. outs() << "\n";
  7060. } else {
  7061. if (MachOOF->getArchTriple().isX86()) {
  7062. outs() << format("\t.byte 0x%02x #bad opcode\n",
  7063. *(Bytes.data() + Index) & 0xff);
  7064. Size = 1; // skip exactly one illegible byte and move on.
  7065. } else if (Arch == Triple::aarch64 ||
  7066. (Arch == Triple::arm && !IsThumb)) {
  7067. uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
  7068. (*(Bytes.data() + Index + 1) & 0xff) << 8 |
  7069. (*(Bytes.data() + Index + 2) & 0xff) << 16 |
  7070. (*(Bytes.data() + Index + 3) & 0xff) << 24;
  7071. outs() << format("\t.long\t0x%08x\n", opcode);
  7072. Size = 4;
  7073. } else if (Arch == Triple::arm) {
  7074. assert(IsThumb && "ARM mode should have been dealt with above");
  7075. uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
  7076. (*(Bytes.data() + Index + 1) & 0xff) << 8;
  7077. outs() << format("\t.short\t0x%04x\n", opcode);
  7078. Size = 2;
  7079. } else{
  7080. WithColor::warning(errs(), "llvm-objdump")
  7081. << "invalid instruction encoding\n";
  7082. if (Size == 0)
  7083. Size = 1; // skip illegible bytes
  7084. }
  7085. }
  7086. }
  7087. // Now that we are done disassembled the first symbol set the bool that
  7088. // were doing this to false.
  7089. FirstSymbol = false;
  7090. }
  7091. if (!symbolTableWorked) {
  7092. // Reading the symbol table didn't work, disassemble the whole section.
  7093. uint64_t SectAddress = Sections[SectIdx].getAddress();
  7094. uint64_t SectSize = Sections[SectIdx].getSize();
  7095. uint64_t InstSize;
  7096. for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
  7097. MCInst Inst;
  7098. uint64_t PC = SectAddress + Index;
  7099. if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, InstSize))
  7100. continue;
  7101. SmallVector<char, 64> AnnotationsBytes;
  7102. raw_svector_ostream Annotations(AnnotationsBytes);
  7103. if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
  7104. Annotations)) {
  7105. if (LeadingAddr) {
  7106. if (FullLeadingAddr) {
  7107. if (MachOOF->is64Bit())
  7108. outs() << format("%016" PRIx64, PC);
  7109. else
  7110. outs() << format("%08" PRIx64, PC);
  7111. } else {
  7112. outs() << format("%8" PRIx64 ":", PC);
  7113. }
  7114. }
  7115. if (ShowRawInsn || Arch == Triple::arm) {
  7116. outs() << "\t";
  7117. dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
  7118. }
  7119. StringRef AnnotationsStr = Annotations.str();
  7120. IP->printInst(&Inst, PC, AnnotationsStr, *STI, outs());
  7121. outs() << "\n";
  7122. } else {
  7123. if (MachOOF->getArchTriple().isX86()) {
  7124. outs() << format("\t.byte 0x%02x #bad opcode\n",
  7125. *(Bytes.data() + Index) & 0xff);
  7126. InstSize = 1; // skip exactly one illegible byte and move on.
  7127. } else {
  7128. WithColor::warning(errs(), "llvm-objdump")
  7129. << "invalid instruction encoding\n";
  7130. if (InstSize == 0)
  7131. InstSize = 1; // skip illegible bytes
  7132. }
  7133. }
  7134. }
  7135. }
  7136. // The TripleName's need to be reset if we are called again for a different
  7137. // architecture.
  7138. TripleName = "";
  7139. ThumbTripleName = "";
  7140. if (SymbolizerInfo.demangled_name != nullptr)
  7141. free(SymbolizerInfo.demangled_name);
  7142. if (ThumbSymbolizerInfo.demangled_name != nullptr)
  7143. free(ThumbSymbolizerInfo.demangled_name);
  7144. }
  7145. }
  7146. //===----------------------------------------------------------------------===//
  7147. // __compact_unwind section dumping
  7148. //===----------------------------------------------------------------------===//
  7149. namespace {
  7150. template <typename T>
  7151. static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
  7152. using llvm::support::little;
  7153. using llvm::support::unaligned;
  7154. if (Offset + sizeof(T) > Contents.size()) {
  7155. outs() << "warning: attempt to read past end of buffer\n";
  7156. return T();
  7157. }
  7158. uint64_t Val =
  7159. support::endian::read<T, little, unaligned>(Contents.data() + Offset);
  7160. return Val;
  7161. }
  7162. template <typename T>
  7163. static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
  7164. T Val = read<T>(Contents, Offset);
  7165. Offset += sizeof(T);
  7166. return Val;
  7167. }
  7168. struct CompactUnwindEntry {
  7169. uint32_t OffsetInSection;
  7170. uint64_t FunctionAddr;
  7171. uint32_t Length;
  7172. uint32_t CompactEncoding;
  7173. uint64_t PersonalityAddr;
  7174. uint64_t LSDAAddr;
  7175. RelocationRef FunctionReloc;
  7176. RelocationRef PersonalityReloc;
  7177. RelocationRef LSDAReloc;
  7178. CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
  7179. : OffsetInSection(Offset) {
  7180. if (Is64)
  7181. read<uint64_t>(Contents, Offset);
  7182. else
  7183. read<uint32_t>(Contents, Offset);
  7184. }
  7185. private:
  7186. template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
  7187. FunctionAddr = readNext<UIntPtr>(Contents, Offset);
  7188. Length = readNext<uint32_t>(Contents, Offset);
  7189. CompactEncoding = readNext<uint32_t>(Contents, Offset);
  7190. PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
  7191. LSDAAddr = readNext<UIntPtr>(Contents, Offset);
  7192. }
  7193. };
  7194. }
  7195. /// Given a relocation from __compact_unwind, consisting of the RelocationRef
  7196. /// and data being relocated, determine the best base Name and Addend to use for
  7197. /// display purposes.
  7198. ///
  7199. /// 1. An Extern relocation will directly reference a symbol (and the data is
  7200. /// then already an addend), so use that.
  7201. /// 2. Otherwise the data is an offset in the object file's layout; try to find
  7202. // a symbol before it in the same section, and use the offset from there.
  7203. /// 3. Finally, if all that fails, fall back to an offset from the start of the
  7204. /// referenced section.
  7205. static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
  7206. std::map<uint64_t, SymbolRef> &Symbols,
  7207. const RelocationRef &Reloc, uint64_t Addr,
  7208. StringRef &Name, uint64_t &Addend) {
  7209. if (Reloc.getSymbol() != Obj->symbol_end()) {
  7210. Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
  7211. Addend = Addr;
  7212. return;
  7213. }
  7214. auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
  7215. SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
  7216. uint64_t SectionAddr = RelocSection.getAddress();
  7217. auto Sym = Symbols.upper_bound(Addr);
  7218. if (Sym == Symbols.begin()) {
  7219. // The first symbol in the object is after this reference, the best we can
  7220. // do is section-relative notation.
  7221. if (Expected<StringRef> NameOrErr = RelocSection.getName())
  7222. Name = *NameOrErr;
  7223. else
  7224. consumeError(NameOrErr.takeError());
  7225. Addend = Addr - SectionAddr;
  7226. return;
  7227. }
  7228. // Go back one so that SymbolAddress <= Addr.
  7229. --Sym;
  7230. section_iterator SymSection =
  7231. unwrapOrError(Sym->second.getSection(), Obj->getFileName());
  7232. if (RelocSection == *SymSection) {
  7233. // There's a valid symbol in the same section before this reference.
  7234. Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
  7235. Addend = Addr - Sym->first;
  7236. return;
  7237. }
  7238. // There is a symbol before this reference, but it's in a different
  7239. // section. Probably not helpful to mention it, so use the section name.
  7240. if (Expected<StringRef> NameOrErr = RelocSection.getName())
  7241. Name = *NameOrErr;
  7242. else
  7243. consumeError(NameOrErr.takeError());
  7244. Addend = Addr - SectionAddr;
  7245. }
  7246. static void printUnwindRelocDest(const MachOObjectFile *Obj,
  7247. std::map<uint64_t, SymbolRef> &Symbols,
  7248. const RelocationRef &Reloc, uint64_t Addr) {
  7249. StringRef Name;
  7250. uint64_t Addend;
  7251. if (!Reloc.getObject())
  7252. return;
  7253. findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
  7254. outs() << Name;
  7255. if (Addend)
  7256. outs() << " + " << format("0x%" PRIx64, Addend);
  7257. }
  7258. static void
  7259. printMachOCompactUnwindSection(const MachOObjectFile *Obj,
  7260. std::map<uint64_t, SymbolRef> &Symbols,
  7261. const SectionRef &CompactUnwind) {
  7262. if (!Obj->isLittleEndian()) {
  7263. outs() << "Skipping big-endian __compact_unwind section\n";
  7264. return;
  7265. }
  7266. bool Is64 = Obj->is64Bit();
  7267. uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
  7268. uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
  7269. StringRef Contents =
  7270. unwrapOrError(CompactUnwind.getContents(), Obj->getFileName());
  7271. SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
  7272. // First populate the initial raw offsets, encodings and so on from the entry.
  7273. for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
  7274. CompactUnwindEntry Entry(Contents, Offset, Is64);
  7275. CompactUnwinds.push_back(Entry);
  7276. }
  7277. // Next we need to look at the relocations to find out what objects are
  7278. // actually being referred to.
  7279. for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
  7280. uint64_t RelocAddress = Reloc.getOffset();
  7281. uint32_t EntryIdx = RelocAddress / EntrySize;
  7282. uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
  7283. CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
  7284. if (OffsetInEntry == 0)
  7285. Entry.FunctionReloc = Reloc;
  7286. else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
  7287. Entry.PersonalityReloc = Reloc;
  7288. else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
  7289. Entry.LSDAReloc = Reloc;
  7290. else {
  7291. outs() << "Invalid relocation in __compact_unwind section\n";
  7292. return;
  7293. }
  7294. }
  7295. // Finally, we're ready to print the data we've gathered.
  7296. outs() << "Contents of __compact_unwind section:\n";
  7297. for (auto &Entry : CompactUnwinds) {
  7298. outs() << " Entry at offset "
  7299. << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
  7300. // 1. Start of the region this entry applies to.
  7301. outs() << " start: " << format("0x%" PRIx64,
  7302. Entry.FunctionAddr) << ' ';
  7303. printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
  7304. outs() << '\n';
  7305. // 2. Length of the region this entry applies to.
  7306. outs() << " length: " << format("0x%" PRIx32, Entry.Length)
  7307. << '\n';
  7308. // 3. The 32-bit compact encoding.
  7309. outs() << " compact encoding: "
  7310. << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
  7311. // 4. The personality function, if present.
  7312. if (Entry.PersonalityReloc.getObject()) {
  7313. outs() << " personality function: "
  7314. << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
  7315. printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
  7316. Entry.PersonalityAddr);
  7317. outs() << '\n';
  7318. }
  7319. // 5. This entry's language-specific data area.
  7320. if (Entry.LSDAReloc.getObject()) {
  7321. outs() << " LSDA: " << format("0x%" PRIx64,
  7322. Entry.LSDAAddr) << ' ';
  7323. printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
  7324. outs() << '\n';
  7325. }
  7326. }
  7327. }
  7328. //===----------------------------------------------------------------------===//
  7329. // __unwind_info section dumping
  7330. //===----------------------------------------------------------------------===//
  7331. static void printRegularSecondLevelUnwindPage(StringRef PageData) {
  7332. ptrdiff_t Pos = 0;
  7333. uint32_t Kind = readNext<uint32_t>(PageData, Pos);
  7334. (void)Kind;
  7335. assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
  7336. uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
  7337. uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
  7338. Pos = EntriesStart;
  7339. for (unsigned i = 0; i < NumEntries; ++i) {
  7340. uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
  7341. uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
  7342. outs() << " [" << i << "]: "
  7343. << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
  7344. << ", "
  7345. << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
  7346. }
  7347. }
  7348. static void printCompressedSecondLevelUnwindPage(
  7349. StringRef PageData, uint32_t FunctionBase,
  7350. const SmallVectorImpl<uint32_t> &CommonEncodings) {
  7351. ptrdiff_t Pos = 0;
  7352. uint32_t Kind = readNext<uint32_t>(PageData, Pos);
  7353. (void)Kind;
  7354. assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
  7355. uint32_t NumCommonEncodings = CommonEncodings.size();
  7356. uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
  7357. uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
  7358. uint16_t PageEncodingsStart = readNext<uint16_t>(PageData, Pos);
  7359. uint16_t NumPageEncodings = readNext<uint16_t>(PageData, Pos);
  7360. SmallVector<uint32_t, 64> PageEncodings;
  7361. if (NumPageEncodings) {
  7362. outs() << " Page encodings: (count = " << NumPageEncodings << ")\n";
  7363. Pos = PageEncodingsStart;
  7364. for (unsigned i = 0; i < NumPageEncodings; ++i) {
  7365. uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
  7366. PageEncodings.push_back(Encoding);
  7367. outs() << " encoding[" << (i + NumCommonEncodings)
  7368. << "]: " << format("0x%08" PRIx32, Encoding) << '\n';
  7369. }
  7370. }
  7371. Pos = EntriesStart;
  7372. for (unsigned i = 0; i < NumEntries; ++i) {
  7373. uint32_t Entry = readNext<uint32_t>(PageData, Pos);
  7374. uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
  7375. uint32_t EncodingIdx = Entry >> 24;
  7376. uint32_t Encoding;
  7377. if (EncodingIdx < NumCommonEncodings)
  7378. Encoding = CommonEncodings[EncodingIdx];
  7379. else
  7380. Encoding = PageEncodings[EncodingIdx - NumCommonEncodings];
  7381. outs() << " [" << i << "]: "
  7382. << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
  7383. << ", "
  7384. << "encoding[" << EncodingIdx
  7385. << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
  7386. }
  7387. }
  7388. static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
  7389. std::map<uint64_t, SymbolRef> &Symbols,
  7390. const SectionRef &UnwindInfo) {
  7391. if (!Obj->isLittleEndian()) {
  7392. outs() << "Skipping big-endian __unwind_info section\n";
  7393. return;
  7394. }
  7395. outs() << "Contents of __unwind_info section:\n";
  7396. StringRef Contents =
  7397. unwrapOrError(UnwindInfo.getContents(), Obj->getFileName());
  7398. ptrdiff_t Pos = 0;
  7399. //===----------------------------------
  7400. // Section header
  7401. //===----------------------------------
  7402. uint32_t Version = readNext<uint32_t>(Contents, Pos);
  7403. outs() << " Version: "
  7404. << format("0x%" PRIx32, Version) << '\n';
  7405. if (Version != 1) {
  7406. outs() << " Skipping section with unknown version\n";
  7407. return;
  7408. }
  7409. uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
  7410. outs() << " Common encodings array section offset: "
  7411. << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
  7412. uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
  7413. outs() << " Number of common encodings in array: "
  7414. << format("0x%" PRIx32, NumCommonEncodings) << '\n';
  7415. uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
  7416. outs() << " Personality function array section offset: "
  7417. << format("0x%" PRIx32, PersonalitiesStart) << '\n';
  7418. uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
  7419. outs() << " Number of personality functions in array: "
  7420. << format("0x%" PRIx32, NumPersonalities) << '\n';
  7421. uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
  7422. outs() << " Index array section offset: "
  7423. << format("0x%" PRIx32, IndicesStart) << '\n';
  7424. uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
  7425. outs() << " Number of indices in array: "
  7426. << format("0x%" PRIx32, NumIndices) << '\n';
  7427. //===----------------------------------
  7428. // A shared list of common encodings
  7429. //===----------------------------------
  7430. // These occupy indices in the range [0, N] whenever an encoding is referenced
  7431. // from a compressed 2nd level index table. In practice the linker only
  7432. // creates ~128 of these, so that indices are available to embed encodings in
  7433. // the 2nd level index.
  7434. SmallVector<uint32_t, 64> CommonEncodings;
  7435. outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
  7436. Pos = CommonEncodingsStart;
  7437. for (unsigned i = 0; i < NumCommonEncodings; ++i) {
  7438. uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
  7439. CommonEncodings.push_back(Encoding);
  7440. outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
  7441. << '\n';
  7442. }
  7443. //===----------------------------------
  7444. // Personality functions used in this executable
  7445. //===----------------------------------
  7446. // There should be only a handful of these (one per source language,
  7447. // roughly). Particularly since they only get 2 bits in the compact encoding.
  7448. outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
  7449. Pos = PersonalitiesStart;
  7450. for (unsigned i = 0; i < NumPersonalities; ++i) {
  7451. uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
  7452. outs() << " personality[" << i + 1
  7453. << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
  7454. }
  7455. //===----------------------------------
  7456. // The level 1 index entries
  7457. //===----------------------------------
  7458. // These specify an approximate place to start searching for the more detailed
  7459. // information, sorted by PC.
  7460. struct IndexEntry {
  7461. uint32_t FunctionOffset;
  7462. uint32_t SecondLevelPageStart;
  7463. uint32_t LSDAStart;
  7464. };
  7465. SmallVector<IndexEntry, 4> IndexEntries;
  7466. outs() << " Top level indices: (count = " << NumIndices << ")\n";
  7467. Pos = IndicesStart;
  7468. for (unsigned i = 0; i < NumIndices; ++i) {
  7469. IndexEntry Entry;
  7470. Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
  7471. Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
  7472. Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
  7473. IndexEntries.push_back(Entry);
  7474. outs() << " [" << i << "]: "
  7475. << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
  7476. << ", "
  7477. << "2nd level page offset="
  7478. << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
  7479. << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
  7480. }
  7481. //===----------------------------------
  7482. // Next come the LSDA tables
  7483. //===----------------------------------
  7484. // The LSDA layout is rather implicit: it's a contiguous array of entries from
  7485. // the first top-level index's LSDAOffset to the last (sentinel).
  7486. outs() << " LSDA descriptors:\n";
  7487. Pos = IndexEntries[0].LSDAStart;
  7488. const uint32_t LSDASize = 2 * sizeof(uint32_t);
  7489. int NumLSDAs =
  7490. (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
  7491. for (int i = 0; i < NumLSDAs; ++i) {
  7492. uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
  7493. uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
  7494. outs() << " [" << i << "]: "
  7495. << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
  7496. << ", "
  7497. << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
  7498. }
  7499. //===----------------------------------
  7500. // Finally, the 2nd level indices
  7501. //===----------------------------------
  7502. // Generally these are 4K in size, and have 2 possible forms:
  7503. // + Regular stores up to 511 entries with disparate encodings
  7504. // + Compressed stores up to 1021 entries if few enough compact encoding
  7505. // values are used.
  7506. outs() << " Second level indices:\n";
  7507. for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
  7508. // The final sentinel top-level index has no associated 2nd level page
  7509. if (IndexEntries[i].SecondLevelPageStart == 0)
  7510. break;
  7511. outs() << " Second level index[" << i << "]: "
  7512. << "offset in section="
  7513. << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
  7514. << ", "
  7515. << "base function offset="
  7516. << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
  7517. Pos = IndexEntries[i].SecondLevelPageStart;
  7518. if (Pos + sizeof(uint32_t) > Contents.size()) {
  7519. outs() << "warning: invalid offset for second level page: " << Pos << '\n';
  7520. continue;
  7521. }
  7522. uint32_t Kind =
  7523. *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
  7524. if (Kind == 2)
  7525. printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
  7526. else if (Kind == 3)
  7527. printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
  7528. IndexEntries[i].FunctionOffset,
  7529. CommonEncodings);
  7530. else
  7531. outs() << " Skipping 2nd level page with unknown kind " << Kind
  7532. << '\n';
  7533. }
  7534. }
  7535. void objdump::printMachOUnwindInfo(const MachOObjectFile *Obj) {
  7536. std::map<uint64_t, SymbolRef> Symbols;
  7537. for (const SymbolRef &SymRef : Obj->symbols()) {
  7538. // Discard any undefined or absolute symbols. They're not going to take part
  7539. // in the convenience lookup for unwind info and just take up resources.
  7540. auto SectOrErr = SymRef.getSection();
  7541. if (!SectOrErr) {
  7542. // TODO: Actually report errors helpfully.
  7543. consumeError(SectOrErr.takeError());
  7544. continue;
  7545. }
  7546. section_iterator Section = *SectOrErr;
  7547. if (Section == Obj->section_end())
  7548. continue;
  7549. uint64_t Addr = cantFail(SymRef.getValue());
  7550. Symbols.insert(std::make_pair(Addr, SymRef));
  7551. }
  7552. for (const SectionRef &Section : Obj->sections()) {
  7553. StringRef SectName;
  7554. if (Expected<StringRef> NameOrErr = Section.getName())
  7555. SectName = *NameOrErr;
  7556. else
  7557. consumeError(NameOrErr.takeError());
  7558. if (SectName == "__compact_unwind")
  7559. printMachOCompactUnwindSection(Obj, Symbols, Section);
  7560. else if (SectName == "__unwind_info")
  7561. printMachOUnwindInfoSection(Obj, Symbols, Section);
  7562. }
  7563. }
  7564. static void PrintMachHeader(uint32_t magic, uint32_t cputype,
  7565. uint32_t cpusubtype, uint32_t filetype,
  7566. uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
  7567. bool verbose) {
  7568. outs() << "Mach header\n";
  7569. outs() << " magic cputype cpusubtype caps filetype ncmds "
  7570. "sizeofcmds flags\n";
  7571. if (verbose) {
  7572. if (magic == MachO::MH_MAGIC)
  7573. outs() << " MH_MAGIC";
  7574. else if (magic == MachO::MH_MAGIC_64)
  7575. outs() << "MH_MAGIC_64";
  7576. else
  7577. outs() << format(" 0x%08" PRIx32, magic);
  7578. switch (cputype) {
  7579. case MachO::CPU_TYPE_I386:
  7580. outs() << " I386";
  7581. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7582. case MachO::CPU_SUBTYPE_I386_ALL:
  7583. outs() << " ALL";
  7584. break;
  7585. default:
  7586. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7587. break;
  7588. }
  7589. break;
  7590. case MachO::CPU_TYPE_X86_64:
  7591. outs() << " X86_64";
  7592. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7593. case MachO::CPU_SUBTYPE_X86_64_ALL:
  7594. outs() << " ALL";
  7595. break;
  7596. case MachO::CPU_SUBTYPE_X86_64_H:
  7597. outs() << " Haswell";
  7598. break;
  7599. default:
  7600. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7601. break;
  7602. }
  7603. break;
  7604. case MachO::CPU_TYPE_ARM:
  7605. outs() << " ARM";
  7606. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7607. case MachO::CPU_SUBTYPE_ARM_ALL:
  7608. outs() << " ALL";
  7609. break;
  7610. case MachO::CPU_SUBTYPE_ARM_V4T:
  7611. outs() << " V4T";
  7612. break;
  7613. case MachO::CPU_SUBTYPE_ARM_V5TEJ:
  7614. outs() << " V5TEJ";
  7615. break;
  7616. case MachO::CPU_SUBTYPE_ARM_XSCALE:
  7617. outs() << " XSCALE";
  7618. break;
  7619. case MachO::CPU_SUBTYPE_ARM_V6:
  7620. outs() << " V6";
  7621. break;
  7622. case MachO::CPU_SUBTYPE_ARM_V6M:
  7623. outs() << " V6M";
  7624. break;
  7625. case MachO::CPU_SUBTYPE_ARM_V7:
  7626. outs() << " V7";
  7627. break;
  7628. case MachO::CPU_SUBTYPE_ARM_V7EM:
  7629. outs() << " V7EM";
  7630. break;
  7631. case MachO::CPU_SUBTYPE_ARM_V7K:
  7632. outs() << " V7K";
  7633. break;
  7634. case MachO::CPU_SUBTYPE_ARM_V7M:
  7635. outs() << " V7M";
  7636. break;
  7637. case MachO::CPU_SUBTYPE_ARM_V7S:
  7638. outs() << " V7S";
  7639. break;
  7640. default:
  7641. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7642. break;
  7643. }
  7644. break;
  7645. case MachO::CPU_TYPE_ARM64:
  7646. outs() << " ARM64";
  7647. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7648. case MachO::CPU_SUBTYPE_ARM64_ALL:
  7649. outs() << " ALL";
  7650. break;
  7651. case MachO::CPU_SUBTYPE_ARM64_V8:
  7652. outs() << " V8";
  7653. break;
  7654. case MachO::CPU_SUBTYPE_ARM64E:
  7655. outs() << " E";
  7656. break;
  7657. default:
  7658. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7659. break;
  7660. }
  7661. break;
  7662. case MachO::CPU_TYPE_ARM64_32:
  7663. outs() << " ARM64_32";
  7664. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7665. case MachO::CPU_SUBTYPE_ARM64_32_V8:
  7666. outs() << " V8";
  7667. break;
  7668. default:
  7669. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7670. break;
  7671. }
  7672. break;
  7673. case MachO::CPU_TYPE_POWERPC:
  7674. outs() << " PPC";
  7675. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7676. case MachO::CPU_SUBTYPE_POWERPC_ALL:
  7677. outs() << " ALL";
  7678. break;
  7679. default:
  7680. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7681. break;
  7682. }
  7683. break;
  7684. case MachO::CPU_TYPE_POWERPC64:
  7685. outs() << " PPC64";
  7686. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7687. case MachO::CPU_SUBTYPE_POWERPC_ALL:
  7688. outs() << " ALL";
  7689. break;
  7690. default:
  7691. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7692. break;
  7693. }
  7694. break;
  7695. default:
  7696. outs() << format(" %7d", cputype);
  7697. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7698. break;
  7699. }
  7700. if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
  7701. outs() << " LIB64";
  7702. } else {
  7703. outs() << format(" 0x%02" PRIx32,
  7704. (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
  7705. }
  7706. switch (filetype) {
  7707. case MachO::MH_OBJECT:
  7708. outs() << " OBJECT";
  7709. break;
  7710. case MachO::MH_EXECUTE:
  7711. outs() << " EXECUTE";
  7712. break;
  7713. case MachO::MH_FVMLIB:
  7714. outs() << " FVMLIB";
  7715. break;
  7716. case MachO::MH_CORE:
  7717. outs() << " CORE";
  7718. break;
  7719. case MachO::MH_PRELOAD:
  7720. outs() << " PRELOAD";
  7721. break;
  7722. case MachO::MH_DYLIB:
  7723. outs() << " DYLIB";
  7724. break;
  7725. case MachO::MH_DYLIB_STUB:
  7726. outs() << " DYLIB_STUB";
  7727. break;
  7728. case MachO::MH_DYLINKER:
  7729. outs() << " DYLINKER";
  7730. break;
  7731. case MachO::MH_BUNDLE:
  7732. outs() << " BUNDLE";
  7733. break;
  7734. case MachO::MH_DSYM:
  7735. outs() << " DSYM";
  7736. break;
  7737. case MachO::MH_KEXT_BUNDLE:
  7738. outs() << " KEXTBUNDLE";
  7739. break;
  7740. default:
  7741. outs() << format(" %10u", filetype);
  7742. break;
  7743. }
  7744. outs() << format(" %5u", ncmds);
  7745. outs() << format(" %10u", sizeofcmds);
  7746. uint32_t f = flags;
  7747. if (f & MachO::MH_NOUNDEFS) {
  7748. outs() << " NOUNDEFS";
  7749. f &= ~MachO::MH_NOUNDEFS;
  7750. }
  7751. if (f & MachO::MH_INCRLINK) {
  7752. outs() << " INCRLINK";
  7753. f &= ~MachO::MH_INCRLINK;
  7754. }
  7755. if (f & MachO::MH_DYLDLINK) {
  7756. outs() << " DYLDLINK";
  7757. f &= ~MachO::MH_DYLDLINK;
  7758. }
  7759. if (f & MachO::MH_BINDATLOAD) {
  7760. outs() << " BINDATLOAD";
  7761. f &= ~MachO::MH_BINDATLOAD;
  7762. }
  7763. if (f & MachO::MH_PREBOUND) {
  7764. outs() << " PREBOUND";
  7765. f &= ~MachO::MH_PREBOUND;
  7766. }
  7767. if (f & MachO::MH_SPLIT_SEGS) {
  7768. outs() << " SPLIT_SEGS";
  7769. f &= ~MachO::MH_SPLIT_SEGS;
  7770. }
  7771. if (f & MachO::MH_LAZY_INIT) {
  7772. outs() << " LAZY_INIT";
  7773. f &= ~MachO::MH_LAZY_INIT;
  7774. }
  7775. if (f & MachO::MH_TWOLEVEL) {
  7776. outs() << " TWOLEVEL";
  7777. f &= ~MachO::MH_TWOLEVEL;
  7778. }
  7779. if (f & MachO::MH_FORCE_FLAT) {
  7780. outs() << " FORCE_FLAT";
  7781. f &= ~MachO::MH_FORCE_FLAT;
  7782. }
  7783. if (f & MachO::MH_NOMULTIDEFS) {
  7784. outs() << " NOMULTIDEFS";
  7785. f &= ~MachO::MH_NOMULTIDEFS;
  7786. }
  7787. if (f & MachO::MH_NOFIXPREBINDING) {
  7788. outs() << " NOFIXPREBINDING";
  7789. f &= ~MachO::MH_NOFIXPREBINDING;
  7790. }
  7791. if (f & MachO::MH_PREBINDABLE) {
  7792. outs() << " PREBINDABLE";
  7793. f &= ~MachO::MH_PREBINDABLE;
  7794. }
  7795. if (f & MachO::MH_ALLMODSBOUND) {
  7796. outs() << " ALLMODSBOUND";
  7797. f &= ~MachO::MH_ALLMODSBOUND;
  7798. }
  7799. if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
  7800. outs() << " SUBSECTIONS_VIA_SYMBOLS";
  7801. f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
  7802. }
  7803. if (f & MachO::MH_CANONICAL) {
  7804. outs() << " CANONICAL";
  7805. f &= ~MachO::MH_CANONICAL;
  7806. }
  7807. if (f & MachO::MH_WEAK_DEFINES) {
  7808. outs() << " WEAK_DEFINES";
  7809. f &= ~MachO::MH_WEAK_DEFINES;
  7810. }
  7811. if (f & MachO::MH_BINDS_TO_WEAK) {
  7812. outs() << " BINDS_TO_WEAK";
  7813. f &= ~MachO::MH_BINDS_TO_WEAK;
  7814. }
  7815. if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
  7816. outs() << " ALLOW_STACK_EXECUTION";
  7817. f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
  7818. }
  7819. if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
  7820. outs() << " DEAD_STRIPPABLE_DYLIB";
  7821. f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
  7822. }
  7823. if (f & MachO::MH_PIE) {
  7824. outs() << " PIE";
  7825. f &= ~MachO::MH_PIE;
  7826. }
  7827. if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
  7828. outs() << " NO_REEXPORTED_DYLIBS";
  7829. f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
  7830. }
  7831. if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
  7832. outs() << " MH_HAS_TLV_DESCRIPTORS";
  7833. f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
  7834. }
  7835. if (f & MachO::MH_NO_HEAP_EXECUTION) {
  7836. outs() << " MH_NO_HEAP_EXECUTION";
  7837. f &= ~MachO::MH_NO_HEAP_EXECUTION;
  7838. }
  7839. if (f & MachO::MH_APP_EXTENSION_SAFE) {
  7840. outs() << " APP_EXTENSION_SAFE";
  7841. f &= ~MachO::MH_APP_EXTENSION_SAFE;
  7842. }
  7843. if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
  7844. outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
  7845. f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
  7846. }
  7847. if (f != 0 || flags == 0)
  7848. outs() << format(" 0x%08" PRIx32, f);
  7849. } else {
  7850. outs() << format(" 0x%08" PRIx32, magic);
  7851. outs() << format(" %7d", cputype);
  7852. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7853. outs() << format(" 0x%02" PRIx32,
  7854. (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
  7855. outs() << format(" %10u", filetype);
  7856. outs() << format(" %5u", ncmds);
  7857. outs() << format(" %10u", sizeofcmds);
  7858. outs() << format(" 0x%08" PRIx32, flags);
  7859. }
  7860. outs() << "\n";
  7861. }
  7862. static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
  7863. StringRef SegName, uint64_t vmaddr,
  7864. uint64_t vmsize, uint64_t fileoff,
  7865. uint64_t filesize, uint32_t maxprot,
  7866. uint32_t initprot, uint32_t nsects,
  7867. uint32_t flags, uint32_t object_size,
  7868. bool verbose) {
  7869. uint64_t expected_cmdsize;
  7870. if (cmd == MachO::LC_SEGMENT) {
  7871. outs() << " cmd LC_SEGMENT\n";
  7872. expected_cmdsize = nsects;
  7873. expected_cmdsize *= sizeof(struct MachO::section);
  7874. expected_cmdsize += sizeof(struct MachO::segment_command);
  7875. } else {
  7876. outs() << " cmd LC_SEGMENT_64\n";
  7877. expected_cmdsize = nsects;
  7878. expected_cmdsize *= sizeof(struct MachO::section_64);
  7879. expected_cmdsize += sizeof(struct MachO::segment_command_64);
  7880. }
  7881. outs() << " cmdsize " << cmdsize;
  7882. if (cmdsize != expected_cmdsize)
  7883. outs() << " Inconsistent size\n";
  7884. else
  7885. outs() << "\n";
  7886. outs() << " segname " << SegName << "\n";
  7887. if (cmd == MachO::LC_SEGMENT_64) {
  7888. outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
  7889. outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
  7890. } else {
  7891. outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
  7892. outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
  7893. }
  7894. outs() << " fileoff " << fileoff;
  7895. if (fileoff > object_size)
  7896. outs() << " (past end of file)\n";
  7897. else
  7898. outs() << "\n";
  7899. outs() << " filesize " << filesize;
  7900. if (fileoff + filesize > object_size)
  7901. outs() << " (past end of file)\n";
  7902. else
  7903. outs() << "\n";
  7904. if (verbose) {
  7905. if ((maxprot &
  7906. ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
  7907. MachO::VM_PROT_EXECUTE)) != 0)
  7908. outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
  7909. else {
  7910. outs() << " maxprot ";
  7911. outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
  7912. outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
  7913. outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
  7914. }
  7915. if ((initprot &
  7916. ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
  7917. MachO::VM_PROT_EXECUTE)) != 0)
  7918. outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
  7919. else {
  7920. outs() << " initprot ";
  7921. outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
  7922. outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
  7923. outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
  7924. }
  7925. } else {
  7926. outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
  7927. outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
  7928. }
  7929. outs() << " nsects " << nsects << "\n";
  7930. if (verbose) {
  7931. outs() << " flags";
  7932. if (flags == 0)
  7933. outs() << " (none)\n";
  7934. else {
  7935. if (flags & MachO::SG_HIGHVM) {
  7936. outs() << " HIGHVM";
  7937. flags &= ~MachO::SG_HIGHVM;
  7938. }
  7939. if (flags & MachO::SG_FVMLIB) {
  7940. outs() << " FVMLIB";
  7941. flags &= ~MachO::SG_FVMLIB;
  7942. }
  7943. if (flags & MachO::SG_NORELOC) {
  7944. outs() << " NORELOC";
  7945. flags &= ~MachO::SG_NORELOC;
  7946. }
  7947. if (flags & MachO::SG_PROTECTED_VERSION_1) {
  7948. outs() << " PROTECTED_VERSION_1";
  7949. flags &= ~MachO::SG_PROTECTED_VERSION_1;
  7950. }
  7951. if (flags)
  7952. outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
  7953. else
  7954. outs() << "\n";
  7955. }
  7956. } else {
  7957. outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
  7958. }
  7959. }
  7960. static void PrintSection(const char *sectname, const char *segname,
  7961. uint64_t addr, uint64_t size, uint32_t offset,
  7962. uint32_t align, uint32_t reloff, uint32_t nreloc,
  7963. uint32_t flags, uint32_t reserved1, uint32_t reserved2,
  7964. uint32_t cmd, const char *sg_segname,
  7965. uint32_t filetype, uint32_t object_size,
  7966. bool verbose) {
  7967. outs() << "Section\n";
  7968. outs() << " sectname " << format("%.16s\n", sectname);
  7969. outs() << " segname " << format("%.16s", segname);
  7970. if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
  7971. outs() << " (does not match segment)\n";
  7972. else
  7973. outs() << "\n";
  7974. if (cmd == MachO::LC_SEGMENT_64) {
  7975. outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
  7976. outs() << " size " << format("0x%016" PRIx64, size);
  7977. } else {
  7978. outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
  7979. outs() << " size " << format("0x%08" PRIx64, size);
  7980. }
  7981. if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
  7982. outs() << " (past end of file)\n";
  7983. else
  7984. outs() << "\n";
  7985. outs() << " offset " << offset;
  7986. if (offset > object_size)
  7987. outs() << " (past end of file)\n";
  7988. else
  7989. outs() << "\n";
  7990. uint32_t align_shifted = 1 << align;
  7991. outs() << " align 2^" << align << " (" << align_shifted << ")\n";
  7992. outs() << " reloff " << reloff;
  7993. if (reloff > object_size)
  7994. outs() << " (past end of file)\n";
  7995. else
  7996. outs() << "\n";
  7997. outs() << " nreloc " << nreloc;
  7998. if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
  7999. outs() << " (past end of file)\n";
  8000. else
  8001. outs() << "\n";
  8002. uint32_t section_type = flags & MachO::SECTION_TYPE;
  8003. if (verbose) {
  8004. outs() << " type";
  8005. if (section_type == MachO::S_REGULAR)
  8006. outs() << " S_REGULAR\n";
  8007. else if (section_type == MachO::S_ZEROFILL)
  8008. outs() << " S_ZEROFILL\n";
  8009. else if (section_type == MachO::S_CSTRING_LITERALS)
  8010. outs() << " S_CSTRING_LITERALS\n";
  8011. else if (section_type == MachO::S_4BYTE_LITERALS)
  8012. outs() << " S_4BYTE_LITERALS\n";
  8013. else if (section_type == MachO::S_8BYTE_LITERALS)
  8014. outs() << " S_8BYTE_LITERALS\n";
  8015. else if (section_type == MachO::S_16BYTE_LITERALS)
  8016. outs() << " S_16BYTE_LITERALS\n";
  8017. else if (section_type == MachO::S_LITERAL_POINTERS)
  8018. outs() << " S_LITERAL_POINTERS\n";
  8019. else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
  8020. outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
  8021. else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
  8022. outs() << " S_LAZY_SYMBOL_POINTERS\n";
  8023. else if (section_type == MachO::S_SYMBOL_STUBS)
  8024. outs() << " S_SYMBOL_STUBS\n";
  8025. else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
  8026. outs() << " S_MOD_INIT_FUNC_POINTERS\n";
  8027. else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
  8028. outs() << " S_MOD_TERM_FUNC_POINTERS\n";
  8029. else if (section_type == MachO::S_COALESCED)
  8030. outs() << " S_COALESCED\n";
  8031. else if (section_type == MachO::S_INTERPOSING)
  8032. outs() << " S_INTERPOSING\n";
  8033. else if (section_type == MachO::S_DTRACE_DOF)
  8034. outs() << " S_DTRACE_DOF\n";
  8035. else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
  8036. outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
  8037. else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
  8038. outs() << " S_THREAD_LOCAL_REGULAR\n";
  8039. else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
  8040. outs() << " S_THREAD_LOCAL_ZEROFILL\n";
  8041. else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
  8042. outs() << " S_THREAD_LOCAL_VARIABLES\n";
  8043. else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
  8044. outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
  8045. else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
  8046. outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
  8047. else
  8048. outs() << format("0x%08" PRIx32, section_type) << "\n";
  8049. outs() << "attributes";
  8050. uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
  8051. if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
  8052. outs() << " PURE_INSTRUCTIONS";
  8053. if (section_attributes & MachO::S_ATTR_NO_TOC)
  8054. outs() << " NO_TOC";
  8055. if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
  8056. outs() << " STRIP_STATIC_SYMS";
  8057. if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
  8058. outs() << " NO_DEAD_STRIP";
  8059. if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
  8060. outs() << " LIVE_SUPPORT";
  8061. if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
  8062. outs() << " SELF_MODIFYING_CODE";
  8063. if (section_attributes & MachO::S_ATTR_DEBUG)
  8064. outs() << " DEBUG";
  8065. if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
  8066. outs() << " SOME_INSTRUCTIONS";
  8067. if (section_attributes & MachO::S_ATTR_EXT_RELOC)
  8068. outs() << " EXT_RELOC";
  8069. if (section_attributes & MachO::S_ATTR_LOC_RELOC)
  8070. outs() << " LOC_RELOC";
  8071. if (section_attributes == 0)
  8072. outs() << " (none)";
  8073. outs() << "\n";
  8074. } else
  8075. outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
  8076. outs() << " reserved1 " << reserved1;
  8077. if (section_type == MachO::S_SYMBOL_STUBS ||
  8078. section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
  8079. section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
  8080. section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
  8081. section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
  8082. outs() << " (index into indirect symbol table)\n";
  8083. else
  8084. outs() << "\n";
  8085. outs() << " reserved2 " << reserved2;
  8086. if (section_type == MachO::S_SYMBOL_STUBS)
  8087. outs() << " (size of stubs)\n";
  8088. else
  8089. outs() << "\n";
  8090. }
  8091. static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
  8092. uint32_t object_size) {
  8093. outs() << " cmd LC_SYMTAB\n";
  8094. outs() << " cmdsize " << st.cmdsize;
  8095. if (st.cmdsize != sizeof(struct MachO::symtab_command))
  8096. outs() << " Incorrect size\n";
  8097. else
  8098. outs() << "\n";
  8099. outs() << " symoff " << st.symoff;
  8100. if (st.symoff > object_size)
  8101. outs() << " (past end of file)\n";
  8102. else
  8103. outs() << "\n";
  8104. outs() << " nsyms " << st.nsyms;
  8105. uint64_t big_size;
  8106. if (Is64Bit) {
  8107. big_size = st.nsyms;
  8108. big_size *= sizeof(struct MachO::nlist_64);
  8109. big_size += st.symoff;
  8110. if (big_size > object_size)
  8111. outs() << " (past end of file)\n";
  8112. else
  8113. outs() << "\n";
  8114. } else {
  8115. big_size = st.nsyms;
  8116. big_size *= sizeof(struct MachO::nlist);
  8117. big_size += st.symoff;
  8118. if (big_size > object_size)
  8119. outs() << " (past end of file)\n";
  8120. else
  8121. outs() << "\n";
  8122. }
  8123. outs() << " stroff " << st.stroff;
  8124. if (st.stroff > object_size)
  8125. outs() << " (past end of file)\n";
  8126. else
  8127. outs() << "\n";
  8128. outs() << " strsize " << st.strsize;
  8129. big_size = st.stroff;
  8130. big_size += st.strsize;
  8131. if (big_size > object_size)
  8132. outs() << " (past end of file)\n";
  8133. else
  8134. outs() << "\n";
  8135. }
  8136. static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
  8137. uint32_t nsyms, uint32_t object_size,
  8138. bool Is64Bit) {
  8139. outs() << " cmd LC_DYSYMTAB\n";
  8140. outs() << " cmdsize " << dyst.cmdsize;
  8141. if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
  8142. outs() << " Incorrect size\n";
  8143. else
  8144. outs() << "\n";
  8145. outs() << " ilocalsym " << dyst.ilocalsym;
  8146. if (dyst.ilocalsym > nsyms)
  8147. outs() << " (greater than the number of symbols)\n";
  8148. else
  8149. outs() << "\n";
  8150. outs() << " nlocalsym " << dyst.nlocalsym;
  8151. uint64_t big_size;
  8152. big_size = dyst.ilocalsym;
  8153. big_size += dyst.nlocalsym;
  8154. if (big_size > nsyms)
  8155. outs() << " (past the end of the symbol table)\n";
  8156. else
  8157. outs() << "\n";
  8158. outs() << " iextdefsym " << dyst.iextdefsym;
  8159. if (dyst.iextdefsym > nsyms)
  8160. outs() << " (greater than the number of symbols)\n";
  8161. else
  8162. outs() << "\n";
  8163. outs() << " nextdefsym " << dyst.nextdefsym;
  8164. big_size = dyst.iextdefsym;
  8165. big_size += dyst.nextdefsym;
  8166. if (big_size > nsyms)
  8167. outs() << " (past the end of the symbol table)\n";
  8168. else
  8169. outs() << "\n";
  8170. outs() << " iundefsym " << dyst.iundefsym;
  8171. if (dyst.iundefsym > nsyms)
  8172. outs() << " (greater than the number of symbols)\n";
  8173. else
  8174. outs() << "\n";
  8175. outs() << " nundefsym " << dyst.nundefsym;
  8176. big_size = dyst.iundefsym;
  8177. big_size += dyst.nundefsym;
  8178. if (big_size > nsyms)
  8179. outs() << " (past the end of the symbol table)\n";
  8180. else
  8181. outs() << "\n";
  8182. outs() << " tocoff " << dyst.tocoff;
  8183. if (dyst.tocoff > object_size)
  8184. outs() << " (past end of file)\n";
  8185. else
  8186. outs() << "\n";
  8187. outs() << " ntoc " << dyst.ntoc;
  8188. big_size = dyst.ntoc;
  8189. big_size *= sizeof(struct MachO::dylib_table_of_contents);
  8190. big_size += dyst.tocoff;
  8191. if (big_size > object_size)
  8192. outs() << " (past end of file)\n";
  8193. else
  8194. outs() << "\n";
  8195. outs() << " modtaboff " << dyst.modtaboff;
  8196. if (dyst.modtaboff > object_size)
  8197. outs() << " (past end of file)\n";
  8198. else
  8199. outs() << "\n";
  8200. outs() << " nmodtab " << dyst.nmodtab;
  8201. uint64_t modtabend;
  8202. if (Is64Bit) {
  8203. modtabend = dyst.nmodtab;
  8204. modtabend *= sizeof(struct MachO::dylib_module_64);
  8205. modtabend += dyst.modtaboff;
  8206. } else {
  8207. modtabend = dyst.nmodtab;
  8208. modtabend *= sizeof(struct MachO::dylib_module);
  8209. modtabend += dyst.modtaboff;
  8210. }
  8211. if (modtabend > object_size)
  8212. outs() << " (past end of file)\n";
  8213. else
  8214. outs() << "\n";
  8215. outs() << " extrefsymoff " << dyst.extrefsymoff;
  8216. if (dyst.extrefsymoff > object_size)
  8217. outs() << " (past end of file)\n";
  8218. else
  8219. outs() << "\n";
  8220. outs() << " nextrefsyms " << dyst.nextrefsyms;
  8221. big_size = dyst.nextrefsyms;
  8222. big_size *= sizeof(struct MachO::dylib_reference);
  8223. big_size += dyst.extrefsymoff;
  8224. if (big_size > object_size)
  8225. outs() << " (past end of file)\n";
  8226. else
  8227. outs() << "\n";
  8228. outs() << " indirectsymoff " << dyst.indirectsymoff;
  8229. if (dyst.indirectsymoff > object_size)
  8230. outs() << " (past end of file)\n";
  8231. else
  8232. outs() << "\n";
  8233. outs() << " nindirectsyms " << dyst.nindirectsyms;
  8234. big_size = dyst.nindirectsyms;
  8235. big_size *= sizeof(uint32_t);
  8236. big_size += dyst.indirectsymoff;
  8237. if (big_size > object_size)
  8238. outs() << " (past end of file)\n";
  8239. else
  8240. outs() << "\n";
  8241. outs() << " extreloff " << dyst.extreloff;
  8242. if (dyst.extreloff > object_size)
  8243. outs() << " (past end of file)\n";
  8244. else
  8245. outs() << "\n";
  8246. outs() << " nextrel " << dyst.nextrel;
  8247. big_size = dyst.nextrel;
  8248. big_size *= sizeof(struct MachO::relocation_info);
  8249. big_size += dyst.extreloff;
  8250. if (big_size > object_size)
  8251. outs() << " (past end of file)\n";
  8252. else
  8253. outs() << "\n";
  8254. outs() << " locreloff " << dyst.locreloff;
  8255. if (dyst.locreloff > object_size)
  8256. outs() << " (past end of file)\n";
  8257. else
  8258. outs() << "\n";
  8259. outs() << " nlocrel " << dyst.nlocrel;
  8260. big_size = dyst.nlocrel;
  8261. big_size *= sizeof(struct MachO::relocation_info);
  8262. big_size += dyst.locreloff;
  8263. if (big_size > object_size)
  8264. outs() << " (past end of file)\n";
  8265. else
  8266. outs() << "\n";
  8267. }
  8268. static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
  8269. uint32_t object_size) {
  8270. if (dc.cmd == MachO::LC_DYLD_INFO)
  8271. outs() << " cmd LC_DYLD_INFO\n";
  8272. else
  8273. outs() << " cmd LC_DYLD_INFO_ONLY\n";
  8274. outs() << " cmdsize " << dc.cmdsize;
  8275. if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
  8276. outs() << " Incorrect size\n";
  8277. else
  8278. outs() << "\n";
  8279. outs() << " rebase_off " << dc.rebase_off;
  8280. if (dc.rebase_off > object_size)
  8281. outs() << " (past end of file)\n";
  8282. else
  8283. outs() << "\n";
  8284. outs() << " rebase_size " << dc.rebase_size;
  8285. uint64_t big_size;
  8286. big_size = dc.rebase_off;
  8287. big_size += dc.rebase_size;
  8288. if (big_size > object_size)
  8289. outs() << " (past end of file)\n";
  8290. else
  8291. outs() << "\n";
  8292. outs() << " bind_off " << dc.bind_off;
  8293. if (dc.bind_off > object_size)
  8294. outs() << " (past end of file)\n";
  8295. else
  8296. outs() << "\n";
  8297. outs() << " bind_size " << dc.bind_size;
  8298. big_size = dc.bind_off;
  8299. big_size += dc.bind_size;
  8300. if (big_size > object_size)
  8301. outs() << " (past end of file)\n";
  8302. else
  8303. outs() << "\n";
  8304. outs() << " weak_bind_off " << dc.weak_bind_off;
  8305. if (dc.weak_bind_off > object_size)
  8306. outs() << " (past end of file)\n";
  8307. else
  8308. outs() << "\n";
  8309. outs() << " weak_bind_size " << dc.weak_bind_size;
  8310. big_size = dc.weak_bind_off;
  8311. big_size += dc.weak_bind_size;
  8312. if (big_size > object_size)
  8313. outs() << " (past end of file)\n";
  8314. else
  8315. outs() << "\n";
  8316. outs() << " lazy_bind_off " << dc.lazy_bind_off;
  8317. if (dc.lazy_bind_off > object_size)
  8318. outs() << " (past end of file)\n";
  8319. else
  8320. outs() << "\n";
  8321. outs() << " lazy_bind_size " << dc.lazy_bind_size;
  8322. big_size = dc.lazy_bind_off;
  8323. big_size += dc.lazy_bind_size;
  8324. if (big_size > object_size)
  8325. outs() << " (past end of file)\n";
  8326. else
  8327. outs() << "\n";
  8328. outs() << " export_off " << dc.export_off;
  8329. if (dc.export_off > object_size)
  8330. outs() << " (past end of file)\n";
  8331. else
  8332. outs() << "\n";
  8333. outs() << " export_size " << dc.export_size;
  8334. big_size = dc.export_off;
  8335. big_size += dc.export_size;
  8336. if (big_size > object_size)
  8337. outs() << " (past end of file)\n";
  8338. else
  8339. outs() << "\n";
  8340. }
  8341. static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
  8342. const char *Ptr) {
  8343. if (dyld.cmd == MachO::LC_ID_DYLINKER)
  8344. outs() << " cmd LC_ID_DYLINKER\n";
  8345. else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
  8346. outs() << " cmd LC_LOAD_DYLINKER\n";
  8347. else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
  8348. outs() << " cmd LC_DYLD_ENVIRONMENT\n";
  8349. else
  8350. outs() << " cmd ?(" << dyld.cmd << ")\n";
  8351. outs() << " cmdsize " << dyld.cmdsize;
  8352. if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
  8353. outs() << " Incorrect size\n";
  8354. else
  8355. outs() << "\n";
  8356. if (dyld.name >= dyld.cmdsize)
  8357. outs() << " name ?(bad offset " << dyld.name << ")\n";
  8358. else {
  8359. const char *P = (const char *)(Ptr) + dyld.name;
  8360. outs() << " name " << P << " (offset " << dyld.name << ")\n";
  8361. }
  8362. }
  8363. static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
  8364. outs() << " cmd LC_UUID\n";
  8365. outs() << " cmdsize " << uuid.cmdsize;
  8366. if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
  8367. outs() << " Incorrect size\n";
  8368. else
  8369. outs() << "\n";
  8370. outs() << " uuid ";
  8371. for (int i = 0; i < 16; ++i) {
  8372. outs() << format("%02" PRIX32, uuid.uuid[i]);
  8373. if (i == 3 || i == 5 || i == 7 || i == 9)
  8374. outs() << "-";
  8375. }
  8376. outs() << "\n";
  8377. }
  8378. static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
  8379. outs() << " cmd LC_RPATH\n";
  8380. outs() << " cmdsize " << rpath.cmdsize;
  8381. if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
  8382. outs() << " Incorrect size\n";
  8383. else
  8384. outs() << "\n";
  8385. if (rpath.path >= rpath.cmdsize)
  8386. outs() << " path ?(bad offset " << rpath.path << ")\n";
  8387. else {
  8388. const char *P = (const char *)(Ptr) + rpath.path;
  8389. outs() << " path " << P << " (offset " << rpath.path << ")\n";
  8390. }
  8391. }
  8392. static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
  8393. StringRef LoadCmdName;
  8394. switch (vd.cmd) {
  8395. case MachO::LC_VERSION_MIN_MACOSX:
  8396. LoadCmdName = "LC_VERSION_MIN_MACOSX";
  8397. break;
  8398. case MachO::LC_VERSION_MIN_IPHONEOS:
  8399. LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
  8400. break;
  8401. case MachO::LC_VERSION_MIN_TVOS:
  8402. LoadCmdName = "LC_VERSION_MIN_TVOS";
  8403. break;
  8404. case MachO::LC_VERSION_MIN_WATCHOS:
  8405. LoadCmdName = "LC_VERSION_MIN_WATCHOS";
  8406. break;
  8407. default:
  8408. llvm_unreachable("Unknown version min load command");
  8409. }
  8410. outs() << " cmd " << LoadCmdName << '\n';
  8411. outs() << " cmdsize " << vd.cmdsize;
  8412. if (vd.cmdsize != sizeof(struct MachO::version_min_command))
  8413. outs() << " Incorrect size\n";
  8414. else
  8415. outs() << "\n";
  8416. outs() << " version "
  8417. << MachOObjectFile::getVersionMinMajor(vd, false) << "."
  8418. << MachOObjectFile::getVersionMinMinor(vd, false);
  8419. uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
  8420. if (Update != 0)
  8421. outs() << "." << Update;
  8422. outs() << "\n";
  8423. if (vd.sdk == 0)
  8424. outs() << " sdk n/a";
  8425. else {
  8426. outs() << " sdk "
  8427. << MachOObjectFile::getVersionMinMajor(vd, true) << "."
  8428. << MachOObjectFile::getVersionMinMinor(vd, true);
  8429. }
  8430. Update = MachOObjectFile::getVersionMinUpdate(vd, true);
  8431. if (Update != 0)
  8432. outs() << "." << Update;
  8433. outs() << "\n";
  8434. }
  8435. static void PrintNoteLoadCommand(MachO::note_command Nt) {
  8436. outs() << " cmd LC_NOTE\n";
  8437. outs() << " cmdsize " << Nt.cmdsize;
  8438. if (Nt.cmdsize != sizeof(struct MachO::note_command))
  8439. outs() << " Incorrect size\n";
  8440. else
  8441. outs() << "\n";
  8442. const char *d = Nt.data_owner;
  8443. outs() << "data_owner " << format("%.16s\n", d);
  8444. outs() << " offset " << Nt.offset << "\n";
  8445. outs() << " size " << Nt.size << "\n";
  8446. }
  8447. static void PrintBuildToolVersion(MachO::build_tool_version bv) {
  8448. outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
  8449. outs() << " version " << MachOObjectFile::getVersionString(bv.version)
  8450. << "\n";
  8451. }
  8452. static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
  8453. MachO::build_version_command bd) {
  8454. outs() << " cmd LC_BUILD_VERSION\n";
  8455. outs() << " cmdsize " << bd.cmdsize;
  8456. if (bd.cmdsize !=
  8457. sizeof(struct MachO::build_version_command) +
  8458. bd.ntools * sizeof(struct MachO::build_tool_version))
  8459. outs() << " Incorrect size\n";
  8460. else
  8461. outs() << "\n";
  8462. outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
  8463. << "\n";
  8464. if (bd.sdk)
  8465. outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
  8466. << "\n";
  8467. else
  8468. outs() << " sdk n/a\n";
  8469. outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
  8470. << "\n";
  8471. outs() << " ntools " << bd.ntools << "\n";
  8472. for (unsigned i = 0; i < bd.ntools; ++i) {
  8473. MachO::build_tool_version bv = obj->getBuildToolVersion(i);
  8474. PrintBuildToolVersion(bv);
  8475. }
  8476. }
  8477. static void PrintSourceVersionCommand(MachO::source_version_command sd) {
  8478. outs() << " cmd LC_SOURCE_VERSION\n";
  8479. outs() << " cmdsize " << sd.cmdsize;
  8480. if (sd.cmdsize != sizeof(struct MachO::source_version_command))
  8481. outs() << " Incorrect size\n";
  8482. else
  8483. outs() << "\n";
  8484. uint64_t a = (sd.version >> 40) & 0xffffff;
  8485. uint64_t b = (sd.version >> 30) & 0x3ff;
  8486. uint64_t c = (sd.version >> 20) & 0x3ff;
  8487. uint64_t d = (sd.version >> 10) & 0x3ff;
  8488. uint64_t e = sd.version & 0x3ff;
  8489. outs() << " version " << a << "." << b;
  8490. if (e != 0)
  8491. outs() << "." << c << "." << d << "." << e;
  8492. else if (d != 0)
  8493. outs() << "." << c << "." << d;
  8494. else if (c != 0)
  8495. outs() << "." << c;
  8496. outs() << "\n";
  8497. }
  8498. static void PrintEntryPointCommand(MachO::entry_point_command ep) {
  8499. outs() << " cmd LC_MAIN\n";
  8500. outs() << " cmdsize " << ep.cmdsize;
  8501. if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
  8502. outs() << " Incorrect size\n";
  8503. else
  8504. outs() << "\n";
  8505. outs() << " entryoff " << ep.entryoff << "\n";
  8506. outs() << " stacksize " << ep.stacksize << "\n";
  8507. }
  8508. static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
  8509. uint32_t object_size) {
  8510. outs() << " cmd LC_ENCRYPTION_INFO\n";
  8511. outs() << " cmdsize " << ec.cmdsize;
  8512. if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
  8513. outs() << " Incorrect size\n";
  8514. else
  8515. outs() << "\n";
  8516. outs() << " cryptoff " << ec.cryptoff;
  8517. if (ec.cryptoff > object_size)
  8518. outs() << " (past end of file)\n";
  8519. else
  8520. outs() << "\n";
  8521. outs() << " cryptsize " << ec.cryptsize;
  8522. if (ec.cryptsize > object_size)
  8523. outs() << " (past end of file)\n";
  8524. else
  8525. outs() << "\n";
  8526. outs() << " cryptid " << ec.cryptid << "\n";
  8527. }
  8528. static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
  8529. uint32_t object_size) {
  8530. outs() << " cmd LC_ENCRYPTION_INFO_64\n";
  8531. outs() << " cmdsize " << ec.cmdsize;
  8532. if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
  8533. outs() << " Incorrect size\n";
  8534. else
  8535. outs() << "\n";
  8536. outs() << " cryptoff " << ec.cryptoff;
  8537. if (ec.cryptoff > object_size)
  8538. outs() << " (past end of file)\n";
  8539. else
  8540. outs() << "\n";
  8541. outs() << " cryptsize " << ec.cryptsize;
  8542. if (ec.cryptsize > object_size)
  8543. outs() << " (past end of file)\n";
  8544. else
  8545. outs() << "\n";
  8546. outs() << " cryptid " << ec.cryptid << "\n";
  8547. outs() << " pad " << ec.pad << "\n";
  8548. }
  8549. static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
  8550. const char *Ptr) {
  8551. outs() << " cmd LC_LINKER_OPTION\n";
  8552. outs() << " cmdsize " << lo.cmdsize;
  8553. if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
  8554. outs() << " Incorrect size\n";
  8555. else
  8556. outs() << "\n";
  8557. outs() << " count " << lo.count << "\n";
  8558. const char *string = Ptr + sizeof(struct MachO::linker_option_command);
  8559. uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
  8560. uint32_t i = 0;
  8561. while (left > 0) {
  8562. while (*string == '\0' && left > 0) {
  8563. string++;
  8564. left--;
  8565. }
  8566. if (left > 0) {
  8567. i++;
  8568. outs() << " string #" << i << " " << format("%.*s\n", left, string);
  8569. uint32_t NullPos = StringRef(string, left).find('\0');
  8570. uint32_t len = std::min(NullPos, left) + 1;
  8571. string += len;
  8572. left -= len;
  8573. }
  8574. }
  8575. if (lo.count != i)
  8576. outs() << " count " << lo.count << " does not match number of strings "
  8577. << i << "\n";
  8578. }
  8579. static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
  8580. const char *Ptr) {
  8581. outs() << " cmd LC_SUB_FRAMEWORK\n";
  8582. outs() << " cmdsize " << sub.cmdsize;
  8583. if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
  8584. outs() << " Incorrect size\n";
  8585. else
  8586. outs() << "\n";
  8587. if (sub.umbrella < sub.cmdsize) {
  8588. const char *P = Ptr + sub.umbrella;
  8589. outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
  8590. } else {
  8591. outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
  8592. }
  8593. }
  8594. static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
  8595. const char *Ptr) {
  8596. outs() << " cmd LC_SUB_UMBRELLA\n";
  8597. outs() << " cmdsize " << sub.cmdsize;
  8598. if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
  8599. outs() << " Incorrect size\n";
  8600. else
  8601. outs() << "\n";
  8602. if (sub.sub_umbrella < sub.cmdsize) {
  8603. const char *P = Ptr + sub.sub_umbrella;
  8604. outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
  8605. } else {
  8606. outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
  8607. }
  8608. }
  8609. static void PrintSubLibraryCommand(MachO::sub_library_command sub,
  8610. const char *Ptr) {
  8611. outs() << " cmd LC_SUB_LIBRARY\n";
  8612. outs() << " cmdsize " << sub.cmdsize;
  8613. if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
  8614. outs() << " Incorrect size\n";
  8615. else
  8616. outs() << "\n";
  8617. if (sub.sub_library < sub.cmdsize) {
  8618. const char *P = Ptr + sub.sub_library;
  8619. outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
  8620. } else {
  8621. outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
  8622. }
  8623. }
  8624. static void PrintSubClientCommand(MachO::sub_client_command sub,
  8625. const char *Ptr) {
  8626. outs() << " cmd LC_SUB_CLIENT\n";
  8627. outs() << " cmdsize " << sub.cmdsize;
  8628. if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
  8629. outs() << " Incorrect size\n";
  8630. else
  8631. outs() << "\n";
  8632. if (sub.client < sub.cmdsize) {
  8633. const char *P = Ptr + sub.client;
  8634. outs() << " client " << P << " (offset " << sub.client << ")\n";
  8635. } else {
  8636. outs() << " client ?(bad offset " << sub.client << ")\n";
  8637. }
  8638. }
  8639. static void PrintRoutinesCommand(MachO::routines_command r) {
  8640. outs() << " cmd LC_ROUTINES\n";
  8641. outs() << " cmdsize " << r.cmdsize;
  8642. if (r.cmdsize != sizeof(struct MachO::routines_command))
  8643. outs() << " Incorrect size\n";
  8644. else
  8645. outs() << "\n";
  8646. outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
  8647. outs() << " init_module " << r.init_module << "\n";
  8648. outs() << " reserved1 " << r.reserved1 << "\n";
  8649. outs() << " reserved2 " << r.reserved2 << "\n";
  8650. outs() << " reserved3 " << r.reserved3 << "\n";
  8651. outs() << " reserved4 " << r.reserved4 << "\n";
  8652. outs() << " reserved5 " << r.reserved5 << "\n";
  8653. outs() << " reserved6 " << r.reserved6 << "\n";
  8654. }
  8655. static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
  8656. outs() << " cmd LC_ROUTINES_64\n";
  8657. outs() << " cmdsize " << r.cmdsize;
  8658. if (r.cmdsize != sizeof(struct MachO::routines_command_64))
  8659. outs() << " Incorrect size\n";
  8660. else
  8661. outs() << "\n";
  8662. outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
  8663. outs() << " init_module " << r.init_module << "\n";
  8664. outs() << " reserved1 " << r.reserved1 << "\n";
  8665. outs() << " reserved2 " << r.reserved2 << "\n";
  8666. outs() << " reserved3 " << r.reserved3 << "\n";
  8667. outs() << " reserved4 " << r.reserved4 << "\n";
  8668. outs() << " reserved5 " << r.reserved5 << "\n";
  8669. outs() << " reserved6 " << r.reserved6 << "\n";
  8670. }
  8671. static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
  8672. outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
  8673. outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
  8674. outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
  8675. outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
  8676. outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
  8677. outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
  8678. outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
  8679. outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
  8680. outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
  8681. outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
  8682. outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
  8683. outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
  8684. outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
  8685. outs() << " es " << format("0x%08" PRIx32, cpu32.es);
  8686. outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
  8687. outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
  8688. }
  8689. static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
  8690. outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
  8691. outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
  8692. outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
  8693. outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
  8694. outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
  8695. outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
  8696. outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
  8697. outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
  8698. outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
  8699. outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
  8700. outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
  8701. outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
  8702. outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
  8703. outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
  8704. outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
  8705. outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
  8706. outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
  8707. outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
  8708. outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
  8709. outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
  8710. outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
  8711. }
  8712. static void Print_mmst_reg(MachO::mmst_reg_t &r) {
  8713. uint32_t f;
  8714. outs() << "\t mmst_reg ";
  8715. for (f = 0; f < 10; f++)
  8716. outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
  8717. outs() << "\n";
  8718. outs() << "\t mmst_rsrv ";
  8719. for (f = 0; f < 6; f++)
  8720. outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
  8721. outs() << "\n";
  8722. }
  8723. static void Print_xmm_reg(MachO::xmm_reg_t &r) {
  8724. uint32_t f;
  8725. outs() << "\t xmm_reg ";
  8726. for (f = 0; f < 16; f++)
  8727. outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
  8728. outs() << "\n";
  8729. }
  8730. static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
  8731. outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
  8732. outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
  8733. outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
  8734. outs() << " denorm " << fpu.fpu_fcw.denorm;
  8735. outs() << " zdiv " << fpu.fpu_fcw.zdiv;
  8736. outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
  8737. outs() << " undfl " << fpu.fpu_fcw.undfl;
  8738. outs() << " precis " << fpu.fpu_fcw.precis << "\n";
  8739. outs() << "\t\t pc ";
  8740. if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
  8741. outs() << "FP_PREC_24B ";
  8742. else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
  8743. outs() << "FP_PREC_53B ";
  8744. else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
  8745. outs() << "FP_PREC_64B ";
  8746. else
  8747. outs() << fpu.fpu_fcw.pc << " ";
  8748. outs() << "rc ";
  8749. if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
  8750. outs() << "FP_RND_NEAR ";
  8751. else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
  8752. outs() << "FP_RND_DOWN ";
  8753. else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
  8754. outs() << "FP_RND_UP ";
  8755. else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
  8756. outs() << "FP_CHOP ";
  8757. outs() << "\n";
  8758. outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
  8759. outs() << " denorm " << fpu.fpu_fsw.denorm;
  8760. outs() << " zdiv " << fpu.fpu_fsw.zdiv;
  8761. outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
  8762. outs() << " undfl " << fpu.fpu_fsw.undfl;
  8763. outs() << " precis " << fpu.fpu_fsw.precis;
  8764. outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
  8765. outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
  8766. outs() << " c0 " << fpu.fpu_fsw.c0;
  8767. outs() << " c1 " << fpu.fpu_fsw.c1;
  8768. outs() << " c2 " << fpu.fpu_fsw.c2;
  8769. outs() << " tos " << fpu.fpu_fsw.tos;
  8770. outs() << " c3 " << fpu.fpu_fsw.c3;
  8771. outs() << " busy " << fpu.fpu_fsw.busy << "\n";
  8772. outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
  8773. outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
  8774. outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
  8775. outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
  8776. outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
  8777. outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
  8778. outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
  8779. outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
  8780. outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
  8781. outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
  8782. outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
  8783. outs() << "\n";
  8784. outs() << "\t fpu_stmm0:\n";
  8785. Print_mmst_reg(fpu.fpu_stmm0);
  8786. outs() << "\t fpu_stmm1:\n";
  8787. Print_mmst_reg(fpu.fpu_stmm1);
  8788. outs() << "\t fpu_stmm2:\n";
  8789. Print_mmst_reg(fpu.fpu_stmm2);
  8790. outs() << "\t fpu_stmm3:\n";
  8791. Print_mmst_reg(fpu.fpu_stmm3);
  8792. outs() << "\t fpu_stmm4:\n";
  8793. Print_mmst_reg(fpu.fpu_stmm4);
  8794. outs() << "\t fpu_stmm5:\n";
  8795. Print_mmst_reg(fpu.fpu_stmm5);
  8796. outs() << "\t fpu_stmm6:\n";
  8797. Print_mmst_reg(fpu.fpu_stmm6);
  8798. outs() << "\t fpu_stmm7:\n";
  8799. Print_mmst_reg(fpu.fpu_stmm7);
  8800. outs() << "\t fpu_xmm0:\n";
  8801. Print_xmm_reg(fpu.fpu_xmm0);
  8802. outs() << "\t fpu_xmm1:\n";
  8803. Print_xmm_reg(fpu.fpu_xmm1);
  8804. outs() << "\t fpu_xmm2:\n";
  8805. Print_xmm_reg(fpu.fpu_xmm2);
  8806. outs() << "\t fpu_xmm3:\n";
  8807. Print_xmm_reg(fpu.fpu_xmm3);
  8808. outs() << "\t fpu_xmm4:\n";
  8809. Print_xmm_reg(fpu.fpu_xmm4);
  8810. outs() << "\t fpu_xmm5:\n";
  8811. Print_xmm_reg(fpu.fpu_xmm5);
  8812. outs() << "\t fpu_xmm6:\n";
  8813. Print_xmm_reg(fpu.fpu_xmm6);
  8814. outs() << "\t fpu_xmm7:\n";
  8815. Print_xmm_reg(fpu.fpu_xmm7);
  8816. outs() << "\t fpu_xmm8:\n";
  8817. Print_xmm_reg(fpu.fpu_xmm8);
  8818. outs() << "\t fpu_xmm9:\n";
  8819. Print_xmm_reg(fpu.fpu_xmm9);
  8820. outs() << "\t fpu_xmm10:\n";
  8821. Print_xmm_reg(fpu.fpu_xmm10);
  8822. outs() << "\t fpu_xmm11:\n";
  8823. Print_xmm_reg(fpu.fpu_xmm11);
  8824. outs() << "\t fpu_xmm12:\n";
  8825. Print_xmm_reg(fpu.fpu_xmm12);
  8826. outs() << "\t fpu_xmm13:\n";
  8827. Print_xmm_reg(fpu.fpu_xmm13);
  8828. outs() << "\t fpu_xmm14:\n";
  8829. Print_xmm_reg(fpu.fpu_xmm14);
  8830. outs() << "\t fpu_xmm15:\n";
  8831. Print_xmm_reg(fpu.fpu_xmm15);
  8832. outs() << "\t fpu_rsrv4:\n";
  8833. for (uint32_t f = 0; f < 6; f++) {
  8834. outs() << "\t ";
  8835. for (uint32_t g = 0; g < 16; g++)
  8836. outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
  8837. outs() << "\n";
  8838. }
  8839. outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
  8840. outs() << "\n";
  8841. }
  8842. static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
  8843. outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
  8844. outs() << " err " << format("0x%08" PRIx32, exc64.err);
  8845. outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
  8846. }
  8847. static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
  8848. outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
  8849. outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
  8850. outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
  8851. outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
  8852. outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
  8853. outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
  8854. outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
  8855. outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
  8856. outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
  8857. outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
  8858. outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
  8859. outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
  8860. outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
  8861. outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
  8862. outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
  8863. outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
  8864. outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
  8865. }
  8866. static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
  8867. outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
  8868. outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
  8869. outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
  8870. outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
  8871. outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
  8872. outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
  8873. outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
  8874. outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
  8875. outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
  8876. outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
  8877. outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
  8878. outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
  8879. outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
  8880. outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
  8881. outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
  8882. outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
  8883. outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
  8884. outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
  8885. outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
  8886. outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
  8887. outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
  8888. outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
  8889. outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
  8890. outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
  8891. outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
  8892. outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
  8893. outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
  8894. outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
  8895. outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
  8896. outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
  8897. outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
  8898. outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
  8899. outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
  8900. outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
  8901. }
  8902. static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
  8903. bool isLittleEndian, uint32_t cputype) {
  8904. if (t.cmd == MachO::LC_THREAD)
  8905. outs() << " cmd LC_THREAD\n";
  8906. else if (t.cmd == MachO::LC_UNIXTHREAD)
  8907. outs() << " cmd LC_UNIXTHREAD\n";
  8908. else
  8909. outs() << " cmd " << t.cmd << " (unknown)\n";
  8910. outs() << " cmdsize " << t.cmdsize;
  8911. if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
  8912. outs() << " Incorrect size\n";
  8913. else
  8914. outs() << "\n";
  8915. const char *begin = Ptr + sizeof(struct MachO::thread_command);
  8916. const char *end = Ptr + t.cmdsize;
  8917. uint32_t flavor, count, left;
  8918. if (cputype == MachO::CPU_TYPE_I386) {
  8919. while (begin < end) {
  8920. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  8921. memcpy((char *)&flavor, begin, sizeof(uint32_t));
  8922. begin += sizeof(uint32_t);
  8923. } else {
  8924. flavor = 0;
  8925. begin = end;
  8926. }
  8927. if (isLittleEndian != sys::IsLittleEndianHost)
  8928. sys::swapByteOrder(flavor);
  8929. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  8930. memcpy((char *)&count, begin, sizeof(uint32_t));
  8931. begin += sizeof(uint32_t);
  8932. } else {
  8933. count = 0;
  8934. begin = end;
  8935. }
  8936. if (isLittleEndian != sys::IsLittleEndianHost)
  8937. sys::swapByteOrder(count);
  8938. if (flavor == MachO::x86_THREAD_STATE32) {
  8939. outs() << " flavor i386_THREAD_STATE\n";
  8940. if (count == MachO::x86_THREAD_STATE32_COUNT)
  8941. outs() << " count i386_THREAD_STATE_COUNT\n";
  8942. else
  8943. outs() << " count " << count
  8944. << " (not x86_THREAD_STATE32_COUNT)\n";
  8945. MachO::x86_thread_state32_t cpu32;
  8946. left = end - begin;
  8947. if (left >= sizeof(MachO::x86_thread_state32_t)) {
  8948. memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
  8949. begin += sizeof(MachO::x86_thread_state32_t);
  8950. } else {
  8951. memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
  8952. memcpy(&cpu32, begin, left);
  8953. begin += left;
  8954. }
  8955. if (isLittleEndian != sys::IsLittleEndianHost)
  8956. swapStruct(cpu32);
  8957. Print_x86_thread_state32_t(cpu32);
  8958. } else if (flavor == MachO::x86_THREAD_STATE) {
  8959. outs() << " flavor x86_THREAD_STATE\n";
  8960. if (count == MachO::x86_THREAD_STATE_COUNT)
  8961. outs() << " count x86_THREAD_STATE_COUNT\n";
  8962. else
  8963. outs() << " count " << count
  8964. << " (not x86_THREAD_STATE_COUNT)\n";
  8965. struct MachO::x86_thread_state_t ts;
  8966. left = end - begin;
  8967. if (left >= sizeof(MachO::x86_thread_state_t)) {
  8968. memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
  8969. begin += sizeof(MachO::x86_thread_state_t);
  8970. } else {
  8971. memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
  8972. memcpy(&ts, begin, left);
  8973. begin += left;
  8974. }
  8975. if (isLittleEndian != sys::IsLittleEndianHost)
  8976. swapStruct(ts);
  8977. if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
  8978. outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
  8979. if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
  8980. outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
  8981. else
  8982. outs() << "tsh.count " << ts.tsh.count
  8983. << " (not x86_THREAD_STATE32_COUNT\n";
  8984. Print_x86_thread_state32_t(ts.uts.ts32);
  8985. } else {
  8986. outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
  8987. << ts.tsh.count << "\n";
  8988. }
  8989. } else {
  8990. outs() << " flavor " << flavor << " (unknown)\n";
  8991. outs() << " count " << count << "\n";
  8992. outs() << " state (unknown)\n";
  8993. begin += count * sizeof(uint32_t);
  8994. }
  8995. }
  8996. } else if (cputype == MachO::CPU_TYPE_X86_64) {
  8997. while (begin < end) {
  8998. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  8999. memcpy((char *)&flavor, begin, sizeof(uint32_t));
  9000. begin += sizeof(uint32_t);
  9001. } else {
  9002. flavor = 0;
  9003. begin = end;
  9004. }
  9005. if (isLittleEndian != sys::IsLittleEndianHost)
  9006. sys::swapByteOrder(flavor);
  9007. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9008. memcpy((char *)&count, begin, sizeof(uint32_t));
  9009. begin += sizeof(uint32_t);
  9010. } else {
  9011. count = 0;
  9012. begin = end;
  9013. }
  9014. if (isLittleEndian != sys::IsLittleEndianHost)
  9015. sys::swapByteOrder(count);
  9016. if (flavor == MachO::x86_THREAD_STATE64) {
  9017. outs() << " flavor x86_THREAD_STATE64\n";
  9018. if (count == MachO::x86_THREAD_STATE64_COUNT)
  9019. outs() << " count x86_THREAD_STATE64_COUNT\n";
  9020. else
  9021. outs() << " count " << count
  9022. << " (not x86_THREAD_STATE64_COUNT)\n";
  9023. MachO::x86_thread_state64_t cpu64;
  9024. left = end - begin;
  9025. if (left >= sizeof(MachO::x86_thread_state64_t)) {
  9026. memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
  9027. begin += sizeof(MachO::x86_thread_state64_t);
  9028. } else {
  9029. memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
  9030. memcpy(&cpu64, begin, left);
  9031. begin += left;
  9032. }
  9033. if (isLittleEndian != sys::IsLittleEndianHost)
  9034. swapStruct(cpu64);
  9035. Print_x86_thread_state64_t(cpu64);
  9036. } else if (flavor == MachO::x86_THREAD_STATE) {
  9037. outs() << " flavor x86_THREAD_STATE\n";
  9038. if (count == MachO::x86_THREAD_STATE_COUNT)
  9039. outs() << " count x86_THREAD_STATE_COUNT\n";
  9040. else
  9041. outs() << " count " << count
  9042. << " (not x86_THREAD_STATE_COUNT)\n";
  9043. struct MachO::x86_thread_state_t ts;
  9044. left = end - begin;
  9045. if (left >= sizeof(MachO::x86_thread_state_t)) {
  9046. memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
  9047. begin += sizeof(MachO::x86_thread_state_t);
  9048. } else {
  9049. memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
  9050. memcpy(&ts, begin, left);
  9051. begin += left;
  9052. }
  9053. if (isLittleEndian != sys::IsLittleEndianHost)
  9054. swapStruct(ts);
  9055. if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
  9056. outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
  9057. if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
  9058. outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
  9059. else
  9060. outs() << "tsh.count " << ts.tsh.count
  9061. << " (not x86_THREAD_STATE64_COUNT\n";
  9062. Print_x86_thread_state64_t(ts.uts.ts64);
  9063. } else {
  9064. outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
  9065. << ts.tsh.count << "\n";
  9066. }
  9067. } else if (flavor == MachO::x86_FLOAT_STATE) {
  9068. outs() << " flavor x86_FLOAT_STATE\n";
  9069. if (count == MachO::x86_FLOAT_STATE_COUNT)
  9070. outs() << " count x86_FLOAT_STATE_COUNT\n";
  9071. else
  9072. outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
  9073. struct MachO::x86_float_state_t fs;
  9074. left = end - begin;
  9075. if (left >= sizeof(MachO::x86_float_state_t)) {
  9076. memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
  9077. begin += sizeof(MachO::x86_float_state_t);
  9078. } else {
  9079. memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
  9080. memcpy(&fs, begin, left);
  9081. begin += left;
  9082. }
  9083. if (isLittleEndian != sys::IsLittleEndianHost)
  9084. swapStruct(fs);
  9085. if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
  9086. outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
  9087. if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
  9088. outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
  9089. else
  9090. outs() << "fsh.count " << fs.fsh.count
  9091. << " (not x86_FLOAT_STATE64_COUNT\n";
  9092. Print_x86_float_state_t(fs.ufs.fs64);
  9093. } else {
  9094. outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
  9095. << fs.fsh.count << "\n";
  9096. }
  9097. } else if (flavor == MachO::x86_EXCEPTION_STATE) {
  9098. outs() << " flavor x86_EXCEPTION_STATE\n";
  9099. if (count == MachO::x86_EXCEPTION_STATE_COUNT)
  9100. outs() << " count x86_EXCEPTION_STATE_COUNT\n";
  9101. else
  9102. outs() << " count " << count
  9103. << " (not x86_EXCEPTION_STATE_COUNT)\n";
  9104. struct MachO::x86_exception_state_t es;
  9105. left = end - begin;
  9106. if (left >= sizeof(MachO::x86_exception_state_t)) {
  9107. memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
  9108. begin += sizeof(MachO::x86_exception_state_t);
  9109. } else {
  9110. memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
  9111. memcpy(&es, begin, left);
  9112. begin += left;
  9113. }
  9114. if (isLittleEndian != sys::IsLittleEndianHost)
  9115. swapStruct(es);
  9116. if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
  9117. outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
  9118. if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
  9119. outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
  9120. else
  9121. outs() << "\t esh.count " << es.esh.count
  9122. << " (not x86_EXCEPTION_STATE64_COUNT\n";
  9123. Print_x86_exception_state_t(es.ues.es64);
  9124. } else {
  9125. outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
  9126. << es.esh.count << "\n";
  9127. }
  9128. } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
  9129. outs() << " flavor x86_EXCEPTION_STATE64\n";
  9130. if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
  9131. outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
  9132. else
  9133. outs() << " count " << count
  9134. << " (not x86_EXCEPTION_STATE64_COUNT)\n";
  9135. struct MachO::x86_exception_state64_t es64;
  9136. left = end - begin;
  9137. if (left >= sizeof(MachO::x86_exception_state64_t)) {
  9138. memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
  9139. begin += sizeof(MachO::x86_exception_state64_t);
  9140. } else {
  9141. memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
  9142. memcpy(&es64, begin, left);
  9143. begin += left;
  9144. }
  9145. if (isLittleEndian != sys::IsLittleEndianHost)
  9146. swapStruct(es64);
  9147. Print_x86_exception_state_t(es64);
  9148. } else {
  9149. outs() << " flavor " << flavor << " (unknown)\n";
  9150. outs() << " count " << count << "\n";
  9151. outs() << " state (unknown)\n";
  9152. begin += count * sizeof(uint32_t);
  9153. }
  9154. }
  9155. } else if (cputype == MachO::CPU_TYPE_ARM) {
  9156. while (begin < end) {
  9157. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9158. memcpy((char *)&flavor, begin, sizeof(uint32_t));
  9159. begin += sizeof(uint32_t);
  9160. } else {
  9161. flavor = 0;
  9162. begin = end;
  9163. }
  9164. if (isLittleEndian != sys::IsLittleEndianHost)
  9165. sys::swapByteOrder(flavor);
  9166. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9167. memcpy((char *)&count, begin, sizeof(uint32_t));
  9168. begin += sizeof(uint32_t);
  9169. } else {
  9170. count = 0;
  9171. begin = end;
  9172. }
  9173. if (isLittleEndian != sys::IsLittleEndianHost)
  9174. sys::swapByteOrder(count);
  9175. if (flavor == MachO::ARM_THREAD_STATE) {
  9176. outs() << " flavor ARM_THREAD_STATE\n";
  9177. if (count == MachO::ARM_THREAD_STATE_COUNT)
  9178. outs() << " count ARM_THREAD_STATE_COUNT\n";
  9179. else
  9180. outs() << " count " << count
  9181. << " (not ARM_THREAD_STATE_COUNT)\n";
  9182. MachO::arm_thread_state32_t cpu32;
  9183. left = end - begin;
  9184. if (left >= sizeof(MachO::arm_thread_state32_t)) {
  9185. memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
  9186. begin += sizeof(MachO::arm_thread_state32_t);
  9187. } else {
  9188. memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
  9189. memcpy(&cpu32, begin, left);
  9190. begin += left;
  9191. }
  9192. if (isLittleEndian != sys::IsLittleEndianHost)
  9193. swapStruct(cpu32);
  9194. Print_arm_thread_state32_t(cpu32);
  9195. } else {
  9196. outs() << " flavor " << flavor << " (unknown)\n";
  9197. outs() << " count " << count << "\n";
  9198. outs() << " state (unknown)\n";
  9199. begin += count * sizeof(uint32_t);
  9200. }
  9201. }
  9202. } else if (cputype == MachO::CPU_TYPE_ARM64 ||
  9203. cputype == MachO::CPU_TYPE_ARM64_32) {
  9204. while (begin < end) {
  9205. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9206. memcpy((char *)&flavor, begin, sizeof(uint32_t));
  9207. begin += sizeof(uint32_t);
  9208. } else {
  9209. flavor = 0;
  9210. begin = end;
  9211. }
  9212. if (isLittleEndian != sys::IsLittleEndianHost)
  9213. sys::swapByteOrder(flavor);
  9214. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9215. memcpy((char *)&count, begin, sizeof(uint32_t));
  9216. begin += sizeof(uint32_t);
  9217. } else {
  9218. count = 0;
  9219. begin = end;
  9220. }
  9221. if (isLittleEndian != sys::IsLittleEndianHost)
  9222. sys::swapByteOrder(count);
  9223. if (flavor == MachO::ARM_THREAD_STATE64) {
  9224. outs() << " flavor ARM_THREAD_STATE64\n";
  9225. if (count == MachO::ARM_THREAD_STATE64_COUNT)
  9226. outs() << " count ARM_THREAD_STATE64_COUNT\n";
  9227. else
  9228. outs() << " count " << count
  9229. << " (not ARM_THREAD_STATE64_COUNT)\n";
  9230. MachO::arm_thread_state64_t cpu64;
  9231. left = end - begin;
  9232. if (left >= sizeof(MachO::arm_thread_state64_t)) {
  9233. memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
  9234. begin += sizeof(MachO::arm_thread_state64_t);
  9235. } else {
  9236. memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
  9237. memcpy(&cpu64, begin, left);
  9238. begin += left;
  9239. }
  9240. if (isLittleEndian != sys::IsLittleEndianHost)
  9241. swapStruct(cpu64);
  9242. Print_arm_thread_state64_t(cpu64);
  9243. } else {
  9244. outs() << " flavor " << flavor << " (unknown)\n";
  9245. outs() << " count " << count << "\n";
  9246. outs() << " state (unknown)\n";
  9247. begin += count * sizeof(uint32_t);
  9248. }
  9249. }
  9250. } else {
  9251. while (begin < end) {
  9252. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9253. memcpy((char *)&flavor, begin, sizeof(uint32_t));
  9254. begin += sizeof(uint32_t);
  9255. } else {
  9256. flavor = 0;
  9257. begin = end;
  9258. }
  9259. if (isLittleEndian != sys::IsLittleEndianHost)
  9260. sys::swapByteOrder(flavor);
  9261. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9262. memcpy((char *)&count, begin, sizeof(uint32_t));
  9263. begin += sizeof(uint32_t);
  9264. } else {
  9265. count = 0;
  9266. begin = end;
  9267. }
  9268. if (isLittleEndian != sys::IsLittleEndianHost)
  9269. sys::swapByteOrder(count);
  9270. outs() << " flavor " << flavor << "\n";
  9271. outs() << " count " << count << "\n";
  9272. outs() << " state (Unknown cputype/cpusubtype)\n";
  9273. begin += count * sizeof(uint32_t);
  9274. }
  9275. }
  9276. }
  9277. static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
  9278. if (dl.cmd == MachO::LC_ID_DYLIB)
  9279. outs() << " cmd LC_ID_DYLIB\n";
  9280. else if (dl.cmd == MachO::LC_LOAD_DYLIB)
  9281. outs() << " cmd LC_LOAD_DYLIB\n";
  9282. else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
  9283. outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
  9284. else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
  9285. outs() << " cmd LC_REEXPORT_DYLIB\n";
  9286. else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
  9287. outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
  9288. else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
  9289. outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
  9290. else
  9291. outs() << " cmd " << dl.cmd << " (unknown)\n";
  9292. outs() << " cmdsize " << dl.cmdsize;
  9293. if (dl.cmdsize < sizeof(struct MachO::dylib_command))
  9294. outs() << " Incorrect size\n";
  9295. else
  9296. outs() << "\n";
  9297. if (dl.dylib.name < dl.cmdsize) {
  9298. const char *P = (const char *)(Ptr) + dl.dylib.name;
  9299. outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
  9300. } else {
  9301. outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
  9302. }
  9303. outs() << " time stamp " << dl.dylib.timestamp << " ";
  9304. time_t t = dl.dylib.timestamp;
  9305. outs() << ctime(&t);
  9306. outs() << " current version ";
  9307. if (dl.dylib.current_version == 0xffffffff)
  9308. outs() << "n/a\n";
  9309. else
  9310. outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
  9311. << ((dl.dylib.current_version >> 8) & 0xff) << "."
  9312. << (dl.dylib.current_version & 0xff) << "\n";
  9313. outs() << "compatibility version ";
  9314. if (dl.dylib.compatibility_version == 0xffffffff)
  9315. outs() << "n/a\n";
  9316. else
  9317. outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
  9318. << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
  9319. << (dl.dylib.compatibility_version & 0xff) << "\n";
  9320. }
  9321. static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
  9322. uint32_t object_size) {
  9323. if (ld.cmd == MachO::LC_CODE_SIGNATURE)
  9324. outs() << " cmd LC_CODE_SIGNATURE\n";
  9325. else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
  9326. outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
  9327. else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
  9328. outs() << " cmd LC_FUNCTION_STARTS\n";
  9329. else if (ld.cmd == MachO::LC_DATA_IN_CODE)
  9330. outs() << " cmd LC_DATA_IN_CODE\n";
  9331. else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
  9332. outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
  9333. else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
  9334. outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
  9335. else if (ld.cmd == MachO::LC_DYLD_EXPORTS_TRIE)
  9336. outs() << " cmd LC_DYLD_EXPORTS_TRIE\n";
  9337. else if (ld.cmd == MachO::LC_DYLD_CHAINED_FIXUPS)
  9338. outs() << " cmd LC_DYLD_CHAINED_FIXUPS\n";
  9339. else
  9340. outs() << " cmd " << ld.cmd << " (?)\n";
  9341. outs() << " cmdsize " << ld.cmdsize;
  9342. if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
  9343. outs() << " Incorrect size\n";
  9344. else
  9345. outs() << "\n";
  9346. outs() << " dataoff " << ld.dataoff;
  9347. if (ld.dataoff > object_size)
  9348. outs() << " (past end of file)\n";
  9349. else
  9350. outs() << "\n";
  9351. outs() << " datasize " << ld.datasize;
  9352. uint64_t big_size = ld.dataoff;
  9353. big_size += ld.datasize;
  9354. if (big_size > object_size)
  9355. outs() << " (past end of file)\n";
  9356. else
  9357. outs() << "\n";
  9358. }
  9359. static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
  9360. uint32_t cputype, bool verbose) {
  9361. StringRef Buf = Obj->getData();
  9362. unsigned Index = 0;
  9363. for (const auto &Command : Obj->load_commands()) {
  9364. outs() << "Load command " << Index++ << "\n";
  9365. if (Command.C.cmd == MachO::LC_SEGMENT) {
  9366. MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
  9367. const char *sg_segname = SLC.segname;
  9368. PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
  9369. SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
  9370. SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
  9371. verbose);
  9372. for (unsigned j = 0; j < SLC.nsects; j++) {
  9373. MachO::section S = Obj->getSection(Command, j);
  9374. PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
  9375. S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
  9376. SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
  9377. }
  9378. } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
  9379. MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
  9380. const char *sg_segname = SLC_64.segname;
  9381. PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
  9382. SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
  9383. SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
  9384. SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
  9385. for (unsigned j = 0; j < SLC_64.nsects; j++) {
  9386. MachO::section_64 S_64 = Obj->getSection64(Command, j);
  9387. PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
  9388. S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
  9389. S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
  9390. sg_segname, filetype, Buf.size(), verbose);
  9391. }
  9392. } else if (Command.C.cmd == MachO::LC_SYMTAB) {
  9393. MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
  9394. PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
  9395. } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
  9396. MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
  9397. MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
  9398. PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
  9399. Obj->is64Bit());
  9400. } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
  9401. Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
  9402. MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
  9403. PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
  9404. } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
  9405. Command.C.cmd == MachO::LC_ID_DYLINKER ||
  9406. Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
  9407. MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
  9408. PrintDyldLoadCommand(Dyld, Command.Ptr);
  9409. } else if (Command.C.cmd == MachO::LC_UUID) {
  9410. MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
  9411. PrintUuidLoadCommand(Uuid);
  9412. } else if (Command.C.cmd == MachO::LC_RPATH) {
  9413. MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
  9414. PrintRpathLoadCommand(Rpath, Command.Ptr);
  9415. } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
  9416. Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
  9417. Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
  9418. Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
  9419. MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
  9420. PrintVersionMinLoadCommand(Vd);
  9421. } else if (Command.C.cmd == MachO::LC_NOTE) {
  9422. MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
  9423. PrintNoteLoadCommand(Nt);
  9424. } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
  9425. MachO::build_version_command Bv =
  9426. Obj->getBuildVersionLoadCommand(Command);
  9427. PrintBuildVersionLoadCommand(Obj, Bv);
  9428. } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
  9429. MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
  9430. PrintSourceVersionCommand(Sd);
  9431. } else if (Command.C.cmd == MachO::LC_MAIN) {
  9432. MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
  9433. PrintEntryPointCommand(Ep);
  9434. } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
  9435. MachO::encryption_info_command Ei =
  9436. Obj->getEncryptionInfoCommand(Command);
  9437. PrintEncryptionInfoCommand(Ei, Buf.size());
  9438. } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
  9439. MachO::encryption_info_command_64 Ei =
  9440. Obj->getEncryptionInfoCommand64(Command);
  9441. PrintEncryptionInfoCommand64(Ei, Buf.size());
  9442. } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
  9443. MachO::linker_option_command Lo =
  9444. Obj->getLinkerOptionLoadCommand(Command);
  9445. PrintLinkerOptionCommand(Lo, Command.Ptr);
  9446. } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
  9447. MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
  9448. PrintSubFrameworkCommand(Sf, Command.Ptr);
  9449. } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
  9450. MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
  9451. PrintSubUmbrellaCommand(Sf, Command.Ptr);
  9452. } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
  9453. MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
  9454. PrintSubLibraryCommand(Sl, Command.Ptr);
  9455. } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
  9456. MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
  9457. PrintSubClientCommand(Sc, Command.Ptr);
  9458. } else if (Command.C.cmd == MachO::LC_ROUTINES) {
  9459. MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
  9460. PrintRoutinesCommand(Rc);
  9461. } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
  9462. MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
  9463. PrintRoutinesCommand64(Rc);
  9464. } else if (Command.C.cmd == MachO::LC_THREAD ||
  9465. Command.C.cmd == MachO::LC_UNIXTHREAD) {
  9466. MachO::thread_command Tc = Obj->getThreadCommand(Command);
  9467. PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
  9468. } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
  9469. Command.C.cmd == MachO::LC_ID_DYLIB ||
  9470. Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
  9471. Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
  9472. Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
  9473. Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
  9474. MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
  9475. PrintDylibCommand(Dl, Command.Ptr);
  9476. } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
  9477. Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
  9478. Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
  9479. Command.C.cmd == MachO::LC_DATA_IN_CODE ||
  9480. Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
  9481. Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT ||
  9482. Command.C.cmd == MachO::LC_DYLD_EXPORTS_TRIE ||
  9483. Command.C.cmd == MachO::LC_DYLD_CHAINED_FIXUPS) {
  9484. MachO::linkedit_data_command Ld =
  9485. Obj->getLinkeditDataLoadCommand(Command);
  9486. PrintLinkEditDataCommand(Ld, Buf.size());
  9487. } else {
  9488. outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
  9489. << ")\n";
  9490. outs() << " cmdsize " << Command.C.cmdsize << "\n";
  9491. // TODO: get and print the raw bytes of the load command.
  9492. }
  9493. // TODO: print all the other kinds of load commands.
  9494. }
  9495. }
  9496. static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
  9497. if (Obj->is64Bit()) {
  9498. MachO::mach_header_64 H_64;
  9499. H_64 = Obj->getHeader64();
  9500. PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
  9501. H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
  9502. } else {
  9503. MachO::mach_header H;
  9504. H = Obj->getHeader();
  9505. PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
  9506. H.sizeofcmds, H.flags, verbose);
  9507. }
  9508. }
  9509. void objdump::printMachOFileHeader(const object::ObjectFile *Obj) {
  9510. const MachOObjectFile *file = cast<const MachOObjectFile>(Obj);
  9511. PrintMachHeader(file, Verbose);
  9512. }
  9513. void objdump::printMachOLoadCommands(const object::ObjectFile *Obj) {
  9514. const MachOObjectFile *file = cast<const MachOObjectFile>(Obj);
  9515. uint32_t filetype = 0;
  9516. uint32_t cputype = 0;
  9517. if (file->is64Bit()) {
  9518. MachO::mach_header_64 H_64;
  9519. H_64 = file->getHeader64();
  9520. filetype = H_64.filetype;
  9521. cputype = H_64.cputype;
  9522. } else {
  9523. MachO::mach_header H;
  9524. H = file->getHeader();
  9525. filetype = H.filetype;
  9526. cputype = H.cputype;
  9527. }
  9528. PrintLoadCommands(file, filetype, cputype, Verbose);
  9529. }
  9530. //===----------------------------------------------------------------------===//
  9531. // export trie dumping
  9532. //===----------------------------------------------------------------------===//
  9533. static void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
  9534. uint64_t BaseSegmentAddress = 0;
  9535. for (const auto &Command : Obj->load_commands()) {
  9536. if (Command.C.cmd == MachO::LC_SEGMENT) {
  9537. MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
  9538. if (Seg.fileoff == 0 && Seg.filesize != 0) {
  9539. BaseSegmentAddress = Seg.vmaddr;
  9540. break;
  9541. }
  9542. } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
  9543. MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
  9544. if (Seg.fileoff == 0 && Seg.filesize != 0) {
  9545. BaseSegmentAddress = Seg.vmaddr;
  9546. break;
  9547. }
  9548. }
  9549. }
  9550. Error Err = Error::success();
  9551. for (const object::ExportEntry &Entry : Obj->exports(Err)) {
  9552. uint64_t Flags = Entry.flags();
  9553. bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
  9554. bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
  9555. bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
  9556. MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
  9557. bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
  9558. MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
  9559. bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
  9560. if (ReExport)
  9561. outs() << "[re-export] ";
  9562. else
  9563. outs() << format("0x%08llX ",
  9564. Entry.address() + BaseSegmentAddress);
  9565. outs() << Entry.name();
  9566. if (WeakDef || ThreadLocal || Resolver || Abs) {
  9567. ListSeparator LS;
  9568. outs() << " [";
  9569. if (WeakDef)
  9570. outs() << LS << "weak_def";
  9571. if (ThreadLocal)
  9572. outs() << LS << "per-thread";
  9573. if (Abs)
  9574. outs() << LS << "absolute";
  9575. if (Resolver)
  9576. outs() << LS << format("resolver=0x%08llX", Entry.other());
  9577. outs() << "]";
  9578. }
  9579. if (ReExport) {
  9580. StringRef DylibName = "unknown";
  9581. int Ordinal = Entry.other() - 1;
  9582. Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
  9583. if (Entry.otherName().empty())
  9584. outs() << " (from " << DylibName << ")";
  9585. else
  9586. outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
  9587. }
  9588. outs() << "\n";
  9589. }
  9590. if (Err)
  9591. reportError(std::move(Err), Obj->getFileName());
  9592. }
  9593. //===----------------------------------------------------------------------===//
  9594. // rebase table dumping
  9595. //===----------------------------------------------------------------------===//
  9596. static void printMachORebaseTable(object::MachOObjectFile *Obj) {
  9597. outs() << "segment section address type\n";
  9598. Error Err = Error::success();
  9599. for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
  9600. StringRef SegmentName = Entry.segmentName();
  9601. StringRef SectionName = Entry.sectionName();
  9602. uint64_t Address = Entry.address();
  9603. // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
  9604. outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
  9605. SegmentName.str().c_str(), SectionName.str().c_str(),
  9606. Address, Entry.typeName().str().c_str());
  9607. }
  9608. if (Err)
  9609. reportError(std::move(Err), Obj->getFileName());
  9610. }
  9611. static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
  9612. StringRef DylibName;
  9613. switch (Ordinal) {
  9614. case MachO::BIND_SPECIAL_DYLIB_SELF:
  9615. return "this-image";
  9616. case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
  9617. return "main-executable";
  9618. case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
  9619. return "flat-namespace";
  9620. default:
  9621. if (Ordinal > 0) {
  9622. std::error_code EC =
  9623. Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
  9624. if (EC)
  9625. return "<<bad library ordinal>>";
  9626. return DylibName;
  9627. }
  9628. }
  9629. return "<<unknown special ordinal>>";
  9630. }
  9631. //===----------------------------------------------------------------------===//
  9632. // bind table dumping
  9633. //===----------------------------------------------------------------------===//
  9634. static void printMachOBindTable(object::MachOObjectFile *Obj) {
  9635. // Build table of sections so names can used in final output.
  9636. outs() << "segment section address type "
  9637. "addend dylib symbol\n";
  9638. Error Err = Error::success();
  9639. for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
  9640. StringRef SegmentName = Entry.segmentName();
  9641. StringRef SectionName = Entry.sectionName();
  9642. uint64_t Address = Entry.address();
  9643. // Table lines look like:
  9644. // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
  9645. StringRef Attr;
  9646. if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
  9647. Attr = " (weak_import)";
  9648. outs() << left_justify(SegmentName, 8) << " "
  9649. << left_justify(SectionName, 18) << " "
  9650. << format_hex(Address, 10, true) << " "
  9651. << left_justify(Entry.typeName(), 8) << " "
  9652. << format_decimal(Entry.addend(), 8) << " "
  9653. << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
  9654. << Entry.symbolName() << Attr << "\n";
  9655. }
  9656. if (Err)
  9657. reportError(std::move(Err), Obj->getFileName());
  9658. }
  9659. //===----------------------------------------------------------------------===//
  9660. // lazy bind table dumping
  9661. //===----------------------------------------------------------------------===//
  9662. static void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
  9663. outs() << "segment section address "
  9664. "dylib symbol\n";
  9665. Error Err = Error::success();
  9666. for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
  9667. StringRef SegmentName = Entry.segmentName();
  9668. StringRef SectionName = Entry.sectionName();
  9669. uint64_t Address = Entry.address();
  9670. // Table lines look like:
  9671. // __DATA __got 0x00012010 libSystem ___stack_chk_guard
  9672. outs() << left_justify(SegmentName, 8) << " "
  9673. << left_justify(SectionName, 18) << " "
  9674. << format_hex(Address, 10, true) << " "
  9675. << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
  9676. << Entry.symbolName() << "\n";
  9677. }
  9678. if (Err)
  9679. reportError(std::move(Err), Obj->getFileName());
  9680. }
  9681. //===----------------------------------------------------------------------===//
  9682. // weak bind table dumping
  9683. //===----------------------------------------------------------------------===//
  9684. static void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
  9685. outs() << "segment section address "
  9686. "type addend symbol\n";
  9687. Error Err = Error::success();
  9688. for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
  9689. // Strong symbols don't have a location to update.
  9690. if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
  9691. outs() << " strong "
  9692. << Entry.symbolName() << "\n";
  9693. continue;
  9694. }
  9695. StringRef SegmentName = Entry.segmentName();
  9696. StringRef SectionName = Entry.sectionName();
  9697. uint64_t Address = Entry.address();
  9698. // Table lines look like:
  9699. // __DATA __data 0x00001000 pointer 0 _foo
  9700. outs() << left_justify(SegmentName, 8) << " "
  9701. << left_justify(SectionName, 18) << " "
  9702. << format_hex(Address, 10, true) << " "
  9703. << left_justify(Entry.typeName(), 8) << " "
  9704. << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
  9705. << "\n";
  9706. }
  9707. if (Err)
  9708. reportError(std::move(Err), Obj->getFileName());
  9709. }
  9710. // get_dyld_bind_info_symbolname() is used for disassembly and passed an
  9711. // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
  9712. // information for that address. If the address is found its binding symbol
  9713. // name is returned. If not nullptr is returned.
  9714. static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
  9715. struct DisassembleInfo *info) {
  9716. if (info->bindtable == nullptr) {
  9717. info->bindtable = std::make_unique<SymbolAddressMap>();
  9718. Error Err = Error::success();
  9719. for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
  9720. uint64_t Address = Entry.address();
  9721. StringRef name = Entry.symbolName();
  9722. if (!name.empty())
  9723. (*info->bindtable)[Address] = name;
  9724. }
  9725. if (Err)
  9726. reportError(std::move(Err), info->O->getFileName());
  9727. }
  9728. auto name = info->bindtable->lookup(ReferenceValue);
  9729. return !name.empty() ? name.data() : nullptr;
  9730. }
  9731. void objdump::printLazyBindTable(ObjectFile *o) {
  9732. outs() << "\nLazy bind table:\n";
  9733. if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  9734. printMachOLazyBindTable(MachO);
  9735. else
  9736. WithColor::error()
  9737. << "This operation is only currently supported "
  9738. "for Mach-O executable files.\n";
  9739. }
  9740. void objdump::printWeakBindTable(ObjectFile *o) {
  9741. outs() << "\nWeak bind table:\n";
  9742. if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  9743. printMachOWeakBindTable(MachO);
  9744. else
  9745. WithColor::error()
  9746. << "This operation is only currently supported "
  9747. "for Mach-O executable files.\n";
  9748. }
  9749. void objdump::printExportsTrie(const ObjectFile *o) {
  9750. outs() << "\nExports trie:\n";
  9751. if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  9752. printMachOExportsTrie(MachO);
  9753. else
  9754. WithColor::error()
  9755. << "This operation is only currently supported "
  9756. "for Mach-O executable files.\n";
  9757. }
  9758. void objdump::printRebaseTable(ObjectFile *o) {
  9759. outs() << "\nRebase table:\n";
  9760. if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  9761. printMachORebaseTable(MachO);
  9762. else
  9763. WithColor::error()
  9764. << "This operation is only currently supported "
  9765. "for Mach-O executable files.\n";
  9766. }
  9767. void objdump::printBindTable(ObjectFile *o) {
  9768. outs() << "\nBind table:\n";
  9769. if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  9770. printMachOBindTable(MachO);
  9771. else
  9772. WithColor::error()
  9773. << "This operation is only currently supported "
  9774. "for Mach-O executable files.\n";
  9775. }