MachODump.cpp 382 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536
  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 "llvm-objdump.h"
  14. #include "llvm-c/Disassembler.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/ADT/Triple.h"
  18. #include "llvm/BinaryFormat/MachO.h"
  19. #include "llvm/Config/config.h"
  20. #include "llvm/DebugInfo/DIContext.h"
  21. #include "llvm/DebugInfo/DWARF/DWARFContext.h"
  22. #include "llvm/Demangle/Demangle.h"
  23. #include "llvm/MC/MCAsmInfo.h"
  24. #include "llvm/MC/MCContext.h"
  25. #include "llvm/MC/MCDisassembler/MCDisassembler.h"
  26. #include "llvm/MC/MCInst.h"
  27. #include "llvm/MC/MCInstPrinter.h"
  28. #include "llvm/MC/MCInstrDesc.h"
  29. #include "llvm/MC/MCInstrInfo.h"
  30. #include "llvm/MC/MCRegisterInfo.h"
  31. #include "llvm/MC/MCSubtargetInfo.h"
  32. #include "llvm/MC/MCTargetOptions.h"
  33. #include "llvm/Object/MachO.h"
  34. #include "llvm/Object/MachOUniversal.h"
  35. #include "llvm/Support/Casting.h"
  36. #include "llvm/Support/CommandLine.h"
  37. #include "llvm/Support/Debug.h"
  38. #include "llvm/Support/Endian.h"
  39. #include "llvm/Support/Format.h"
  40. #include "llvm/Support/FormattedStream.h"
  41. #include "llvm/Support/GraphWriter.h"
  42. #include "llvm/Support/LEB128.h"
  43. #include "llvm/Support/MemoryBuffer.h"
  44. #include "llvm/Support/TargetRegistry.h"
  45. #include "llvm/Support/TargetSelect.h"
  46. #include "llvm/Support/ToolOutputFile.h"
  47. #include "llvm/Support/WithColor.h"
  48. #include "llvm/Support/raw_ostream.h"
  49. #include <algorithm>
  50. #include <cstring>
  51. #include <system_error>
  52. #ifdef HAVE_LIBXAR
  53. extern "C" {
  54. #error #include <xar/xar.h>
  55. }
  56. #endif
  57. using namespace llvm;
  58. using namespace llvm::object;
  59. using namespace llvm::objdump;
  60. cl::OptionCategory objdump::MachOCat("llvm-objdump MachO Specific Options");
  61. cl::opt<bool> objdump::FirstPrivateHeader(
  62. "private-header",
  63. cl::desc("Display only the first format specific file header"),
  64. cl::cat(MachOCat));
  65. cl::opt<bool> objdump::ExportsTrie("exports-trie",
  66. cl::desc("Display mach-o exported symbols"),
  67. cl::cat(MachOCat));
  68. cl::opt<bool> objdump::Rebase("rebase",
  69. cl::desc("Display mach-o rebasing info"),
  70. cl::cat(MachOCat));
  71. cl::opt<bool> objdump::Bind("bind", cl::desc("Display mach-o binding info"),
  72. cl::cat(MachOCat));
  73. cl::opt<bool> objdump::LazyBind("lazy-bind",
  74. cl::desc("Display mach-o lazy binding info"),
  75. cl::cat(MachOCat));
  76. cl::opt<bool> objdump::WeakBind("weak-bind",
  77. cl::desc("Display mach-o weak binding info"),
  78. cl::cat(MachOCat));
  79. static cl::opt<bool>
  80. UseDbg("g", cl::Grouping,
  81. cl::desc("Print line information from debug info if available"),
  82. cl::cat(MachOCat));
  83. static cl::opt<std::string> DSYMFile("dsym",
  84. cl::desc("Use .dSYM file for debug info"),
  85. cl::cat(MachOCat));
  86. static cl::opt<bool> FullLeadingAddr("full-leading-addr",
  87. cl::desc("Print full leading address"),
  88. cl::cat(MachOCat));
  89. static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
  90. cl::desc("Print no leading headers"),
  91. cl::cat(MachOCat));
  92. cl::opt<bool> objdump::UniversalHeaders(
  93. "universal-headers",
  94. cl::desc("Print Mach-O universal headers (requires --macho)"),
  95. cl::cat(MachOCat));
  96. static cl::opt<bool> ArchiveMemberOffsets(
  97. "archive-member-offsets",
  98. cl::desc("Print the offset to each archive member for Mach-O archives "
  99. "(requires --macho and --archive-headers)"),
  100. cl::cat(MachOCat));
  101. cl::opt<bool> objdump::IndirectSymbols(
  102. "indirect-symbols",
  103. cl::desc(
  104. "Print indirect symbol table for Mach-O objects (requires --macho)"),
  105. cl::cat(MachOCat));
  106. cl::opt<bool> objdump::DataInCode(
  107. "data-in-code",
  108. cl::desc(
  109. "Print the data in code table for Mach-O objects (requires --macho)"),
  110. cl::cat(MachOCat));
  111. cl::opt<bool>
  112. objdump::LinkOptHints("link-opt-hints",
  113. cl::desc("Print the linker optimization hints for "
  114. "Mach-O objects (requires --macho)"),
  115. cl::cat(MachOCat));
  116. cl::opt<bool>
  117. objdump::InfoPlist("info-plist",
  118. cl::desc("Print the info plist section as strings for "
  119. "Mach-O objects (requires --macho)"),
  120. cl::cat(MachOCat));
  121. cl::opt<bool>
  122. objdump::DylibsUsed("dylibs-used",
  123. cl::desc("Print the shared libraries used for linked "
  124. "Mach-O files (requires --macho)"),
  125. cl::cat(MachOCat));
  126. cl::opt<bool> objdump::DylibId("dylib-id",
  127. cl::desc("Print the shared library's id for the "
  128. "dylib Mach-O file (requires --macho)"),
  129. cl::cat(MachOCat));
  130. static cl::opt<bool>
  131. NonVerbose("non-verbose",
  132. cl::desc("Print the info for Mach-O objects in non-verbose or "
  133. "numeric form (requires --macho)"),
  134. cl::cat(MachOCat));
  135. cl::opt<bool>
  136. objdump::ObjcMetaData("objc-meta-data",
  137. cl::desc("Print the Objective-C runtime meta data "
  138. "for Mach-O files (requires --macho)"),
  139. cl::cat(MachOCat));
  140. static cl::opt<std::string> DisSymName(
  141. "dis-symname",
  142. cl::desc("disassemble just this symbol's instructions (requires --macho)"),
  143. cl::cat(MachOCat));
  144. static cl::opt<bool> NoSymbolicOperands(
  145. "no-symbolic-operands",
  146. cl::desc("do not symbolic operands when disassembling (requires --macho)"),
  147. cl::cat(MachOCat));
  148. static cl::list<std::string>
  149. ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
  150. cl::ZeroOrMore, cl::cat(MachOCat));
  151. static bool ArchAll = false;
  152. static std::string ThumbTripleName;
  153. static const Target *GetTarget(const MachOObjectFile *MachOObj,
  154. const char **McpuDefault,
  155. const Target **ThumbTarget) {
  156. // Figure out the target triple.
  157. Triple TT(TripleName);
  158. if (TripleName.empty()) {
  159. TT = MachOObj->getArchTriple(McpuDefault);
  160. TripleName = TT.str();
  161. }
  162. if (TT.getArch() == Triple::arm) {
  163. // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
  164. // that support ARM are also capable of Thumb mode.
  165. Triple ThumbTriple = TT;
  166. std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
  167. ThumbTriple.setArchName(ThumbName);
  168. ThumbTripleName = ThumbTriple.str();
  169. }
  170. // Get the target specific parser.
  171. std::string Error;
  172. const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
  173. if (TheTarget && ThumbTripleName.empty())
  174. return TheTarget;
  175. *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
  176. if (*ThumbTarget)
  177. return TheTarget;
  178. WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
  179. if (!TheTarget)
  180. errs() << TripleName;
  181. else
  182. errs() << ThumbTripleName;
  183. errs() << "', see --version and --triple.\n";
  184. return nullptr;
  185. }
  186. namespace {
  187. struct SymbolSorter {
  188. bool operator()(const SymbolRef &A, const SymbolRef &B) {
  189. Expected<SymbolRef::Type> ATypeOrErr = A.getType();
  190. if (!ATypeOrErr)
  191. reportError(ATypeOrErr.takeError(), A.getObject()->getFileName());
  192. SymbolRef::Type AType = *ATypeOrErr;
  193. Expected<SymbolRef::Type> BTypeOrErr = B.getType();
  194. if (!BTypeOrErr)
  195. reportError(BTypeOrErr.takeError(), B.getObject()->getFileName());
  196. SymbolRef::Type BType = *BTypeOrErr;
  197. uint64_t AAddr =
  198. (AType != SymbolRef::ST_Function) ? 0 : cantFail(A.getValue());
  199. uint64_t BAddr =
  200. (BType != SymbolRef::ST_Function) ? 0 : cantFail(B.getValue());
  201. return AAddr < BAddr;
  202. }
  203. };
  204. } // namespace
  205. // Types for the storted data in code table that is built before disassembly
  206. // and the predicate function to sort them.
  207. typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
  208. typedef std::vector<DiceTableEntry> DiceTable;
  209. typedef DiceTable::iterator dice_table_iterator;
  210. #ifdef HAVE_LIBXAR
  211. namespace {
  212. struct ScopedXarFile {
  213. xar_t xar;
  214. ScopedXarFile(const char *filename, int32_t flags)
  215. : xar(xar_open(filename, flags)) {}
  216. ~ScopedXarFile() {
  217. if (xar)
  218. xar_close(xar);
  219. }
  220. ScopedXarFile(const ScopedXarFile &) = delete;
  221. ScopedXarFile &operator=(const ScopedXarFile &) = delete;
  222. operator xar_t() { return xar; }
  223. };
  224. struct ScopedXarIter {
  225. xar_iter_t iter;
  226. ScopedXarIter() : iter(xar_iter_new()) {}
  227. ~ScopedXarIter() {
  228. if (iter)
  229. xar_iter_free(iter);
  230. }
  231. ScopedXarIter(const ScopedXarIter &) = delete;
  232. ScopedXarIter &operator=(const ScopedXarIter &) = delete;
  233. operator xar_iter_t() { return iter; }
  234. };
  235. } // namespace
  236. #endif // defined(HAVE_LIBXAR)
  237. // This is used to search for a data in code table entry for the PC being
  238. // disassembled. The j parameter has the PC in j.first. A single data in code
  239. // table entry can cover many bytes for each of its Kind's. So if the offset,
  240. // aka the i.first value, of the data in code table entry plus its Length
  241. // covers the PC being searched for this will return true. If not it will
  242. // return false.
  243. static bool compareDiceTableEntries(const DiceTableEntry &i,
  244. const DiceTableEntry &j) {
  245. uint16_t Length;
  246. i.second.getLength(Length);
  247. return j.first >= i.first && j.first < i.first + Length;
  248. }
  249. static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
  250. unsigned short Kind) {
  251. uint32_t Value, Size = 1;
  252. switch (Kind) {
  253. default:
  254. case MachO::DICE_KIND_DATA:
  255. if (Length >= 4) {
  256. if (!NoShowRawInsn)
  257. dumpBytes(makeArrayRef(bytes, 4), outs());
  258. Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
  259. outs() << "\t.long " << Value;
  260. Size = 4;
  261. } else if (Length >= 2) {
  262. if (!NoShowRawInsn)
  263. dumpBytes(makeArrayRef(bytes, 2), outs());
  264. Value = bytes[1] << 8 | bytes[0];
  265. outs() << "\t.short " << Value;
  266. Size = 2;
  267. } else {
  268. if (!NoShowRawInsn)
  269. dumpBytes(makeArrayRef(bytes, 2), outs());
  270. Value = bytes[0];
  271. outs() << "\t.byte " << Value;
  272. Size = 1;
  273. }
  274. if (Kind == MachO::DICE_KIND_DATA)
  275. outs() << "\t@ KIND_DATA\n";
  276. else
  277. outs() << "\t@ data in code kind = " << Kind << "\n";
  278. break;
  279. case MachO::DICE_KIND_JUMP_TABLE8:
  280. if (!NoShowRawInsn)
  281. dumpBytes(makeArrayRef(bytes, 1), outs());
  282. Value = bytes[0];
  283. outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
  284. Size = 1;
  285. break;
  286. case MachO::DICE_KIND_JUMP_TABLE16:
  287. if (!NoShowRawInsn)
  288. dumpBytes(makeArrayRef(bytes, 2), outs());
  289. Value = bytes[1] << 8 | bytes[0];
  290. outs() << "\t.short " << format("%5u", Value & 0xffff)
  291. << "\t@ KIND_JUMP_TABLE16\n";
  292. Size = 2;
  293. break;
  294. case MachO::DICE_KIND_JUMP_TABLE32:
  295. case MachO::DICE_KIND_ABS_JUMP_TABLE32:
  296. if (!NoShowRawInsn)
  297. dumpBytes(makeArrayRef(bytes, 4), outs());
  298. Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
  299. outs() << "\t.long " << Value;
  300. if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
  301. outs() << "\t@ KIND_JUMP_TABLE32\n";
  302. else
  303. outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
  304. Size = 4;
  305. break;
  306. }
  307. return Size;
  308. }
  309. static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
  310. std::vector<SectionRef> &Sections,
  311. std::vector<SymbolRef> &Symbols,
  312. SmallVectorImpl<uint64_t> &FoundFns,
  313. uint64_t &BaseSegmentAddress) {
  314. const StringRef FileName = MachOObj->getFileName();
  315. for (const SymbolRef &Symbol : MachOObj->symbols()) {
  316. StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
  317. if (!SymName.startswith("ltmp"))
  318. Symbols.push_back(Symbol);
  319. }
  320. for (const SectionRef &Section : MachOObj->sections())
  321. Sections.push_back(Section);
  322. bool BaseSegmentAddressSet = false;
  323. for (const auto &Command : MachOObj->load_commands()) {
  324. if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
  325. // We found a function starts segment, parse the addresses for later
  326. // consumption.
  327. MachO::linkedit_data_command LLC =
  328. MachOObj->getLinkeditDataLoadCommand(Command);
  329. MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
  330. } else if (Command.C.cmd == MachO::LC_SEGMENT) {
  331. MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
  332. StringRef SegName = SLC.segname;
  333. if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
  334. BaseSegmentAddressSet = true;
  335. BaseSegmentAddress = SLC.vmaddr;
  336. }
  337. } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
  338. MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(Command);
  339. StringRef SegName = SLC.segname;
  340. if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
  341. BaseSegmentAddressSet = true;
  342. BaseSegmentAddress = SLC.vmaddr;
  343. }
  344. }
  345. }
  346. }
  347. static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes,
  348. DiceTable &Dices, uint64_t &InstSize) {
  349. // Check the data in code table here to see if this is data not an
  350. // instruction to be disassembled.
  351. DiceTable Dice;
  352. Dice.push_back(std::make_pair(PC, DiceRef()));
  353. dice_table_iterator DTI =
  354. std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
  355. compareDiceTableEntries);
  356. if (DTI != Dices.end()) {
  357. uint16_t Length;
  358. DTI->second.getLength(Length);
  359. uint16_t Kind;
  360. DTI->second.getKind(Kind);
  361. InstSize = DumpDataInCode(bytes, Length, Kind);
  362. if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
  363. (PC == (DTI->first + Length - 1)) && (Length & 1))
  364. InstSize++;
  365. return true;
  366. }
  367. return false;
  368. }
  369. static void printRelocationTargetName(const MachOObjectFile *O,
  370. const MachO::any_relocation_info &RE,
  371. raw_string_ostream &Fmt) {
  372. // Target of a scattered relocation is an address. In the interest of
  373. // generating pretty output, scan through the symbol table looking for a
  374. // symbol that aligns with that address. If we find one, print it.
  375. // Otherwise, we just print the hex address of the target.
  376. const StringRef FileName = O->getFileName();
  377. if (O->isRelocationScattered(RE)) {
  378. uint32_t Val = O->getPlainRelocationSymbolNum(RE);
  379. for (const SymbolRef &Symbol : O->symbols()) {
  380. uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
  381. if (Addr != Val)
  382. continue;
  383. Fmt << unwrapOrError(Symbol.getName(), FileName);
  384. return;
  385. }
  386. // If we couldn't find a symbol that this relocation refers to, try
  387. // to find a section beginning instead.
  388. for (const SectionRef &Section : ToolSectionFilter(*O)) {
  389. uint64_t Addr = Section.getAddress();
  390. if (Addr != Val)
  391. continue;
  392. StringRef NameOrErr = unwrapOrError(Section.getName(), O->getFileName());
  393. Fmt << NameOrErr;
  394. return;
  395. }
  396. Fmt << format("0x%x", Val);
  397. return;
  398. }
  399. StringRef S;
  400. bool isExtern = O->getPlainRelocationExternal(RE);
  401. uint64_t Val = O->getPlainRelocationSymbolNum(RE);
  402. if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND &&
  403. (O->getArch() == Triple::aarch64 || O->getArch() == Triple::aarch64_be)) {
  404. Fmt << format("0x%0" PRIx64, Val);
  405. return;
  406. }
  407. if (isExtern) {
  408. symbol_iterator SI = O->symbol_begin();
  409. advance(SI, Val);
  410. S = unwrapOrError(SI->getName(), FileName);
  411. } else {
  412. section_iterator SI = O->section_begin();
  413. // Adjust for the fact that sections are 1-indexed.
  414. if (Val == 0) {
  415. Fmt << "0 (?,?)";
  416. return;
  417. }
  418. uint32_t I = Val - 1;
  419. while (I != 0 && SI != O->section_end()) {
  420. --I;
  421. advance(SI, 1);
  422. }
  423. if (SI == O->section_end()) {
  424. Fmt << Val << " (?,?)";
  425. } else {
  426. if (Expected<StringRef> NameOrErr = SI->getName())
  427. S = *NameOrErr;
  428. else
  429. consumeError(NameOrErr.takeError());
  430. }
  431. }
  432. Fmt << S;
  433. }
  434. Error objdump::getMachORelocationValueString(const MachOObjectFile *Obj,
  435. const RelocationRef &RelRef,
  436. SmallVectorImpl<char> &Result) {
  437. DataRefImpl Rel = RelRef.getRawDataRefImpl();
  438. MachO::any_relocation_info RE = Obj->getRelocation(Rel);
  439. unsigned Arch = Obj->getArch();
  440. std::string FmtBuf;
  441. raw_string_ostream Fmt(FmtBuf);
  442. unsigned Type = Obj->getAnyRelocationType(RE);
  443. bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
  444. // Determine any addends that should be displayed with the relocation.
  445. // These require decoding the relocation type, which is triple-specific.
  446. // X86_64 has entirely custom relocation types.
  447. if (Arch == Triple::x86_64) {
  448. switch (Type) {
  449. case MachO::X86_64_RELOC_GOT_LOAD:
  450. case MachO::X86_64_RELOC_GOT: {
  451. printRelocationTargetName(Obj, RE, Fmt);
  452. Fmt << "@GOT";
  453. if (IsPCRel)
  454. Fmt << "PCREL";
  455. break;
  456. }
  457. case MachO::X86_64_RELOC_SUBTRACTOR: {
  458. DataRefImpl RelNext = Rel;
  459. Obj->moveRelocationNext(RelNext);
  460. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  461. // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
  462. // X86_64_RELOC_UNSIGNED.
  463. // NOTE: Scattered relocations don't exist on x86_64.
  464. unsigned RType = Obj->getAnyRelocationType(RENext);
  465. if (RType != MachO::X86_64_RELOC_UNSIGNED)
  466. reportError(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
  467. "X86_64_RELOC_SUBTRACTOR.");
  468. // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
  469. // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
  470. printRelocationTargetName(Obj, RENext, Fmt);
  471. Fmt << "-";
  472. printRelocationTargetName(Obj, RE, Fmt);
  473. break;
  474. }
  475. case MachO::X86_64_RELOC_TLV:
  476. printRelocationTargetName(Obj, RE, Fmt);
  477. Fmt << "@TLV";
  478. if (IsPCRel)
  479. Fmt << "P";
  480. break;
  481. case MachO::X86_64_RELOC_SIGNED_1:
  482. printRelocationTargetName(Obj, RE, Fmt);
  483. Fmt << "-1";
  484. break;
  485. case MachO::X86_64_RELOC_SIGNED_2:
  486. printRelocationTargetName(Obj, RE, Fmt);
  487. Fmt << "-2";
  488. break;
  489. case MachO::X86_64_RELOC_SIGNED_4:
  490. printRelocationTargetName(Obj, RE, Fmt);
  491. Fmt << "-4";
  492. break;
  493. default:
  494. printRelocationTargetName(Obj, RE, Fmt);
  495. break;
  496. }
  497. // X86 and ARM share some relocation types in common.
  498. } else if (Arch == Triple::x86 || Arch == Triple::arm ||
  499. Arch == Triple::ppc) {
  500. // Generic relocation types...
  501. switch (Type) {
  502. case MachO::GENERIC_RELOC_PAIR: // prints no info
  503. return Error::success();
  504. case MachO::GENERIC_RELOC_SECTDIFF: {
  505. DataRefImpl RelNext = Rel;
  506. Obj->moveRelocationNext(RelNext);
  507. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  508. // X86 sect diff's must be followed by a relocation of type
  509. // GENERIC_RELOC_PAIR.
  510. unsigned RType = Obj->getAnyRelocationType(RENext);
  511. if (RType != MachO::GENERIC_RELOC_PAIR)
  512. reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
  513. "GENERIC_RELOC_SECTDIFF.");
  514. printRelocationTargetName(Obj, RE, Fmt);
  515. Fmt << "-";
  516. printRelocationTargetName(Obj, RENext, Fmt);
  517. break;
  518. }
  519. }
  520. if (Arch == Triple::x86 || Arch == Triple::ppc) {
  521. switch (Type) {
  522. case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
  523. DataRefImpl RelNext = Rel;
  524. Obj->moveRelocationNext(RelNext);
  525. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  526. // X86 sect diff's must be followed by a relocation of type
  527. // GENERIC_RELOC_PAIR.
  528. unsigned RType = Obj->getAnyRelocationType(RENext);
  529. if (RType != MachO::GENERIC_RELOC_PAIR)
  530. reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
  531. "GENERIC_RELOC_LOCAL_SECTDIFF.");
  532. printRelocationTargetName(Obj, RE, Fmt);
  533. Fmt << "-";
  534. printRelocationTargetName(Obj, RENext, Fmt);
  535. break;
  536. }
  537. case MachO::GENERIC_RELOC_TLV: {
  538. printRelocationTargetName(Obj, RE, Fmt);
  539. Fmt << "@TLV";
  540. if (IsPCRel)
  541. Fmt << "P";
  542. break;
  543. }
  544. default:
  545. printRelocationTargetName(Obj, RE, Fmt);
  546. }
  547. } else { // ARM-specific relocations
  548. switch (Type) {
  549. case MachO::ARM_RELOC_HALF:
  550. case MachO::ARM_RELOC_HALF_SECTDIFF: {
  551. // Half relocations steal a bit from the length field to encode
  552. // whether this is an upper16 or a lower16 relocation.
  553. bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
  554. if (isUpper)
  555. Fmt << ":upper16:(";
  556. else
  557. Fmt << ":lower16:(";
  558. printRelocationTargetName(Obj, RE, Fmt);
  559. DataRefImpl RelNext = Rel;
  560. Obj->moveRelocationNext(RelNext);
  561. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  562. // ARM half relocs must be followed by a relocation of type
  563. // ARM_RELOC_PAIR.
  564. unsigned RType = Obj->getAnyRelocationType(RENext);
  565. if (RType != MachO::ARM_RELOC_PAIR)
  566. reportError(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
  567. "ARM_RELOC_HALF");
  568. // NOTE: The half of the target virtual address is stashed in the
  569. // address field of the secondary relocation, but we can't reverse
  570. // engineer the constant offset from it without decoding the movw/movt
  571. // instruction to find the other half in its immediate field.
  572. // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
  573. // symbol/section pointer of the follow-on relocation.
  574. if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
  575. Fmt << "-";
  576. printRelocationTargetName(Obj, RENext, Fmt);
  577. }
  578. Fmt << ")";
  579. break;
  580. }
  581. default: {
  582. printRelocationTargetName(Obj, RE, Fmt);
  583. }
  584. }
  585. }
  586. } else
  587. printRelocationTargetName(Obj, RE, Fmt);
  588. Fmt.flush();
  589. Result.append(FmtBuf.begin(), FmtBuf.end());
  590. return Error::success();
  591. }
  592. static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
  593. uint32_t n, uint32_t count,
  594. uint32_t stride, uint64_t addr) {
  595. MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
  596. uint32_t nindirectsyms = Dysymtab.nindirectsyms;
  597. if (n > nindirectsyms)
  598. outs() << " (entries start past the end of the indirect symbol "
  599. "table) (reserved1 field greater than the table size)";
  600. else if (n + count > nindirectsyms)
  601. outs() << " (entries extends past the end of the indirect symbol "
  602. "table)";
  603. outs() << "\n";
  604. uint32_t cputype = O->getHeader().cputype;
  605. if (cputype & MachO::CPU_ARCH_ABI64)
  606. outs() << "address index";
  607. else
  608. outs() << "address index";
  609. if (verbose)
  610. outs() << " name\n";
  611. else
  612. outs() << "\n";
  613. for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
  614. if (cputype & MachO::CPU_ARCH_ABI64)
  615. outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
  616. else
  617. outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
  618. MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
  619. uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
  620. if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
  621. outs() << "LOCAL\n";
  622. continue;
  623. }
  624. if (indirect_symbol ==
  625. (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
  626. outs() << "LOCAL ABSOLUTE\n";
  627. continue;
  628. }
  629. if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
  630. outs() << "ABSOLUTE\n";
  631. continue;
  632. }
  633. outs() << format("%5u ", indirect_symbol);
  634. if (verbose) {
  635. MachO::symtab_command Symtab = O->getSymtabLoadCommand();
  636. if (indirect_symbol < Symtab.nsyms) {
  637. symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
  638. SymbolRef Symbol = *Sym;
  639. outs() << unwrapOrError(Symbol.getName(), O->getFileName());
  640. } else {
  641. outs() << "?";
  642. }
  643. }
  644. outs() << "\n";
  645. }
  646. }
  647. static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
  648. for (const auto &Load : O->load_commands()) {
  649. if (Load.C.cmd == MachO::LC_SEGMENT_64) {
  650. MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
  651. for (unsigned J = 0; J < Seg.nsects; ++J) {
  652. MachO::section_64 Sec = O->getSection64(Load, J);
  653. uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
  654. if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
  655. section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
  656. section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
  657. section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
  658. section_type == MachO::S_SYMBOL_STUBS) {
  659. uint32_t stride;
  660. if (section_type == MachO::S_SYMBOL_STUBS)
  661. stride = Sec.reserved2;
  662. else
  663. stride = 8;
  664. if (stride == 0) {
  665. outs() << "Can't print indirect symbols for (" << Sec.segname << ","
  666. << Sec.sectname << ") "
  667. << "(size of stubs in reserved2 field is zero)\n";
  668. continue;
  669. }
  670. uint32_t count = Sec.size / stride;
  671. outs() << "Indirect symbols for (" << Sec.segname << ","
  672. << Sec.sectname << ") " << count << " entries";
  673. uint32_t n = Sec.reserved1;
  674. PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
  675. }
  676. }
  677. } else if (Load.C.cmd == MachO::LC_SEGMENT) {
  678. MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
  679. for (unsigned J = 0; J < Seg.nsects; ++J) {
  680. MachO::section Sec = O->getSection(Load, J);
  681. uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
  682. if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
  683. section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
  684. section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
  685. section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
  686. section_type == MachO::S_SYMBOL_STUBS) {
  687. uint32_t stride;
  688. if (section_type == MachO::S_SYMBOL_STUBS)
  689. stride = Sec.reserved2;
  690. else
  691. stride = 4;
  692. if (stride == 0) {
  693. outs() << "Can't print indirect symbols for (" << Sec.segname << ","
  694. << Sec.sectname << ") "
  695. << "(size of stubs in reserved2 field is zero)\n";
  696. continue;
  697. }
  698. uint32_t count = Sec.size / stride;
  699. outs() << "Indirect symbols for (" << Sec.segname << ","
  700. << Sec.sectname << ") " << count << " entries";
  701. uint32_t n = Sec.reserved1;
  702. PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
  703. }
  704. }
  705. }
  706. }
  707. }
  708. static void PrintRType(const uint64_t cputype, const unsigned r_type) {
  709. static char const *generic_r_types[] = {
  710. "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
  711. " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
  712. " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
  713. };
  714. static char const *x86_64_r_types[] = {
  715. "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
  716. "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
  717. " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
  718. };
  719. static char const *arm_r_types[] = {
  720. "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
  721. "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
  722. " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
  723. };
  724. static char const *arm64_r_types[] = {
  725. "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
  726. "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
  727. "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
  728. };
  729. if (r_type > 0xf){
  730. outs() << format("%-7u", r_type) << " ";
  731. return;
  732. }
  733. switch (cputype) {
  734. case MachO::CPU_TYPE_I386:
  735. outs() << generic_r_types[r_type];
  736. break;
  737. case MachO::CPU_TYPE_X86_64:
  738. outs() << x86_64_r_types[r_type];
  739. break;
  740. case MachO::CPU_TYPE_ARM:
  741. outs() << arm_r_types[r_type];
  742. break;
  743. case MachO::CPU_TYPE_ARM64:
  744. case MachO::CPU_TYPE_ARM64_32:
  745. outs() << arm64_r_types[r_type];
  746. break;
  747. default:
  748. outs() << format("%-7u ", r_type);
  749. }
  750. }
  751. static void PrintRLength(const uint64_t cputype, const unsigned r_type,
  752. const unsigned r_length, const bool previous_arm_half){
  753. if (cputype == MachO::CPU_TYPE_ARM &&
  754. (r_type == MachO::ARM_RELOC_HALF ||
  755. r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
  756. if ((r_length & 0x1) == 0)
  757. outs() << "lo/";
  758. else
  759. outs() << "hi/";
  760. if ((r_length & 0x1) == 0)
  761. outs() << "arm ";
  762. else
  763. outs() << "thm ";
  764. } else {
  765. switch (r_length) {
  766. case 0:
  767. outs() << "byte ";
  768. break;
  769. case 1:
  770. outs() << "word ";
  771. break;
  772. case 2:
  773. outs() << "long ";
  774. break;
  775. case 3:
  776. if (cputype == MachO::CPU_TYPE_X86_64)
  777. outs() << "quad ";
  778. else
  779. outs() << format("?(%2d) ", r_length);
  780. break;
  781. default:
  782. outs() << format("?(%2d) ", r_length);
  783. }
  784. }
  785. }
  786. static void PrintRelocationEntries(const MachOObjectFile *O,
  787. const relocation_iterator Begin,
  788. const relocation_iterator End,
  789. const uint64_t cputype,
  790. const bool verbose) {
  791. const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
  792. bool previous_arm_half = false;
  793. bool previous_sectdiff = false;
  794. uint32_t sectdiff_r_type = 0;
  795. for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
  796. const DataRefImpl Rel = Reloc->getRawDataRefImpl();
  797. const MachO::any_relocation_info RE = O->getRelocation(Rel);
  798. const unsigned r_type = O->getAnyRelocationType(RE);
  799. const bool r_scattered = O->isRelocationScattered(RE);
  800. const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
  801. const unsigned r_length = O->getAnyRelocationLength(RE);
  802. const unsigned r_address = O->getAnyRelocationAddress(RE);
  803. const bool r_extern = (r_scattered ? false :
  804. O->getPlainRelocationExternal(RE));
  805. const uint32_t r_value = (r_scattered ?
  806. O->getScatteredRelocationValue(RE) : 0);
  807. const unsigned r_symbolnum = (r_scattered ? 0 :
  808. O->getPlainRelocationSymbolNum(RE));
  809. if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
  810. if (verbose) {
  811. // scattered: address
  812. if ((cputype == MachO::CPU_TYPE_I386 &&
  813. r_type == MachO::GENERIC_RELOC_PAIR) ||
  814. (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
  815. outs() << " ";
  816. else
  817. outs() << format("%08x ", (unsigned int)r_address);
  818. // scattered: pcrel
  819. if (r_pcrel)
  820. outs() << "True ";
  821. else
  822. outs() << "False ";
  823. // scattered: length
  824. PrintRLength(cputype, r_type, r_length, previous_arm_half);
  825. // scattered: extern & type
  826. outs() << "n/a ";
  827. PrintRType(cputype, r_type);
  828. // scattered: scattered & value
  829. outs() << format("True 0x%08x", (unsigned int)r_value);
  830. if (previous_sectdiff == false) {
  831. if ((cputype == MachO::CPU_TYPE_ARM &&
  832. r_type == MachO::ARM_RELOC_PAIR))
  833. outs() << format(" half = 0x%04x ", (unsigned int)r_address);
  834. } else if (cputype == MachO::CPU_TYPE_ARM &&
  835. sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
  836. outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
  837. if ((cputype == MachO::CPU_TYPE_I386 &&
  838. (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
  839. r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
  840. (cputype == MachO::CPU_TYPE_ARM &&
  841. (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
  842. sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
  843. sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
  844. previous_sectdiff = true;
  845. sectdiff_r_type = r_type;
  846. } else {
  847. previous_sectdiff = false;
  848. sectdiff_r_type = 0;
  849. }
  850. if (cputype == MachO::CPU_TYPE_ARM &&
  851. (r_type == MachO::ARM_RELOC_HALF ||
  852. r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
  853. previous_arm_half = true;
  854. else
  855. previous_arm_half = false;
  856. outs() << "\n";
  857. }
  858. else {
  859. // scattered: address pcrel length extern type scattered value
  860. outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
  861. (unsigned int)r_address, r_pcrel, r_length, r_type,
  862. (unsigned int)r_value);
  863. }
  864. }
  865. else {
  866. if (verbose) {
  867. // plain: address
  868. if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
  869. outs() << " ";
  870. else
  871. outs() << format("%08x ", (unsigned int)r_address);
  872. // plain: pcrel
  873. if (r_pcrel)
  874. outs() << "True ";
  875. else
  876. outs() << "False ";
  877. // plain: length
  878. PrintRLength(cputype, r_type, r_length, previous_arm_half);
  879. if (r_extern) {
  880. // plain: extern & type & scattered
  881. outs() << "True ";
  882. PrintRType(cputype, r_type);
  883. outs() << "False ";
  884. // plain: symbolnum/value
  885. if (r_symbolnum > Symtab.nsyms)
  886. outs() << format("?(%d)\n", r_symbolnum);
  887. else {
  888. SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
  889. Expected<StringRef> SymNameNext = Symbol.getName();
  890. const char *name = NULL;
  891. if (SymNameNext)
  892. name = SymNameNext->data();
  893. if (name == NULL)
  894. outs() << format("?(%d)\n", r_symbolnum);
  895. else
  896. outs() << name << "\n";
  897. }
  898. }
  899. else {
  900. // plain: extern & type & scattered
  901. outs() << "False ";
  902. PrintRType(cputype, r_type);
  903. outs() << "False ";
  904. // plain: symbolnum/value
  905. if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
  906. outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
  907. else if ((cputype == MachO::CPU_TYPE_ARM64 ||
  908. cputype == MachO::CPU_TYPE_ARM64_32) &&
  909. r_type == MachO::ARM64_RELOC_ADDEND)
  910. outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
  911. else {
  912. outs() << format("%d ", r_symbolnum);
  913. if (r_symbolnum == MachO::R_ABS)
  914. outs() << "R_ABS\n";
  915. else {
  916. // in this case, r_symbolnum is actually a 1-based section number
  917. uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
  918. if (r_symbolnum > 0 && r_symbolnum <= nsects) {
  919. object::DataRefImpl DRI;
  920. DRI.d.a = r_symbolnum-1;
  921. StringRef SegName = O->getSectionFinalSegmentName(DRI);
  922. if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
  923. outs() << "(" << SegName << "," << *NameOrErr << ")\n";
  924. else
  925. outs() << "(?,?)\n";
  926. }
  927. else {
  928. outs() << "(?,?)\n";
  929. }
  930. }
  931. }
  932. }
  933. if (cputype == MachO::CPU_TYPE_ARM &&
  934. (r_type == MachO::ARM_RELOC_HALF ||
  935. r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
  936. previous_arm_half = true;
  937. else
  938. previous_arm_half = false;
  939. }
  940. else {
  941. // plain: address pcrel length extern type scattered symbolnum/section
  942. outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
  943. (unsigned int)r_address, r_pcrel, r_length, r_extern,
  944. r_type, r_symbolnum);
  945. }
  946. }
  947. }
  948. }
  949. static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
  950. const uint64_t cputype = O->getHeader().cputype;
  951. const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
  952. if (Dysymtab.nextrel != 0) {
  953. outs() << "External relocation information " << Dysymtab.nextrel
  954. << " entries";
  955. outs() << "\naddress pcrel length extern type scattered "
  956. "symbolnum/value\n";
  957. PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
  958. verbose);
  959. }
  960. if (Dysymtab.nlocrel != 0) {
  961. outs() << format("Local relocation information %u entries",
  962. Dysymtab.nlocrel);
  963. outs() << "\naddress pcrel length extern type scattered "
  964. "symbolnum/value\n";
  965. PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
  966. verbose);
  967. }
  968. for (const auto &Load : O->load_commands()) {
  969. if (Load.C.cmd == MachO::LC_SEGMENT_64) {
  970. const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
  971. for (unsigned J = 0; J < Seg.nsects; ++J) {
  972. const MachO::section_64 Sec = O->getSection64(Load, J);
  973. if (Sec.nreloc != 0) {
  974. DataRefImpl DRI;
  975. DRI.d.a = J;
  976. const StringRef SegName = O->getSectionFinalSegmentName(DRI);
  977. if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
  978. outs() << "Relocation information (" << SegName << "," << *NameOrErr
  979. << format(") %u entries", Sec.nreloc);
  980. else
  981. outs() << "Relocation information (" << SegName << ",?) "
  982. << format("%u entries", Sec.nreloc);
  983. outs() << "\naddress pcrel length extern type scattered "
  984. "symbolnum/value\n";
  985. PrintRelocationEntries(O, O->section_rel_begin(DRI),
  986. O->section_rel_end(DRI), cputype, verbose);
  987. }
  988. }
  989. } else if (Load.C.cmd == MachO::LC_SEGMENT) {
  990. const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
  991. for (unsigned J = 0; J < Seg.nsects; ++J) {
  992. const MachO::section Sec = O->getSection(Load, J);
  993. if (Sec.nreloc != 0) {
  994. DataRefImpl DRI;
  995. DRI.d.a = J;
  996. const StringRef SegName = O->getSectionFinalSegmentName(DRI);
  997. if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
  998. outs() << "Relocation information (" << SegName << "," << *NameOrErr
  999. << format(") %u entries", Sec.nreloc);
  1000. else
  1001. outs() << "Relocation information (" << SegName << ",?) "
  1002. << format("%u entries", Sec.nreloc);
  1003. outs() << "\naddress pcrel length extern type scattered "
  1004. "symbolnum/value\n";
  1005. PrintRelocationEntries(O, O->section_rel_begin(DRI),
  1006. O->section_rel_end(DRI), cputype, verbose);
  1007. }
  1008. }
  1009. }
  1010. }
  1011. }
  1012. static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
  1013. MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
  1014. uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
  1015. outs() << "Data in code table (" << nentries << " entries)\n";
  1016. outs() << "offset length kind\n";
  1017. for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
  1018. ++DI) {
  1019. uint32_t Offset;
  1020. DI->getOffset(Offset);
  1021. outs() << format("0x%08" PRIx32, Offset) << " ";
  1022. uint16_t Length;
  1023. DI->getLength(Length);
  1024. outs() << format("%6u", Length) << " ";
  1025. uint16_t Kind;
  1026. DI->getKind(Kind);
  1027. if (verbose) {
  1028. switch (Kind) {
  1029. case MachO::DICE_KIND_DATA:
  1030. outs() << "DATA";
  1031. break;
  1032. case MachO::DICE_KIND_JUMP_TABLE8:
  1033. outs() << "JUMP_TABLE8";
  1034. break;
  1035. case MachO::DICE_KIND_JUMP_TABLE16:
  1036. outs() << "JUMP_TABLE16";
  1037. break;
  1038. case MachO::DICE_KIND_JUMP_TABLE32:
  1039. outs() << "JUMP_TABLE32";
  1040. break;
  1041. case MachO::DICE_KIND_ABS_JUMP_TABLE32:
  1042. outs() << "ABS_JUMP_TABLE32";
  1043. break;
  1044. default:
  1045. outs() << format("0x%04" PRIx32, Kind);
  1046. break;
  1047. }
  1048. } else
  1049. outs() << format("0x%04" PRIx32, Kind);
  1050. outs() << "\n";
  1051. }
  1052. }
  1053. static void PrintLinkOptHints(MachOObjectFile *O) {
  1054. MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
  1055. const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
  1056. uint32_t nloh = LohLC.datasize;
  1057. outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
  1058. for (uint32_t i = 0; i < nloh;) {
  1059. unsigned n;
  1060. uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
  1061. i += n;
  1062. outs() << " identifier " << identifier << " ";
  1063. if (i >= nloh)
  1064. return;
  1065. switch (identifier) {
  1066. case 1:
  1067. outs() << "AdrpAdrp\n";
  1068. break;
  1069. case 2:
  1070. outs() << "AdrpLdr\n";
  1071. break;
  1072. case 3:
  1073. outs() << "AdrpAddLdr\n";
  1074. break;
  1075. case 4:
  1076. outs() << "AdrpLdrGotLdr\n";
  1077. break;
  1078. case 5:
  1079. outs() << "AdrpAddStr\n";
  1080. break;
  1081. case 6:
  1082. outs() << "AdrpLdrGotStr\n";
  1083. break;
  1084. case 7:
  1085. outs() << "AdrpAdd\n";
  1086. break;
  1087. case 8:
  1088. outs() << "AdrpLdrGot\n";
  1089. break;
  1090. default:
  1091. outs() << "Unknown identifier value\n";
  1092. break;
  1093. }
  1094. uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
  1095. i += n;
  1096. outs() << " narguments " << narguments << "\n";
  1097. if (i >= nloh)
  1098. return;
  1099. for (uint32_t j = 0; j < narguments; j++) {
  1100. uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
  1101. i += n;
  1102. outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
  1103. if (i >= nloh)
  1104. return;
  1105. }
  1106. }
  1107. }
  1108. static void PrintDylibs(MachOObjectFile *O, bool JustId) {
  1109. unsigned Index = 0;
  1110. for (const auto &Load : O->load_commands()) {
  1111. if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
  1112. (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
  1113. Load.C.cmd == MachO::LC_LOAD_DYLIB ||
  1114. Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
  1115. Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
  1116. Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
  1117. Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
  1118. MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
  1119. if (dl.dylib.name < dl.cmdsize) {
  1120. const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
  1121. if (JustId)
  1122. outs() << p << "\n";
  1123. else {
  1124. outs() << "\t" << p;
  1125. outs() << " (compatibility version "
  1126. << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
  1127. << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
  1128. << (dl.dylib.compatibility_version & 0xff) << ",";
  1129. outs() << " current version "
  1130. << ((dl.dylib.current_version >> 16) & 0xffff) << "."
  1131. << ((dl.dylib.current_version >> 8) & 0xff) << "."
  1132. << (dl.dylib.current_version & 0xff);
  1133. if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
  1134. outs() << ", weak";
  1135. if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
  1136. outs() << ", reexport";
  1137. if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
  1138. outs() << ", upward";
  1139. if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
  1140. outs() << ", lazy";
  1141. outs() << ")\n";
  1142. }
  1143. } else {
  1144. outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
  1145. if (Load.C.cmd == MachO::LC_ID_DYLIB)
  1146. outs() << "LC_ID_DYLIB ";
  1147. else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
  1148. outs() << "LC_LOAD_DYLIB ";
  1149. else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
  1150. outs() << "LC_LOAD_WEAK_DYLIB ";
  1151. else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
  1152. outs() << "LC_LAZY_LOAD_DYLIB ";
  1153. else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
  1154. outs() << "LC_REEXPORT_DYLIB ";
  1155. else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
  1156. outs() << "LC_LOAD_UPWARD_DYLIB ";
  1157. else
  1158. outs() << "LC_??? ";
  1159. outs() << "command " << Index++ << "\n";
  1160. }
  1161. }
  1162. }
  1163. }
  1164. typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
  1165. static void CreateSymbolAddressMap(MachOObjectFile *O,
  1166. SymbolAddressMap *AddrMap) {
  1167. // Create a map of symbol addresses to symbol names.
  1168. const StringRef FileName = O->getFileName();
  1169. for (const SymbolRef &Symbol : O->symbols()) {
  1170. SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
  1171. if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
  1172. ST == SymbolRef::ST_Other) {
  1173. uint64_t Address = cantFail(Symbol.getValue());
  1174. StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
  1175. if (!SymName.startswith(".objc"))
  1176. (*AddrMap)[Address] = SymName;
  1177. }
  1178. }
  1179. }
  1180. // GuessSymbolName is passed the address of what might be a symbol and a
  1181. // pointer to the SymbolAddressMap. It returns the name of a symbol
  1182. // with that address or nullptr if no symbol is found with that address.
  1183. static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
  1184. const char *SymbolName = nullptr;
  1185. // A DenseMap can't lookup up some values.
  1186. if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
  1187. StringRef name = AddrMap->lookup(value);
  1188. if (!name.empty())
  1189. SymbolName = name.data();
  1190. }
  1191. return SymbolName;
  1192. }
  1193. static void DumpCstringChar(const char c) {
  1194. char p[2];
  1195. p[0] = c;
  1196. p[1] = '\0';
  1197. outs().write_escaped(p);
  1198. }
  1199. static void DumpCstringSection(MachOObjectFile *O, const char *sect,
  1200. uint32_t sect_size, uint64_t sect_addr,
  1201. bool print_addresses) {
  1202. for (uint32_t i = 0; i < sect_size; i++) {
  1203. if (print_addresses) {
  1204. if (O->is64Bit())
  1205. outs() << format("%016" PRIx64, sect_addr + i) << " ";
  1206. else
  1207. outs() << format("%08" PRIx64, sect_addr + i) << " ";
  1208. }
  1209. for (; i < sect_size && sect[i] != '\0'; i++)
  1210. DumpCstringChar(sect[i]);
  1211. if (i < sect_size && sect[i] == '\0')
  1212. outs() << "\n";
  1213. }
  1214. }
  1215. static void DumpLiteral4(uint32_t l, float f) {
  1216. outs() << format("0x%08" PRIx32, l);
  1217. if ((l & 0x7f800000) != 0x7f800000)
  1218. outs() << format(" (%.16e)\n", f);
  1219. else {
  1220. if (l == 0x7f800000)
  1221. outs() << " (+Infinity)\n";
  1222. else if (l == 0xff800000)
  1223. outs() << " (-Infinity)\n";
  1224. else if ((l & 0x00400000) == 0x00400000)
  1225. outs() << " (non-signaling Not-a-Number)\n";
  1226. else
  1227. outs() << " (signaling Not-a-Number)\n";
  1228. }
  1229. }
  1230. static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
  1231. uint32_t sect_size, uint64_t sect_addr,
  1232. bool print_addresses) {
  1233. for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
  1234. if (print_addresses) {
  1235. if (O->is64Bit())
  1236. outs() << format("%016" PRIx64, sect_addr + i) << " ";
  1237. else
  1238. outs() << format("%08" PRIx64, sect_addr + i) << " ";
  1239. }
  1240. float f;
  1241. memcpy(&f, sect + i, sizeof(float));
  1242. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1243. sys::swapByteOrder(f);
  1244. uint32_t l;
  1245. memcpy(&l, sect + i, sizeof(uint32_t));
  1246. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1247. sys::swapByteOrder(l);
  1248. DumpLiteral4(l, f);
  1249. }
  1250. }
  1251. static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
  1252. double d) {
  1253. outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
  1254. uint32_t Hi, Lo;
  1255. Hi = (O->isLittleEndian()) ? l1 : l0;
  1256. Lo = (O->isLittleEndian()) ? l0 : l1;
  1257. // Hi is the high word, so this is equivalent to if(isfinite(d))
  1258. if ((Hi & 0x7ff00000) != 0x7ff00000)
  1259. outs() << format(" (%.16e)\n", d);
  1260. else {
  1261. if (Hi == 0x7ff00000 && Lo == 0)
  1262. outs() << " (+Infinity)\n";
  1263. else if (Hi == 0xfff00000 && Lo == 0)
  1264. outs() << " (-Infinity)\n";
  1265. else if ((Hi & 0x00080000) == 0x00080000)
  1266. outs() << " (non-signaling Not-a-Number)\n";
  1267. else
  1268. outs() << " (signaling Not-a-Number)\n";
  1269. }
  1270. }
  1271. static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
  1272. uint32_t sect_size, uint64_t sect_addr,
  1273. bool print_addresses) {
  1274. for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
  1275. if (print_addresses) {
  1276. if (O->is64Bit())
  1277. outs() << format("%016" PRIx64, sect_addr + i) << " ";
  1278. else
  1279. outs() << format("%08" PRIx64, sect_addr + i) << " ";
  1280. }
  1281. double d;
  1282. memcpy(&d, sect + i, sizeof(double));
  1283. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1284. sys::swapByteOrder(d);
  1285. uint32_t l0, l1;
  1286. memcpy(&l0, sect + i, sizeof(uint32_t));
  1287. memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
  1288. if (O->isLittleEndian() != sys::IsLittleEndianHost) {
  1289. sys::swapByteOrder(l0);
  1290. sys::swapByteOrder(l1);
  1291. }
  1292. DumpLiteral8(O, l0, l1, d);
  1293. }
  1294. }
  1295. static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
  1296. outs() << format("0x%08" PRIx32, l0) << " ";
  1297. outs() << format("0x%08" PRIx32, l1) << " ";
  1298. outs() << format("0x%08" PRIx32, l2) << " ";
  1299. outs() << format("0x%08" PRIx32, l3) << "\n";
  1300. }
  1301. static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
  1302. uint32_t sect_size, uint64_t sect_addr,
  1303. bool print_addresses) {
  1304. for (uint32_t i = 0; i < sect_size; i += 16) {
  1305. if (print_addresses) {
  1306. if (O->is64Bit())
  1307. outs() << format("%016" PRIx64, sect_addr + i) << " ";
  1308. else
  1309. outs() << format("%08" PRIx64, sect_addr + i) << " ";
  1310. }
  1311. uint32_t l0, l1, l2, l3;
  1312. memcpy(&l0, sect + i, sizeof(uint32_t));
  1313. memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
  1314. memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
  1315. memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
  1316. if (O->isLittleEndian() != sys::IsLittleEndianHost) {
  1317. sys::swapByteOrder(l0);
  1318. sys::swapByteOrder(l1);
  1319. sys::swapByteOrder(l2);
  1320. sys::swapByteOrder(l3);
  1321. }
  1322. DumpLiteral16(l0, l1, l2, l3);
  1323. }
  1324. }
  1325. static void DumpLiteralPointerSection(MachOObjectFile *O,
  1326. const SectionRef &Section,
  1327. const char *sect, uint32_t sect_size,
  1328. uint64_t sect_addr,
  1329. bool print_addresses) {
  1330. // Collect the literal sections in this Mach-O file.
  1331. std::vector<SectionRef> LiteralSections;
  1332. for (const SectionRef &Section : O->sections()) {
  1333. DataRefImpl Ref = Section.getRawDataRefImpl();
  1334. uint32_t section_type;
  1335. if (O->is64Bit()) {
  1336. const MachO::section_64 Sec = O->getSection64(Ref);
  1337. section_type = Sec.flags & MachO::SECTION_TYPE;
  1338. } else {
  1339. const MachO::section Sec = O->getSection(Ref);
  1340. section_type = Sec.flags & MachO::SECTION_TYPE;
  1341. }
  1342. if (section_type == MachO::S_CSTRING_LITERALS ||
  1343. section_type == MachO::S_4BYTE_LITERALS ||
  1344. section_type == MachO::S_8BYTE_LITERALS ||
  1345. section_type == MachO::S_16BYTE_LITERALS)
  1346. LiteralSections.push_back(Section);
  1347. }
  1348. // Set the size of the literal pointer.
  1349. uint32_t lp_size = O->is64Bit() ? 8 : 4;
  1350. // Collect the external relocation symbols for the literal pointers.
  1351. std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
  1352. for (const RelocationRef &Reloc : Section.relocations()) {
  1353. DataRefImpl Rel;
  1354. MachO::any_relocation_info RE;
  1355. bool isExtern = false;
  1356. Rel = Reloc.getRawDataRefImpl();
  1357. RE = O->getRelocation(Rel);
  1358. isExtern = O->getPlainRelocationExternal(RE);
  1359. if (isExtern) {
  1360. uint64_t RelocOffset = Reloc.getOffset();
  1361. symbol_iterator RelocSym = Reloc.getSymbol();
  1362. Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
  1363. }
  1364. }
  1365. array_pod_sort(Relocs.begin(), Relocs.end());
  1366. // Dump each literal pointer.
  1367. for (uint32_t i = 0; i < sect_size; i += lp_size) {
  1368. if (print_addresses) {
  1369. if (O->is64Bit())
  1370. outs() << format("%016" PRIx64, sect_addr + i) << " ";
  1371. else
  1372. outs() << format("%08" PRIx64, sect_addr + i) << " ";
  1373. }
  1374. uint64_t lp;
  1375. if (O->is64Bit()) {
  1376. memcpy(&lp, sect + i, sizeof(uint64_t));
  1377. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1378. sys::swapByteOrder(lp);
  1379. } else {
  1380. uint32_t li;
  1381. memcpy(&li, sect + i, sizeof(uint32_t));
  1382. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1383. sys::swapByteOrder(li);
  1384. lp = li;
  1385. }
  1386. // First look for an external relocation entry for this literal pointer.
  1387. auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
  1388. return P.first == i;
  1389. });
  1390. if (Reloc != Relocs.end()) {
  1391. symbol_iterator RelocSym = Reloc->second;
  1392. StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
  1393. outs() << "external relocation entry for symbol:" << SymName << "\n";
  1394. continue;
  1395. }
  1396. // For local references see what the section the literal pointer points to.
  1397. auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
  1398. return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
  1399. });
  1400. if (Sect == LiteralSections.end()) {
  1401. outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
  1402. continue;
  1403. }
  1404. uint64_t SectAddress = Sect->getAddress();
  1405. uint64_t SectSize = Sect->getSize();
  1406. StringRef SectName;
  1407. Expected<StringRef> SectNameOrErr = Sect->getName();
  1408. if (SectNameOrErr)
  1409. SectName = *SectNameOrErr;
  1410. else
  1411. consumeError(SectNameOrErr.takeError());
  1412. DataRefImpl Ref = Sect->getRawDataRefImpl();
  1413. StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
  1414. outs() << SegmentName << ":" << SectName << ":";
  1415. uint32_t section_type;
  1416. if (O->is64Bit()) {
  1417. const MachO::section_64 Sec = O->getSection64(Ref);
  1418. section_type = Sec.flags & MachO::SECTION_TYPE;
  1419. } else {
  1420. const MachO::section Sec = O->getSection(Ref);
  1421. section_type = Sec.flags & MachO::SECTION_TYPE;
  1422. }
  1423. StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName());
  1424. const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
  1425. switch (section_type) {
  1426. case MachO::S_CSTRING_LITERALS:
  1427. for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
  1428. i++) {
  1429. DumpCstringChar(Contents[i]);
  1430. }
  1431. outs() << "\n";
  1432. break;
  1433. case MachO::S_4BYTE_LITERALS:
  1434. float f;
  1435. memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
  1436. uint32_t l;
  1437. memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
  1438. if (O->isLittleEndian() != sys::IsLittleEndianHost) {
  1439. sys::swapByteOrder(f);
  1440. sys::swapByteOrder(l);
  1441. }
  1442. DumpLiteral4(l, f);
  1443. break;
  1444. case MachO::S_8BYTE_LITERALS: {
  1445. double d;
  1446. memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
  1447. uint32_t l0, l1;
  1448. memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
  1449. memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
  1450. sizeof(uint32_t));
  1451. if (O->isLittleEndian() != sys::IsLittleEndianHost) {
  1452. sys::swapByteOrder(f);
  1453. sys::swapByteOrder(l0);
  1454. sys::swapByteOrder(l1);
  1455. }
  1456. DumpLiteral8(O, l0, l1, d);
  1457. break;
  1458. }
  1459. case MachO::S_16BYTE_LITERALS: {
  1460. uint32_t l0, l1, l2, l3;
  1461. memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
  1462. memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
  1463. sizeof(uint32_t));
  1464. memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
  1465. sizeof(uint32_t));
  1466. memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
  1467. sizeof(uint32_t));
  1468. if (O->isLittleEndian() != sys::IsLittleEndianHost) {
  1469. sys::swapByteOrder(l0);
  1470. sys::swapByteOrder(l1);
  1471. sys::swapByteOrder(l2);
  1472. sys::swapByteOrder(l3);
  1473. }
  1474. DumpLiteral16(l0, l1, l2, l3);
  1475. break;
  1476. }
  1477. }
  1478. }
  1479. }
  1480. static void DumpInitTermPointerSection(MachOObjectFile *O,
  1481. const SectionRef &Section,
  1482. const char *sect,
  1483. uint32_t sect_size, uint64_t sect_addr,
  1484. SymbolAddressMap *AddrMap,
  1485. bool verbose) {
  1486. uint32_t stride;
  1487. stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
  1488. // Collect the external relocation symbols for the pointers.
  1489. std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
  1490. for (const RelocationRef &Reloc : Section.relocations()) {
  1491. DataRefImpl Rel;
  1492. MachO::any_relocation_info RE;
  1493. bool isExtern = false;
  1494. Rel = Reloc.getRawDataRefImpl();
  1495. RE = O->getRelocation(Rel);
  1496. isExtern = O->getPlainRelocationExternal(RE);
  1497. if (isExtern) {
  1498. uint64_t RelocOffset = Reloc.getOffset();
  1499. symbol_iterator RelocSym = Reloc.getSymbol();
  1500. Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
  1501. }
  1502. }
  1503. array_pod_sort(Relocs.begin(), Relocs.end());
  1504. for (uint32_t i = 0; i < sect_size; i += stride) {
  1505. const char *SymbolName = nullptr;
  1506. uint64_t p;
  1507. if (O->is64Bit()) {
  1508. outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
  1509. uint64_t pointer_value;
  1510. memcpy(&pointer_value, sect + i, stride);
  1511. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1512. sys::swapByteOrder(pointer_value);
  1513. outs() << format("0x%016" PRIx64, pointer_value);
  1514. p = pointer_value;
  1515. } else {
  1516. outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
  1517. uint32_t pointer_value;
  1518. memcpy(&pointer_value, sect + i, stride);
  1519. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1520. sys::swapByteOrder(pointer_value);
  1521. outs() << format("0x%08" PRIx32, pointer_value);
  1522. p = pointer_value;
  1523. }
  1524. if (verbose) {
  1525. // First look for an external relocation entry for this pointer.
  1526. auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
  1527. return P.first == i;
  1528. });
  1529. if (Reloc != Relocs.end()) {
  1530. symbol_iterator RelocSym = Reloc->second;
  1531. outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
  1532. } else {
  1533. SymbolName = GuessSymbolName(p, AddrMap);
  1534. if (SymbolName)
  1535. outs() << " " << SymbolName;
  1536. }
  1537. }
  1538. outs() << "\n";
  1539. }
  1540. }
  1541. static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
  1542. uint32_t size, uint64_t addr) {
  1543. uint32_t cputype = O->getHeader().cputype;
  1544. if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
  1545. uint32_t j;
  1546. for (uint32_t i = 0; i < size; i += j, addr += j) {
  1547. if (O->is64Bit())
  1548. outs() << format("%016" PRIx64, addr) << "\t";
  1549. else
  1550. outs() << format("%08" PRIx64, addr) << "\t";
  1551. for (j = 0; j < 16 && i + j < size; j++) {
  1552. uint8_t byte_word = *(sect + i + j);
  1553. outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
  1554. }
  1555. outs() << "\n";
  1556. }
  1557. } else {
  1558. uint32_t j;
  1559. for (uint32_t i = 0; i < size; i += j, addr += j) {
  1560. if (O->is64Bit())
  1561. outs() << format("%016" PRIx64, addr) << "\t";
  1562. else
  1563. outs() << format("%08" PRIx64, addr) << "\t";
  1564. for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
  1565. j += sizeof(int32_t)) {
  1566. if (i + j + sizeof(int32_t) <= size) {
  1567. uint32_t long_word;
  1568. memcpy(&long_word, sect + i + j, sizeof(int32_t));
  1569. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1570. sys::swapByteOrder(long_word);
  1571. outs() << format("%08" PRIx32, long_word) << " ";
  1572. } else {
  1573. for (uint32_t k = 0; i + j + k < size; k++) {
  1574. uint8_t byte_word = *(sect + i + j + k);
  1575. outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
  1576. }
  1577. }
  1578. }
  1579. outs() << "\n";
  1580. }
  1581. }
  1582. }
  1583. static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
  1584. StringRef DisSegName, StringRef DisSectName);
  1585. static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
  1586. uint32_t size, uint32_t addr);
  1587. #ifdef HAVE_LIBXAR
  1588. static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
  1589. uint32_t size, bool verbose,
  1590. bool PrintXarHeader, bool PrintXarFileHeaders,
  1591. std::string XarMemberName);
  1592. #endif // defined(HAVE_LIBXAR)
  1593. static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
  1594. bool verbose) {
  1595. SymbolAddressMap AddrMap;
  1596. if (verbose)
  1597. CreateSymbolAddressMap(O, &AddrMap);
  1598. for (unsigned i = 0; i < FilterSections.size(); ++i) {
  1599. StringRef DumpSection = FilterSections[i];
  1600. std::pair<StringRef, StringRef> DumpSegSectName;
  1601. DumpSegSectName = DumpSection.split(',');
  1602. StringRef DumpSegName, DumpSectName;
  1603. if (!DumpSegSectName.second.empty()) {
  1604. DumpSegName = DumpSegSectName.first;
  1605. DumpSectName = DumpSegSectName.second;
  1606. } else {
  1607. DumpSegName = "";
  1608. DumpSectName = DumpSegSectName.first;
  1609. }
  1610. for (const SectionRef &Section : O->sections()) {
  1611. StringRef SectName;
  1612. Expected<StringRef> SecNameOrErr = Section.getName();
  1613. if (SecNameOrErr)
  1614. SectName = *SecNameOrErr;
  1615. else
  1616. consumeError(SecNameOrErr.takeError());
  1617. if (!DumpSection.empty())
  1618. FoundSectionSet.insert(DumpSection);
  1619. DataRefImpl Ref = Section.getRawDataRefImpl();
  1620. StringRef SegName = O->getSectionFinalSegmentName(Ref);
  1621. if ((DumpSegName.empty() || SegName == DumpSegName) &&
  1622. (SectName == DumpSectName)) {
  1623. uint32_t section_flags;
  1624. if (O->is64Bit()) {
  1625. const MachO::section_64 Sec = O->getSection64(Ref);
  1626. section_flags = Sec.flags;
  1627. } else {
  1628. const MachO::section Sec = O->getSection(Ref);
  1629. section_flags = Sec.flags;
  1630. }
  1631. uint32_t section_type = section_flags & MachO::SECTION_TYPE;
  1632. StringRef BytesStr =
  1633. unwrapOrError(Section.getContents(), O->getFileName());
  1634. const char *sect = reinterpret_cast<const char *>(BytesStr.data());
  1635. uint32_t sect_size = BytesStr.size();
  1636. uint64_t sect_addr = Section.getAddress();
  1637. if (!NoLeadingHeaders)
  1638. outs() << "Contents of (" << SegName << "," << SectName
  1639. << ") section\n";
  1640. if (verbose) {
  1641. if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
  1642. (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
  1643. DisassembleMachO(Filename, O, SegName, SectName);
  1644. continue;
  1645. }
  1646. if (SegName == "__TEXT" && SectName == "__info_plist") {
  1647. outs() << sect;
  1648. continue;
  1649. }
  1650. if (SegName == "__OBJC" && SectName == "__protocol") {
  1651. DumpProtocolSection(O, sect, sect_size, sect_addr);
  1652. continue;
  1653. }
  1654. #ifdef HAVE_LIBXAR
  1655. if (SegName == "__LLVM" && SectName == "__bundle") {
  1656. DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
  1657. ArchiveHeaders, "");
  1658. continue;
  1659. }
  1660. #endif // defined(HAVE_LIBXAR)
  1661. switch (section_type) {
  1662. case MachO::S_REGULAR:
  1663. DumpRawSectionContents(O, sect, sect_size, sect_addr);
  1664. break;
  1665. case MachO::S_ZEROFILL:
  1666. outs() << "zerofill section and has no contents in the file\n";
  1667. break;
  1668. case MachO::S_CSTRING_LITERALS:
  1669. DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
  1670. break;
  1671. case MachO::S_4BYTE_LITERALS:
  1672. DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
  1673. break;
  1674. case MachO::S_8BYTE_LITERALS:
  1675. DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
  1676. break;
  1677. case MachO::S_16BYTE_LITERALS:
  1678. DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
  1679. break;
  1680. case MachO::S_LITERAL_POINTERS:
  1681. DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
  1682. !NoLeadingAddr);
  1683. break;
  1684. case MachO::S_MOD_INIT_FUNC_POINTERS:
  1685. case MachO::S_MOD_TERM_FUNC_POINTERS:
  1686. DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
  1687. &AddrMap, verbose);
  1688. break;
  1689. default:
  1690. outs() << "Unknown section type ("
  1691. << format("0x%08" PRIx32, section_type) << ")\n";
  1692. DumpRawSectionContents(O, sect, sect_size, sect_addr);
  1693. break;
  1694. }
  1695. } else {
  1696. if (section_type == MachO::S_ZEROFILL)
  1697. outs() << "zerofill section and has no contents in the file\n";
  1698. else
  1699. DumpRawSectionContents(O, sect, sect_size, sect_addr);
  1700. }
  1701. }
  1702. }
  1703. }
  1704. }
  1705. static void DumpInfoPlistSectionContents(StringRef Filename,
  1706. MachOObjectFile *O) {
  1707. for (const SectionRef &Section : O->sections()) {
  1708. StringRef SectName;
  1709. Expected<StringRef> SecNameOrErr = Section.getName();
  1710. if (SecNameOrErr)
  1711. SectName = *SecNameOrErr;
  1712. else
  1713. consumeError(SecNameOrErr.takeError());
  1714. DataRefImpl Ref = Section.getRawDataRefImpl();
  1715. StringRef SegName = O->getSectionFinalSegmentName(Ref);
  1716. if (SegName == "__TEXT" && SectName == "__info_plist") {
  1717. if (!NoLeadingHeaders)
  1718. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  1719. StringRef BytesStr =
  1720. unwrapOrError(Section.getContents(), O->getFileName());
  1721. const char *sect = reinterpret_cast<const char *>(BytesStr.data());
  1722. outs() << format("%.*s", BytesStr.size(), sect) << "\n";
  1723. return;
  1724. }
  1725. }
  1726. }
  1727. // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
  1728. // and if it is and there is a list of architecture flags is specified then
  1729. // check to make sure this Mach-O file is one of those architectures or all
  1730. // architectures were specified. If not then an error is generated and this
  1731. // routine returns false. Else it returns true.
  1732. static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
  1733. auto *MachO = dyn_cast<MachOObjectFile>(O);
  1734. if (!MachO || ArchAll || ArchFlags.empty())
  1735. return true;
  1736. MachO::mach_header H;
  1737. MachO::mach_header_64 H_64;
  1738. Triple T;
  1739. const char *McpuDefault, *ArchFlag;
  1740. if (MachO->is64Bit()) {
  1741. H_64 = MachO->MachOObjectFile::getHeader64();
  1742. T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
  1743. &McpuDefault, &ArchFlag);
  1744. } else {
  1745. H = MachO->MachOObjectFile::getHeader();
  1746. T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
  1747. &McpuDefault, &ArchFlag);
  1748. }
  1749. const std::string ArchFlagName(ArchFlag);
  1750. if (!llvm::is_contained(ArchFlags, ArchFlagName)) {
  1751. WithColor::error(errs(), "llvm-objdump")
  1752. << Filename << ": no architecture specified.\n";
  1753. return false;
  1754. }
  1755. return true;
  1756. }
  1757. static void printObjcMetaData(MachOObjectFile *O, bool verbose);
  1758. // ProcessMachO() is passed a single opened Mach-O file, which may be an
  1759. // archive member and or in a slice of a universal file. It prints the
  1760. // the file name and header info and then processes it according to the
  1761. // command line options.
  1762. static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
  1763. StringRef ArchiveMemberName = StringRef(),
  1764. StringRef ArchitectureName = StringRef()) {
  1765. // If we are doing some processing here on the Mach-O file print the header
  1766. // info. And don't print it otherwise like in the case of printing the
  1767. // UniversalHeaders or ArchiveHeaders.
  1768. if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
  1769. Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
  1770. DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
  1771. (!FilterSections.empty())) {
  1772. if (!NoLeadingHeaders) {
  1773. outs() << Name;
  1774. if (!ArchiveMemberName.empty())
  1775. outs() << '(' << ArchiveMemberName << ')';
  1776. if (!ArchitectureName.empty())
  1777. outs() << " (architecture " << ArchitectureName << ")";
  1778. outs() << ":\n";
  1779. }
  1780. }
  1781. // To use the report_error() form with an ArchiveName and FileName set
  1782. // these up based on what is passed for Name and ArchiveMemberName.
  1783. StringRef ArchiveName;
  1784. StringRef FileName;
  1785. if (!ArchiveMemberName.empty()) {
  1786. ArchiveName = Name;
  1787. FileName = ArchiveMemberName;
  1788. } else {
  1789. ArchiveName = StringRef();
  1790. FileName = Name;
  1791. }
  1792. // If we need the symbol table to do the operation then check it here to
  1793. // produce a good error message as to where the Mach-O file comes from in
  1794. // the error message.
  1795. if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
  1796. if (Error Err = MachOOF->checkSymbolTable())
  1797. reportError(std::move(Err), FileName, ArchiveName, ArchitectureName);
  1798. if (DisassembleAll) {
  1799. for (const SectionRef &Section : MachOOF->sections()) {
  1800. StringRef SectName;
  1801. if (Expected<StringRef> NameOrErr = Section.getName())
  1802. SectName = *NameOrErr;
  1803. else
  1804. consumeError(NameOrErr.takeError());
  1805. if (SectName.equals("__text")) {
  1806. DataRefImpl Ref = Section.getRawDataRefImpl();
  1807. StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
  1808. DisassembleMachO(FileName, MachOOF, SegName, SectName);
  1809. }
  1810. }
  1811. }
  1812. else if (Disassemble) {
  1813. if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
  1814. MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
  1815. DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
  1816. else
  1817. DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
  1818. }
  1819. if (IndirectSymbols)
  1820. PrintIndirectSymbols(MachOOF, !NonVerbose);
  1821. if (DataInCode)
  1822. PrintDataInCodeTable(MachOOF, !NonVerbose);
  1823. if (LinkOptHints)
  1824. PrintLinkOptHints(MachOOF);
  1825. if (Relocations)
  1826. PrintRelocations(MachOOF, !NonVerbose);
  1827. if (SectionHeaders)
  1828. printSectionHeaders(MachOOF);
  1829. if (SectionContents)
  1830. printSectionContents(MachOOF);
  1831. if (!FilterSections.empty())
  1832. DumpSectionContents(FileName, MachOOF, !NonVerbose);
  1833. if (InfoPlist)
  1834. DumpInfoPlistSectionContents(FileName, MachOOF);
  1835. if (DylibsUsed)
  1836. PrintDylibs(MachOOF, false);
  1837. if (DylibId)
  1838. PrintDylibs(MachOOF, true);
  1839. if (SymbolTable)
  1840. printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
  1841. if (UnwindInfo)
  1842. printMachOUnwindInfo(MachOOF);
  1843. if (PrivateHeaders) {
  1844. printMachOFileHeader(MachOOF);
  1845. printMachOLoadCommands(MachOOF);
  1846. }
  1847. if (FirstPrivateHeader)
  1848. printMachOFileHeader(MachOOF);
  1849. if (ObjcMetaData)
  1850. printObjcMetaData(MachOOF, !NonVerbose);
  1851. if (ExportsTrie)
  1852. printExportsTrie(MachOOF);
  1853. if (Rebase)
  1854. printRebaseTable(MachOOF);
  1855. if (Bind)
  1856. printBindTable(MachOOF);
  1857. if (LazyBind)
  1858. printLazyBindTable(MachOOF);
  1859. if (WeakBind)
  1860. printWeakBindTable(MachOOF);
  1861. if (DwarfDumpType != DIDT_Null) {
  1862. std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
  1863. // Dump the complete DWARF structure.
  1864. DIDumpOptions DumpOpts;
  1865. DumpOpts.DumpType = DwarfDumpType;
  1866. DICtx->dump(outs(), DumpOpts);
  1867. }
  1868. }
  1869. // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
  1870. static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
  1871. outs() << " cputype (" << cputype << ")\n";
  1872. outs() << " cpusubtype (" << cpusubtype << ")\n";
  1873. }
  1874. // printCPUType() helps print_fat_headers by printing the cputype and
  1875. // pusubtype (symbolically for the one's it knows about).
  1876. static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
  1877. switch (cputype) {
  1878. case MachO::CPU_TYPE_I386:
  1879. switch (cpusubtype) {
  1880. case MachO::CPU_SUBTYPE_I386_ALL:
  1881. outs() << " cputype CPU_TYPE_I386\n";
  1882. outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
  1883. break;
  1884. default:
  1885. printUnknownCPUType(cputype, cpusubtype);
  1886. break;
  1887. }
  1888. break;
  1889. case MachO::CPU_TYPE_X86_64:
  1890. switch (cpusubtype) {
  1891. case MachO::CPU_SUBTYPE_X86_64_ALL:
  1892. outs() << " cputype CPU_TYPE_X86_64\n";
  1893. outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
  1894. break;
  1895. case MachO::CPU_SUBTYPE_X86_64_H:
  1896. outs() << " cputype CPU_TYPE_X86_64\n";
  1897. outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
  1898. break;
  1899. default:
  1900. printUnknownCPUType(cputype, cpusubtype);
  1901. break;
  1902. }
  1903. break;
  1904. case MachO::CPU_TYPE_ARM:
  1905. switch (cpusubtype) {
  1906. case MachO::CPU_SUBTYPE_ARM_ALL:
  1907. outs() << " cputype CPU_TYPE_ARM\n";
  1908. outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
  1909. break;
  1910. case MachO::CPU_SUBTYPE_ARM_V4T:
  1911. outs() << " cputype CPU_TYPE_ARM\n";
  1912. outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
  1913. break;
  1914. case MachO::CPU_SUBTYPE_ARM_V5TEJ:
  1915. outs() << " cputype CPU_TYPE_ARM\n";
  1916. outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
  1917. break;
  1918. case MachO::CPU_SUBTYPE_ARM_XSCALE:
  1919. outs() << " cputype CPU_TYPE_ARM\n";
  1920. outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
  1921. break;
  1922. case MachO::CPU_SUBTYPE_ARM_V6:
  1923. outs() << " cputype CPU_TYPE_ARM\n";
  1924. outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
  1925. break;
  1926. case MachO::CPU_SUBTYPE_ARM_V6M:
  1927. outs() << " cputype CPU_TYPE_ARM\n";
  1928. outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
  1929. break;
  1930. case MachO::CPU_SUBTYPE_ARM_V7:
  1931. outs() << " cputype CPU_TYPE_ARM\n";
  1932. outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
  1933. break;
  1934. case MachO::CPU_SUBTYPE_ARM_V7EM:
  1935. outs() << " cputype CPU_TYPE_ARM\n";
  1936. outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
  1937. break;
  1938. case MachO::CPU_SUBTYPE_ARM_V7K:
  1939. outs() << " cputype CPU_TYPE_ARM\n";
  1940. outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
  1941. break;
  1942. case MachO::CPU_SUBTYPE_ARM_V7M:
  1943. outs() << " cputype CPU_TYPE_ARM\n";
  1944. outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
  1945. break;
  1946. case MachO::CPU_SUBTYPE_ARM_V7S:
  1947. outs() << " cputype CPU_TYPE_ARM\n";
  1948. outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
  1949. break;
  1950. default:
  1951. printUnknownCPUType(cputype, cpusubtype);
  1952. break;
  1953. }
  1954. break;
  1955. case MachO::CPU_TYPE_ARM64:
  1956. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  1957. case MachO::CPU_SUBTYPE_ARM64_ALL:
  1958. outs() << " cputype CPU_TYPE_ARM64\n";
  1959. outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
  1960. break;
  1961. case MachO::CPU_SUBTYPE_ARM64_V8:
  1962. outs() << " cputype CPU_TYPE_ARM64\n";
  1963. outs() << " cpusubtype CPU_SUBTYPE_ARM64_V8\n";
  1964. break;
  1965. case MachO::CPU_SUBTYPE_ARM64E:
  1966. outs() << " cputype CPU_TYPE_ARM64\n";
  1967. outs() << " cpusubtype CPU_SUBTYPE_ARM64E\n";
  1968. break;
  1969. default:
  1970. printUnknownCPUType(cputype, cpusubtype);
  1971. break;
  1972. }
  1973. break;
  1974. case MachO::CPU_TYPE_ARM64_32:
  1975. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  1976. case MachO::CPU_SUBTYPE_ARM64_32_V8:
  1977. outs() << " cputype CPU_TYPE_ARM64_32\n";
  1978. outs() << " cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
  1979. break;
  1980. default:
  1981. printUnknownCPUType(cputype, cpusubtype);
  1982. break;
  1983. }
  1984. break;
  1985. default:
  1986. printUnknownCPUType(cputype, cpusubtype);
  1987. break;
  1988. }
  1989. }
  1990. static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
  1991. bool verbose) {
  1992. outs() << "Fat headers\n";
  1993. if (verbose) {
  1994. if (UB->getMagic() == MachO::FAT_MAGIC)
  1995. outs() << "fat_magic FAT_MAGIC\n";
  1996. else // UB->getMagic() == MachO::FAT_MAGIC_64
  1997. outs() << "fat_magic FAT_MAGIC_64\n";
  1998. } else
  1999. outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
  2000. uint32_t nfat_arch = UB->getNumberOfObjects();
  2001. StringRef Buf = UB->getData();
  2002. uint64_t size = Buf.size();
  2003. uint64_t big_size = sizeof(struct MachO::fat_header) +
  2004. nfat_arch * sizeof(struct MachO::fat_arch);
  2005. outs() << "nfat_arch " << UB->getNumberOfObjects();
  2006. if (nfat_arch == 0)
  2007. outs() << " (malformed, contains zero architecture types)\n";
  2008. else if (big_size > size)
  2009. outs() << " (malformed, architectures past end of file)\n";
  2010. else
  2011. outs() << "\n";
  2012. for (uint32_t i = 0; i < nfat_arch; ++i) {
  2013. MachOUniversalBinary::ObjectForArch OFA(UB, i);
  2014. uint32_t cputype = OFA.getCPUType();
  2015. uint32_t cpusubtype = OFA.getCPUSubType();
  2016. outs() << "architecture ";
  2017. for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
  2018. MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
  2019. uint32_t other_cputype = other_OFA.getCPUType();
  2020. uint32_t other_cpusubtype = other_OFA.getCPUSubType();
  2021. if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
  2022. (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
  2023. (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
  2024. outs() << "(illegal duplicate architecture) ";
  2025. break;
  2026. }
  2027. }
  2028. if (verbose) {
  2029. outs() << OFA.getArchFlagName() << "\n";
  2030. printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  2031. } else {
  2032. outs() << i << "\n";
  2033. outs() << " cputype " << cputype << "\n";
  2034. outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
  2035. << "\n";
  2036. }
  2037. if (verbose &&
  2038. (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
  2039. outs() << " capabilities CPU_SUBTYPE_LIB64\n";
  2040. else
  2041. outs() << " capabilities "
  2042. << format("0x%" PRIx32,
  2043. (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
  2044. outs() << " offset " << OFA.getOffset();
  2045. if (OFA.getOffset() > size)
  2046. outs() << " (past end of file)";
  2047. if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0)
  2048. outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
  2049. outs() << "\n";
  2050. outs() << " size " << OFA.getSize();
  2051. big_size = OFA.getOffset() + OFA.getSize();
  2052. if (big_size > size)
  2053. outs() << " (past end of file)";
  2054. outs() << "\n";
  2055. outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
  2056. << ")\n";
  2057. }
  2058. }
  2059. static void printArchiveChild(StringRef Filename, const Archive::Child &C,
  2060. size_t ChildIndex, bool verbose,
  2061. bool print_offset,
  2062. StringRef ArchitectureName = StringRef()) {
  2063. if (print_offset)
  2064. outs() << C.getChildOffset() << "\t";
  2065. sys::fs::perms Mode =
  2066. unwrapOrError(C.getAccessMode(), getFileNameForError(C, ChildIndex),
  2067. Filename, ArchitectureName);
  2068. if (verbose) {
  2069. // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
  2070. // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
  2071. outs() << "-";
  2072. outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
  2073. outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
  2074. outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
  2075. outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
  2076. outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
  2077. outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
  2078. outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
  2079. outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
  2080. outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
  2081. } else {
  2082. outs() << format("0%o ", Mode);
  2083. }
  2084. outs() << format("%3d/%-3d %5" PRId64 " ",
  2085. unwrapOrError(C.getUID(), getFileNameForError(C, ChildIndex),
  2086. Filename, ArchitectureName),
  2087. unwrapOrError(C.getGID(), getFileNameForError(C, ChildIndex),
  2088. Filename, ArchitectureName),
  2089. unwrapOrError(C.getRawSize(),
  2090. getFileNameForError(C, ChildIndex), Filename,
  2091. ArchitectureName));
  2092. StringRef RawLastModified = C.getRawLastModified();
  2093. if (verbose) {
  2094. unsigned Seconds;
  2095. if (RawLastModified.getAsInteger(10, Seconds))
  2096. outs() << "(date: \"" << RawLastModified
  2097. << "\" contains non-decimal chars) ";
  2098. else {
  2099. // Since cime(3) returns a 26 character string of the form:
  2100. // "Sun Sep 16 01:03:52 1973\n\0"
  2101. // just print 24 characters.
  2102. time_t t = Seconds;
  2103. outs() << format("%.24s ", ctime(&t));
  2104. }
  2105. } else {
  2106. outs() << RawLastModified << " ";
  2107. }
  2108. if (verbose) {
  2109. Expected<StringRef> NameOrErr = C.getName();
  2110. if (!NameOrErr) {
  2111. consumeError(NameOrErr.takeError());
  2112. outs() << unwrapOrError(C.getRawName(),
  2113. getFileNameForError(C, ChildIndex), Filename,
  2114. ArchitectureName)
  2115. << "\n";
  2116. } else {
  2117. StringRef Name = NameOrErr.get();
  2118. outs() << Name << "\n";
  2119. }
  2120. } else {
  2121. outs() << unwrapOrError(C.getRawName(), getFileNameForError(C, ChildIndex),
  2122. Filename, ArchitectureName)
  2123. << "\n";
  2124. }
  2125. }
  2126. static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
  2127. bool print_offset,
  2128. StringRef ArchitectureName = StringRef()) {
  2129. Error Err = Error::success();
  2130. size_t I = 0;
  2131. for (const auto &C : A->children(Err, false))
  2132. printArchiveChild(Filename, C, I++, verbose, print_offset,
  2133. ArchitectureName);
  2134. if (Err)
  2135. reportError(std::move(Err), Filename, "", ArchitectureName);
  2136. }
  2137. static bool ValidateArchFlags() {
  2138. // Check for -arch all and verifiy the -arch flags are valid.
  2139. for (unsigned i = 0; i < ArchFlags.size(); ++i) {
  2140. if (ArchFlags[i] == "all") {
  2141. ArchAll = true;
  2142. } else {
  2143. if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
  2144. WithColor::error(errs(), "llvm-objdump")
  2145. << "unknown architecture named '" + ArchFlags[i] +
  2146. "'for the -arch option\n";
  2147. return false;
  2148. }
  2149. }
  2150. }
  2151. return true;
  2152. }
  2153. // ParseInputMachO() parses the named Mach-O file in Filename and handles the
  2154. // -arch flags selecting just those slices as specified by them and also parses
  2155. // archive files. Then for each individual Mach-O file ProcessMachO() is
  2156. // called to process the file based on the command line options.
  2157. void objdump::parseInputMachO(StringRef Filename) {
  2158. if (!ValidateArchFlags())
  2159. return;
  2160. // Attempt to open the binary.
  2161. Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
  2162. if (!BinaryOrErr) {
  2163. if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
  2164. reportError(std::move(E), Filename);
  2165. else
  2166. outs() << Filename << ": is not an object file\n";
  2167. return;
  2168. }
  2169. Binary &Bin = *BinaryOrErr.get().getBinary();
  2170. if (Archive *A = dyn_cast<Archive>(&Bin)) {
  2171. outs() << "Archive : " << Filename << "\n";
  2172. if (ArchiveHeaders)
  2173. printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
  2174. Error Err = Error::success();
  2175. unsigned I = -1;
  2176. for (auto &C : A->children(Err)) {
  2177. ++I;
  2178. Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
  2179. if (!ChildOrErr) {
  2180. if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
  2181. reportError(std::move(E), getFileNameForError(C, I), Filename);
  2182. continue;
  2183. }
  2184. if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
  2185. if (!checkMachOAndArchFlags(O, Filename))
  2186. return;
  2187. ProcessMachO(Filename, O, O->getFileName());
  2188. }
  2189. }
  2190. if (Err)
  2191. reportError(std::move(Err), Filename);
  2192. return;
  2193. }
  2194. if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
  2195. parseInputMachO(UB);
  2196. return;
  2197. }
  2198. if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
  2199. if (!checkMachOAndArchFlags(O, Filename))
  2200. return;
  2201. if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
  2202. ProcessMachO(Filename, MachOOF);
  2203. else
  2204. WithColor::error(errs(), "llvm-objdump")
  2205. << Filename << "': "
  2206. << "object is not a Mach-O file type.\n";
  2207. return;
  2208. }
  2209. llvm_unreachable("Input object can't be invalid at this point");
  2210. }
  2211. void objdump::parseInputMachO(MachOUniversalBinary *UB) {
  2212. if (!ValidateArchFlags())
  2213. return;
  2214. auto Filename = UB->getFileName();
  2215. if (UniversalHeaders)
  2216. printMachOUniversalHeaders(UB, !NonVerbose);
  2217. // If we have a list of architecture flags specified dump only those.
  2218. if (!ArchAll && !ArchFlags.empty()) {
  2219. // Look for a slice in the universal binary that matches each ArchFlag.
  2220. bool ArchFound;
  2221. for (unsigned i = 0; i < ArchFlags.size(); ++i) {
  2222. ArchFound = false;
  2223. for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
  2224. E = UB->end_objects();
  2225. I != E; ++I) {
  2226. if (ArchFlags[i] == I->getArchFlagName()) {
  2227. ArchFound = true;
  2228. Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
  2229. I->getAsObjectFile();
  2230. std::string ArchitectureName;
  2231. if (ArchFlags.size() > 1)
  2232. ArchitectureName = I->getArchFlagName();
  2233. if (ObjOrErr) {
  2234. ObjectFile &O = *ObjOrErr.get();
  2235. if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
  2236. ProcessMachO(Filename, MachOOF, "", ArchitectureName);
  2237. } else if (Error E = isNotObjectErrorInvalidFileType(
  2238. ObjOrErr.takeError())) {
  2239. reportError(std::move(E), "", Filename, ArchitectureName);
  2240. continue;
  2241. } else if (Expected<std::unique_ptr<Archive>> AOrErr =
  2242. I->getAsArchive()) {
  2243. std::unique_ptr<Archive> &A = *AOrErr;
  2244. outs() << "Archive : " << Filename;
  2245. if (!ArchitectureName.empty())
  2246. outs() << " (architecture " << ArchitectureName << ")";
  2247. outs() << "\n";
  2248. if (ArchiveHeaders)
  2249. printArchiveHeaders(Filename, A.get(), !NonVerbose,
  2250. ArchiveMemberOffsets, ArchitectureName);
  2251. Error Err = Error::success();
  2252. unsigned I = -1;
  2253. for (auto &C : A->children(Err)) {
  2254. ++I;
  2255. Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
  2256. if (!ChildOrErr) {
  2257. if (Error E =
  2258. isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
  2259. reportError(std::move(E), getFileNameForError(C, I), Filename,
  2260. ArchitectureName);
  2261. continue;
  2262. }
  2263. if (MachOObjectFile *O =
  2264. dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
  2265. ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
  2266. }
  2267. if (Err)
  2268. reportError(std::move(Err), Filename);
  2269. } else {
  2270. consumeError(AOrErr.takeError());
  2271. reportError(Filename,
  2272. "Mach-O universal file for architecture " +
  2273. StringRef(I->getArchFlagName()) +
  2274. " is not a Mach-O file or an archive file");
  2275. }
  2276. }
  2277. }
  2278. if (!ArchFound) {
  2279. WithColor::error(errs(), "llvm-objdump")
  2280. << "file: " + Filename + " does not contain "
  2281. << "architecture: " + ArchFlags[i] + "\n";
  2282. return;
  2283. }
  2284. }
  2285. return;
  2286. }
  2287. // No architecture flags were specified so if this contains a slice that
  2288. // matches the host architecture dump only that.
  2289. if (!ArchAll) {
  2290. for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
  2291. E = UB->end_objects();
  2292. I != E; ++I) {
  2293. if (MachOObjectFile::getHostArch().getArchName() ==
  2294. I->getArchFlagName()) {
  2295. Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
  2296. std::string ArchiveName;
  2297. ArchiveName.clear();
  2298. if (ObjOrErr) {
  2299. ObjectFile &O = *ObjOrErr.get();
  2300. if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
  2301. ProcessMachO(Filename, MachOOF);
  2302. } else if (Error E =
  2303. isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
  2304. reportError(std::move(E), Filename);
  2305. } else if (Expected<std::unique_ptr<Archive>> AOrErr =
  2306. I->getAsArchive()) {
  2307. std::unique_ptr<Archive> &A = *AOrErr;
  2308. outs() << "Archive : " << Filename << "\n";
  2309. if (ArchiveHeaders)
  2310. printArchiveHeaders(Filename, A.get(), !NonVerbose,
  2311. ArchiveMemberOffsets);
  2312. Error Err = Error::success();
  2313. unsigned I = -1;
  2314. for (auto &C : A->children(Err)) {
  2315. ++I;
  2316. Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
  2317. if (!ChildOrErr) {
  2318. if (Error E =
  2319. isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
  2320. reportError(std::move(E), getFileNameForError(C, I), Filename);
  2321. continue;
  2322. }
  2323. if (MachOObjectFile *O =
  2324. dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
  2325. ProcessMachO(Filename, O, O->getFileName());
  2326. }
  2327. if (Err)
  2328. reportError(std::move(Err), Filename);
  2329. } else {
  2330. consumeError(AOrErr.takeError());
  2331. reportError(Filename, "Mach-O universal file for architecture " +
  2332. StringRef(I->getArchFlagName()) +
  2333. " is not a Mach-O file or an archive file");
  2334. }
  2335. return;
  2336. }
  2337. }
  2338. }
  2339. // Either all architectures have been specified or none have been specified
  2340. // and this does not contain the host architecture so dump all the slices.
  2341. bool moreThanOneArch = UB->getNumberOfObjects() > 1;
  2342. for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
  2343. E = UB->end_objects();
  2344. I != E; ++I) {
  2345. Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
  2346. std::string ArchitectureName;
  2347. if (moreThanOneArch)
  2348. ArchitectureName = I->getArchFlagName();
  2349. if (ObjOrErr) {
  2350. ObjectFile &Obj = *ObjOrErr.get();
  2351. if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
  2352. ProcessMachO(Filename, MachOOF, "", ArchitectureName);
  2353. } else if (Error E =
  2354. isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
  2355. reportError(std::move(E), Filename, "", ArchitectureName);
  2356. } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
  2357. std::unique_ptr<Archive> &A = *AOrErr;
  2358. outs() << "Archive : " << Filename;
  2359. if (!ArchitectureName.empty())
  2360. outs() << " (architecture " << ArchitectureName << ")";
  2361. outs() << "\n";
  2362. if (ArchiveHeaders)
  2363. printArchiveHeaders(Filename, A.get(), !NonVerbose,
  2364. ArchiveMemberOffsets, ArchitectureName);
  2365. Error Err = Error::success();
  2366. unsigned I = -1;
  2367. for (auto &C : A->children(Err)) {
  2368. ++I;
  2369. Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
  2370. if (!ChildOrErr) {
  2371. if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
  2372. reportError(std::move(E), getFileNameForError(C, I), Filename,
  2373. ArchitectureName);
  2374. continue;
  2375. }
  2376. if (MachOObjectFile *O =
  2377. dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
  2378. if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
  2379. ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
  2380. ArchitectureName);
  2381. }
  2382. }
  2383. if (Err)
  2384. reportError(std::move(Err), Filename);
  2385. } else {
  2386. consumeError(AOrErr.takeError());
  2387. reportError(Filename, "Mach-O universal file for architecture " +
  2388. StringRef(I->getArchFlagName()) +
  2389. " is not a Mach-O file or an archive file");
  2390. }
  2391. }
  2392. }
  2393. namespace {
  2394. // The block of info used by the Symbolizer call backs.
  2395. struct DisassembleInfo {
  2396. DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
  2397. std::vector<SectionRef> *Sections, bool verbose)
  2398. : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
  2399. bool verbose;
  2400. MachOObjectFile *O;
  2401. SectionRef S;
  2402. SymbolAddressMap *AddrMap;
  2403. std::vector<SectionRef> *Sections;
  2404. const char *class_name = nullptr;
  2405. const char *selector_name = nullptr;
  2406. std::unique_ptr<char[]> method = nullptr;
  2407. char *demangled_name = nullptr;
  2408. uint64_t adrp_addr = 0;
  2409. uint32_t adrp_inst = 0;
  2410. std::unique_ptr<SymbolAddressMap> bindtable;
  2411. uint32_t depth = 0;
  2412. };
  2413. } // namespace
  2414. // SymbolizerGetOpInfo() is the operand information call back function.
  2415. // This is called to get the symbolic information for operand(s) of an
  2416. // instruction when it is being done. This routine does this from
  2417. // the relocation information, symbol table, etc. That block of information
  2418. // is a pointer to the struct DisassembleInfo that was passed when the
  2419. // disassembler context was created and passed to back to here when
  2420. // called back by the disassembler for instruction operands that could have
  2421. // relocation information. The address of the instruction containing operand is
  2422. // at the Pc parameter. The immediate value the operand has is passed in
  2423. // op_info->Value and is at Offset past the start of the instruction and has a
  2424. // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
  2425. // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
  2426. // names and addends of the symbolic expression to add for the operand. The
  2427. // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
  2428. // information is returned then this function returns 1 else it returns 0.
  2429. static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
  2430. uint64_t Size, int TagType, void *TagBuf) {
  2431. struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
  2432. struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
  2433. uint64_t value = op_info->Value;
  2434. // Make sure all fields returned are zero if we don't set them.
  2435. memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
  2436. op_info->Value = value;
  2437. // If the TagType is not the value 1 which it code knows about or if no
  2438. // verbose symbolic information is wanted then just return 0, indicating no
  2439. // information is being returned.
  2440. if (TagType != 1 || !info->verbose)
  2441. return 0;
  2442. unsigned int Arch = info->O->getArch();
  2443. if (Arch == Triple::x86) {
  2444. if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
  2445. return 0;
  2446. if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
  2447. // TODO:
  2448. // Search the external relocation entries of a fully linked image
  2449. // (if any) for an entry that matches this segment offset.
  2450. // uint32_t seg_offset = (Pc + Offset);
  2451. return 0;
  2452. }
  2453. // In MH_OBJECT filetypes search the section's relocation entries (if any)
  2454. // for an entry for this section offset.
  2455. uint32_t sect_addr = info->S.getAddress();
  2456. uint32_t sect_offset = (Pc + Offset) - sect_addr;
  2457. bool reloc_found = false;
  2458. DataRefImpl Rel;
  2459. MachO::any_relocation_info RE;
  2460. bool isExtern = false;
  2461. SymbolRef Symbol;
  2462. bool r_scattered = false;
  2463. uint32_t r_value, pair_r_value, r_type;
  2464. for (const RelocationRef &Reloc : info->S.relocations()) {
  2465. uint64_t RelocOffset = Reloc.getOffset();
  2466. if (RelocOffset == sect_offset) {
  2467. Rel = Reloc.getRawDataRefImpl();
  2468. RE = info->O->getRelocation(Rel);
  2469. r_type = info->O->getAnyRelocationType(RE);
  2470. r_scattered = info->O->isRelocationScattered(RE);
  2471. if (r_scattered) {
  2472. r_value = info->O->getScatteredRelocationValue(RE);
  2473. if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
  2474. r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
  2475. DataRefImpl RelNext = Rel;
  2476. info->O->moveRelocationNext(RelNext);
  2477. MachO::any_relocation_info RENext;
  2478. RENext = info->O->getRelocation(RelNext);
  2479. if (info->O->isRelocationScattered(RENext))
  2480. pair_r_value = info->O->getScatteredRelocationValue(RENext);
  2481. else
  2482. return 0;
  2483. }
  2484. } else {
  2485. isExtern = info->O->getPlainRelocationExternal(RE);
  2486. if (isExtern) {
  2487. symbol_iterator RelocSym = Reloc.getSymbol();
  2488. Symbol = *RelocSym;
  2489. }
  2490. }
  2491. reloc_found = true;
  2492. break;
  2493. }
  2494. }
  2495. if (reloc_found && isExtern) {
  2496. op_info->AddSymbol.Present = 1;
  2497. op_info->AddSymbol.Name =
  2498. unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
  2499. // For i386 extern relocation entries the value in the instruction is
  2500. // the offset from the symbol, and value is already set in op_info->Value.
  2501. return 1;
  2502. }
  2503. if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
  2504. r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
  2505. const char *add = GuessSymbolName(r_value, info->AddrMap);
  2506. const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
  2507. uint32_t offset = value - (r_value - pair_r_value);
  2508. op_info->AddSymbol.Present = 1;
  2509. if (add != nullptr)
  2510. op_info->AddSymbol.Name = add;
  2511. else
  2512. op_info->AddSymbol.Value = r_value;
  2513. op_info->SubtractSymbol.Present = 1;
  2514. if (sub != nullptr)
  2515. op_info->SubtractSymbol.Name = sub;
  2516. else
  2517. op_info->SubtractSymbol.Value = pair_r_value;
  2518. op_info->Value = offset;
  2519. return 1;
  2520. }
  2521. return 0;
  2522. }
  2523. if (Arch == Triple::x86_64) {
  2524. if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
  2525. return 0;
  2526. // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
  2527. // relocation entries of a linked image (if any) for an entry that matches
  2528. // this segment offset.
  2529. if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
  2530. uint64_t seg_offset = Pc + Offset;
  2531. bool reloc_found = false;
  2532. DataRefImpl Rel;
  2533. MachO::any_relocation_info RE;
  2534. bool isExtern = false;
  2535. SymbolRef Symbol;
  2536. for (const RelocationRef &Reloc : info->O->external_relocations()) {
  2537. uint64_t RelocOffset = Reloc.getOffset();
  2538. if (RelocOffset == seg_offset) {
  2539. Rel = Reloc.getRawDataRefImpl();
  2540. RE = info->O->getRelocation(Rel);
  2541. // external relocation entries should always be external.
  2542. isExtern = info->O->getPlainRelocationExternal(RE);
  2543. if (isExtern) {
  2544. symbol_iterator RelocSym = Reloc.getSymbol();
  2545. Symbol = *RelocSym;
  2546. }
  2547. reloc_found = true;
  2548. break;
  2549. }
  2550. }
  2551. if (reloc_found && isExtern) {
  2552. // The Value passed in will be adjusted by the Pc if the instruction
  2553. // adds the Pc. But for x86_64 external relocation entries the Value
  2554. // is the offset from the external symbol.
  2555. if (info->O->getAnyRelocationPCRel(RE))
  2556. op_info->Value -= Pc + Offset + Size;
  2557. const char *name =
  2558. unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
  2559. op_info->AddSymbol.Present = 1;
  2560. op_info->AddSymbol.Name = name;
  2561. return 1;
  2562. }
  2563. return 0;
  2564. }
  2565. // In MH_OBJECT filetypes search the section's relocation entries (if any)
  2566. // for an entry for this section offset.
  2567. uint64_t sect_addr = info->S.getAddress();
  2568. uint64_t sect_offset = (Pc + Offset) - sect_addr;
  2569. bool reloc_found = false;
  2570. DataRefImpl Rel;
  2571. MachO::any_relocation_info RE;
  2572. bool isExtern = false;
  2573. SymbolRef Symbol;
  2574. for (const RelocationRef &Reloc : info->S.relocations()) {
  2575. uint64_t RelocOffset = Reloc.getOffset();
  2576. if (RelocOffset == sect_offset) {
  2577. Rel = Reloc.getRawDataRefImpl();
  2578. RE = info->O->getRelocation(Rel);
  2579. // NOTE: Scattered relocations don't exist on x86_64.
  2580. isExtern = info->O->getPlainRelocationExternal(RE);
  2581. if (isExtern) {
  2582. symbol_iterator RelocSym = Reloc.getSymbol();
  2583. Symbol = *RelocSym;
  2584. }
  2585. reloc_found = true;
  2586. break;
  2587. }
  2588. }
  2589. if (reloc_found && isExtern) {
  2590. // The Value passed in will be adjusted by the Pc if the instruction
  2591. // adds the Pc. But for x86_64 external relocation entries the Value
  2592. // is the offset from the external symbol.
  2593. if (info->O->getAnyRelocationPCRel(RE))
  2594. op_info->Value -= Pc + Offset + Size;
  2595. const char *name =
  2596. unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
  2597. unsigned Type = info->O->getAnyRelocationType(RE);
  2598. if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
  2599. DataRefImpl RelNext = Rel;
  2600. info->O->moveRelocationNext(RelNext);
  2601. MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
  2602. unsigned TypeNext = info->O->getAnyRelocationType(RENext);
  2603. bool isExternNext = info->O->getPlainRelocationExternal(RENext);
  2604. unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
  2605. if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
  2606. op_info->SubtractSymbol.Present = 1;
  2607. op_info->SubtractSymbol.Name = name;
  2608. symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
  2609. Symbol = *RelocSymNext;
  2610. name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
  2611. }
  2612. }
  2613. // TODO: add the VariantKinds to op_info->VariantKind for relocation types
  2614. // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
  2615. op_info->AddSymbol.Present = 1;
  2616. op_info->AddSymbol.Name = name;
  2617. return 1;
  2618. }
  2619. return 0;
  2620. }
  2621. if (Arch == Triple::arm) {
  2622. if (Offset != 0 || (Size != 4 && Size != 2))
  2623. return 0;
  2624. if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
  2625. // TODO:
  2626. // Search the external relocation entries of a fully linked image
  2627. // (if any) for an entry that matches this segment offset.
  2628. // uint32_t seg_offset = (Pc + Offset);
  2629. return 0;
  2630. }
  2631. // In MH_OBJECT filetypes search the section's relocation entries (if any)
  2632. // for an entry for this section offset.
  2633. uint32_t sect_addr = info->S.getAddress();
  2634. uint32_t sect_offset = (Pc + Offset) - sect_addr;
  2635. DataRefImpl Rel;
  2636. MachO::any_relocation_info RE;
  2637. bool isExtern = false;
  2638. SymbolRef Symbol;
  2639. bool r_scattered = false;
  2640. uint32_t r_value, pair_r_value, r_type, r_length, other_half;
  2641. auto Reloc =
  2642. find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
  2643. uint64_t RelocOffset = Reloc.getOffset();
  2644. return RelocOffset == sect_offset;
  2645. });
  2646. if (Reloc == info->S.relocations().end())
  2647. return 0;
  2648. Rel = Reloc->getRawDataRefImpl();
  2649. RE = info->O->getRelocation(Rel);
  2650. r_length = info->O->getAnyRelocationLength(RE);
  2651. r_scattered = info->O->isRelocationScattered(RE);
  2652. if (r_scattered) {
  2653. r_value = info->O->getScatteredRelocationValue(RE);
  2654. r_type = info->O->getScatteredRelocationType(RE);
  2655. } else {
  2656. r_type = info->O->getAnyRelocationType(RE);
  2657. isExtern = info->O->getPlainRelocationExternal(RE);
  2658. if (isExtern) {
  2659. symbol_iterator RelocSym = Reloc->getSymbol();
  2660. Symbol = *RelocSym;
  2661. }
  2662. }
  2663. if (r_type == MachO::ARM_RELOC_HALF ||
  2664. r_type == MachO::ARM_RELOC_SECTDIFF ||
  2665. r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
  2666. r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
  2667. DataRefImpl RelNext = Rel;
  2668. info->O->moveRelocationNext(RelNext);
  2669. MachO::any_relocation_info RENext;
  2670. RENext = info->O->getRelocation(RelNext);
  2671. other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
  2672. if (info->O->isRelocationScattered(RENext))
  2673. pair_r_value = info->O->getScatteredRelocationValue(RENext);
  2674. }
  2675. if (isExtern) {
  2676. const char *name =
  2677. unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
  2678. op_info->AddSymbol.Present = 1;
  2679. op_info->AddSymbol.Name = name;
  2680. switch (r_type) {
  2681. case MachO::ARM_RELOC_HALF:
  2682. if ((r_length & 0x1) == 1) {
  2683. op_info->Value = value << 16 | other_half;
  2684. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
  2685. } else {
  2686. op_info->Value = other_half << 16 | value;
  2687. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
  2688. }
  2689. break;
  2690. default:
  2691. break;
  2692. }
  2693. return 1;
  2694. }
  2695. // If we have a branch that is not an external relocation entry then
  2696. // return 0 so the code in tryAddingSymbolicOperand() can use the
  2697. // SymbolLookUp call back with the branch target address to look up the
  2698. // symbol and possibility add an annotation for a symbol stub.
  2699. if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
  2700. r_type == MachO::ARM_THUMB_RELOC_BR22))
  2701. return 0;
  2702. uint32_t offset = 0;
  2703. if (r_type == MachO::ARM_RELOC_HALF ||
  2704. r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
  2705. if ((r_length & 0x1) == 1)
  2706. value = value << 16 | other_half;
  2707. else
  2708. value = other_half << 16 | value;
  2709. }
  2710. if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
  2711. r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
  2712. offset = value - r_value;
  2713. value = r_value;
  2714. }
  2715. if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
  2716. if ((r_length & 0x1) == 1)
  2717. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
  2718. else
  2719. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
  2720. const char *add = GuessSymbolName(r_value, info->AddrMap);
  2721. const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
  2722. int32_t offset = value - (r_value - pair_r_value);
  2723. op_info->AddSymbol.Present = 1;
  2724. if (add != nullptr)
  2725. op_info->AddSymbol.Name = add;
  2726. else
  2727. op_info->AddSymbol.Value = r_value;
  2728. op_info->SubtractSymbol.Present = 1;
  2729. if (sub != nullptr)
  2730. op_info->SubtractSymbol.Name = sub;
  2731. else
  2732. op_info->SubtractSymbol.Value = pair_r_value;
  2733. op_info->Value = offset;
  2734. return 1;
  2735. }
  2736. op_info->AddSymbol.Present = 1;
  2737. op_info->Value = offset;
  2738. if (r_type == MachO::ARM_RELOC_HALF) {
  2739. if ((r_length & 0x1) == 1)
  2740. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
  2741. else
  2742. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
  2743. }
  2744. const char *add = GuessSymbolName(value, info->AddrMap);
  2745. if (add != nullptr) {
  2746. op_info->AddSymbol.Name = add;
  2747. return 1;
  2748. }
  2749. op_info->AddSymbol.Value = value;
  2750. return 1;
  2751. }
  2752. if (Arch == Triple::aarch64) {
  2753. if (Offset != 0 || Size != 4)
  2754. return 0;
  2755. if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
  2756. // TODO:
  2757. // Search the external relocation entries of a fully linked image
  2758. // (if any) for an entry that matches this segment offset.
  2759. // uint64_t seg_offset = (Pc + Offset);
  2760. return 0;
  2761. }
  2762. // In MH_OBJECT filetypes search the section's relocation entries (if any)
  2763. // for an entry for this section offset.
  2764. uint64_t sect_addr = info->S.getAddress();
  2765. uint64_t sect_offset = (Pc + Offset) - sect_addr;
  2766. auto Reloc =
  2767. find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
  2768. uint64_t RelocOffset = Reloc.getOffset();
  2769. return RelocOffset == sect_offset;
  2770. });
  2771. if (Reloc == info->S.relocations().end())
  2772. return 0;
  2773. DataRefImpl Rel = Reloc->getRawDataRefImpl();
  2774. MachO::any_relocation_info RE = info->O->getRelocation(Rel);
  2775. uint32_t r_type = info->O->getAnyRelocationType(RE);
  2776. if (r_type == MachO::ARM64_RELOC_ADDEND) {
  2777. DataRefImpl RelNext = Rel;
  2778. info->O->moveRelocationNext(RelNext);
  2779. MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
  2780. if (value == 0) {
  2781. value = info->O->getPlainRelocationSymbolNum(RENext);
  2782. op_info->Value = value;
  2783. }
  2784. }
  2785. // NOTE: Scattered relocations don't exist on arm64.
  2786. if (!info->O->getPlainRelocationExternal(RE))
  2787. return 0;
  2788. const char *name =
  2789. unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
  2790. .data();
  2791. op_info->AddSymbol.Present = 1;
  2792. op_info->AddSymbol.Name = name;
  2793. switch (r_type) {
  2794. case MachO::ARM64_RELOC_PAGE21:
  2795. /* @page */
  2796. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
  2797. break;
  2798. case MachO::ARM64_RELOC_PAGEOFF12:
  2799. /* @pageoff */
  2800. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
  2801. break;
  2802. case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
  2803. /* @gotpage */
  2804. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
  2805. break;
  2806. case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
  2807. /* @gotpageoff */
  2808. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
  2809. break;
  2810. case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
  2811. /* @tvlppage is not implemented in llvm-mc */
  2812. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
  2813. break;
  2814. case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
  2815. /* @tvlppageoff is not implemented in llvm-mc */
  2816. op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
  2817. break;
  2818. default:
  2819. case MachO::ARM64_RELOC_BRANCH26:
  2820. op_info->VariantKind = LLVMDisassembler_VariantKind_None;
  2821. break;
  2822. }
  2823. return 1;
  2824. }
  2825. return 0;
  2826. }
  2827. // GuessCstringPointer is passed the address of what might be a pointer to a
  2828. // literal string in a cstring section. If that address is in a cstring section
  2829. // it returns a pointer to that string. Else it returns nullptr.
  2830. static const char *GuessCstringPointer(uint64_t ReferenceValue,
  2831. struct DisassembleInfo *info) {
  2832. for (const auto &Load : info->O->load_commands()) {
  2833. if (Load.C.cmd == MachO::LC_SEGMENT_64) {
  2834. MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
  2835. for (unsigned J = 0; J < Seg.nsects; ++J) {
  2836. MachO::section_64 Sec = info->O->getSection64(Load, J);
  2837. uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
  2838. if (section_type == MachO::S_CSTRING_LITERALS &&
  2839. ReferenceValue >= Sec.addr &&
  2840. ReferenceValue < Sec.addr + Sec.size) {
  2841. uint64_t sect_offset = ReferenceValue - Sec.addr;
  2842. uint64_t object_offset = Sec.offset + sect_offset;
  2843. StringRef MachOContents = info->O->getData();
  2844. uint64_t object_size = MachOContents.size();
  2845. const char *object_addr = (const char *)MachOContents.data();
  2846. if (object_offset < object_size) {
  2847. const char *name = object_addr + object_offset;
  2848. return name;
  2849. } else {
  2850. return nullptr;
  2851. }
  2852. }
  2853. }
  2854. } else if (Load.C.cmd == MachO::LC_SEGMENT) {
  2855. MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
  2856. for (unsigned J = 0; J < Seg.nsects; ++J) {
  2857. MachO::section Sec = info->O->getSection(Load, J);
  2858. uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
  2859. if (section_type == MachO::S_CSTRING_LITERALS &&
  2860. ReferenceValue >= Sec.addr &&
  2861. ReferenceValue < Sec.addr + Sec.size) {
  2862. uint64_t sect_offset = ReferenceValue - Sec.addr;
  2863. uint64_t object_offset = Sec.offset + sect_offset;
  2864. StringRef MachOContents = info->O->getData();
  2865. uint64_t object_size = MachOContents.size();
  2866. const char *object_addr = (const char *)MachOContents.data();
  2867. if (object_offset < object_size) {
  2868. const char *name = object_addr + object_offset;
  2869. return name;
  2870. } else {
  2871. return nullptr;
  2872. }
  2873. }
  2874. }
  2875. }
  2876. }
  2877. return nullptr;
  2878. }
  2879. // GuessIndirectSymbol returns the name of the indirect symbol for the
  2880. // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
  2881. // an address of a symbol stub or a lazy or non-lazy pointer to associate the
  2882. // symbol name being referenced by the stub or pointer.
  2883. static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
  2884. struct DisassembleInfo *info) {
  2885. MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
  2886. MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
  2887. for (const auto &Load : info->O->load_commands()) {
  2888. if (Load.C.cmd == MachO::LC_SEGMENT_64) {
  2889. MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
  2890. for (unsigned J = 0; J < Seg.nsects; ++J) {
  2891. MachO::section_64 Sec = info->O->getSection64(Load, J);
  2892. uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
  2893. if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
  2894. section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
  2895. section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
  2896. section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
  2897. section_type == MachO::S_SYMBOL_STUBS) &&
  2898. ReferenceValue >= Sec.addr &&
  2899. ReferenceValue < Sec.addr + Sec.size) {
  2900. uint32_t stride;
  2901. if (section_type == MachO::S_SYMBOL_STUBS)
  2902. stride = Sec.reserved2;
  2903. else
  2904. stride = 8;
  2905. if (stride == 0)
  2906. return nullptr;
  2907. uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
  2908. if (index < Dysymtab.nindirectsyms) {
  2909. uint32_t indirect_symbol =
  2910. info->O->getIndirectSymbolTableEntry(Dysymtab, index);
  2911. if (indirect_symbol < Symtab.nsyms) {
  2912. symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
  2913. return unwrapOrError(Sym->getName(), info->O->getFileName())
  2914. .data();
  2915. }
  2916. }
  2917. }
  2918. }
  2919. } else if (Load.C.cmd == MachO::LC_SEGMENT) {
  2920. MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
  2921. for (unsigned J = 0; J < Seg.nsects; ++J) {
  2922. MachO::section Sec = info->O->getSection(Load, J);
  2923. uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
  2924. if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
  2925. section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
  2926. section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
  2927. section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
  2928. section_type == MachO::S_SYMBOL_STUBS) &&
  2929. ReferenceValue >= Sec.addr &&
  2930. ReferenceValue < Sec.addr + Sec.size) {
  2931. uint32_t stride;
  2932. if (section_type == MachO::S_SYMBOL_STUBS)
  2933. stride = Sec.reserved2;
  2934. else
  2935. stride = 4;
  2936. if (stride == 0)
  2937. return nullptr;
  2938. uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
  2939. if (index < Dysymtab.nindirectsyms) {
  2940. uint32_t indirect_symbol =
  2941. info->O->getIndirectSymbolTableEntry(Dysymtab, index);
  2942. if (indirect_symbol < Symtab.nsyms) {
  2943. symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
  2944. return unwrapOrError(Sym->getName(), info->O->getFileName())
  2945. .data();
  2946. }
  2947. }
  2948. }
  2949. }
  2950. }
  2951. }
  2952. return nullptr;
  2953. }
  2954. // method_reference() is called passing it the ReferenceName that might be
  2955. // a reference it to an Objective-C method call. If so then it allocates and
  2956. // assembles a method call string with the values last seen and saved in
  2957. // the DisassembleInfo's class_name and selector_name fields. This is saved
  2958. // into the method field of the info and any previous string is free'ed.
  2959. // Then the class_name field in the info is set to nullptr. The method call
  2960. // string is set into ReferenceName and ReferenceType is set to
  2961. // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
  2962. // then both ReferenceType and ReferenceName are left unchanged.
  2963. static void method_reference(struct DisassembleInfo *info,
  2964. uint64_t *ReferenceType,
  2965. const char **ReferenceName) {
  2966. unsigned int Arch = info->O->getArch();
  2967. if (*ReferenceName != nullptr) {
  2968. if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
  2969. if (info->selector_name != nullptr) {
  2970. if (info->class_name != nullptr) {
  2971. info->method = std::make_unique<char[]>(
  2972. 5 + strlen(info->class_name) + strlen(info->selector_name));
  2973. char *method = info->method.get();
  2974. if (method != nullptr) {
  2975. strcpy(method, "+[");
  2976. strcat(method, info->class_name);
  2977. strcat(method, " ");
  2978. strcat(method, info->selector_name);
  2979. strcat(method, "]");
  2980. *ReferenceName = method;
  2981. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
  2982. }
  2983. } else {
  2984. info->method =
  2985. std::make_unique<char[]>(9 + strlen(info->selector_name));
  2986. char *method = info->method.get();
  2987. if (method != nullptr) {
  2988. if (Arch == Triple::x86_64)
  2989. strcpy(method, "-[%rdi ");
  2990. else if (Arch == Triple::aarch64)
  2991. strcpy(method, "-[x0 ");
  2992. else
  2993. strcpy(method, "-[r? ");
  2994. strcat(method, info->selector_name);
  2995. strcat(method, "]");
  2996. *ReferenceName = method;
  2997. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
  2998. }
  2999. }
  3000. info->class_name = nullptr;
  3001. }
  3002. } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
  3003. if (info->selector_name != nullptr) {
  3004. info->method =
  3005. std::make_unique<char[]>(17 + strlen(info->selector_name));
  3006. char *method = info->method.get();
  3007. if (method != nullptr) {
  3008. if (Arch == Triple::x86_64)
  3009. strcpy(method, "-[[%rdi super] ");
  3010. else if (Arch == Triple::aarch64)
  3011. strcpy(method, "-[[x0 super] ");
  3012. else
  3013. strcpy(method, "-[[r? super] ");
  3014. strcat(method, info->selector_name);
  3015. strcat(method, "]");
  3016. *ReferenceName = method;
  3017. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
  3018. }
  3019. info->class_name = nullptr;
  3020. }
  3021. }
  3022. }
  3023. }
  3024. // GuessPointerPointer() is passed the address of what might be a pointer to
  3025. // a reference to an Objective-C class, selector, message ref or cfstring.
  3026. // If so the value of the pointer is returned and one of the booleans are set
  3027. // to true. If not zero is returned and all the booleans are set to false.
  3028. static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
  3029. struct DisassembleInfo *info,
  3030. bool &classref, bool &selref, bool &msgref,
  3031. bool &cfstring) {
  3032. classref = false;
  3033. selref = false;
  3034. msgref = false;
  3035. cfstring = false;
  3036. for (const auto &Load : info->O->load_commands()) {
  3037. if (Load.C.cmd == MachO::LC_SEGMENT_64) {
  3038. MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
  3039. for (unsigned J = 0; J < Seg.nsects; ++J) {
  3040. MachO::section_64 Sec = info->O->getSection64(Load, J);
  3041. if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
  3042. strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
  3043. strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
  3044. strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
  3045. strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
  3046. ReferenceValue >= Sec.addr &&
  3047. ReferenceValue < Sec.addr + Sec.size) {
  3048. uint64_t sect_offset = ReferenceValue - Sec.addr;
  3049. uint64_t object_offset = Sec.offset + sect_offset;
  3050. StringRef MachOContents = info->O->getData();
  3051. uint64_t object_size = MachOContents.size();
  3052. const char *object_addr = (const char *)MachOContents.data();
  3053. if (object_offset < object_size) {
  3054. uint64_t pointer_value;
  3055. memcpy(&pointer_value, object_addr + object_offset,
  3056. sizeof(uint64_t));
  3057. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3058. sys::swapByteOrder(pointer_value);
  3059. if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
  3060. selref = true;
  3061. else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
  3062. strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
  3063. classref = true;
  3064. else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
  3065. ReferenceValue + 8 < Sec.addr + Sec.size) {
  3066. msgref = true;
  3067. memcpy(&pointer_value, object_addr + object_offset + 8,
  3068. sizeof(uint64_t));
  3069. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3070. sys::swapByteOrder(pointer_value);
  3071. } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
  3072. cfstring = true;
  3073. return pointer_value;
  3074. } else {
  3075. return 0;
  3076. }
  3077. }
  3078. }
  3079. }
  3080. // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
  3081. }
  3082. return 0;
  3083. }
  3084. // get_pointer_64 returns a pointer to the bytes in the object file at the
  3085. // Address from a section in the Mach-O file. And indirectly returns the
  3086. // offset into the section, number of bytes left in the section past the offset
  3087. // and which section is was being referenced. If the Address is not in a
  3088. // section nullptr is returned.
  3089. static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
  3090. uint32_t &left, SectionRef &S,
  3091. DisassembleInfo *info,
  3092. bool objc_only = false) {
  3093. offset = 0;
  3094. left = 0;
  3095. S = SectionRef();
  3096. for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
  3097. uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
  3098. uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
  3099. if (SectSize == 0)
  3100. continue;
  3101. if (objc_only) {
  3102. StringRef SectName;
  3103. Expected<StringRef> SecNameOrErr =
  3104. ((*(info->Sections))[SectIdx]).getName();
  3105. if (SecNameOrErr)
  3106. SectName = *SecNameOrErr;
  3107. else
  3108. consumeError(SecNameOrErr.takeError());
  3109. DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
  3110. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  3111. if (SegName != "__OBJC" && SectName != "__cstring")
  3112. continue;
  3113. }
  3114. if (Address >= SectAddress && Address < SectAddress + SectSize) {
  3115. S = (*(info->Sections))[SectIdx];
  3116. offset = Address - SectAddress;
  3117. left = SectSize - offset;
  3118. StringRef SectContents = unwrapOrError(
  3119. ((*(info->Sections))[SectIdx]).getContents(), info->O->getFileName());
  3120. return SectContents.data() + offset;
  3121. }
  3122. }
  3123. return nullptr;
  3124. }
  3125. static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
  3126. uint32_t &left, SectionRef &S,
  3127. DisassembleInfo *info,
  3128. bool objc_only = false) {
  3129. return get_pointer_64(Address, offset, left, S, info, objc_only);
  3130. }
  3131. // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
  3132. // the symbol indirectly through n_value. Based on the relocation information
  3133. // for the specified section offset in the specified section reference.
  3134. // If no relocation information is found and a non-zero ReferenceValue for the
  3135. // symbol is passed, look up that address in the info's AddrMap.
  3136. static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
  3137. DisassembleInfo *info, uint64_t &n_value,
  3138. uint64_t ReferenceValue = 0) {
  3139. n_value = 0;
  3140. if (!info->verbose)
  3141. return nullptr;
  3142. // See if there is an external relocation entry at the sect_offset.
  3143. bool reloc_found = false;
  3144. DataRefImpl Rel;
  3145. MachO::any_relocation_info RE;
  3146. bool isExtern = false;
  3147. SymbolRef Symbol;
  3148. for (const RelocationRef &Reloc : S.relocations()) {
  3149. uint64_t RelocOffset = Reloc.getOffset();
  3150. if (RelocOffset == sect_offset) {
  3151. Rel = Reloc.getRawDataRefImpl();
  3152. RE = info->O->getRelocation(Rel);
  3153. if (info->O->isRelocationScattered(RE))
  3154. continue;
  3155. isExtern = info->O->getPlainRelocationExternal(RE);
  3156. if (isExtern) {
  3157. symbol_iterator RelocSym = Reloc.getSymbol();
  3158. Symbol = *RelocSym;
  3159. }
  3160. reloc_found = true;
  3161. break;
  3162. }
  3163. }
  3164. // If there is an external relocation entry for a symbol in this section
  3165. // at this section_offset then use that symbol's value for the n_value
  3166. // and return its name.
  3167. const char *SymbolName = nullptr;
  3168. if (reloc_found && isExtern) {
  3169. n_value = cantFail(Symbol.getValue());
  3170. StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
  3171. if (!Name.empty()) {
  3172. SymbolName = Name.data();
  3173. return SymbolName;
  3174. }
  3175. }
  3176. // TODO: For fully linked images, look through the external relocation
  3177. // entries off the dynamic symtab command. For these the r_offset is from the
  3178. // start of the first writeable segment in the Mach-O file. So the offset
  3179. // to this section from that segment is passed to this routine by the caller,
  3180. // as the database_offset. Which is the difference of the section's starting
  3181. // address and the first writable segment.
  3182. //
  3183. // NOTE: need add passing the database_offset to this routine.
  3184. // We did not find an external relocation entry so look up the ReferenceValue
  3185. // as an address of a symbol and if found return that symbol's name.
  3186. SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
  3187. return SymbolName;
  3188. }
  3189. static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
  3190. DisassembleInfo *info,
  3191. uint32_t ReferenceValue) {
  3192. uint64_t n_value64;
  3193. return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
  3194. }
  3195. namespace {
  3196. // These are structs in the Objective-C meta data and read to produce the
  3197. // comments for disassembly. While these are part of the ABI they are no
  3198. // public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
  3199. // .
  3200. // The cfstring object in a 64-bit Mach-O file.
  3201. struct cfstring64_t {
  3202. uint64_t isa; // class64_t * (64-bit pointer)
  3203. uint64_t flags; // flag bits
  3204. uint64_t characters; // char * (64-bit pointer)
  3205. uint64_t length; // number of non-NULL characters in above
  3206. };
  3207. // The class object in a 64-bit Mach-O file.
  3208. struct class64_t {
  3209. uint64_t isa; // class64_t * (64-bit pointer)
  3210. uint64_t superclass; // class64_t * (64-bit pointer)
  3211. uint64_t cache; // Cache (64-bit pointer)
  3212. uint64_t vtable; // IMP * (64-bit pointer)
  3213. uint64_t data; // class_ro64_t * (64-bit pointer)
  3214. };
  3215. struct class32_t {
  3216. uint32_t isa; /* class32_t * (32-bit pointer) */
  3217. uint32_t superclass; /* class32_t * (32-bit pointer) */
  3218. uint32_t cache; /* Cache (32-bit pointer) */
  3219. uint32_t vtable; /* IMP * (32-bit pointer) */
  3220. uint32_t data; /* class_ro32_t * (32-bit pointer) */
  3221. };
  3222. struct class_ro64_t {
  3223. uint32_t flags;
  3224. uint32_t instanceStart;
  3225. uint32_t instanceSize;
  3226. uint32_t reserved;
  3227. uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
  3228. uint64_t name; // const char * (64-bit pointer)
  3229. uint64_t baseMethods; // const method_list_t * (64-bit pointer)
  3230. uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
  3231. uint64_t ivars; // const ivar_list_t * (64-bit pointer)
  3232. uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
  3233. uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
  3234. };
  3235. struct class_ro32_t {
  3236. uint32_t flags;
  3237. uint32_t instanceStart;
  3238. uint32_t instanceSize;
  3239. uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
  3240. uint32_t name; /* const char * (32-bit pointer) */
  3241. uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
  3242. uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
  3243. uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
  3244. uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
  3245. uint32_t baseProperties; /* const struct objc_property_list *
  3246. (32-bit pointer) */
  3247. };
  3248. /* Values for class_ro{64,32}_t->flags */
  3249. #define RO_META (1 << 0)
  3250. #define RO_ROOT (1 << 1)
  3251. #define RO_HAS_CXX_STRUCTORS (1 << 2)
  3252. struct method_list64_t {
  3253. uint32_t entsize;
  3254. uint32_t count;
  3255. /* struct method64_t first; These structures follow inline */
  3256. };
  3257. struct method_list32_t {
  3258. uint32_t entsize;
  3259. uint32_t count;
  3260. /* struct method32_t first; These structures follow inline */
  3261. };
  3262. struct method64_t {
  3263. uint64_t name; /* SEL (64-bit pointer) */
  3264. uint64_t types; /* const char * (64-bit pointer) */
  3265. uint64_t imp; /* IMP (64-bit pointer) */
  3266. };
  3267. struct method32_t {
  3268. uint32_t name; /* SEL (32-bit pointer) */
  3269. uint32_t types; /* const char * (32-bit pointer) */
  3270. uint32_t imp; /* IMP (32-bit pointer) */
  3271. };
  3272. struct protocol_list64_t {
  3273. uint64_t count; /* uintptr_t (a 64-bit value) */
  3274. /* struct protocol64_t * list[0]; These pointers follow inline */
  3275. };
  3276. struct protocol_list32_t {
  3277. uint32_t count; /* uintptr_t (a 32-bit value) */
  3278. /* struct protocol32_t * list[0]; These pointers follow inline */
  3279. };
  3280. struct protocol64_t {
  3281. uint64_t isa; /* id * (64-bit pointer) */
  3282. uint64_t name; /* const char * (64-bit pointer) */
  3283. uint64_t protocols; /* struct protocol_list64_t *
  3284. (64-bit pointer) */
  3285. uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
  3286. uint64_t classMethods; /* method_list_t * (64-bit pointer) */
  3287. uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
  3288. uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
  3289. uint64_t instanceProperties; /* struct objc_property_list *
  3290. (64-bit pointer) */
  3291. };
  3292. struct protocol32_t {
  3293. uint32_t isa; /* id * (32-bit pointer) */
  3294. uint32_t name; /* const char * (32-bit pointer) */
  3295. uint32_t protocols; /* struct protocol_list_t *
  3296. (32-bit pointer) */
  3297. uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
  3298. uint32_t classMethods; /* method_list_t * (32-bit pointer) */
  3299. uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
  3300. uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
  3301. uint32_t instanceProperties; /* struct objc_property_list *
  3302. (32-bit pointer) */
  3303. };
  3304. struct ivar_list64_t {
  3305. uint32_t entsize;
  3306. uint32_t count;
  3307. /* struct ivar64_t first; These structures follow inline */
  3308. };
  3309. struct ivar_list32_t {
  3310. uint32_t entsize;
  3311. uint32_t count;
  3312. /* struct ivar32_t first; These structures follow inline */
  3313. };
  3314. struct ivar64_t {
  3315. uint64_t offset; /* uintptr_t * (64-bit pointer) */
  3316. uint64_t name; /* const char * (64-bit pointer) */
  3317. uint64_t type; /* const char * (64-bit pointer) */
  3318. uint32_t alignment;
  3319. uint32_t size;
  3320. };
  3321. struct ivar32_t {
  3322. uint32_t offset; /* uintptr_t * (32-bit pointer) */
  3323. uint32_t name; /* const char * (32-bit pointer) */
  3324. uint32_t type; /* const char * (32-bit pointer) */
  3325. uint32_t alignment;
  3326. uint32_t size;
  3327. };
  3328. struct objc_property_list64 {
  3329. uint32_t entsize;
  3330. uint32_t count;
  3331. /* struct objc_property64 first; These structures follow inline */
  3332. };
  3333. struct objc_property_list32 {
  3334. uint32_t entsize;
  3335. uint32_t count;
  3336. /* struct objc_property32 first; These structures follow inline */
  3337. };
  3338. struct objc_property64 {
  3339. uint64_t name; /* const char * (64-bit pointer) */
  3340. uint64_t attributes; /* const char * (64-bit pointer) */
  3341. };
  3342. struct objc_property32 {
  3343. uint32_t name; /* const char * (32-bit pointer) */
  3344. uint32_t attributes; /* const char * (32-bit pointer) */
  3345. };
  3346. struct category64_t {
  3347. uint64_t name; /* const char * (64-bit pointer) */
  3348. uint64_t cls; /* struct class_t * (64-bit pointer) */
  3349. uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
  3350. uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
  3351. uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
  3352. uint64_t instanceProperties; /* struct objc_property_list *
  3353. (64-bit pointer) */
  3354. };
  3355. struct category32_t {
  3356. uint32_t name; /* const char * (32-bit pointer) */
  3357. uint32_t cls; /* struct class_t * (32-bit pointer) */
  3358. uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
  3359. uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
  3360. uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
  3361. uint32_t instanceProperties; /* struct objc_property_list *
  3362. (32-bit pointer) */
  3363. };
  3364. struct objc_image_info64 {
  3365. uint32_t version;
  3366. uint32_t flags;
  3367. };
  3368. struct objc_image_info32 {
  3369. uint32_t version;
  3370. uint32_t flags;
  3371. };
  3372. struct imageInfo_t {
  3373. uint32_t version;
  3374. uint32_t flags;
  3375. };
  3376. /* masks for objc_image_info.flags */
  3377. #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
  3378. #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
  3379. #define OBJC_IMAGE_IS_SIMULATED (1 << 5)
  3380. #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
  3381. struct message_ref64 {
  3382. uint64_t imp; /* IMP (64-bit pointer) */
  3383. uint64_t sel; /* SEL (64-bit pointer) */
  3384. };
  3385. struct message_ref32 {
  3386. uint32_t imp; /* IMP (32-bit pointer) */
  3387. uint32_t sel; /* SEL (32-bit pointer) */
  3388. };
  3389. // Objective-C 1 (32-bit only) meta data structs.
  3390. struct objc_module_t {
  3391. uint32_t version;
  3392. uint32_t size;
  3393. uint32_t name; /* char * (32-bit pointer) */
  3394. uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
  3395. };
  3396. struct objc_symtab_t {
  3397. uint32_t sel_ref_cnt;
  3398. uint32_t refs; /* SEL * (32-bit pointer) */
  3399. uint16_t cls_def_cnt;
  3400. uint16_t cat_def_cnt;
  3401. // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
  3402. };
  3403. struct objc_class_t {
  3404. uint32_t isa; /* struct objc_class * (32-bit pointer) */
  3405. uint32_t super_class; /* struct objc_class * (32-bit pointer) */
  3406. uint32_t name; /* const char * (32-bit pointer) */
  3407. int32_t version;
  3408. int32_t info;
  3409. int32_t instance_size;
  3410. uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
  3411. uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
  3412. uint32_t cache; /* struct objc_cache * (32-bit pointer) */
  3413. uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
  3414. };
  3415. #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
  3416. // class is not a metaclass
  3417. #define CLS_CLASS 0x1
  3418. // class is a metaclass
  3419. #define CLS_META 0x2
  3420. struct objc_category_t {
  3421. uint32_t category_name; /* char * (32-bit pointer) */
  3422. uint32_t class_name; /* char * (32-bit pointer) */
  3423. uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
  3424. uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
  3425. uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
  3426. };
  3427. struct objc_ivar_t {
  3428. uint32_t ivar_name; /* char * (32-bit pointer) */
  3429. uint32_t ivar_type; /* char * (32-bit pointer) */
  3430. int32_t ivar_offset;
  3431. };
  3432. struct objc_ivar_list_t {
  3433. int32_t ivar_count;
  3434. // struct objc_ivar_t ivar_list[1]; /* variable length structure */
  3435. };
  3436. struct objc_method_list_t {
  3437. uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
  3438. int32_t method_count;
  3439. // struct objc_method_t method_list[1]; /* variable length structure */
  3440. };
  3441. struct objc_method_t {
  3442. uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
  3443. uint32_t method_types; /* char * (32-bit pointer) */
  3444. uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
  3445. (32-bit pointer) */
  3446. };
  3447. struct objc_protocol_list_t {
  3448. uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
  3449. int32_t count;
  3450. // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
  3451. // (32-bit pointer) */
  3452. };
  3453. struct objc_protocol_t {
  3454. uint32_t isa; /* struct objc_class * (32-bit pointer) */
  3455. uint32_t protocol_name; /* char * (32-bit pointer) */
  3456. uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
  3457. uint32_t instance_methods; /* struct objc_method_description_list *
  3458. (32-bit pointer) */
  3459. uint32_t class_methods; /* struct objc_method_description_list *
  3460. (32-bit pointer) */
  3461. };
  3462. struct objc_method_description_list_t {
  3463. int32_t count;
  3464. // struct objc_method_description_t list[1];
  3465. };
  3466. struct objc_method_description_t {
  3467. uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
  3468. uint32_t types; /* char * (32-bit pointer) */
  3469. };
  3470. inline void swapStruct(struct cfstring64_t &cfs) {
  3471. sys::swapByteOrder(cfs.isa);
  3472. sys::swapByteOrder(cfs.flags);
  3473. sys::swapByteOrder(cfs.characters);
  3474. sys::swapByteOrder(cfs.length);
  3475. }
  3476. inline void swapStruct(struct class64_t &c) {
  3477. sys::swapByteOrder(c.isa);
  3478. sys::swapByteOrder(c.superclass);
  3479. sys::swapByteOrder(c.cache);
  3480. sys::swapByteOrder(c.vtable);
  3481. sys::swapByteOrder(c.data);
  3482. }
  3483. inline void swapStruct(struct class32_t &c) {
  3484. sys::swapByteOrder(c.isa);
  3485. sys::swapByteOrder(c.superclass);
  3486. sys::swapByteOrder(c.cache);
  3487. sys::swapByteOrder(c.vtable);
  3488. sys::swapByteOrder(c.data);
  3489. }
  3490. inline void swapStruct(struct class_ro64_t &cro) {
  3491. sys::swapByteOrder(cro.flags);
  3492. sys::swapByteOrder(cro.instanceStart);
  3493. sys::swapByteOrder(cro.instanceSize);
  3494. sys::swapByteOrder(cro.reserved);
  3495. sys::swapByteOrder(cro.ivarLayout);
  3496. sys::swapByteOrder(cro.name);
  3497. sys::swapByteOrder(cro.baseMethods);
  3498. sys::swapByteOrder(cro.baseProtocols);
  3499. sys::swapByteOrder(cro.ivars);
  3500. sys::swapByteOrder(cro.weakIvarLayout);
  3501. sys::swapByteOrder(cro.baseProperties);
  3502. }
  3503. inline void swapStruct(struct class_ro32_t &cro) {
  3504. sys::swapByteOrder(cro.flags);
  3505. sys::swapByteOrder(cro.instanceStart);
  3506. sys::swapByteOrder(cro.instanceSize);
  3507. sys::swapByteOrder(cro.ivarLayout);
  3508. sys::swapByteOrder(cro.name);
  3509. sys::swapByteOrder(cro.baseMethods);
  3510. sys::swapByteOrder(cro.baseProtocols);
  3511. sys::swapByteOrder(cro.ivars);
  3512. sys::swapByteOrder(cro.weakIvarLayout);
  3513. sys::swapByteOrder(cro.baseProperties);
  3514. }
  3515. inline void swapStruct(struct method_list64_t &ml) {
  3516. sys::swapByteOrder(ml.entsize);
  3517. sys::swapByteOrder(ml.count);
  3518. }
  3519. inline void swapStruct(struct method_list32_t &ml) {
  3520. sys::swapByteOrder(ml.entsize);
  3521. sys::swapByteOrder(ml.count);
  3522. }
  3523. inline void swapStruct(struct method64_t &m) {
  3524. sys::swapByteOrder(m.name);
  3525. sys::swapByteOrder(m.types);
  3526. sys::swapByteOrder(m.imp);
  3527. }
  3528. inline void swapStruct(struct method32_t &m) {
  3529. sys::swapByteOrder(m.name);
  3530. sys::swapByteOrder(m.types);
  3531. sys::swapByteOrder(m.imp);
  3532. }
  3533. inline void swapStruct(struct protocol_list64_t &pl) {
  3534. sys::swapByteOrder(pl.count);
  3535. }
  3536. inline void swapStruct(struct protocol_list32_t &pl) {
  3537. sys::swapByteOrder(pl.count);
  3538. }
  3539. inline void swapStruct(struct protocol64_t &p) {
  3540. sys::swapByteOrder(p.isa);
  3541. sys::swapByteOrder(p.name);
  3542. sys::swapByteOrder(p.protocols);
  3543. sys::swapByteOrder(p.instanceMethods);
  3544. sys::swapByteOrder(p.classMethods);
  3545. sys::swapByteOrder(p.optionalInstanceMethods);
  3546. sys::swapByteOrder(p.optionalClassMethods);
  3547. sys::swapByteOrder(p.instanceProperties);
  3548. }
  3549. inline void swapStruct(struct protocol32_t &p) {
  3550. sys::swapByteOrder(p.isa);
  3551. sys::swapByteOrder(p.name);
  3552. sys::swapByteOrder(p.protocols);
  3553. sys::swapByteOrder(p.instanceMethods);
  3554. sys::swapByteOrder(p.classMethods);
  3555. sys::swapByteOrder(p.optionalInstanceMethods);
  3556. sys::swapByteOrder(p.optionalClassMethods);
  3557. sys::swapByteOrder(p.instanceProperties);
  3558. }
  3559. inline void swapStruct(struct ivar_list64_t &il) {
  3560. sys::swapByteOrder(il.entsize);
  3561. sys::swapByteOrder(il.count);
  3562. }
  3563. inline void swapStruct(struct ivar_list32_t &il) {
  3564. sys::swapByteOrder(il.entsize);
  3565. sys::swapByteOrder(il.count);
  3566. }
  3567. inline void swapStruct(struct ivar64_t &i) {
  3568. sys::swapByteOrder(i.offset);
  3569. sys::swapByteOrder(i.name);
  3570. sys::swapByteOrder(i.type);
  3571. sys::swapByteOrder(i.alignment);
  3572. sys::swapByteOrder(i.size);
  3573. }
  3574. inline void swapStruct(struct ivar32_t &i) {
  3575. sys::swapByteOrder(i.offset);
  3576. sys::swapByteOrder(i.name);
  3577. sys::swapByteOrder(i.type);
  3578. sys::swapByteOrder(i.alignment);
  3579. sys::swapByteOrder(i.size);
  3580. }
  3581. inline void swapStruct(struct objc_property_list64 &pl) {
  3582. sys::swapByteOrder(pl.entsize);
  3583. sys::swapByteOrder(pl.count);
  3584. }
  3585. inline void swapStruct(struct objc_property_list32 &pl) {
  3586. sys::swapByteOrder(pl.entsize);
  3587. sys::swapByteOrder(pl.count);
  3588. }
  3589. inline void swapStruct(struct objc_property64 &op) {
  3590. sys::swapByteOrder(op.name);
  3591. sys::swapByteOrder(op.attributes);
  3592. }
  3593. inline void swapStruct(struct objc_property32 &op) {
  3594. sys::swapByteOrder(op.name);
  3595. sys::swapByteOrder(op.attributes);
  3596. }
  3597. inline void swapStruct(struct category64_t &c) {
  3598. sys::swapByteOrder(c.name);
  3599. sys::swapByteOrder(c.cls);
  3600. sys::swapByteOrder(c.instanceMethods);
  3601. sys::swapByteOrder(c.classMethods);
  3602. sys::swapByteOrder(c.protocols);
  3603. sys::swapByteOrder(c.instanceProperties);
  3604. }
  3605. inline void swapStruct(struct category32_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 objc_image_info64 &o) {
  3614. sys::swapByteOrder(o.version);
  3615. sys::swapByteOrder(o.flags);
  3616. }
  3617. inline void swapStruct(struct objc_image_info32 &o) {
  3618. sys::swapByteOrder(o.version);
  3619. sys::swapByteOrder(o.flags);
  3620. }
  3621. inline void swapStruct(struct imageInfo_t &o) {
  3622. sys::swapByteOrder(o.version);
  3623. sys::swapByteOrder(o.flags);
  3624. }
  3625. inline void swapStruct(struct message_ref64 &mr) {
  3626. sys::swapByteOrder(mr.imp);
  3627. sys::swapByteOrder(mr.sel);
  3628. }
  3629. inline void swapStruct(struct message_ref32 &mr) {
  3630. sys::swapByteOrder(mr.imp);
  3631. sys::swapByteOrder(mr.sel);
  3632. }
  3633. inline void swapStruct(struct objc_module_t &module) {
  3634. sys::swapByteOrder(module.version);
  3635. sys::swapByteOrder(module.size);
  3636. sys::swapByteOrder(module.name);
  3637. sys::swapByteOrder(module.symtab);
  3638. }
  3639. inline void swapStruct(struct objc_symtab_t &symtab) {
  3640. sys::swapByteOrder(symtab.sel_ref_cnt);
  3641. sys::swapByteOrder(symtab.refs);
  3642. sys::swapByteOrder(symtab.cls_def_cnt);
  3643. sys::swapByteOrder(symtab.cat_def_cnt);
  3644. }
  3645. inline void swapStruct(struct objc_class_t &objc_class) {
  3646. sys::swapByteOrder(objc_class.isa);
  3647. sys::swapByteOrder(objc_class.super_class);
  3648. sys::swapByteOrder(objc_class.name);
  3649. sys::swapByteOrder(objc_class.version);
  3650. sys::swapByteOrder(objc_class.info);
  3651. sys::swapByteOrder(objc_class.instance_size);
  3652. sys::swapByteOrder(objc_class.ivars);
  3653. sys::swapByteOrder(objc_class.methodLists);
  3654. sys::swapByteOrder(objc_class.cache);
  3655. sys::swapByteOrder(objc_class.protocols);
  3656. }
  3657. inline void swapStruct(struct objc_category_t &objc_category) {
  3658. sys::swapByteOrder(objc_category.category_name);
  3659. sys::swapByteOrder(objc_category.class_name);
  3660. sys::swapByteOrder(objc_category.instance_methods);
  3661. sys::swapByteOrder(objc_category.class_methods);
  3662. sys::swapByteOrder(objc_category.protocols);
  3663. }
  3664. inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
  3665. sys::swapByteOrder(objc_ivar_list.ivar_count);
  3666. }
  3667. inline void swapStruct(struct objc_ivar_t &objc_ivar) {
  3668. sys::swapByteOrder(objc_ivar.ivar_name);
  3669. sys::swapByteOrder(objc_ivar.ivar_type);
  3670. sys::swapByteOrder(objc_ivar.ivar_offset);
  3671. }
  3672. inline void swapStruct(struct objc_method_list_t &method_list) {
  3673. sys::swapByteOrder(method_list.obsolete);
  3674. sys::swapByteOrder(method_list.method_count);
  3675. }
  3676. inline void swapStruct(struct objc_method_t &method) {
  3677. sys::swapByteOrder(method.method_name);
  3678. sys::swapByteOrder(method.method_types);
  3679. sys::swapByteOrder(method.method_imp);
  3680. }
  3681. inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
  3682. sys::swapByteOrder(protocol_list.next);
  3683. sys::swapByteOrder(protocol_list.count);
  3684. }
  3685. inline void swapStruct(struct objc_protocol_t &protocol) {
  3686. sys::swapByteOrder(protocol.isa);
  3687. sys::swapByteOrder(protocol.protocol_name);
  3688. sys::swapByteOrder(protocol.protocol_list);
  3689. sys::swapByteOrder(protocol.instance_methods);
  3690. sys::swapByteOrder(protocol.class_methods);
  3691. }
  3692. inline void swapStruct(struct objc_method_description_list_t &mdl) {
  3693. sys::swapByteOrder(mdl.count);
  3694. }
  3695. inline void swapStruct(struct objc_method_description_t &md) {
  3696. sys::swapByteOrder(md.name);
  3697. sys::swapByteOrder(md.types);
  3698. }
  3699. } // namespace
  3700. static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
  3701. struct DisassembleInfo *info);
  3702. // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
  3703. // to an Objective-C class and returns the class name. It is also passed the
  3704. // address of the pointer, so when the pointer is zero as it can be in an .o
  3705. // file, that is used to look for an external relocation entry with a symbol
  3706. // name.
  3707. static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
  3708. uint64_t ReferenceValue,
  3709. struct DisassembleInfo *info) {
  3710. const char *r;
  3711. uint32_t offset, left;
  3712. SectionRef S;
  3713. // The pointer_value can be 0 in an object file and have a relocation
  3714. // entry for the class symbol at the ReferenceValue (the address of the
  3715. // pointer).
  3716. if (pointer_value == 0) {
  3717. r = get_pointer_64(ReferenceValue, offset, left, S, info);
  3718. if (r == nullptr || left < sizeof(uint64_t))
  3719. return nullptr;
  3720. uint64_t n_value;
  3721. const char *symbol_name = get_symbol_64(offset, S, info, n_value);
  3722. if (symbol_name == nullptr)
  3723. return nullptr;
  3724. const char *class_name = strrchr(symbol_name, '$');
  3725. if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
  3726. return class_name + 2;
  3727. else
  3728. return nullptr;
  3729. }
  3730. // The case were the pointer_value is non-zero and points to a class defined
  3731. // in this Mach-O file.
  3732. r = get_pointer_64(pointer_value, offset, left, S, info);
  3733. if (r == nullptr || left < sizeof(struct class64_t))
  3734. return nullptr;
  3735. struct class64_t c;
  3736. memcpy(&c, r, sizeof(struct class64_t));
  3737. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3738. swapStruct(c);
  3739. if (c.data == 0)
  3740. return nullptr;
  3741. r = get_pointer_64(c.data, offset, left, S, info);
  3742. if (r == nullptr || left < sizeof(struct class_ro64_t))
  3743. return nullptr;
  3744. struct class_ro64_t cro;
  3745. memcpy(&cro, r, sizeof(struct class_ro64_t));
  3746. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3747. swapStruct(cro);
  3748. if (cro.name == 0)
  3749. return nullptr;
  3750. const char *name = get_pointer_64(cro.name, offset, left, S, info);
  3751. return name;
  3752. }
  3753. // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
  3754. // pointer to a cfstring and returns its name or nullptr.
  3755. static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
  3756. struct DisassembleInfo *info) {
  3757. const char *r, *name;
  3758. uint32_t offset, left;
  3759. SectionRef S;
  3760. struct cfstring64_t cfs;
  3761. uint64_t cfs_characters;
  3762. r = get_pointer_64(ReferenceValue, offset, left, S, info);
  3763. if (r == nullptr || left < sizeof(struct cfstring64_t))
  3764. return nullptr;
  3765. memcpy(&cfs, r, sizeof(struct cfstring64_t));
  3766. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3767. swapStruct(cfs);
  3768. if (cfs.characters == 0) {
  3769. uint64_t n_value;
  3770. const char *symbol_name = get_symbol_64(
  3771. offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
  3772. if (symbol_name == nullptr)
  3773. return nullptr;
  3774. cfs_characters = n_value;
  3775. } else
  3776. cfs_characters = cfs.characters;
  3777. name = get_pointer_64(cfs_characters, offset, left, S, info);
  3778. return name;
  3779. }
  3780. // get_objc2_64bit_selref() is used for disassembly and is passed a the address
  3781. // of a pointer to an Objective-C selector reference when the pointer value is
  3782. // zero as in a .o file and is likely to have a external relocation entry with
  3783. // who's symbol's n_value is the real pointer to the selector name. If that is
  3784. // the case the real pointer to the selector name is returned else 0 is
  3785. // returned
  3786. static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
  3787. struct DisassembleInfo *info) {
  3788. uint32_t offset, left;
  3789. SectionRef S;
  3790. const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
  3791. if (r == nullptr || left < sizeof(uint64_t))
  3792. return 0;
  3793. uint64_t n_value;
  3794. const char *symbol_name = get_symbol_64(offset, S, info, n_value);
  3795. if (symbol_name == nullptr)
  3796. return 0;
  3797. return n_value;
  3798. }
  3799. static const SectionRef get_section(MachOObjectFile *O, const char *segname,
  3800. const char *sectname) {
  3801. for (const SectionRef &Section : O->sections()) {
  3802. StringRef SectName;
  3803. Expected<StringRef> SecNameOrErr = Section.getName();
  3804. if (SecNameOrErr)
  3805. SectName = *SecNameOrErr;
  3806. else
  3807. consumeError(SecNameOrErr.takeError());
  3808. DataRefImpl Ref = Section.getRawDataRefImpl();
  3809. StringRef SegName = O->getSectionFinalSegmentName(Ref);
  3810. if (SegName == segname && SectName == sectname)
  3811. return Section;
  3812. }
  3813. return SectionRef();
  3814. }
  3815. static void
  3816. walk_pointer_list_64(const char *listname, const SectionRef S,
  3817. MachOObjectFile *O, struct DisassembleInfo *info,
  3818. void (*func)(uint64_t, struct DisassembleInfo *info)) {
  3819. if (S == SectionRef())
  3820. return;
  3821. StringRef SectName;
  3822. Expected<StringRef> SecNameOrErr = S.getName();
  3823. if (SecNameOrErr)
  3824. SectName = *SecNameOrErr;
  3825. else
  3826. consumeError(SecNameOrErr.takeError());
  3827. DataRefImpl Ref = S.getRawDataRefImpl();
  3828. StringRef SegName = O->getSectionFinalSegmentName(Ref);
  3829. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  3830. StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
  3831. const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
  3832. for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
  3833. uint32_t left = S.getSize() - i;
  3834. uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
  3835. uint64_t p = 0;
  3836. memcpy(&p, Contents + i, size);
  3837. if (i + sizeof(uint64_t) > S.getSize())
  3838. outs() << listname << " list pointer extends past end of (" << SegName
  3839. << "," << SectName << ") section\n";
  3840. outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
  3841. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  3842. sys::swapByteOrder(p);
  3843. uint64_t n_value = 0;
  3844. const char *name = get_symbol_64(i, S, info, n_value, p);
  3845. if (name == nullptr)
  3846. name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
  3847. if (n_value != 0) {
  3848. outs() << format("0x%" PRIx64, n_value);
  3849. if (p != 0)
  3850. outs() << " + " << format("0x%" PRIx64, p);
  3851. } else
  3852. outs() << format("0x%" PRIx64, p);
  3853. if (name != nullptr)
  3854. outs() << " " << name;
  3855. outs() << "\n";
  3856. p += n_value;
  3857. if (func)
  3858. func(p, info);
  3859. }
  3860. }
  3861. static void
  3862. walk_pointer_list_32(const char *listname, const SectionRef S,
  3863. MachOObjectFile *O, struct DisassembleInfo *info,
  3864. void (*func)(uint32_t, struct DisassembleInfo *info)) {
  3865. if (S == SectionRef())
  3866. return;
  3867. StringRef SectName = unwrapOrError(S.getName(), O->getFileName());
  3868. DataRefImpl Ref = S.getRawDataRefImpl();
  3869. StringRef SegName = O->getSectionFinalSegmentName(Ref);
  3870. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  3871. StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
  3872. const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
  3873. for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
  3874. uint32_t left = S.getSize() - i;
  3875. uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
  3876. uint32_t p = 0;
  3877. memcpy(&p, Contents + i, size);
  3878. if (i + sizeof(uint32_t) > S.getSize())
  3879. outs() << listname << " list pointer extends past end of (" << SegName
  3880. << "," << SectName << ") section\n";
  3881. uint32_t Address = S.getAddress() + i;
  3882. outs() << format("%08" PRIx32, Address) << " ";
  3883. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  3884. sys::swapByteOrder(p);
  3885. outs() << format("0x%" PRIx32, p);
  3886. const char *name = get_symbol_32(i, S, info, p);
  3887. if (name != nullptr)
  3888. outs() << " " << name;
  3889. outs() << "\n";
  3890. if (func)
  3891. func(p, info);
  3892. }
  3893. }
  3894. static void print_layout_map(const char *layout_map, uint32_t left) {
  3895. if (layout_map == nullptr)
  3896. return;
  3897. outs() << " layout map: ";
  3898. do {
  3899. outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
  3900. left--;
  3901. layout_map++;
  3902. } while (*layout_map != '\0' && left != 0);
  3903. outs() << "\n";
  3904. }
  3905. static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
  3906. uint32_t offset, left;
  3907. SectionRef S;
  3908. const char *layout_map;
  3909. if (p == 0)
  3910. return;
  3911. layout_map = get_pointer_64(p, offset, left, S, info);
  3912. print_layout_map(layout_map, left);
  3913. }
  3914. static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
  3915. uint32_t offset, left;
  3916. SectionRef S;
  3917. const char *layout_map;
  3918. if (p == 0)
  3919. return;
  3920. layout_map = get_pointer_32(p, offset, left, S, info);
  3921. print_layout_map(layout_map, left);
  3922. }
  3923. static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
  3924. const char *indent) {
  3925. struct method_list64_t ml;
  3926. struct method64_t m;
  3927. const char *r;
  3928. uint32_t offset, xoffset, left, i;
  3929. SectionRef S, xS;
  3930. const char *name, *sym_name;
  3931. uint64_t n_value;
  3932. r = get_pointer_64(p, offset, left, S, info);
  3933. if (r == nullptr)
  3934. return;
  3935. memset(&ml, '\0', sizeof(struct method_list64_t));
  3936. if (left < sizeof(struct method_list64_t)) {
  3937. memcpy(&ml, r, left);
  3938. outs() << " (method_list_t entends past the end of the section)\n";
  3939. } else
  3940. memcpy(&ml, r, sizeof(struct method_list64_t));
  3941. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3942. swapStruct(ml);
  3943. outs() << indent << "\t\t entsize " << ml.entsize << "\n";
  3944. outs() << indent << "\t\t count " << ml.count << "\n";
  3945. p += sizeof(struct method_list64_t);
  3946. offset += sizeof(struct method_list64_t);
  3947. for (i = 0; i < ml.count; i++) {
  3948. r = get_pointer_64(p, offset, left, S, info);
  3949. if (r == nullptr)
  3950. return;
  3951. memset(&m, '\0', sizeof(struct method64_t));
  3952. if (left < sizeof(struct method64_t)) {
  3953. memcpy(&m, r, left);
  3954. outs() << indent << " (method_t extends past the end of the section)\n";
  3955. } else
  3956. memcpy(&m, r, sizeof(struct method64_t));
  3957. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3958. swapStruct(m);
  3959. outs() << indent << "\t\t name ";
  3960. sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
  3961. info, n_value, m.name);
  3962. if (n_value != 0) {
  3963. if (info->verbose && sym_name != nullptr)
  3964. outs() << sym_name;
  3965. else
  3966. outs() << format("0x%" PRIx64, n_value);
  3967. if (m.name != 0)
  3968. outs() << " + " << format("0x%" PRIx64, m.name);
  3969. } else
  3970. outs() << format("0x%" PRIx64, m.name);
  3971. name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
  3972. if (name != nullptr)
  3973. outs() << format(" %.*s", left, name);
  3974. outs() << "\n";
  3975. outs() << indent << "\t\t types ";
  3976. sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
  3977. info, n_value, m.types);
  3978. if (n_value != 0) {
  3979. if (info->verbose && sym_name != nullptr)
  3980. outs() << sym_name;
  3981. else
  3982. outs() << format("0x%" PRIx64, n_value);
  3983. if (m.types != 0)
  3984. outs() << " + " << format("0x%" PRIx64, m.types);
  3985. } else
  3986. outs() << format("0x%" PRIx64, m.types);
  3987. name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
  3988. if (name != nullptr)
  3989. outs() << format(" %.*s", left, name);
  3990. outs() << "\n";
  3991. outs() << indent << "\t\t imp ";
  3992. name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
  3993. n_value, m.imp);
  3994. if (info->verbose && name == nullptr) {
  3995. if (n_value != 0) {
  3996. outs() << format("0x%" PRIx64, n_value) << " ";
  3997. if (m.imp != 0)
  3998. outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
  3999. } else
  4000. outs() << format("0x%" PRIx64, m.imp) << " ";
  4001. }
  4002. if (name != nullptr)
  4003. outs() << name;
  4004. outs() << "\n";
  4005. p += sizeof(struct method64_t);
  4006. offset += sizeof(struct method64_t);
  4007. }
  4008. }
  4009. static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
  4010. const char *indent) {
  4011. struct method_list32_t ml;
  4012. struct method32_t m;
  4013. const char *r, *name;
  4014. uint32_t offset, xoffset, left, i;
  4015. SectionRef S, xS;
  4016. r = get_pointer_32(p, offset, left, S, info);
  4017. if (r == nullptr)
  4018. return;
  4019. memset(&ml, '\0', sizeof(struct method_list32_t));
  4020. if (left < sizeof(struct method_list32_t)) {
  4021. memcpy(&ml, r, left);
  4022. outs() << " (method_list_t entends past the end of the section)\n";
  4023. } else
  4024. memcpy(&ml, r, sizeof(struct method_list32_t));
  4025. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4026. swapStruct(ml);
  4027. outs() << indent << "\t\t entsize " << ml.entsize << "\n";
  4028. outs() << indent << "\t\t count " << ml.count << "\n";
  4029. p += sizeof(struct method_list32_t);
  4030. offset += sizeof(struct method_list32_t);
  4031. for (i = 0; i < ml.count; i++) {
  4032. r = get_pointer_32(p, offset, left, S, info);
  4033. if (r == nullptr)
  4034. return;
  4035. memset(&m, '\0', sizeof(struct method32_t));
  4036. if (left < sizeof(struct method32_t)) {
  4037. memcpy(&ml, r, left);
  4038. outs() << indent << " (method_t entends past the end of the section)\n";
  4039. } else
  4040. memcpy(&m, r, sizeof(struct method32_t));
  4041. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4042. swapStruct(m);
  4043. outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
  4044. name = get_pointer_32(m.name, xoffset, left, xS, info);
  4045. if (name != nullptr)
  4046. outs() << format(" %.*s", left, name);
  4047. outs() << "\n";
  4048. outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
  4049. name = get_pointer_32(m.types, xoffset, left, xS, info);
  4050. if (name != nullptr)
  4051. outs() << format(" %.*s", left, name);
  4052. outs() << "\n";
  4053. outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
  4054. name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
  4055. m.imp);
  4056. if (name != nullptr)
  4057. outs() << " " << name;
  4058. outs() << "\n";
  4059. p += sizeof(struct method32_t);
  4060. offset += sizeof(struct method32_t);
  4061. }
  4062. }
  4063. static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
  4064. uint32_t offset, left, xleft;
  4065. SectionRef S;
  4066. struct objc_method_list_t method_list;
  4067. struct objc_method_t method;
  4068. const char *r, *methods, *name, *SymbolName;
  4069. int32_t i;
  4070. r = get_pointer_32(p, offset, left, S, info, true);
  4071. if (r == nullptr)
  4072. return true;
  4073. outs() << "\n";
  4074. if (left > sizeof(struct objc_method_list_t)) {
  4075. memcpy(&method_list, r, sizeof(struct objc_method_list_t));
  4076. } else {
  4077. outs() << "\t\t objc_method_list extends past end of the section\n";
  4078. memset(&method_list, '\0', sizeof(struct objc_method_list_t));
  4079. memcpy(&method_list, r, left);
  4080. }
  4081. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4082. swapStruct(method_list);
  4083. outs() << "\t\t obsolete "
  4084. << format("0x%08" PRIx32, method_list.obsolete) << "\n";
  4085. outs() << "\t\t method_count " << method_list.method_count << "\n";
  4086. methods = r + sizeof(struct objc_method_list_t);
  4087. for (i = 0; i < method_list.method_count; i++) {
  4088. if ((i + 1) * sizeof(struct objc_method_t) > left) {
  4089. outs() << "\t\t remaining method's extend past the of the section\n";
  4090. break;
  4091. }
  4092. memcpy(&method, methods + i * sizeof(struct objc_method_t),
  4093. sizeof(struct objc_method_t));
  4094. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4095. swapStruct(method);
  4096. outs() << "\t\t method_name "
  4097. << format("0x%08" PRIx32, method.method_name);
  4098. if (info->verbose) {
  4099. name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
  4100. if (name != nullptr)
  4101. outs() << format(" %.*s", xleft, name);
  4102. else
  4103. outs() << " (not in an __OBJC section)";
  4104. }
  4105. outs() << "\n";
  4106. outs() << "\t\t method_types "
  4107. << format("0x%08" PRIx32, method.method_types);
  4108. if (info->verbose) {
  4109. name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
  4110. if (name != nullptr)
  4111. outs() << format(" %.*s", xleft, name);
  4112. else
  4113. outs() << " (not in an __OBJC section)";
  4114. }
  4115. outs() << "\n";
  4116. outs() << "\t\t method_imp "
  4117. << format("0x%08" PRIx32, method.method_imp) << " ";
  4118. if (info->verbose) {
  4119. SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
  4120. if (SymbolName != nullptr)
  4121. outs() << SymbolName;
  4122. }
  4123. outs() << "\n";
  4124. }
  4125. return false;
  4126. }
  4127. static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
  4128. struct protocol_list64_t pl;
  4129. uint64_t q, n_value;
  4130. struct protocol64_t pc;
  4131. const char *r;
  4132. uint32_t offset, xoffset, left, i;
  4133. SectionRef S, xS;
  4134. const char *name, *sym_name;
  4135. r = get_pointer_64(p, offset, left, S, info);
  4136. if (r == nullptr)
  4137. return;
  4138. memset(&pl, '\0', sizeof(struct protocol_list64_t));
  4139. if (left < sizeof(struct protocol_list64_t)) {
  4140. memcpy(&pl, r, left);
  4141. outs() << " (protocol_list_t entends past the end of the section)\n";
  4142. } else
  4143. memcpy(&pl, r, sizeof(struct protocol_list64_t));
  4144. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4145. swapStruct(pl);
  4146. outs() << " count " << pl.count << "\n";
  4147. p += sizeof(struct protocol_list64_t);
  4148. offset += sizeof(struct protocol_list64_t);
  4149. for (i = 0; i < pl.count; i++) {
  4150. r = get_pointer_64(p, offset, left, S, info);
  4151. if (r == nullptr)
  4152. return;
  4153. q = 0;
  4154. if (left < sizeof(uint64_t)) {
  4155. memcpy(&q, r, left);
  4156. outs() << " (protocol_t * entends past the end of the section)\n";
  4157. } else
  4158. memcpy(&q, r, sizeof(uint64_t));
  4159. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4160. sys::swapByteOrder(q);
  4161. outs() << "\t\t list[" << i << "] ";
  4162. sym_name = get_symbol_64(offset, S, info, n_value, q);
  4163. if (n_value != 0) {
  4164. if (info->verbose && sym_name != nullptr)
  4165. outs() << sym_name;
  4166. else
  4167. outs() << format("0x%" PRIx64, n_value);
  4168. if (q != 0)
  4169. outs() << " + " << format("0x%" PRIx64, q);
  4170. } else
  4171. outs() << format("0x%" PRIx64, q);
  4172. outs() << " (struct protocol_t *)\n";
  4173. r = get_pointer_64(q + n_value, offset, left, S, info);
  4174. if (r == nullptr)
  4175. return;
  4176. memset(&pc, '\0', sizeof(struct protocol64_t));
  4177. if (left < sizeof(struct protocol64_t)) {
  4178. memcpy(&pc, r, left);
  4179. outs() << " (protocol_t entends past the end of the section)\n";
  4180. } else
  4181. memcpy(&pc, r, sizeof(struct protocol64_t));
  4182. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4183. swapStruct(pc);
  4184. outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
  4185. outs() << "\t\t\t name ";
  4186. sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
  4187. info, n_value, pc.name);
  4188. if (n_value != 0) {
  4189. if (info->verbose && sym_name != nullptr)
  4190. outs() << sym_name;
  4191. else
  4192. outs() << format("0x%" PRIx64, n_value);
  4193. if (pc.name != 0)
  4194. outs() << " + " << format("0x%" PRIx64, pc.name);
  4195. } else
  4196. outs() << format("0x%" PRIx64, pc.name);
  4197. name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
  4198. if (name != nullptr)
  4199. outs() << format(" %.*s", left, name);
  4200. outs() << "\n";
  4201. outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
  4202. outs() << "\t\t instanceMethods ";
  4203. sym_name =
  4204. get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
  4205. S, info, n_value, pc.instanceMethods);
  4206. if (n_value != 0) {
  4207. if (info->verbose && sym_name != nullptr)
  4208. outs() << sym_name;
  4209. else
  4210. outs() << format("0x%" PRIx64, n_value);
  4211. if (pc.instanceMethods != 0)
  4212. outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
  4213. } else
  4214. outs() << format("0x%" PRIx64, pc.instanceMethods);
  4215. outs() << " (struct method_list_t *)\n";
  4216. if (pc.instanceMethods + n_value != 0)
  4217. print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
  4218. outs() << "\t\t classMethods ";
  4219. sym_name =
  4220. get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
  4221. info, n_value, pc.classMethods);
  4222. if (n_value != 0) {
  4223. if (info->verbose && sym_name != nullptr)
  4224. outs() << sym_name;
  4225. else
  4226. outs() << format("0x%" PRIx64, n_value);
  4227. if (pc.classMethods != 0)
  4228. outs() << " + " << format("0x%" PRIx64, pc.classMethods);
  4229. } else
  4230. outs() << format("0x%" PRIx64, pc.classMethods);
  4231. outs() << " (struct method_list_t *)\n";
  4232. if (pc.classMethods + n_value != 0)
  4233. print_method_list64_t(pc.classMethods + n_value, info, "\t");
  4234. outs() << "\t optionalInstanceMethods "
  4235. << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
  4236. outs() << "\t optionalClassMethods "
  4237. << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
  4238. outs() << "\t instanceProperties "
  4239. << format("0x%" PRIx64, pc.instanceProperties) << "\n";
  4240. p += sizeof(uint64_t);
  4241. offset += sizeof(uint64_t);
  4242. }
  4243. }
  4244. static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
  4245. struct protocol_list32_t pl;
  4246. uint32_t q;
  4247. struct protocol32_t pc;
  4248. const char *r;
  4249. uint32_t offset, xoffset, left, i;
  4250. SectionRef S, xS;
  4251. const char *name;
  4252. r = get_pointer_32(p, offset, left, S, info);
  4253. if (r == nullptr)
  4254. return;
  4255. memset(&pl, '\0', sizeof(struct protocol_list32_t));
  4256. if (left < sizeof(struct protocol_list32_t)) {
  4257. memcpy(&pl, r, left);
  4258. outs() << " (protocol_list_t entends past the end of the section)\n";
  4259. } else
  4260. memcpy(&pl, r, sizeof(struct protocol_list32_t));
  4261. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4262. swapStruct(pl);
  4263. outs() << " count " << pl.count << "\n";
  4264. p += sizeof(struct protocol_list32_t);
  4265. offset += sizeof(struct protocol_list32_t);
  4266. for (i = 0; i < pl.count; i++) {
  4267. r = get_pointer_32(p, offset, left, S, info);
  4268. if (r == nullptr)
  4269. return;
  4270. q = 0;
  4271. if (left < sizeof(uint32_t)) {
  4272. memcpy(&q, r, left);
  4273. outs() << " (protocol_t * entends past the end of the section)\n";
  4274. } else
  4275. memcpy(&q, r, sizeof(uint32_t));
  4276. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4277. sys::swapByteOrder(q);
  4278. outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
  4279. << " (struct protocol_t *)\n";
  4280. r = get_pointer_32(q, offset, left, S, info);
  4281. if (r == nullptr)
  4282. return;
  4283. memset(&pc, '\0', sizeof(struct protocol32_t));
  4284. if (left < sizeof(struct protocol32_t)) {
  4285. memcpy(&pc, r, left);
  4286. outs() << " (protocol_t entends past the end of the section)\n";
  4287. } else
  4288. memcpy(&pc, r, sizeof(struct protocol32_t));
  4289. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4290. swapStruct(pc);
  4291. outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
  4292. outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
  4293. name = get_pointer_32(pc.name, xoffset, left, xS, info);
  4294. if (name != nullptr)
  4295. outs() << format(" %.*s", left, name);
  4296. outs() << "\n";
  4297. outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
  4298. outs() << "\t\t instanceMethods "
  4299. << format("0x%" PRIx32, pc.instanceMethods)
  4300. << " (struct method_list_t *)\n";
  4301. if (pc.instanceMethods != 0)
  4302. print_method_list32_t(pc.instanceMethods, info, "\t");
  4303. outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
  4304. << " (struct method_list_t *)\n";
  4305. if (pc.classMethods != 0)
  4306. print_method_list32_t(pc.classMethods, info, "\t");
  4307. outs() << "\t optionalInstanceMethods "
  4308. << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
  4309. outs() << "\t optionalClassMethods "
  4310. << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
  4311. outs() << "\t instanceProperties "
  4312. << format("0x%" PRIx32, pc.instanceProperties) << "\n";
  4313. p += sizeof(uint32_t);
  4314. offset += sizeof(uint32_t);
  4315. }
  4316. }
  4317. static void print_indent(uint32_t indent) {
  4318. for (uint32_t i = 0; i < indent;) {
  4319. if (indent - i >= 8) {
  4320. outs() << "\t";
  4321. i += 8;
  4322. } else {
  4323. for (uint32_t j = i; j < indent; j++)
  4324. outs() << " ";
  4325. return;
  4326. }
  4327. }
  4328. }
  4329. static bool print_method_description_list(uint32_t p, uint32_t indent,
  4330. struct DisassembleInfo *info) {
  4331. uint32_t offset, left, xleft;
  4332. SectionRef S;
  4333. struct objc_method_description_list_t mdl;
  4334. struct objc_method_description_t md;
  4335. const char *r, *list, *name;
  4336. int32_t i;
  4337. r = get_pointer_32(p, offset, left, S, info, true);
  4338. if (r == nullptr)
  4339. return true;
  4340. outs() << "\n";
  4341. if (left > sizeof(struct objc_method_description_list_t)) {
  4342. memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
  4343. } else {
  4344. print_indent(indent);
  4345. outs() << " objc_method_description_list extends past end of the section\n";
  4346. memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
  4347. memcpy(&mdl, r, left);
  4348. }
  4349. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4350. swapStruct(mdl);
  4351. print_indent(indent);
  4352. outs() << " count " << mdl.count << "\n";
  4353. list = r + sizeof(struct objc_method_description_list_t);
  4354. for (i = 0; i < mdl.count; i++) {
  4355. if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
  4356. print_indent(indent);
  4357. outs() << " remaining list entries extend past the of the section\n";
  4358. break;
  4359. }
  4360. print_indent(indent);
  4361. outs() << " list[" << i << "]\n";
  4362. memcpy(&md, list + i * sizeof(struct objc_method_description_t),
  4363. sizeof(struct objc_method_description_t));
  4364. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4365. swapStruct(md);
  4366. print_indent(indent);
  4367. outs() << " name " << format("0x%08" PRIx32, md.name);
  4368. if (info->verbose) {
  4369. name = get_pointer_32(md.name, offset, xleft, S, info, true);
  4370. if (name != nullptr)
  4371. outs() << format(" %.*s", xleft, name);
  4372. else
  4373. outs() << " (not in an __OBJC section)";
  4374. }
  4375. outs() << "\n";
  4376. print_indent(indent);
  4377. outs() << " types " << format("0x%08" PRIx32, md.types);
  4378. if (info->verbose) {
  4379. name = get_pointer_32(md.types, offset, xleft, S, info, true);
  4380. if (name != nullptr)
  4381. outs() << format(" %.*s", xleft, name);
  4382. else
  4383. outs() << " (not in an __OBJC section)";
  4384. }
  4385. outs() << "\n";
  4386. }
  4387. return false;
  4388. }
  4389. static bool print_protocol_list(uint32_t p, uint32_t indent,
  4390. struct DisassembleInfo *info);
  4391. static bool print_protocol(uint32_t p, uint32_t indent,
  4392. struct DisassembleInfo *info) {
  4393. uint32_t offset, left;
  4394. SectionRef S;
  4395. struct objc_protocol_t protocol;
  4396. const char *r, *name;
  4397. r = get_pointer_32(p, offset, left, S, info, true);
  4398. if (r == nullptr)
  4399. return true;
  4400. outs() << "\n";
  4401. if (left >= sizeof(struct objc_protocol_t)) {
  4402. memcpy(&protocol, r, sizeof(struct objc_protocol_t));
  4403. } else {
  4404. print_indent(indent);
  4405. outs() << " Protocol extends past end of the section\n";
  4406. memset(&protocol, '\0', sizeof(struct objc_protocol_t));
  4407. memcpy(&protocol, r, left);
  4408. }
  4409. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4410. swapStruct(protocol);
  4411. print_indent(indent);
  4412. outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
  4413. << "\n";
  4414. print_indent(indent);
  4415. outs() << " protocol_name "
  4416. << format("0x%08" PRIx32, protocol.protocol_name);
  4417. if (info->verbose) {
  4418. name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
  4419. if (name != nullptr)
  4420. outs() << format(" %.*s", left, name);
  4421. else
  4422. outs() << " (not in an __OBJC section)";
  4423. }
  4424. outs() << "\n";
  4425. print_indent(indent);
  4426. outs() << " protocol_list "
  4427. << format("0x%08" PRIx32, protocol.protocol_list);
  4428. if (print_protocol_list(protocol.protocol_list, indent + 4, info))
  4429. outs() << " (not in an __OBJC section)\n";
  4430. print_indent(indent);
  4431. outs() << " instance_methods "
  4432. << format("0x%08" PRIx32, protocol.instance_methods);
  4433. if (print_method_description_list(protocol.instance_methods, indent, info))
  4434. outs() << " (not in an __OBJC section)\n";
  4435. print_indent(indent);
  4436. outs() << " class_methods "
  4437. << format("0x%08" PRIx32, protocol.class_methods);
  4438. if (print_method_description_list(protocol.class_methods, indent, info))
  4439. outs() << " (not in an __OBJC section)\n";
  4440. return false;
  4441. }
  4442. static bool print_protocol_list(uint32_t p, uint32_t indent,
  4443. struct DisassembleInfo *info) {
  4444. uint32_t offset, left, l;
  4445. SectionRef S;
  4446. struct objc_protocol_list_t protocol_list;
  4447. const char *r, *list;
  4448. int32_t i;
  4449. r = get_pointer_32(p, offset, left, S, info, true);
  4450. if (r == nullptr)
  4451. return true;
  4452. outs() << "\n";
  4453. if (left > sizeof(struct objc_protocol_list_t)) {
  4454. memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
  4455. } else {
  4456. outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
  4457. memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
  4458. memcpy(&protocol_list, r, left);
  4459. }
  4460. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4461. swapStruct(protocol_list);
  4462. print_indent(indent);
  4463. outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
  4464. << "\n";
  4465. print_indent(indent);
  4466. outs() << " count " << protocol_list.count << "\n";
  4467. list = r + sizeof(struct objc_protocol_list_t);
  4468. for (i = 0; i < protocol_list.count; i++) {
  4469. if ((i + 1) * sizeof(uint32_t) > left) {
  4470. outs() << "\t\t remaining list entries extend past the of the section\n";
  4471. break;
  4472. }
  4473. memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
  4474. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4475. sys::swapByteOrder(l);
  4476. print_indent(indent);
  4477. outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
  4478. if (print_protocol(l, indent, info))
  4479. outs() << "(not in an __OBJC section)\n";
  4480. }
  4481. return false;
  4482. }
  4483. static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
  4484. struct ivar_list64_t il;
  4485. struct ivar64_t i;
  4486. const char *r;
  4487. uint32_t offset, xoffset, left, j;
  4488. SectionRef S, xS;
  4489. const char *name, *sym_name, *ivar_offset_p;
  4490. uint64_t ivar_offset, n_value;
  4491. r = get_pointer_64(p, offset, left, S, info);
  4492. if (r == nullptr)
  4493. return;
  4494. memset(&il, '\0', sizeof(struct ivar_list64_t));
  4495. if (left < sizeof(struct ivar_list64_t)) {
  4496. memcpy(&il, r, left);
  4497. outs() << " (ivar_list_t entends past the end of the section)\n";
  4498. } else
  4499. memcpy(&il, r, sizeof(struct ivar_list64_t));
  4500. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4501. swapStruct(il);
  4502. outs() << " entsize " << il.entsize << "\n";
  4503. outs() << " count " << il.count << "\n";
  4504. p += sizeof(struct ivar_list64_t);
  4505. offset += sizeof(struct ivar_list64_t);
  4506. for (j = 0; j < il.count; j++) {
  4507. r = get_pointer_64(p, offset, left, S, info);
  4508. if (r == nullptr)
  4509. return;
  4510. memset(&i, '\0', sizeof(struct ivar64_t));
  4511. if (left < sizeof(struct ivar64_t)) {
  4512. memcpy(&i, r, left);
  4513. outs() << " (ivar_t entends past the end of the section)\n";
  4514. } else
  4515. memcpy(&i, r, sizeof(struct ivar64_t));
  4516. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4517. swapStruct(i);
  4518. outs() << "\t\t\t offset ";
  4519. sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
  4520. info, n_value, i.offset);
  4521. if (n_value != 0) {
  4522. if (info->verbose && sym_name != nullptr)
  4523. outs() << sym_name;
  4524. else
  4525. outs() << format("0x%" PRIx64, n_value);
  4526. if (i.offset != 0)
  4527. outs() << " + " << format("0x%" PRIx64, i.offset);
  4528. } else
  4529. outs() << format("0x%" PRIx64, i.offset);
  4530. ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
  4531. if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
  4532. memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
  4533. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4534. sys::swapByteOrder(ivar_offset);
  4535. outs() << " " << ivar_offset << "\n";
  4536. } else
  4537. outs() << "\n";
  4538. outs() << "\t\t\t name ";
  4539. sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
  4540. n_value, i.name);
  4541. if (n_value != 0) {
  4542. if (info->verbose && sym_name != nullptr)
  4543. outs() << sym_name;
  4544. else
  4545. outs() << format("0x%" PRIx64, n_value);
  4546. if (i.name != 0)
  4547. outs() << " + " << format("0x%" PRIx64, i.name);
  4548. } else
  4549. outs() << format("0x%" PRIx64, i.name);
  4550. name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
  4551. if (name != nullptr)
  4552. outs() << format(" %.*s", left, name);
  4553. outs() << "\n";
  4554. outs() << "\t\t\t type ";
  4555. sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
  4556. n_value, i.name);
  4557. name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
  4558. if (n_value != 0) {
  4559. if (info->verbose && sym_name != nullptr)
  4560. outs() << sym_name;
  4561. else
  4562. outs() << format("0x%" PRIx64, n_value);
  4563. if (i.type != 0)
  4564. outs() << " + " << format("0x%" PRIx64, i.type);
  4565. } else
  4566. outs() << format("0x%" PRIx64, i.type);
  4567. if (name != nullptr)
  4568. outs() << format(" %.*s", left, name);
  4569. outs() << "\n";
  4570. outs() << "\t\t\talignment " << i.alignment << "\n";
  4571. outs() << "\t\t\t size " << i.size << "\n";
  4572. p += sizeof(struct ivar64_t);
  4573. offset += sizeof(struct ivar64_t);
  4574. }
  4575. }
  4576. static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
  4577. struct ivar_list32_t il;
  4578. struct ivar32_t i;
  4579. const char *r;
  4580. uint32_t offset, xoffset, left, j;
  4581. SectionRef S, xS;
  4582. const char *name, *ivar_offset_p;
  4583. uint32_t ivar_offset;
  4584. r = get_pointer_32(p, offset, left, S, info);
  4585. if (r == nullptr)
  4586. return;
  4587. memset(&il, '\0', sizeof(struct ivar_list32_t));
  4588. if (left < sizeof(struct ivar_list32_t)) {
  4589. memcpy(&il, r, left);
  4590. outs() << " (ivar_list_t entends past the end of the section)\n";
  4591. } else
  4592. memcpy(&il, r, sizeof(struct ivar_list32_t));
  4593. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4594. swapStruct(il);
  4595. outs() << " entsize " << il.entsize << "\n";
  4596. outs() << " count " << il.count << "\n";
  4597. p += sizeof(struct ivar_list32_t);
  4598. offset += sizeof(struct ivar_list32_t);
  4599. for (j = 0; j < il.count; j++) {
  4600. r = get_pointer_32(p, offset, left, S, info);
  4601. if (r == nullptr)
  4602. return;
  4603. memset(&i, '\0', sizeof(struct ivar32_t));
  4604. if (left < sizeof(struct ivar32_t)) {
  4605. memcpy(&i, r, left);
  4606. outs() << " (ivar_t entends past the end of the section)\n";
  4607. } else
  4608. memcpy(&i, r, sizeof(struct ivar32_t));
  4609. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4610. swapStruct(i);
  4611. outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
  4612. ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
  4613. if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
  4614. memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
  4615. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4616. sys::swapByteOrder(ivar_offset);
  4617. outs() << " " << ivar_offset << "\n";
  4618. } else
  4619. outs() << "\n";
  4620. outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
  4621. name = get_pointer_32(i.name, xoffset, left, xS, info);
  4622. if (name != nullptr)
  4623. outs() << format(" %.*s", left, name);
  4624. outs() << "\n";
  4625. outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
  4626. name = get_pointer_32(i.type, xoffset, left, xS, info);
  4627. if (name != nullptr)
  4628. outs() << format(" %.*s", left, name);
  4629. outs() << "\n";
  4630. outs() << "\t\t\talignment " << i.alignment << "\n";
  4631. outs() << "\t\t\t size " << i.size << "\n";
  4632. p += sizeof(struct ivar32_t);
  4633. offset += sizeof(struct ivar32_t);
  4634. }
  4635. }
  4636. static void print_objc_property_list64(uint64_t p,
  4637. struct DisassembleInfo *info) {
  4638. struct objc_property_list64 opl;
  4639. struct objc_property64 op;
  4640. const char *r;
  4641. uint32_t offset, xoffset, left, j;
  4642. SectionRef S, xS;
  4643. const char *name, *sym_name;
  4644. uint64_t n_value;
  4645. r = get_pointer_64(p, offset, left, S, info);
  4646. if (r == nullptr)
  4647. return;
  4648. memset(&opl, '\0', sizeof(struct objc_property_list64));
  4649. if (left < sizeof(struct objc_property_list64)) {
  4650. memcpy(&opl, r, left);
  4651. outs() << " (objc_property_list entends past the end of the section)\n";
  4652. } else
  4653. memcpy(&opl, r, sizeof(struct objc_property_list64));
  4654. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4655. swapStruct(opl);
  4656. outs() << " entsize " << opl.entsize << "\n";
  4657. outs() << " count " << opl.count << "\n";
  4658. p += sizeof(struct objc_property_list64);
  4659. offset += sizeof(struct objc_property_list64);
  4660. for (j = 0; j < opl.count; j++) {
  4661. r = get_pointer_64(p, offset, left, S, info);
  4662. if (r == nullptr)
  4663. return;
  4664. memset(&op, '\0', sizeof(struct objc_property64));
  4665. if (left < sizeof(struct objc_property64)) {
  4666. memcpy(&op, r, left);
  4667. outs() << " (objc_property entends past the end of the section)\n";
  4668. } else
  4669. memcpy(&op, r, sizeof(struct objc_property64));
  4670. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4671. swapStruct(op);
  4672. outs() << "\t\t\t name ";
  4673. sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
  4674. info, n_value, op.name);
  4675. if (n_value != 0) {
  4676. if (info->verbose && sym_name != nullptr)
  4677. outs() << sym_name;
  4678. else
  4679. outs() << format("0x%" PRIx64, n_value);
  4680. if (op.name != 0)
  4681. outs() << " + " << format("0x%" PRIx64, op.name);
  4682. } else
  4683. outs() << format("0x%" PRIx64, op.name);
  4684. name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
  4685. if (name != nullptr)
  4686. outs() << format(" %.*s", left, name);
  4687. outs() << "\n";
  4688. outs() << "\t\t\tattributes ";
  4689. sym_name =
  4690. get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
  4691. info, n_value, op.attributes);
  4692. if (n_value != 0) {
  4693. if (info->verbose && sym_name != nullptr)
  4694. outs() << sym_name;
  4695. else
  4696. outs() << format("0x%" PRIx64, n_value);
  4697. if (op.attributes != 0)
  4698. outs() << " + " << format("0x%" PRIx64, op.attributes);
  4699. } else
  4700. outs() << format("0x%" PRIx64, op.attributes);
  4701. name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
  4702. if (name != nullptr)
  4703. outs() << format(" %.*s", left, name);
  4704. outs() << "\n";
  4705. p += sizeof(struct objc_property64);
  4706. offset += sizeof(struct objc_property64);
  4707. }
  4708. }
  4709. static void print_objc_property_list32(uint32_t p,
  4710. struct DisassembleInfo *info) {
  4711. struct objc_property_list32 opl;
  4712. struct objc_property32 op;
  4713. const char *r;
  4714. uint32_t offset, xoffset, left, j;
  4715. SectionRef S, xS;
  4716. const char *name;
  4717. r = get_pointer_32(p, offset, left, S, info);
  4718. if (r == nullptr)
  4719. return;
  4720. memset(&opl, '\0', sizeof(struct objc_property_list32));
  4721. if (left < sizeof(struct objc_property_list32)) {
  4722. memcpy(&opl, r, left);
  4723. outs() << " (objc_property_list entends past the end of the section)\n";
  4724. } else
  4725. memcpy(&opl, r, sizeof(struct objc_property_list32));
  4726. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4727. swapStruct(opl);
  4728. outs() << " entsize " << opl.entsize << "\n";
  4729. outs() << " count " << opl.count << "\n";
  4730. p += sizeof(struct objc_property_list32);
  4731. offset += sizeof(struct objc_property_list32);
  4732. for (j = 0; j < opl.count; j++) {
  4733. r = get_pointer_32(p, offset, left, S, info);
  4734. if (r == nullptr)
  4735. return;
  4736. memset(&op, '\0', sizeof(struct objc_property32));
  4737. if (left < sizeof(struct objc_property32)) {
  4738. memcpy(&op, r, left);
  4739. outs() << " (objc_property entends past the end of the section)\n";
  4740. } else
  4741. memcpy(&op, r, sizeof(struct objc_property32));
  4742. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4743. swapStruct(op);
  4744. outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
  4745. name = get_pointer_32(op.name, xoffset, left, xS, info);
  4746. if (name != nullptr)
  4747. outs() << format(" %.*s", left, name);
  4748. outs() << "\n";
  4749. outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
  4750. name = get_pointer_32(op.attributes, xoffset, left, xS, info);
  4751. if (name != nullptr)
  4752. outs() << format(" %.*s", left, name);
  4753. outs() << "\n";
  4754. p += sizeof(struct objc_property32);
  4755. offset += sizeof(struct objc_property32);
  4756. }
  4757. }
  4758. static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
  4759. bool &is_meta_class) {
  4760. struct class_ro64_t cro;
  4761. const char *r;
  4762. uint32_t offset, xoffset, left;
  4763. SectionRef S, xS;
  4764. const char *name, *sym_name;
  4765. uint64_t n_value;
  4766. r = get_pointer_64(p, offset, left, S, info);
  4767. if (r == nullptr || left < sizeof(struct class_ro64_t))
  4768. return false;
  4769. memcpy(&cro, r, sizeof(struct class_ro64_t));
  4770. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4771. swapStruct(cro);
  4772. outs() << " flags " << format("0x%" PRIx32, cro.flags);
  4773. if (cro.flags & RO_META)
  4774. outs() << " RO_META";
  4775. if (cro.flags & RO_ROOT)
  4776. outs() << " RO_ROOT";
  4777. if (cro.flags & RO_HAS_CXX_STRUCTORS)
  4778. outs() << " RO_HAS_CXX_STRUCTORS";
  4779. outs() << "\n";
  4780. outs() << " instanceStart " << cro.instanceStart << "\n";
  4781. outs() << " instanceSize " << cro.instanceSize << "\n";
  4782. outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
  4783. << "\n";
  4784. outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
  4785. << "\n";
  4786. print_layout_map64(cro.ivarLayout, info);
  4787. outs() << " name ";
  4788. sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
  4789. info, n_value, cro.name);
  4790. if (n_value != 0) {
  4791. if (info->verbose && sym_name != nullptr)
  4792. outs() << sym_name;
  4793. else
  4794. outs() << format("0x%" PRIx64, n_value);
  4795. if (cro.name != 0)
  4796. outs() << " + " << format("0x%" PRIx64, cro.name);
  4797. } else
  4798. outs() << format("0x%" PRIx64, cro.name);
  4799. name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
  4800. if (name != nullptr)
  4801. outs() << format(" %.*s", left, name);
  4802. outs() << "\n";
  4803. outs() << " baseMethods ";
  4804. sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
  4805. S, info, n_value, cro.baseMethods);
  4806. if (n_value != 0) {
  4807. if (info->verbose && sym_name != nullptr)
  4808. outs() << sym_name;
  4809. else
  4810. outs() << format("0x%" PRIx64, n_value);
  4811. if (cro.baseMethods != 0)
  4812. outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
  4813. } else
  4814. outs() << format("0x%" PRIx64, cro.baseMethods);
  4815. outs() << " (struct method_list_t *)\n";
  4816. if (cro.baseMethods + n_value != 0)
  4817. print_method_list64_t(cro.baseMethods + n_value, info, "");
  4818. outs() << " baseProtocols ";
  4819. sym_name =
  4820. get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
  4821. info, n_value, cro.baseProtocols);
  4822. if (n_value != 0) {
  4823. if (info->verbose && sym_name != nullptr)
  4824. outs() << sym_name;
  4825. else
  4826. outs() << format("0x%" PRIx64, n_value);
  4827. if (cro.baseProtocols != 0)
  4828. outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
  4829. } else
  4830. outs() << format("0x%" PRIx64, cro.baseProtocols);
  4831. outs() << "\n";
  4832. if (cro.baseProtocols + n_value != 0)
  4833. print_protocol_list64_t(cro.baseProtocols + n_value, info);
  4834. outs() << " ivars ";
  4835. sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
  4836. info, n_value, cro.ivars);
  4837. if (n_value != 0) {
  4838. if (info->verbose && sym_name != nullptr)
  4839. outs() << sym_name;
  4840. else
  4841. outs() << format("0x%" PRIx64, n_value);
  4842. if (cro.ivars != 0)
  4843. outs() << " + " << format("0x%" PRIx64, cro.ivars);
  4844. } else
  4845. outs() << format("0x%" PRIx64, cro.ivars);
  4846. outs() << "\n";
  4847. if (cro.ivars + n_value != 0)
  4848. print_ivar_list64_t(cro.ivars + n_value, info);
  4849. outs() << " weakIvarLayout ";
  4850. sym_name =
  4851. get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
  4852. info, n_value, cro.weakIvarLayout);
  4853. if (n_value != 0) {
  4854. if (info->verbose && sym_name != nullptr)
  4855. outs() << sym_name;
  4856. else
  4857. outs() << format("0x%" PRIx64, n_value);
  4858. if (cro.weakIvarLayout != 0)
  4859. outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
  4860. } else
  4861. outs() << format("0x%" PRIx64, cro.weakIvarLayout);
  4862. outs() << "\n";
  4863. print_layout_map64(cro.weakIvarLayout + n_value, info);
  4864. outs() << " baseProperties ";
  4865. sym_name =
  4866. get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
  4867. info, n_value, cro.baseProperties);
  4868. if (n_value != 0) {
  4869. if (info->verbose && sym_name != nullptr)
  4870. outs() << sym_name;
  4871. else
  4872. outs() << format("0x%" PRIx64, n_value);
  4873. if (cro.baseProperties != 0)
  4874. outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
  4875. } else
  4876. outs() << format("0x%" PRIx64, cro.baseProperties);
  4877. outs() << "\n";
  4878. if (cro.baseProperties + n_value != 0)
  4879. print_objc_property_list64(cro.baseProperties + n_value, info);
  4880. is_meta_class = (cro.flags & RO_META) != 0;
  4881. return true;
  4882. }
  4883. static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
  4884. bool &is_meta_class) {
  4885. struct class_ro32_t cro;
  4886. const char *r;
  4887. uint32_t offset, xoffset, left;
  4888. SectionRef S, xS;
  4889. const char *name;
  4890. r = get_pointer_32(p, offset, left, S, info);
  4891. if (r == nullptr)
  4892. return false;
  4893. memset(&cro, '\0', sizeof(struct class_ro32_t));
  4894. if (left < sizeof(struct class_ro32_t)) {
  4895. memcpy(&cro, r, left);
  4896. outs() << " (class_ro_t entends past the end of the section)\n";
  4897. } else
  4898. memcpy(&cro, r, sizeof(struct class_ro32_t));
  4899. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4900. swapStruct(cro);
  4901. outs() << " flags " << format("0x%" PRIx32, cro.flags);
  4902. if (cro.flags & RO_META)
  4903. outs() << " RO_META";
  4904. if (cro.flags & RO_ROOT)
  4905. outs() << " RO_ROOT";
  4906. if (cro.flags & RO_HAS_CXX_STRUCTORS)
  4907. outs() << " RO_HAS_CXX_STRUCTORS";
  4908. outs() << "\n";
  4909. outs() << " instanceStart " << cro.instanceStart << "\n";
  4910. outs() << " instanceSize " << cro.instanceSize << "\n";
  4911. outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
  4912. << "\n";
  4913. print_layout_map32(cro.ivarLayout, info);
  4914. outs() << " name " << format("0x%" PRIx32, cro.name);
  4915. name = get_pointer_32(cro.name, xoffset, left, xS, info);
  4916. if (name != nullptr)
  4917. outs() << format(" %.*s", left, name);
  4918. outs() << "\n";
  4919. outs() << " baseMethods "
  4920. << format("0x%" PRIx32, cro.baseMethods)
  4921. << " (struct method_list_t *)\n";
  4922. if (cro.baseMethods != 0)
  4923. print_method_list32_t(cro.baseMethods, info, "");
  4924. outs() << " baseProtocols "
  4925. << format("0x%" PRIx32, cro.baseProtocols) << "\n";
  4926. if (cro.baseProtocols != 0)
  4927. print_protocol_list32_t(cro.baseProtocols, info);
  4928. outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
  4929. << "\n";
  4930. if (cro.ivars != 0)
  4931. print_ivar_list32_t(cro.ivars, info);
  4932. outs() << " weakIvarLayout "
  4933. << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
  4934. print_layout_map32(cro.weakIvarLayout, info);
  4935. outs() << " baseProperties "
  4936. << format("0x%" PRIx32, cro.baseProperties) << "\n";
  4937. if (cro.baseProperties != 0)
  4938. print_objc_property_list32(cro.baseProperties, info);
  4939. is_meta_class = (cro.flags & RO_META) != 0;
  4940. return true;
  4941. }
  4942. static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
  4943. struct class64_t c;
  4944. const char *r;
  4945. uint32_t offset, left;
  4946. SectionRef S;
  4947. const char *name;
  4948. uint64_t isa_n_value, n_value;
  4949. r = get_pointer_64(p, offset, left, S, info);
  4950. if (r == nullptr || left < sizeof(struct class64_t))
  4951. return;
  4952. memcpy(&c, r, sizeof(struct class64_t));
  4953. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4954. swapStruct(c);
  4955. outs() << " isa " << format("0x%" PRIx64, c.isa);
  4956. name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
  4957. isa_n_value, c.isa);
  4958. if (name != nullptr)
  4959. outs() << " " << name;
  4960. outs() << "\n";
  4961. outs() << " superclass " << format("0x%" PRIx64, c.superclass);
  4962. name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
  4963. n_value, c.superclass);
  4964. if (name != nullptr)
  4965. outs() << " " << name;
  4966. else {
  4967. name = get_dyld_bind_info_symbolname(S.getAddress() +
  4968. offset + offsetof(struct class64_t, superclass), info);
  4969. if (name != nullptr)
  4970. outs() << " " << name;
  4971. }
  4972. outs() << "\n";
  4973. outs() << " cache " << format("0x%" PRIx64, c.cache);
  4974. name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
  4975. n_value, c.cache);
  4976. if (name != nullptr)
  4977. outs() << " " << name;
  4978. outs() << "\n";
  4979. outs() << " vtable " << format("0x%" PRIx64, c.vtable);
  4980. name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
  4981. n_value, c.vtable);
  4982. if (name != nullptr)
  4983. outs() << " " << name;
  4984. outs() << "\n";
  4985. name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
  4986. n_value, c.data);
  4987. outs() << " data ";
  4988. if (n_value != 0) {
  4989. if (info->verbose && name != nullptr)
  4990. outs() << name;
  4991. else
  4992. outs() << format("0x%" PRIx64, n_value);
  4993. if (c.data != 0)
  4994. outs() << " + " << format("0x%" PRIx64, c.data);
  4995. } else
  4996. outs() << format("0x%" PRIx64, c.data);
  4997. outs() << " (struct class_ro_t *)";
  4998. // This is a Swift class if some of the low bits of the pointer are set.
  4999. if ((c.data + n_value) & 0x7)
  5000. outs() << " Swift class";
  5001. outs() << "\n";
  5002. bool is_meta_class;
  5003. if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
  5004. return;
  5005. if (!is_meta_class &&
  5006. c.isa + isa_n_value != p &&
  5007. c.isa + isa_n_value != 0 &&
  5008. info->depth < 100) {
  5009. info->depth++;
  5010. outs() << "Meta Class\n";
  5011. print_class64_t(c.isa + isa_n_value, info);
  5012. }
  5013. }
  5014. static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
  5015. struct class32_t c;
  5016. const char *r;
  5017. uint32_t offset, left;
  5018. SectionRef S;
  5019. const char *name;
  5020. r = get_pointer_32(p, offset, left, S, info);
  5021. if (r == nullptr)
  5022. return;
  5023. memset(&c, '\0', sizeof(struct class32_t));
  5024. if (left < sizeof(struct class32_t)) {
  5025. memcpy(&c, r, left);
  5026. outs() << " (class_t entends past the end of the section)\n";
  5027. } else
  5028. memcpy(&c, r, sizeof(struct class32_t));
  5029. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5030. swapStruct(c);
  5031. outs() << " isa " << format("0x%" PRIx32, c.isa);
  5032. name =
  5033. get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
  5034. if (name != nullptr)
  5035. outs() << " " << name;
  5036. outs() << "\n";
  5037. outs() << " superclass " << format("0x%" PRIx32, c.superclass);
  5038. name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
  5039. c.superclass);
  5040. if (name != nullptr)
  5041. outs() << " " << name;
  5042. outs() << "\n";
  5043. outs() << " cache " << format("0x%" PRIx32, c.cache);
  5044. name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
  5045. c.cache);
  5046. if (name != nullptr)
  5047. outs() << " " << name;
  5048. outs() << "\n";
  5049. outs() << " vtable " << format("0x%" PRIx32, c.vtable);
  5050. name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
  5051. c.vtable);
  5052. if (name != nullptr)
  5053. outs() << " " << name;
  5054. outs() << "\n";
  5055. name =
  5056. get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
  5057. outs() << " data " << format("0x%" PRIx32, c.data)
  5058. << " (struct class_ro_t *)";
  5059. // This is a Swift class if some of the low bits of the pointer are set.
  5060. if (c.data & 0x3)
  5061. outs() << " Swift class";
  5062. outs() << "\n";
  5063. bool is_meta_class;
  5064. if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
  5065. return;
  5066. if (!is_meta_class) {
  5067. outs() << "Meta Class\n";
  5068. print_class32_t(c.isa, info);
  5069. }
  5070. }
  5071. static void print_objc_class_t(struct objc_class_t *objc_class,
  5072. struct DisassembleInfo *info) {
  5073. uint32_t offset, left, xleft;
  5074. const char *name, *p, *ivar_list;
  5075. SectionRef S;
  5076. int32_t i;
  5077. struct objc_ivar_list_t objc_ivar_list;
  5078. struct objc_ivar_t ivar;
  5079. outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
  5080. if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
  5081. name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
  5082. if (name != nullptr)
  5083. outs() << format(" %.*s", left, name);
  5084. else
  5085. outs() << " (not in an __OBJC section)";
  5086. }
  5087. outs() << "\n";
  5088. outs() << "\t super_class "
  5089. << format("0x%08" PRIx32, objc_class->super_class);
  5090. if (info->verbose) {
  5091. name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
  5092. if (name != nullptr)
  5093. outs() << format(" %.*s", left, name);
  5094. else
  5095. outs() << " (not in an __OBJC section)";
  5096. }
  5097. outs() << "\n";
  5098. outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
  5099. if (info->verbose) {
  5100. name = get_pointer_32(objc_class->name, offset, left, S, info, true);
  5101. if (name != nullptr)
  5102. outs() << format(" %.*s", left, name);
  5103. else
  5104. outs() << " (not in an __OBJC section)";
  5105. }
  5106. outs() << "\n";
  5107. outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
  5108. << "\n";
  5109. outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
  5110. if (info->verbose) {
  5111. if (CLS_GETINFO(objc_class, CLS_CLASS))
  5112. outs() << " CLS_CLASS";
  5113. else if (CLS_GETINFO(objc_class, CLS_META))
  5114. outs() << " CLS_META";
  5115. }
  5116. outs() << "\n";
  5117. outs() << "\t instance_size "
  5118. << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
  5119. p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
  5120. outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
  5121. if (p != nullptr) {
  5122. if (left > sizeof(struct objc_ivar_list_t)) {
  5123. outs() << "\n";
  5124. memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
  5125. } else {
  5126. outs() << " (entends past the end of the section)\n";
  5127. memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
  5128. memcpy(&objc_ivar_list, p, left);
  5129. }
  5130. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5131. swapStruct(objc_ivar_list);
  5132. outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
  5133. ivar_list = p + sizeof(struct objc_ivar_list_t);
  5134. for (i = 0; i < objc_ivar_list.ivar_count; i++) {
  5135. if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
  5136. outs() << "\t\t remaining ivar's extend past the of the section\n";
  5137. break;
  5138. }
  5139. memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
  5140. sizeof(struct objc_ivar_t));
  5141. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5142. swapStruct(ivar);
  5143. outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
  5144. if (info->verbose) {
  5145. name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
  5146. if (name != nullptr)
  5147. outs() << format(" %.*s", xleft, name);
  5148. else
  5149. outs() << " (not in an __OBJC section)";
  5150. }
  5151. outs() << "\n";
  5152. outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
  5153. if (info->verbose) {
  5154. name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
  5155. if (name != nullptr)
  5156. outs() << format(" %.*s", xleft, name);
  5157. else
  5158. outs() << " (not in an __OBJC section)";
  5159. }
  5160. outs() << "\n";
  5161. outs() << "\t\t ivar_offset "
  5162. << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
  5163. }
  5164. } else {
  5165. outs() << " (not in an __OBJC section)\n";
  5166. }
  5167. outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
  5168. if (print_method_list(objc_class->methodLists, info))
  5169. outs() << " (not in an __OBJC section)\n";
  5170. outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
  5171. << "\n";
  5172. outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
  5173. if (print_protocol_list(objc_class->protocols, 16, info))
  5174. outs() << " (not in an __OBJC section)\n";
  5175. }
  5176. static void print_objc_objc_category_t(struct objc_category_t *objc_category,
  5177. struct DisassembleInfo *info) {
  5178. uint32_t offset, left;
  5179. const char *name;
  5180. SectionRef S;
  5181. outs() << "\t category name "
  5182. << format("0x%08" PRIx32, objc_category->category_name);
  5183. if (info->verbose) {
  5184. name = get_pointer_32(objc_category->category_name, offset, left, S, info,
  5185. true);
  5186. if (name != nullptr)
  5187. outs() << format(" %.*s", left, name);
  5188. else
  5189. outs() << " (not in an __OBJC section)";
  5190. }
  5191. outs() << "\n";
  5192. outs() << "\t\t class name "
  5193. << format("0x%08" PRIx32, objc_category->class_name);
  5194. if (info->verbose) {
  5195. name =
  5196. get_pointer_32(objc_category->class_name, offset, left, S, info, true);
  5197. if (name != nullptr)
  5198. outs() << format(" %.*s", left, name);
  5199. else
  5200. outs() << " (not in an __OBJC section)";
  5201. }
  5202. outs() << "\n";
  5203. outs() << "\t instance methods "
  5204. << format("0x%08" PRIx32, objc_category->instance_methods);
  5205. if (print_method_list(objc_category->instance_methods, info))
  5206. outs() << " (not in an __OBJC section)\n";
  5207. outs() << "\t class methods "
  5208. << format("0x%08" PRIx32, objc_category->class_methods);
  5209. if (print_method_list(objc_category->class_methods, info))
  5210. outs() << " (not in an __OBJC section)\n";
  5211. }
  5212. static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
  5213. struct category64_t c;
  5214. const char *r;
  5215. uint32_t offset, xoffset, left;
  5216. SectionRef S, xS;
  5217. const char *name, *sym_name;
  5218. uint64_t n_value;
  5219. r = get_pointer_64(p, offset, left, S, info);
  5220. if (r == nullptr)
  5221. return;
  5222. memset(&c, '\0', sizeof(struct category64_t));
  5223. if (left < sizeof(struct category64_t)) {
  5224. memcpy(&c, r, left);
  5225. outs() << " (category_t entends past the end of the section)\n";
  5226. } else
  5227. memcpy(&c, r, sizeof(struct category64_t));
  5228. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5229. swapStruct(c);
  5230. outs() << " name ";
  5231. sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
  5232. info, n_value, c.name);
  5233. if (n_value != 0) {
  5234. if (info->verbose && sym_name != nullptr)
  5235. outs() << sym_name;
  5236. else
  5237. outs() << format("0x%" PRIx64, n_value);
  5238. if (c.name != 0)
  5239. outs() << " + " << format("0x%" PRIx64, c.name);
  5240. } else
  5241. outs() << format("0x%" PRIx64, c.name);
  5242. name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
  5243. if (name != nullptr)
  5244. outs() << format(" %.*s", left, name);
  5245. outs() << "\n";
  5246. outs() << " cls ";
  5247. sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
  5248. n_value, c.cls);
  5249. if (n_value != 0) {
  5250. if (info->verbose && sym_name != nullptr)
  5251. outs() << sym_name;
  5252. else
  5253. outs() << format("0x%" PRIx64, n_value);
  5254. if (c.cls != 0)
  5255. outs() << " + " << format("0x%" PRIx64, c.cls);
  5256. } else
  5257. outs() << format("0x%" PRIx64, c.cls);
  5258. outs() << "\n";
  5259. if (c.cls + n_value != 0)
  5260. print_class64_t(c.cls + n_value, info);
  5261. outs() << " instanceMethods ";
  5262. sym_name =
  5263. get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
  5264. info, n_value, c.instanceMethods);
  5265. if (n_value != 0) {
  5266. if (info->verbose && sym_name != nullptr)
  5267. outs() << sym_name;
  5268. else
  5269. outs() << format("0x%" PRIx64, n_value);
  5270. if (c.instanceMethods != 0)
  5271. outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
  5272. } else
  5273. outs() << format("0x%" PRIx64, c.instanceMethods);
  5274. outs() << "\n";
  5275. if (c.instanceMethods + n_value != 0)
  5276. print_method_list64_t(c.instanceMethods + n_value, info, "");
  5277. outs() << " classMethods ";
  5278. sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
  5279. S, info, n_value, c.classMethods);
  5280. if (n_value != 0) {
  5281. if (info->verbose && sym_name != nullptr)
  5282. outs() << sym_name;
  5283. else
  5284. outs() << format("0x%" PRIx64, n_value);
  5285. if (c.classMethods != 0)
  5286. outs() << " + " << format("0x%" PRIx64, c.classMethods);
  5287. } else
  5288. outs() << format("0x%" PRIx64, c.classMethods);
  5289. outs() << "\n";
  5290. if (c.classMethods + n_value != 0)
  5291. print_method_list64_t(c.classMethods + n_value, info, "");
  5292. outs() << " protocols ";
  5293. sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
  5294. info, n_value, c.protocols);
  5295. if (n_value != 0) {
  5296. if (info->verbose && sym_name != nullptr)
  5297. outs() << sym_name;
  5298. else
  5299. outs() << format("0x%" PRIx64, n_value);
  5300. if (c.protocols != 0)
  5301. outs() << " + " << format("0x%" PRIx64, c.protocols);
  5302. } else
  5303. outs() << format("0x%" PRIx64, c.protocols);
  5304. outs() << "\n";
  5305. if (c.protocols + n_value != 0)
  5306. print_protocol_list64_t(c.protocols + n_value, info);
  5307. outs() << "instanceProperties ";
  5308. sym_name =
  5309. get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
  5310. S, info, n_value, c.instanceProperties);
  5311. if (n_value != 0) {
  5312. if (info->verbose && sym_name != nullptr)
  5313. outs() << sym_name;
  5314. else
  5315. outs() << format("0x%" PRIx64, n_value);
  5316. if (c.instanceProperties != 0)
  5317. outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
  5318. } else
  5319. outs() << format("0x%" PRIx64, c.instanceProperties);
  5320. outs() << "\n";
  5321. if (c.instanceProperties + n_value != 0)
  5322. print_objc_property_list64(c.instanceProperties + n_value, info);
  5323. }
  5324. static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
  5325. struct category32_t c;
  5326. const char *r;
  5327. uint32_t offset, left;
  5328. SectionRef S, xS;
  5329. const char *name;
  5330. r = get_pointer_32(p, offset, left, S, info);
  5331. if (r == nullptr)
  5332. return;
  5333. memset(&c, '\0', sizeof(struct category32_t));
  5334. if (left < sizeof(struct category32_t)) {
  5335. memcpy(&c, r, left);
  5336. outs() << " (category_t entends past the end of the section)\n";
  5337. } else
  5338. memcpy(&c, r, sizeof(struct category32_t));
  5339. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5340. swapStruct(c);
  5341. outs() << " name " << format("0x%" PRIx32, c.name);
  5342. name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
  5343. c.name);
  5344. if (name)
  5345. outs() << " " << name;
  5346. outs() << "\n";
  5347. outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
  5348. if (c.cls != 0)
  5349. print_class32_t(c.cls, info);
  5350. outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
  5351. << "\n";
  5352. if (c.instanceMethods != 0)
  5353. print_method_list32_t(c.instanceMethods, info, "");
  5354. outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
  5355. << "\n";
  5356. if (c.classMethods != 0)
  5357. print_method_list32_t(c.classMethods, info, "");
  5358. outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
  5359. if (c.protocols != 0)
  5360. print_protocol_list32_t(c.protocols, info);
  5361. outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
  5362. << "\n";
  5363. if (c.instanceProperties != 0)
  5364. print_objc_property_list32(c.instanceProperties, info);
  5365. }
  5366. static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
  5367. uint32_t i, left, offset, xoffset;
  5368. uint64_t p, n_value;
  5369. struct message_ref64 mr;
  5370. const char *name, *sym_name;
  5371. const char *r;
  5372. SectionRef xS;
  5373. if (S == SectionRef())
  5374. return;
  5375. StringRef SectName;
  5376. Expected<StringRef> SecNameOrErr = S.getName();
  5377. if (SecNameOrErr)
  5378. SectName = *SecNameOrErr;
  5379. else
  5380. consumeError(SecNameOrErr.takeError());
  5381. DataRefImpl Ref = S.getRawDataRefImpl();
  5382. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  5383. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  5384. offset = 0;
  5385. for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
  5386. p = S.getAddress() + i;
  5387. r = get_pointer_64(p, offset, left, S, info);
  5388. if (r == nullptr)
  5389. return;
  5390. memset(&mr, '\0', sizeof(struct message_ref64));
  5391. if (left < sizeof(struct message_ref64)) {
  5392. memcpy(&mr, r, left);
  5393. outs() << " (message_ref entends past the end of the section)\n";
  5394. } else
  5395. memcpy(&mr, r, sizeof(struct message_ref64));
  5396. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5397. swapStruct(mr);
  5398. outs() << " imp ";
  5399. name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
  5400. n_value, mr.imp);
  5401. if (n_value != 0) {
  5402. outs() << format("0x%" PRIx64, n_value) << " ";
  5403. if (mr.imp != 0)
  5404. outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
  5405. } else
  5406. outs() << format("0x%" PRIx64, mr.imp) << " ";
  5407. if (name != nullptr)
  5408. outs() << " " << name;
  5409. outs() << "\n";
  5410. outs() << " sel ";
  5411. sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
  5412. info, n_value, mr.sel);
  5413. if (n_value != 0) {
  5414. if (info->verbose && sym_name != nullptr)
  5415. outs() << sym_name;
  5416. else
  5417. outs() << format("0x%" PRIx64, n_value);
  5418. if (mr.sel != 0)
  5419. outs() << " + " << format("0x%" PRIx64, mr.sel);
  5420. } else
  5421. outs() << format("0x%" PRIx64, mr.sel);
  5422. name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
  5423. if (name != nullptr)
  5424. outs() << format(" %.*s", left, name);
  5425. outs() << "\n";
  5426. offset += sizeof(struct message_ref64);
  5427. }
  5428. }
  5429. static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
  5430. uint32_t i, left, offset, xoffset, p;
  5431. struct message_ref32 mr;
  5432. const char *name, *r;
  5433. SectionRef xS;
  5434. if (S == SectionRef())
  5435. return;
  5436. StringRef SectName;
  5437. Expected<StringRef> SecNameOrErr = S.getName();
  5438. if (SecNameOrErr)
  5439. SectName = *SecNameOrErr;
  5440. else
  5441. consumeError(SecNameOrErr.takeError());
  5442. DataRefImpl Ref = S.getRawDataRefImpl();
  5443. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  5444. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  5445. offset = 0;
  5446. for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
  5447. p = S.getAddress() + i;
  5448. r = get_pointer_32(p, offset, left, S, info);
  5449. if (r == nullptr)
  5450. return;
  5451. memset(&mr, '\0', sizeof(struct message_ref32));
  5452. if (left < sizeof(struct message_ref32)) {
  5453. memcpy(&mr, r, left);
  5454. outs() << " (message_ref entends past the end of the section)\n";
  5455. } else
  5456. memcpy(&mr, r, sizeof(struct message_ref32));
  5457. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5458. swapStruct(mr);
  5459. outs() << " imp " << format("0x%" PRIx32, mr.imp);
  5460. name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
  5461. mr.imp);
  5462. if (name != nullptr)
  5463. outs() << " " << name;
  5464. outs() << "\n";
  5465. outs() << " sel " << format("0x%" PRIx32, mr.sel);
  5466. name = get_pointer_32(mr.sel, xoffset, left, xS, info);
  5467. if (name != nullptr)
  5468. outs() << " " << name;
  5469. outs() << "\n";
  5470. offset += sizeof(struct message_ref32);
  5471. }
  5472. }
  5473. static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
  5474. uint32_t left, offset, swift_version;
  5475. uint64_t p;
  5476. struct objc_image_info64 o;
  5477. const char *r;
  5478. if (S == SectionRef())
  5479. return;
  5480. StringRef SectName;
  5481. Expected<StringRef> SecNameOrErr = S.getName();
  5482. if (SecNameOrErr)
  5483. SectName = *SecNameOrErr;
  5484. else
  5485. consumeError(SecNameOrErr.takeError());
  5486. DataRefImpl Ref = S.getRawDataRefImpl();
  5487. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  5488. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  5489. p = S.getAddress();
  5490. r = get_pointer_64(p, offset, left, S, info);
  5491. if (r == nullptr)
  5492. return;
  5493. memset(&o, '\0', sizeof(struct objc_image_info64));
  5494. if (left < sizeof(struct objc_image_info64)) {
  5495. memcpy(&o, r, left);
  5496. outs() << " (objc_image_info entends past the end of the section)\n";
  5497. } else
  5498. memcpy(&o, r, sizeof(struct objc_image_info64));
  5499. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5500. swapStruct(o);
  5501. outs() << " version " << o.version << "\n";
  5502. outs() << " flags " << format("0x%" PRIx32, o.flags);
  5503. if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
  5504. outs() << " OBJC_IMAGE_IS_REPLACEMENT";
  5505. if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
  5506. outs() << " OBJC_IMAGE_SUPPORTS_GC";
  5507. if (o.flags & OBJC_IMAGE_IS_SIMULATED)
  5508. outs() << " OBJC_IMAGE_IS_SIMULATED";
  5509. if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
  5510. outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
  5511. swift_version = (o.flags >> 8) & 0xff;
  5512. if (swift_version != 0) {
  5513. if (swift_version == 1)
  5514. outs() << " Swift 1.0";
  5515. else if (swift_version == 2)
  5516. outs() << " Swift 1.1";
  5517. else if(swift_version == 3)
  5518. outs() << " Swift 2.0";
  5519. else if(swift_version == 4)
  5520. outs() << " Swift 3.0";
  5521. else if(swift_version == 5)
  5522. outs() << " Swift 4.0";
  5523. else if(swift_version == 6)
  5524. outs() << " Swift 4.1/Swift 4.2";
  5525. else if(swift_version == 7)
  5526. outs() << " Swift 5 or later";
  5527. else
  5528. outs() << " unknown future Swift version (" << swift_version << ")";
  5529. }
  5530. outs() << "\n";
  5531. }
  5532. static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
  5533. uint32_t left, offset, swift_version, p;
  5534. struct objc_image_info32 o;
  5535. const char *r;
  5536. if (S == SectionRef())
  5537. return;
  5538. StringRef SectName;
  5539. Expected<StringRef> SecNameOrErr = S.getName();
  5540. if (SecNameOrErr)
  5541. SectName = *SecNameOrErr;
  5542. else
  5543. consumeError(SecNameOrErr.takeError());
  5544. DataRefImpl Ref = S.getRawDataRefImpl();
  5545. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  5546. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  5547. p = S.getAddress();
  5548. r = get_pointer_32(p, offset, left, S, info);
  5549. if (r == nullptr)
  5550. return;
  5551. memset(&o, '\0', sizeof(struct objc_image_info32));
  5552. if (left < sizeof(struct objc_image_info32)) {
  5553. memcpy(&o, r, left);
  5554. outs() << " (objc_image_info entends past the end of the section)\n";
  5555. } else
  5556. memcpy(&o, r, sizeof(struct objc_image_info32));
  5557. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5558. swapStruct(o);
  5559. outs() << " version " << o.version << "\n";
  5560. outs() << " flags " << format("0x%" PRIx32, o.flags);
  5561. if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
  5562. outs() << " OBJC_IMAGE_IS_REPLACEMENT";
  5563. if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
  5564. outs() << " OBJC_IMAGE_SUPPORTS_GC";
  5565. swift_version = (o.flags >> 8) & 0xff;
  5566. if (swift_version != 0) {
  5567. if (swift_version == 1)
  5568. outs() << " Swift 1.0";
  5569. else if (swift_version == 2)
  5570. outs() << " Swift 1.1";
  5571. else if(swift_version == 3)
  5572. outs() << " Swift 2.0";
  5573. else if(swift_version == 4)
  5574. outs() << " Swift 3.0";
  5575. else if(swift_version == 5)
  5576. outs() << " Swift 4.0";
  5577. else if(swift_version == 6)
  5578. outs() << " Swift 4.1/Swift 4.2";
  5579. else if(swift_version == 7)
  5580. outs() << " Swift 5 or later";
  5581. else
  5582. outs() << " unknown future Swift version (" << swift_version << ")";
  5583. }
  5584. outs() << "\n";
  5585. }
  5586. static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
  5587. uint32_t left, offset, p;
  5588. struct imageInfo_t o;
  5589. const char *r;
  5590. StringRef SectName;
  5591. Expected<StringRef> SecNameOrErr = S.getName();
  5592. if (SecNameOrErr)
  5593. SectName = *SecNameOrErr;
  5594. else
  5595. consumeError(SecNameOrErr.takeError());
  5596. DataRefImpl Ref = S.getRawDataRefImpl();
  5597. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  5598. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  5599. p = S.getAddress();
  5600. r = get_pointer_32(p, offset, left, S, info);
  5601. if (r == nullptr)
  5602. return;
  5603. memset(&o, '\0', sizeof(struct imageInfo_t));
  5604. if (left < sizeof(struct imageInfo_t)) {
  5605. memcpy(&o, r, left);
  5606. outs() << " (imageInfo entends past the end of the section)\n";
  5607. } else
  5608. memcpy(&o, r, sizeof(struct imageInfo_t));
  5609. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5610. swapStruct(o);
  5611. outs() << " version " << o.version << "\n";
  5612. outs() << " flags " << format("0x%" PRIx32, o.flags);
  5613. if (o.flags & 0x1)
  5614. outs() << " F&C";
  5615. if (o.flags & 0x2)
  5616. outs() << " GC";
  5617. if (o.flags & 0x4)
  5618. outs() << " GC-only";
  5619. else
  5620. outs() << " RR";
  5621. outs() << "\n";
  5622. }
  5623. static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
  5624. SymbolAddressMap AddrMap;
  5625. if (verbose)
  5626. CreateSymbolAddressMap(O, &AddrMap);
  5627. std::vector<SectionRef> Sections;
  5628. for (const SectionRef &Section : O->sections())
  5629. Sections.push_back(Section);
  5630. struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
  5631. SectionRef CL = get_section(O, "__OBJC2", "__class_list");
  5632. if (CL == SectionRef())
  5633. CL = get_section(O, "__DATA", "__objc_classlist");
  5634. if (CL == SectionRef())
  5635. CL = get_section(O, "__DATA_CONST", "__objc_classlist");
  5636. if (CL == SectionRef())
  5637. CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
  5638. info.S = CL;
  5639. walk_pointer_list_64("class", CL, O, &info, print_class64_t);
  5640. SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
  5641. if (CR == SectionRef())
  5642. CR = get_section(O, "__DATA", "__objc_classrefs");
  5643. if (CR == SectionRef())
  5644. CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
  5645. if (CR == SectionRef())
  5646. CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
  5647. info.S = CR;
  5648. walk_pointer_list_64("class refs", CR, O, &info, nullptr);
  5649. SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
  5650. if (SR == SectionRef())
  5651. SR = get_section(O, "__DATA", "__objc_superrefs");
  5652. if (SR == SectionRef())
  5653. SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
  5654. if (SR == SectionRef())
  5655. SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
  5656. info.S = SR;
  5657. walk_pointer_list_64("super refs", SR, O, &info, nullptr);
  5658. SectionRef CA = get_section(O, "__OBJC2", "__category_list");
  5659. if (CA == SectionRef())
  5660. CA = get_section(O, "__DATA", "__objc_catlist");
  5661. if (CA == SectionRef())
  5662. CA = get_section(O, "__DATA_CONST", "__objc_catlist");
  5663. if (CA == SectionRef())
  5664. CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
  5665. info.S = CA;
  5666. walk_pointer_list_64("category", CA, O, &info, print_category64_t);
  5667. SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
  5668. if (PL == SectionRef())
  5669. PL = get_section(O, "__DATA", "__objc_protolist");
  5670. if (PL == SectionRef())
  5671. PL = get_section(O, "__DATA_CONST", "__objc_protolist");
  5672. if (PL == SectionRef())
  5673. PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
  5674. info.S = PL;
  5675. walk_pointer_list_64("protocol", PL, O, &info, nullptr);
  5676. SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
  5677. if (MR == SectionRef())
  5678. MR = get_section(O, "__DATA", "__objc_msgrefs");
  5679. if (MR == SectionRef())
  5680. MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
  5681. if (MR == SectionRef())
  5682. MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
  5683. info.S = MR;
  5684. print_message_refs64(MR, &info);
  5685. SectionRef II = get_section(O, "__OBJC2", "__image_info");
  5686. if (II == SectionRef())
  5687. II = get_section(O, "__DATA", "__objc_imageinfo");
  5688. if (II == SectionRef())
  5689. II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
  5690. if (II == SectionRef())
  5691. II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
  5692. info.S = II;
  5693. print_image_info64(II, &info);
  5694. }
  5695. static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
  5696. SymbolAddressMap AddrMap;
  5697. if (verbose)
  5698. CreateSymbolAddressMap(O, &AddrMap);
  5699. std::vector<SectionRef> Sections;
  5700. for (const SectionRef &Section : O->sections())
  5701. Sections.push_back(Section);
  5702. struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
  5703. SectionRef CL = get_section(O, "__OBJC2", "__class_list");
  5704. if (CL == SectionRef())
  5705. CL = get_section(O, "__DATA", "__objc_classlist");
  5706. if (CL == SectionRef())
  5707. CL = get_section(O, "__DATA_CONST", "__objc_classlist");
  5708. if (CL == SectionRef())
  5709. CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
  5710. info.S = CL;
  5711. walk_pointer_list_32("class", CL, O, &info, print_class32_t);
  5712. SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
  5713. if (CR == SectionRef())
  5714. CR = get_section(O, "__DATA", "__objc_classrefs");
  5715. if (CR == SectionRef())
  5716. CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
  5717. if (CR == SectionRef())
  5718. CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
  5719. info.S = CR;
  5720. walk_pointer_list_32("class refs", CR, O, &info, nullptr);
  5721. SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
  5722. if (SR == SectionRef())
  5723. SR = get_section(O, "__DATA", "__objc_superrefs");
  5724. if (SR == SectionRef())
  5725. SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
  5726. if (SR == SectionRef())
  5727. SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
  5728. info.S = SR;
  5729. walk_pointer_list_32("super refs", SR, O, &info, nullptr);
  5730. SectionRef CA = get_section(O, "__OBJC2", "__category_list");
  5731. if (CA == SectionRef())
  5732. CA = get_section(O, "__DATA", "__objc_catlist");
  5733. if (CA == SectionRef())
  5734. CA = get_section(O, "__DATA_CONST", "__objc_catlist");
  5735. if (CA == SectionRef())
  5736. CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
  5737. info.S = CA;
  5738. walk_pointer_list_32("category", CA, O, &info, print_category32_t);
  5739. SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
  5740. if (PL == SectionRef())
  5741. PL = get_section(O, "__DATA", "__objc_protolist");
  5742. if (PL == SectionRef())
  5743. PL = get_section(O, "__DATA_CONST", "__objc_protolist");
  5744. if (PL == SectionRef())
  5745. PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
  5746. info.S = PL;
  5747. walk_pointer_list_32("protocol", PL, O, &info, nullptr);
  5748. SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
  5749. if (MR == SectionRef())
  5750. MR = get_section(O, "__DATA", "__objc_msgrefs");
  5751. if (MR == SectionRef())
  5752. MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
  5753. if (MR == SectionRef())
  5754. MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
  5755. info.S = MR;
  5756. print_message_refs32(MR, &info);
  5757. SectionRef II = get_section(O, "__OBJC2", "__image_info");
  5758. if (II == SectionRef())
  5759. II = get_section(O, "__DATA", "__objc_imageinfo");
  5760. if (II == SectionRef())
  5761. II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
  5762. if (II == SectionRef())
  5763. II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
  5764. info.S = II;
  5765. print_image_info32(II, &info);
  5766. }
  5767. static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
  5768. uint32_t i, j, p, offset, xoffset, left, defs_left, def;
  5769. const char *r, *name, *defs;
  5770. struct objc_module_t module;
  5771. SectionRef S, xS;
  5772. struct objc_symtab_t symtab;
  5773. struct objc_class_t objc_class;
  5774. struct objc_category_t objc_category;
  5775. outs() << "Objective-C segment\n";
  5776. S = get_section(O, "__OBJC", "__module_info");
  5777. if (S == SectionRef())
  5778. return false;
  5779. SymbolAddressMap AddrMap;
  5780. if (verbose)
  5781. CreateSymbolAddressMap(O, &AddrMap);
  5782. std::vector<SectionRef> Sections;
  5783. for (const SectionRef &Section : O->sections())
  5784. Sections.push_back(Section);
  5785. struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
  5786. for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
  5787. p = S.getAddress() + i;
  5788. r = get_pointer_32(p, offset, left, S, &info, true);
  5789. if (r == nullptr)
  5790. return true;
  5791. memset(&module, '\0', sizeof(struct objc_module_t));
  5792. if (left < sizeof(struct objc_module_t)) {
  5793. memcpy(&module, r, left);
  5794. outs() << " (module extends past end of __module_info section)\n";
  5795. } else
  5796. memcpy(&module, r, sizeof(struct objc_module_t));
  5797. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5798. swapStruct(module);
  5799. outs() << "Module " << format("0x%" PRIx32, p) << "\n";
  5800. outs() << " version " << module.version << "\n";
  5801. outs() << " size " << module.size << "\n";
  5802. outs() << " name ";
  5803. name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
  5804. if (name != nullptr)
  5805. outs() << format("%.*s", left, name);
  5806. else
  5807. outs() << format("0x%08" PRIx32, module.name)
  5808. << "(not in an __OBJC section)";
  5809. outs() << "\n";
  5810. r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
  5811. if (module.symtab == 0 || r == nullptr) {
  5812. outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
  5813. << " (not in an __OBJC section)\n";
  5814. continue;
  5815. }
  5816. outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
  5817. memset(&symtab, '\0', sizeof(struct objc_symtab_t));
  5818. defs_left = 0;
  5819. defs = nullptr;
  5820. if (left < sizeof(struct objc_symtab_t)) {
  5821. memcpy(&symtab, r, left);
  5822. outs() << "\tsymtab extends past end of an __OBJC section)\n";
  5823. } else {
  5824. memcpy(&symtab, r, sizeof(struct objc_symtab_t));
  5825. if (left > sizeof(struct objc_symtab_t)) {
  5826. defs_left = left - sizeof(struct objc_symtab_t);
  5827. defs = r + sizeof(struct objc_symtab_t);
  5828. }
  5829. }
  5830. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5831. swapStruct(symtab);
  5832. outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
  5833. r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
  5834. outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
  5835. if (r == nullptr)
  5836. outs() << " (not in an __OBJC section)";
  5837. outs() << "\n";
  5838. outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
  5839. outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
  5840. if (symtab.cls_def_cnt > 0)
  5841. outs() << "\tClass Definitions\n";
  5842. for (j = 0; j < symtab.cls_def_cnt; j++) {
  5843. if ((j + 1) * sizeof(uint32_t) > defs_left) {
  5844. outs() << "\t(remaining class defs entries entends past the end of the "
  5845. << "section)\n";
  5846. break;
  5847. }
  5848. memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
  5849. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5850. sys::swapByteOrder(def);
  5851. r = get_pointer_32(def, xoffset, left, xS, &info, true);
  5852. outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
  5853. if (r != nullptr) {
  5854. if (left > sizeof(struct objc_class_t)) {
  5855. outs() << "\n";
  5856. memcpy(&objc_class, r, sizeof(struct objc_class_t));
  5857. } else {
  5858. outs() << " (entends past the end of the section)\n";
  5859. memset(&objc_class, '\0', sizeof(struct objc_class_t));
  5860. memcpy(&objc_class, r, left);
  5861. }
  5862. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5863. swapStruct(objc_class);
  5864. print_objc_class_t(&objc_class, &info);
  5865. } else {
  5866. outs() << "(not in an __OBJC section)\n";
  5867. }
  5868. if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
  5869. outs() << "\tMeta Class";
  5870. r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
  5871. if (r != nullptr) {
  5872. if (left > sizeof(struct objc_class_t)) {
  5873. outs() << "\n";
  5874. memcpy(&objc_class, r, sizeof(struct objc_class_t));
  5875. } else {
  5876. outs() << " (entends past the end of the section)\n";
  5877. memset(&objc_class, '\0', sizeof(struct objc_class_t));
  5878. memcpy(&objc_class, r, left);
  5879. }
  5880. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5881. swapStruct(objc_class);
  5882. print_objc_class_t(&objc_class, &info);
  5883. } else {
  5884. outs() << "(not in an __OBJC section)\n";
  5885. }
  5886. }
  5887. }
  5888. if (symtab.cat_def_cnt > 0)
  5889. outs() << "\tCategory Definitions\n";
  5890. for (j = 0; j < symtab.cat_def_cnt; j++) {
  5891. if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
  5892. outs() << "\t(remaining category defs entries entends past the end of "
  5893. << "the section)\n";
  5894. break;
  5895. }
  5896. memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
  5897. sizeof(uint32_t));
  5898. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5899. sys::swapByteOrder(def);
  5900. r = get_pointer_32(def, xoffset, left, xS, &info, true);
  5901. outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
  5902. << format("0x%08" PRIx32, def);
  5903. if (r != nullptr) {
  5904. if (left > sizeof(struct objc_category_t)) {
  5905. outs() << "\n";
  5906. memcpy(&objc_category, r, sizeof(struct objc_category_t));
  5907. } else {
  5908. outs() << " (entends past the end of the section)\n";
  5909. memset(&objc_category, '\0', sizeof(struct objc_category_t));
  5910. memcpy(&objc_category, r, left);
  5911. }
  5912. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5913. swapStruct(objc_category);
  5914. print_objc_objc_category_t(&objc_category, &info);
  5915. } else {
  5916. outs() << "(not in an __OBJC section)\n";
  5917. }
  5918. }
  5919. }
  5920. const SectionRef II = get_section(O, "__OBJC", "__image_info");
  5921. if (II != SectionRef())
  5922. print_image_info(II, &info);
  5923. return true;
  5924. }
  5925. static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
  5926. uint32_t size, uint32_t addr) {
  5927. SymbolAddressMap AddrMap;
  5928. CreateSymbolAddressMap(O, &AddrMap);
  5929. std::vector<SectionRef> Sections;
  5930. for (const SectionRef &Section : O->sections())
  5931. Sections.push_back(Section);
  5932. struct DisassembleInfo info(O, &AddrMap, &Sections, true);
  5933. const char *p;
  5934. struct objc_protocol_t protocol;
  5935. uint32_t left, paddr;
  5936. for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
  5937. memset(&protocol, '\0', sizeof(struct objc_protocol_t));
  5938. left = size - (p - sect);
  5939. if (left < sizeof(struct objc_protocol_t)) {
  5940. outs() << "Protocol extends past end of __protocol section\n";
  5941. memcpy(&protocol, p, left);
  5942. } else
  5943. memcpy(&protocol, p, sizeof(struct objc_protocol_t));
  5944. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5945. swapStruct(protocol);
  5946. paddr = addr + (p - sect);
  5947. outs() << "Protocol " << format("0x%" PRIx32, paddr);
  5948. if (print_protocol(paddr, 0, &info))
  5949. outs() << "(not in an __OBJC section)\n";
  5950. }
  5951. }
  5952. #ifdef HAVE_LIBXAR
  5953. static inline void swapStruct(struct xar_header &xar) {
  5954. sys::swapByteOrder(xar.magic);
  5955. sys::swapByteOrder(xar.size);
  5956. sys::swapByteOrder(xar.version);
  5957. sys::swapByteOrder(xar.toc_length_compressed);
  5958. sys::swapByteOrder(xar.toc_length_uncompressed);
  5959. sys::swapByteOrder(xar.cksum_alg);
  5960. }
  5961. static void PrintModeVerbose(uint32_t mode) {
  5962. switch(mode & S_IFMT){
  5963. case S_IFDIR:
  5964. outs() << "d";
  5965. break;
  5966. case S_IFCHR:
  5967. outs() << "c";
  5968. break;
  5969. case S_IFBLK:
  5970. outs() << "b";
  5971. break;
  5972. case S_IFREG:
  5973. outs() << "-";
  5974. break;
  5975. case S_IFLNK:
  5976. outs() << "l";
  5977. break;
  5978. case S_IFSOCK:
  5979. outs() << "s";
  5980. break;
  5981. default:
  5982. outs() << "?";
  5983. break;
  5984. }
  5985. /* owner permissions */
  5986. if(mode & S_IREAD)
  5987. outs() << "r";
  5988. else
  5989. outs() << "-";
  5990. if(mode & S_IWRITE)
  5991. outs() << "w";
  5992. else
  5993. outs() << "-";
  5994. if(mode & S_ISUID)
  5995. outs() << "s";
  5996. else if(mode & S_IEXEC)
  5997. outs() << "x";
  5998. else
  5999. outs() << "-";
  6000. /* group permissions */
  6001. if(mode & (S_IREAD >> 3))
  6002. outs() << "r";
  6003. else
  6004. outs() << "-";
  6005. if(mode & (S_IWRITE >> 3))
  6006. outs() << "w";
  6007. else
  6008. outs() << "-";
  6009. if(mode & S_ISGID)
  6010. outs() << "s";
  6011. else if(mode & (S_IEXEC >> 3))
  6012. outs() << "x";
  6013. else
  6014. outs() << "-";
  6015. /* other permissions */
  6016. if(mode & (S_IREAD >> 6))
  6017. outs() << "r";
  6018. else
  6019. outs() << "-";
  6020. if(mode & (S_IWRITE >> 6))
  6021. outs() << "w";
  6022. else
  6023. outs() << "-";
  6024. if(mode & S_ISVTX)
  6025. outs() << "t";
  6026. else if(mode & (S_IEXEC >> 6))
  6027. outs() << "x";
  6028. else
  6029. outs() << "-";
  6030. }
  6031. static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
  6032. xar_file_t xf;
  6033. const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
  6034. char *endp;
  6035. uint32_t mode_value;
  6036. ScopedXarIter xi;
  6037. if (!xi) {
  6038. WithColor::error(errs(), "llvm-objdump")
  6039. << "can't obtain an xar iterator for xar archive " << XarFilename
  6040. << "\n";
  6041. return;
  6042. }
  6043. // Go through the xar's files.
  6044. for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
  6045. ScopedXarIter xp;
  6046. if(!xp){
  6047. WithColor::error(errs(), "llvm-objdump")
  6048. << "can't obtain an xar iterator for xar archive " << XarFilename
  6049. << "\n";
  6050. return;
  6051. }
  6052. type = nullptr;
  6053. mode = nullptr;
  6054. user = nullptr;
  6055. group = nullptr;
  6056. size = nullptr;
  6057. mtime = nullptr;
  6058. name = nullptr;
  6059. for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
  6060. const char *val = nullptr;
  6061. xar_prop_get(xf, key, &val);
  6062. #if 0 // Useful for debugging.
  6063. outs() << "key: " << key << " value: " << val << "\n";
  6064. #endif
  6065. if(strcmp(key, "type") == 0)
  6066. type = val;
  6067. if(strcmp(key, "mode") == 0)
  6068. mode = val;
  6069. if(strcmp(key, "user") == 0)
  6070. user = val;
  6071. if(strcmp(key, "group") == 0)
  6072. group = val;
  6073. if(strcmp(key, "data/size") == 0)
  6074. size = val;
  6075. if(strcmp(key, "mtime") == 0)
  6076. mtime = val;
  6077. if(strcmp(key, "name") == 0)
  6078. name = val;
  6079. }
  6080. if(mode != nullptr){
  6081. mode_value = strtoul(mode, &endp, 8);
  6082. if(*endp != '\0')
  6083. outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
  6084. if(strcmp(type, "file") == 0)
  6085. mode_value |= S_IFREG;
  6086. PrintModeVerbose(mode_value);
  6087. outs() << " ";
  6088. }
  6089. if(user != nullptr)
  6090. outs() << format("%10s/", user);
  6091. if(group != nullptr)
  6092. outs() << format("%-10s ", group);
  6093. if(size != nullptr)
  6094. outs() << format("%7s ", size);
  6095. if(mtime != nullptr){
  6096. for(m = mtime; *m != 'T' && *m != '\0'; m++)
  6097. outs() << *m;
  6098. if(*m == 'T')
  6099. m++;
  6100. outs() << " ";
  6101. for( ; *m != 'Z' && *m != '\0'; m++)
  6102. outs() << *m;
  6103. outs() << " ";
  6104. }
  6105. if(name != nullptr)
  6106. outs() << name;
  6107. outs() << "\n";
  6108. }
  6109. }
  6110. static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
  6111. uint32_t size, bool verbose,
  6112. bool PrintXarHeader, bool PrintXarFileHeaders,
  6113. std::string XarMemberName) {
  6114. if(size < sizeof(struct xar_header)) {
  6115. outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
  6116. "of struct xar_header)\n";
  6117. return;
  6118. }
  6119. struct xar_header XarHeader;
  6120. memcpy(&XarHeader, sect, sizeof(struct xar_header));
  6121. if (sys::IsLittleEndianHost)
  6122. swapStruct(XarHeader);
  6123. if (PrintXarHeader) {
  6124. if (!XarMemberName.empty())
  6125. outs() << "In xar member " << XarMemberName << ": ";
  6126. else
  6127. outs() << "For (__LLVM,__bundle) section: ";
  6128. outs() << "xar header\n";
  6129. if (XarHeader.magic == XAR_HEADER_MAGIC)
  6130. outs() << " magic XAR_HEADER_MAGIC\n";
  6131. else
  6132. outs() << " magic "
  6133. << format_hex(XarHeader.magic, 10, true)
  6134. << " (not XAR_HEADER_MAGIC)\n";
  6135. outs() << " size " << XarHeader.size << "\n";
  6136. outs() << " version " << XarHeader.version << "\n";
  6137. outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
  6138. << "\n";
  6139. outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
  6140. << "\n";
  6141. outs() << " cksum_alg ";
  6142. switch (XarHeader.cksum_alg) {
  6143. case XAR_CKSUM_NONE:
  6144. outs() << "XAR_CKSUM_NONE\n";
  6145. break;
  6146. case XAR_CKSUM_SHA1:
  6147. outs() << "XAR_CKSUM_SHA1\n";
  6148. break;
  6149. case XAR_CKSUM_MD5:
  6150. outs() << "XAR_CKSUM_MD5\n";
  6151. break;
  6152. #ifdef XAR_CKSUM_SHA256
  6153. case XAR_CKSUM_SHA256:
  6154. outs() << "XAR_CKSUM_SHA256\n";
  6155. break;
  6156. #endif
  6157. #ifdef XAR_CKSUM_SHA512
  6158. case XAR_CKSUM_SHA512:
  6159. outs() << "XAR_CKSUM_SHA512\n";
  6160. break;
  6161. #endif
  6162. default:
  6163. outs() << XarHeader.cksum_alg << "\n";
  6164. }
  6165. }
  6166. SmallString<128> XarFilename;
  6167. int FD;
  6168. std::error_code XarEC =
  6169. sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
  6170. if (XarEC) {
  6171. WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
  6172. return;
  6173. }
  6174. ToolOutputFile XarFile(XarFilename, FD);
  6175. raw_fd_ostream &XarOut = XarFile.os();
  6176. StringRef XarContents(sect, size);
  6177. XarOut << XarContents;
  6178. XarOut.close();
  6179. if (XarOut.has_error())
  6180. return;
  6181. ScopedXarFile xar(XarFilename.c_str(), READ);
  6182. if (!xar) {
  6183. WithColor::error(errs(), "llvm-objdump")
  6184. << "can't create temporary xar archive " << XarFilename << "\n";
  6185. return;
  6186. }
  6187. SmallString<128> TocFilename;
  6188. std::error_code TocEC =
  6189. sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
  6190. if (TocEC) {
  6191. WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
  6192. return;
  6193. }
  6194. xar_serialize(xar, TocFilename.c_str());
  6195. if (PrintXarFileHeaders) {
  6196. if (!XarMemberName.empty())
  6197. outs() << "In xar member " << XarMemberName << ": ";
  6198. else
  6199. outs() << "For (__LLVM,__bundle) section: ";
  6200. outs() << "xar archive files:\n";
  6201. PrintXarFilesSummary(XarFilename.c_str(), xar);
  6202. }
  6203. ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
  6204. MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
  6205. if (std::error_code EC = FileOrErr.getError()) {
  6206. WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
  6207. return;
  6208. }
  6209. std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
  6210. if (!XarMemberName.empty())
  6211. outs() << "In xar member " << XarMemberName << ": ";
  6212. else
  6213. outs() << "For (__LLVM,__bundle) section: ";
  6214. outs() << "xar table of contents:\n";
  6215. outs() << Buffer->getBuffer() << "\n";
  6216. // TODO: Go through the xar's files.
  6217. ScopedXarIter xi;
  6218. if(!xi){
  6219. WithColor::error(errs(), "llvm-objdump")
  6220. << "can't obtain an xar iterator for xar archive "
  6221. << XarFilename.c_str() << "\n";
  6222. return;
  6223. }
  6224. for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
  6225. const char *key;
  6226. const char *member_name, *member_type, *member_size_string;
  6227. size_t member_size;
  6228. ScopedXarIter xp;
  6229. if(!xp){
  6230. WithColor::error(errs(), "llvm-objdump")
  6231. << "can't obtain an xar iterator for xar archive "
  6232. << XarFilename.c_str() << "\n";
  6233. return;
  6234. }
  6235. member_name = NULL;
  6236. member_type = NULL;
  6237. member_size_string = NULL;
  6238. for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
  6239. const char *val = nullptr;
  6240. xar_prop_get(xf, key, &val);
  6241. #if 0 // Useful for debugging.
  6242. outs() << "key: " << key << " value: " << val << "\n";
  6243. #endif
  6244. if (strcmp(key, "name") == 0)
  6245. member_name = val;
  6246. if (strcmp(key, "type") == 0)
  6247. member_type = val;
  6248. if (strcmp(key, "data/size") == 0)
  6249. member_size_string = val;
  6250. }
  6251. /*
  6252. * If we find a file with a name, date/size and type properties
  6253. * and with the type being "file" see if that is a xar file.
  6254. */
  6255. if (member_name != NULL && member_type != NULL &&
  6256. strcmp(member_type, "file") == 0 &&
  6257. member_size_string != NULL){
  6258. // Extract the file into a buffer.
  6259. char *endptr;
  6260. member_size = strtoul(member_size_string, &endptr, 10);
  6261. if (*endptr == '\0' && member_size != 0) {
  6262. char *buffer;
  6263. if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
  6264. #if 0 // Useful for debugging.
  6265. outs() << "xar member: " << member_name << " extracted\n";
  6266. #endif
  6267. // Set the XarMemberName we want to see printed in the header.
  6268. std::string OldXarMemberName;
  6269. // If XarMemberName is already set this is nested. So
  6270. // save the old name and create the nested name.
  6271. if (!XarMemberName.empty()) {
  6272. OldXarMemberName = XarMemberName;
  6273. XarMemberName =
  6274. (Twine("[") + XarMemberName + "]" + member_name).str();
  6275. } else {
  6276. OldXarMemberName = "";
  6277. XarMemberName = member_name;
  6278. }
  6279. // See if this is could be a xar file (nested).
  6280. if (member_size >= sizeof(struct xar_header)) {
  6281. #if 0 // Useful for debugging.
  6282. outs() << "could be a xar file: " << member_name << "\n";
  6283. #endif
  6284. memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
  6285. if (sys::IsLittleEndianHost)
  6286. swapStruct(XarHeader);
  6287. if (XarHeader.magic == XAR_HEADER_MAGIC)
  6288. DumpBitcodeSection(O, buffer, member_size, verbose,
  6289. PrintXarHeader, PrintXarFileHeaders,
  6290. XarMemberName);
  6291. }
  6292. XarMemberName = OldXarMemberName;
  6293. delete buffer;
  6294. }
  6295. }
  6296. }
  6297. }
  6298. }
  6299. #endif // defined(HAVE_LIBXAR)
  6300. static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
  6301. if (O->is64Bit())
  6302. printObjc2_64bit_MetaData(O, verbose);
  6303. else {
  6304. MachO::mach_header H;
  6305. H = O->getHeader();
  6306. if (H.cputype == MachO::CPU_TYPE_ARM)
  6307. printObjc2_32bit_MetaData(O, verbose);
  6308. else {
  6309. // This is the 32-bit non-arm cputype case. Which is normally
  6310. // the first Objective-C ABI. But it may be the case of a
  6311. // binary for the iOS simulator which is the second Objective-C
  6312. // ABI. In that case printObjc1_32bit_MetaData() will determine that
  6313. // and return false.
  6314. if (!printObjc1_32bit_MetaData(O, verbose))
  6315. printObjc2_32bit_MetaData(O, verbose);
  6316. }
  6317. }
  6318. }
  6319. // GuessLiteralPointer returns a string which for the item in the Mach-O file
  6320. // for the address passed in as ReferenceValue for printing as a comment with
  6321. // the instruction and also returns the corresponding type of that item
  6322. // indirectly through ReferenceType.
  6323. //
  6324. // If ReferenceValue is an address of literal cstring then a pointer to the
  6325. // cstring is returned and ReferenceType is set to
  6326. // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
  6327. //
  6328. // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
  6329. // Class ref that name is returned and the ReferenceType is set accordingly.
  6330. //
  6331. // Lastly, literals which are Symbol address in a literal pool are looked for
  6332. // and if found the symbol name is returned and ReferenceType is set to
  6333. // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
  6334. //
  6335. // If there is no item in the Mach-O file for the address passed in as
  6336. // ReferenceValue nullptr is returned and ReferenceType is unchanged.
  6337. static const char *GuessLiteralPointer(uint64_t ReferenceValue,
  6338. uint64_t ReferencePC,
  6339. uint64_t *ReferenceType,
  6340. struct DisassembleInfo *info) {
  6341. // First see if there is an external relocation entry at the ReferencePC.
  6342. if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
  6343. uint64_t sect_addr = info->S.getAddress();
  6344. uint64_t sect_offset = ReferencePC - sect_addr;
  6345. bool reloc_found = false;
  6346. DataRefImpl Rel;
  6347. MachO::any_relocation_info RE;
  6348. bool isExtern = false;
  6349. SymbolRef Symbol;
  6350. for (const RelocationRef &Reloc : info->S.relocations()) {
  6351. uint64_t RelocOffset = Reloc.getOffset();
  6352. if (RelocOffset == sect_offset) {
  6353. Rel = Reloc.getRawDataRefImpl();
  6354. RE = info->O->getRelocation(Rel);
  6355. if (info->O->isRelocationScattered(RE))
  6356. continue;
  6357. isExtern = info->O->getPlainRelocationExternal(RE);
  6358. if (isExtern) {
  6359. symbol_iterator RelocSym = Reloc.getSymbol();
  6360. Symbol = *RelocSym;
  6361. }
  6362. reloc_found = true;
  6363. break;
  6364. }
  6365. }
  6366. // If there is an external relocation entry for a symbol in a section
  6367. // then used that symbol's value for the value of the reference.
  6368. if (reloc_found && isExtern) {
  6369. if (info->O->getAnyRelocationPCRel(RE)) {
  6370. unsigned Type = info->O->getAnyRelocationType(RE);
  6371. if (Type == MachO::X86_64_RELOC_SIGNED) {
  6372. ReferenceValue = cantFail(Symbol.getValue());
  6373. }
  6374. }
  6375. }
  6376. }
  6377. // Look for literals such as Objective-C CFStrings refs, Selector refs,
  6378. // Message refs and Class refs.
  6379. bool classref, selref, msgref, cfstring;
  6380. uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
  6381. selref, msgref, cfstring);
  6382. if (classref && pointer_value == 0) {
  6383. // Note the ReferenceValue is a pointer into the __objc_classrefs section.
  6384. // And the pointer_value in that section is typically zero as it will be
  6385. // set by dyld as part of the "bind information".
  6386. const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
  6387. if (name != nullptr) {
  6388. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
  6389. const char *class_name = strrchr(name, '$');
  6390. if (class_name != nullptr && class_name[1] == '_' &&
  6391. class_name[2] != '\0') {
  6392. info->class_name = class_name + 2;
  6393. return name;
  6394. }
  6395. }
  6396. }
  6397. if (classref) {
  6398. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
  6399. const char *name =
  6400. get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
  6401. if (name != nullptr)
  6402. info->class_name = name;
  6403. else
  6404. name = "bad class ref";
  6405. return name;
  6406. }
  6407. if (cfstring) {
  6408. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
  6409. const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
  6410. return name;
  6411. }
  6412. if (selref && pointer_value == 0)
  6413. pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
  6414. if (pointer_value != 0)
  6415. ReferenceValue = pointer_value;
  6416. const char *name = GuessCstringPointer(ReferenceValue, info);
  6417. if (name) {
  6418. if (pointer_value != 0 && selref) {
  6419. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
  6420. info->selector_name = name;
  6421. } else if (pointer_value != 0 && msgref) {
  6422. info->class_name = nullptr;
  6423. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
  6424. info->selector_name = name;
  6425. } else
  6426. *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
  6427. return name;
  6428. }
  6429. // Lastly look for an indirect symbol with this ReferenceValue which is in
  6430. // a literal pool. If found return that symbol name.
  6431. name = GuessIndirectSymbol(ReferenceValue, info);
  6432. if (name) {
  6433. *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
  6434. return name;
  6435. }
  6436. return nullptr;
  6437. }
  6438. // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
  6439. // the Symbolizer. It looks up the ReferenceValue using the info passed via the
  6440. // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
  6441. // is created and returns the symbol name that matches the ReferenceValue or
  6442. // nullptr if none. The ReferenceType is passed in for the IN type of
  6443. // reference the instruction is making from the values in defined in the header
  6444. // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
  6445. // Out type and the ReferenceName will also be set which is added as a comment
  6446. // to the disassembled instruction.
  6447. //
  6448. // If the symbol name is a C++ mangled name then the demangled name is
  6449. // returned through ReferenceName and ReferenceType is set to
  6450. // LLVMDisassembler_ReferenceType_DeMangled_Name .
  6451. //
  6452. // When this is called to get a symbol name for a branch target then the
  6453. // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
  6454. // SymbolValue will be looked for in the indirect symbol table to determine if
  6455. // it is an address for a symbol stub. If so then the symbol name for that
  6456. // stub is returned indirectly through ReferenceName and then ReferenceType is
  6457. // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
  6458. //
  6459. // When this is called with an value loaded via a PC relative load then
  6460. // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
  6461. // SymbolValue is checked to be an address of literal pointer, symbol pointer,
  6462. // or an Objective-C meta data reference. If so the output ReferenceType is
  6463. // set to correspond to that as well as setting the ReferenceName.
  6464. static const char *SymbolizerSymbolLookUp(void *DisInfo,
  6465. uint64_t ReferenceValue,
  6466. uint64_t *ReferenceType,
  6467. uint64_t ReferencePC,
  6468. const char **ReferenceName) {
  6469. struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
  6470. // If no verbose symbolic information is wanted then just return nullptr.
  6471. if (!info->verbose) {
  6472. *ReferenceName = nullptr;
  6473. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6474. return nullptr;
  6475. }
  6476. const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
  6477. if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
  6478. *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
  6479. if (*ReferenceName != nullptr) {
  6480. method_reference(info, ReferenceType, ReferenceName);
  6481. if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
  6482. *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
  6483. } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
  6484. if (info->demangled_name != nullptr)
  6485. free(info->demangled_name);
  6486. int status;
  6487. info->demangled_name =
  6488. itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
  6489. if (info->demangled_name != nullptr) {
  6490. *ReferenceName = info->demangled_name;
  6491. *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
  6492. } else
  6493. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6494. } else
  6495. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6496. } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
  6497. *ReferenceName =
  6498. GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
  6499. if (*ReferenceName)
  6500. method_reference(info, ReferenceType, ReferenceName);
  6501. else
  6502. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6503. // If this is arm64 and the reference is an adrp instruction save the
  6504. // instruction, passed in ReferenceValue and the address of the instruction
  6505. // for use later if we see and add immediate instruction.
  6506. } else if (info->O->getArch() == Triple::aarch64 &&
  6507. *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
  6508. info->adrp_inst = ReferenceValue;
  6509. info->adrp_addr = ReferencePC;
  6510. SymbolName = nullptr;
  6511. *ReferenceName = nullptr;
  6512. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6513. // If this is arm64 and reference is an add immediate instruction and we
  6514. // have
  6515. // seen an adrp instruction just before it and the adrp's Xd register
  6516. // matches
  6517. // this add's Xn register reconstruct the value being referenced and look to
  6518. // see if it is a literal pointer. Note the add immediate instruction is
  6519. // passed in ReferenceValue.
  6520. } else if (info->O->getArch() == Triple::aarch64 &&
  6521. *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
  6522. ReferencePC - 4 == info->adrp_addr &&
  6523. (info->adrp_inst & 0x9f000000) == 0x90000000 &&
  6524. (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
  6525. uint32_t addxri_inst;
  6526. uint64_t adrp_imm, addxri_imm;
  6527. adrp_imm =
  6528. ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
  6529. if (info->adrp_inst & 0x0200000)
  6530. adrp_imm |= 0xfffffffffc000000LL;
  6531. addxri_inst = ReferenceValue;
  6532. addxri_imm = (addxri_inst >> 10) & 0xfff;
  6533. if (((addxri_inst >> 22) & 0x3) == 1)
  6534. addxri_imm <<= 12;
  6535. ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
  6536. (adrp_imm << 12) + addxri_imm;
  6537. *ReferenceName =
  6538. GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
  6539. if (*ReferenceName == nullptr)
  6540. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6541. // If this is arm64 and the reference is a load register instruction and we
  6542. // have seen an adrp instruction just before it and the adrp's Xd register
  6543. // matches this add's Xn register reconstruct the value being referenced and
  6544. // look to see if it is a literal pointer. Note the load register
  6545. // instruction is passed in ReferenceValue.
  6546. } else if (info->O->getArch() == Triple::aarch64 &&
  6547. *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
  6548. ReferencePC - 4 == info->adrp_addr &&
  6549. (info->adrp_inst & 0x9f000000) == 0x90000000 &&
  6550. (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
  6551. uint32_t ldrxui_inst;
  6552. uint64_t adrp_imm, ldrxui_imm;
  6553. adrp_imm =
  6554. ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
  6555. if (info->adrp_inst & 0x0200000)
  6556. adrp_imm |= 0xfffffffffc000000LL;
  6557. ldrxui_inst = ReferenceValue;
  6558. ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
  6559. ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
  6560. (adrp_imm << 12) + (ldrxui_imm << 3);
  6561. *ReferenceName =
  6562. GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
  6563. if (*ReferenceName == nullptr)
  6564. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6565. }
  6566. // If this arm64 and is an load register (PC-relative) instruction the
  6567. // ReferenceValue is the PC plus the immediate value.
  6568. else if (info->O->getArch() == Triple::aarch64 &&
  6569. (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
  6570. *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
  6571. *ReferenceName =
  6572. GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
  6573. if (*ReferenceName == nullptr)
  6574. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6575. } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
  6576. if (info->demangled_name != nullptr)
  6577. free(info->demangled_name);
  6578. int status;
  6579. info->demangled_name =
  6580. itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
  6581. if (info->demangled_name != nullptr) {
  6582. *ReferenceName = info->demangled_name;
  6583. *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
  6584. }
  6585. }
  6586. else {
  6587. *ReferenceName = nullptr;
  6588. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6589. }
  6590. return SymbolName;
  6591. }
  6592. /// Emits the comments that are stored in the CommentStream.
  6593. /// Each comment in the CommentStream must end with a newline.
  6594. static void emitComments(raw_svector_ostream &CommentStream,
  6595. SmallString<128> &CommentsToEmit,
  6596. formatted_raw_ostream &FormattedOS,
  6597. const MCAsmInfo &MAI) {
  6598. // Flush the stream before taking its content.
  6599. StringRef Comments = CommentsToEmit.str();
  6600. // Get the default information for printing a comment.
  6601. StringRef CommentBegin = MAI.getCommentString();
  6602. unsigned CommentColumn = MAI.getCommentColumn();
  6603. bool IsFirst = true;
  6604. while (!Comments.empty()) {
  6605. if (!IsFirst)
  6606. FormattedOS << '\n';
  6607. // Emit a line of comments.
  6608. FormattedOS.PadToColumn(CommentColumn);
  6609. size_t Position = Comments.find('\n');
  6610. FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
  6611. // Move after the newline character.
  6612. Comments = Comments.substr(Position + 1);
  6613. IsFirst = false;
  6614. }
  6615. FormattedOS.flush();
  6616. // Tell the comment stream that the vector changed underneath it.
  6617. CommentsToEmit.clear();
  6618. }
  6619. static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
  6620. StringRef DisSegName, StringRef DisSectName) {
  6621. const char *McpuDefault = nullptr;
  6622. const Target *ThumbTarget = nullptr;
  6623. const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
  6624. if (!TheTarget) {
  6625. // GetTarget prints out stuff.
  6626. return;
  6627. }
  6628. std::string MachOMCPU;
  6629. if (MCPU.empty() && McpuDefault)
  6630. MachOMCPU = McpuDefault;
  6631. else
  6632. MachOMCPU = MCPU;
  6633. #define CHECK_TARGET_INFO_CREATION(NAME) \
  6634. do { \
  6635. if (!NAME) { \
  6636. WithColor::error(errs(), "llvm-objdump") \
  6637. << "couldn't initialize disassembler for target " << TripleName \
  6638. << '\n'; \
  6639. return; \
  6640. } \
  6641. } while (false)
  6642. #define CHECK_THUMB_TARGET_INFO_CREATION(NAME) \
  6643. do { \
  6644. if (!NAME) { \
  6645. WithColor::error(errs(), "llvm-objdump") \
  6646. << "couldn't initialize disassembler for target " << ThumbTripleName \
  6647. << '\n'; \
  6648. return; \
  6649. } \
  6650. } while (false)
  6651. std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
  6652. CHECK_TARGET_INFO_CREATION(InstrInfo);
  6653. std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
  6654. if (ThumbTarget) {
  6655. ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
  6656. CHECK_THUMB_TARGET_INFO_CREATION(ThumbInstrInfo);
  6657. }
  6658. // Package up features to be passed to target/subtarget
  6659. std::string FeaturesStr;
  6660. if (!MAttrs.empty()) {
  6661. SubtargetFeatures Features;
  6662. for (unsigned i = 0; i != MAttrs.size(); ++i)
  6663. Features.AddFeature(MAttrs[i]);
  6664. FeaturesStr = Features.getString();
  6665. }
  6666. MCTargetOptions MCOptions;
  6667. // Set up disassembler.
  6668. std::unique_ptr<const MCRegisterInfo> MRI(
  6669. TheTarget->createMCRegInfo(TripleName));
  6670. CHECK_TARGET_INFO_CREATION(MRI);
  6671. std::unique_ptr<const MCAsmInfo> AsmInfo(
  6672. TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
  6673. CHECK_TARGET_INFO_CREATION(AsmInfo);
  6674. std::unique_ptr<const MCSubtargetInfo> STI(
  6675. TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
  6676. CHECK_TARGET_INFO_CREATION(STI);
  6677. MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
  6678. std::unique_ptr<MCDisassembler> DisAsm(
  6679. TheTarget->createMCDisassembler(*STI, Ctx));
  6680. CHECK_TARGET_INFO_CREATION(DisAsm);
  6681. std::unique_ptr<MCSymbolizer> Symbolizer;
  6682. struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
  6683. std::unique_ptr<MCRelocationInfo> RelInfo(
  6684. TheTarget->createMCRelocationInfo(TripleName, Ctx));
  6685. if (RelInfo) {
  6686. Symbolizer.reset(TheTarget->createMCSymbolizer(
  6687. TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
  6688. &SymbolizerInfo, &Ctx, std::move(RelInfo)));
  6689. DisAsm->setSymbolizer(std::move(Symbolizer));
  6690. }
  6691. int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
  6692. std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
  6693. Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
  6694. CHECK_TARGET_INFO_CREATION(IP);
  6695. // Set the display preference for hex vs. decimal immediates.
  6696. IP->setPrintImmHex(PrintImmHex);
  6697. // Comment stream and backing vector.
  6698. SmallString<128> CommentsToEmit;
  6699. raw_svector_ostream CommentStream(CommentsToEmit);
  6700. // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
  6701. // if it is done then arm64 comments for string literals don't get printed
  6702. // and some constant get printed instead and not setting it causes intel
  6703. // (32-bit and 64-bit) comments printed with different spacing before the
  6704. // comment causing different diffs with the 'C' disassembler library API.
  6705. // IP->setCommentStream(CommentStream);
  6706. // Set up separate thumb disassembler if needed.
  6707. std::unique_ptr<const MCRegisterInfo> ThumbMRI;
  6708. std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
  6709. std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
  6710. std::unique_ptr<MCDisassembler> ThumbDisAsm;
  6711. std::unique_ptr<MCInstPrinter> ThumbIP;
  6712. std::unique_ptr<MCContext> ThumbCtx;
  6713. std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
  6714. struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
  6715. std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
  6716. if (ThumbTarget) {
  6717. ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
  6718. CHECK_THUMB_TARGET_INFO_CREATION(ThumbMRI);
  6719. ThumbAsmInfo.reset(
  6720. ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName, MCOptions));
  6721. CHECK_THUMB_TARGET_INFO_CREATION(ThumbAsmInfo);
  6722. ThumbSTI.reset(
  6723. ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
  6724. FeaturesStr));
  6725. CHECK_THUMB_TARGET_INFO_CREATION(ThumbSTI);
  6726. ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
  6727. ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
  6728. CHECK_THUMB_TARGET_INFO_CREATION(ThumbDisAsm);
  6729. MCContext *PtrThumbCtx = ThumbCtx.get();
  6730. ThumbRelInfo.reset(
  6731. ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
  6732. if (ThumbRelInfo) {
  6733. ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
  6734. ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
  6735. &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
  6736. ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
  6737. }
  6738. int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
  6739. ThumbIP.reset(ThumbTarget->createMCInstPrinter(
  6740. Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
  6741. *ThumbInstrInfo, *ThumbMRI));
  6742. CHECK_THUMB_TARGET_INFO_CREATION(ThumbIP);
  6743. // Set the display preference for hex vs. decimal immediates.
  6744. ThumbIP->setPrintImmHex(PrintImmHex);
  6745. }
  6746. #undef CHECK_TARGET_INFO_CREATION
  6747. #undef CHECK_THUMB_TARGET_INFO_CREATION
  6748. MachO::mach_header Header = MachOOF->getHeader();
  6749. // FIXME: Using the -cfg command line option, this code used to be able to
  6750. // annotate relocations with the referenced symbol's name, and if this was
  6751. // inside a __[cf]string section, the data it points to. This is now replaced
  6752. // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
  6753. std::vector<SectionRef> Sections;
  6754. std::vector<SymbolRef> Symbols;
  6755. SmallVector<uint64_t, 8> FoundFns;
  6756. uint64_t BaseSegmentAddress = 0;
  6757. getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
  6758. BaseSegmentAddress);
  6759. // Sort the symbols by address, just in case they didn't come in that way.
  6760. llvm::sort(Symbols, SymbolSorter());
  6761. // Build a data in code table that is sorted on by the address of each entry.
  6762. uint64_t BaseAddress = 0;
  6763. if (Header.filetype == MachO::MH_OBJECT)
  6764. BaseAddress = Sections[0].getAddress();
  6765. else
  6766. BaseAddress = BaseSegmentAddress;
  6767. DiceTable Dices;
  6768. for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
  6769. DI != DE; ++DI) {
  6770. uint32_t Offset;
  6771. DI->getOffset(Offset);
  6772. Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
  6773. }
  6774. array_pod_sort(Dices.begin(), Dices.end());
  6775. // Try to find debug info and set up the DIContext for it.
  6776. std::unique_ptr<DIContext> diContext;
  6777. std::unique_ptr<Binary> DSYMBinary;
  6778. std::unique_ptr<MemoryBuffer> DSYMBuf;
  6779. if (UseDbg) {
  6780. ObjectFile *DbgObj = MachOOF;
  6781. // A separate DSym file path was specified, parse it as a macho file,
  6782. // get the sections and supply it to the section name parsing machinery.
  6783. if (!DSYMFile.empty()) {
  6784. std::string DSYMPath(DSYMFile);
  6785. // If DSYMPath is a .dSYM directory, append the Mach-O file.
  6786. if (llvm::sys::fs::is_directory(DSYMPath) &&
  6787. llvm::sys::path::extension(DSYMPath) == ".dSYM") {
  6788. SmallString<128> ShortName(llvm::sys::path::filename(DSYMPath));
  6789. llvm::sys::path::replace_extension(ShortName, "");
  6790. SmallString<1024> FullPath(DSYMPath);
  6791. llvm::sys::path::append(FullPath, "Contents", "Resources", "DWARF",
  6792. ShortName);
  6793. DSYMPath = std::string(FullPath.str());
  6794. }
  6795. // Load the file.
  6796. ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
  6797. MemoryBuffer::getFileOrSTDIN(DSYMPath);
  6798. if (std::error_code EC = BufOrErr.getError()) {
  6799. reportError(errorCodeToError(EC), DSYMPath);
  6800. return;
  6801. }
  6802. // We need to keep the file alive, because we're replacing DbgObj with it.
  6803. DSYMBuf = std::move(BufOrErr.get());
  6804. Expected<std::unique_ptr<Binary>> BinaryOrErr =
  6805. createBinary(DSYMBuf.get()->getMemBufferRef());
  6806. if (!BinaryOrErr) {
  6807. reportError(BinaryOrErr.takeError(), DSYMPath);
  6808. return;
  6809. }
  6810. // We need to keep the Binary alive with the buffer
  6811. DSYMBinary = std::move(BinaryOrErr.get());
  6812. if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) {
  6813. // this is a Mach-O object file, use it
  6814. if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) {
  6815. DbgObj = MachDSYM;
  6816. }
  6817. else {
  6818. WithColor::error(errs(), "llvm-objdump")
  6819. << DSYMPath << " is not a Mach-O file type.\n";
  6820. return;
  6821. }
  6822. }
  6823. else if (auto UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())){
  6824. // this is a Universal Binary, find a Mach-O for this architecture
  6825. uint32_t CPUType, CPUSubType;
  6826. const char *ArchFlag;
  6827. if (MachOOF->is64Bit()) {
  6828. const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
  6829. CPUType = H_64.cputype;
  6830. CPUSubType = H_64.cpusubtype;
  6831. } else {
  6832. const MachO::mach_header H = MachOOF->getHeader();
  6833. CPUType = H.cputype;
  6834. CPUSubType = H.cpusubtype;
  6835. }
  6836. Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr,
  6837. &ArchFlag);
  6838. Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
  6839. UB->getMachOObjectForArch(ArchFlag);
  6840. if (!MachDSYM) {
  6841. reportError(MachDSYM.takeError(), DSYMPath);
  6842. return;
  6843. }
  6844. // We need to keep the Binary alive with the buffer
  6845. DbgObj = &*MachDSYM.get();
  6846. DSYMBinary = std::move(*MachDSYM);
  6847. }
  6848. else {
  6849. WithColor::error(errs(), "llvm-objdump")
  6850. << DSYMPath << " is not a Mach-O or Universal file type.\n";
  6851. return;
  6852. }
  6853. }
  6854. // Setup the DIContext
  6855. diContext = DWARFContext::create(*DbgObj);
  6856. }
  6857. if (FilterSections.empty())
  6858. outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
  6859. for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
  6860. Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName();
  6861. if (!SecNameOrErr) {
  6862. consumeError(SecNameOrErr.takeError());
  6863. continue;
  6864. }
  6865. if (*SecNameOrErr != DisSectName)
  6866. continue;
  6867. DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
  6868. StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
  6869. if (SegmentName != DisSegName)
  6870. continue;
  6871. StringRef BytesStr =
  6872. unwrapOrError(Sections[SectIdx].getContents(), Filename);
  6873. ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
  6874. uint64_t SectAddress = Sections[SectIdx].getAddress();
  6875. bool symbolTableWorked = false;
  6876. // Create a map of symbol addresses to symbol names for use by
  6877. // the SymbolizerSymbolLookUp() routine.
  6878. SymbolAddressMap AddrMap;
  6879. bool DisSymNameFound = false;
  6880. for (const SymbolRef &Symbol : MachOOF->symbols()) {
  6881. SymbolRef::Type ST =
  6882. unwrapOrError(Symbol.getType(), MachOOF->getFileName());
  6883. if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
  6884. ST == SymbolRef::ST_Other) {
  6885. uint64_t Address = cantFail(Symbol.getValue());
  6886. StringRef SymName =
  6887. unwrapOrError(Symbol.getName(), MachOOF->getFileName());
  6888. AddrMap[Address] = SymName;
  6889. if (!DisSymName.empty() && DisSymName == SymName)
  6890. DisSymNameFound = true;
  6891. }
  6892. }
  6893. if (!DisSymName.empty() && !DisSymNameFound) {
  6894. outs() << "Can't find -dis-symname: " << DisSymName << "\n";
  6895. return;
  6896. }
  6897. // Set up the block of info used by the Symbolizer call backs.
  6898. SymbolizerInfo.verbose = !NoSymbolicOperands;
  6899. SymbolizerInfo.O = MachOOF;
  6900. SymbolizerInfo.S = Sections[SectIdx];
  6901. SymbolizerInfo.AddrMap = &AddrMap;
  6902. SymbolizerInfo.Sections = &Sections;
  6903. // Same for the ThumbSymbolizer
  6904. ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
  6905. ThumbSymbolizerInfo.O = MachOOF;
  6906. ThumbSymbolizerInfo.S = Sections[SectIdx];
  6907. ThumbSymbolizerInfo.AddrMap = &AddrMap;
  6908. ThumbSymbolizerInfo.Sections = &Sections;
  6909. unsigned int Arch = MachOOF->getArch();
  6910. // Skip all symbols if this is a stubs file.
  6911. if (Bytes.empty())
  6912. return;
  6913. // If the section has symbols but no symbol at the start of the section
  6914. // these are used to make sure the bytes before the first symbol are
  6915. // disassembled.
  6916. bool FirstSymbol = true;
  6917. bool FirstSymbolAtSectionStart = true;
  6918. // Disassemble symbol by symbol.
  6919. for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
  6920. StringRef SymName =
  6921. unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
  6922. SymbolRef::Type ST =
  6923. unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
  6924. if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
  6925. continue;
  6926. // Make sure the symbol is defined in this section.
  6927. bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
  6928. if (!containsSym) {
  6929. if (!DisSymName.empty() && DisSymName == SymName) {
  6930. outs() << "-dis-symname: " << DisSymName << " not in the section\n";
  6931. return;
  6932. }
  6933. continue;
  6934. }
  6935. // The __mh_execute_header is special and we need to deal with that fact
  6936. // this symbol is before the start of the (__TEXT,__text) section and at the
  6937. // address of the start of the __TEXT segment. This is because this symbol
  6938. // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
  6939. // start of the section in a standard MH_EXECUTE filetype.
  6940. if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
  6941. outs() << "-dis-symname: __mh_execute_header not in any section\n";
  6942. return;
  6943. }
  6944. // When this code is trying to disassemble a symbol at a time and in the
  6945. // case there is only the __mh_execute_header symbol left as in a stripped
  6946. // executable, we need to deal with this by ignoring this symbol so the
  6947. // whole section is disassembled and this symbol is then not displayed.
  6948. if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
  6949. SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
  6950. SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
  6951. continue;
  6952. // If we are only disassembling one symbol see if this is that symbol.
  6953. if (!DisSymName.empty() && DisSymName != SymName)
  6954. continue;
  6955. // Start at the address of the symbol relative to the section's address.
  6956. uint64_t SectSize = Sections[SectIdx].getSize();
  6957. uint64_t Start = cantFail(Symbols[SymIdx].getValue());
  6958. uint64_t SectionAddress = Sections[SectIdx].getAddress();
  6959. Start -= SectionAddress;
  6960. if (Start > SectSize) {
  6961. outs() << "section data ends, " << SymName
  6962. << " lies outside valid range\n";
  6963. return;
  6964. }
  6965. // Stop disassembling either at the beginning of the next symbol or at
  6966. // the end of the section.
  6967. bool containsNextSym = false;
  6968. uint64_t NextSym = 0;
  6969. uint64_t NextSymIdx = SymIdx + 1;
  6970. while (Symbols.size() > NextSymIdx) {
  6971. SymbolRef::Type NextSymType = unwrapOrError(
  6972. Symbols[NextSymIdx].getType(), MachOOF->getFileName());
  6973. if (NextSymType == SymbolRef::ST_Function) {
  6974. containsNextSym =
  6975. Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
  6976. NextSym = cantFail(Symbols[NextSymIdx].getValue());
  6977. NextSym -= SectionAddress;
  6978. break;
  6979. }
  6980. ++NextSymIdx;
  6981. }
  6982. uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
  6983. uint64_t Size;
  6984. symbolTableWorked = true;
  6985. DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
  6986. uint32_t SymbolFlags = cantFail(MachOOF->getSymbolFlags(Symb));
  6987. bool IsThumb = SymbolFlags & SymbolRef::SF_Thumb;
  6988. // We only need the dedicated Thumb target if there's a real choice
  6989. // (i.e. we're not targeting M-class) and the function is Thumb.
  6990. bool UseThumbTarget = IsThumb && ThumbTarget;
  6991. // If we are not specifying a symbol to start disassembly with and this
  6992. // is the first symbol in the section but not at the start of the section
  6993. // then move the disassembly index to the start of the section and
  6994. // don't print the symbol name just yet. This is so the bytes before the
  6995. // first symbol are disassembled.
  6996. uint64_t SymbolStart = Start;
  6997. if (DisSymName.empty() && FirstSymbol && Start != 0) {
  6998. FirstSymbolAtSectionStart = false;
  6999. Start = 0;
  7000. }
  7001. else
  7002. outs() << SymName << ":\n";
  7003. DILineInfo lastLine;
  7004. for (uint64_t Index = Start; Index < End; Index += Size) {
  7005. MCInst Inst;
  7006. // If this is the first symbol in the section and it was not at the
  7007. // start of the section, see if we are at its Index now and if so print
  7008. // the symbol name.
  7009. if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
  7010. outs() << SymName << ":\n";
  7011. uint64_t PC = SectAddress + Index;
  7012. if (!NoLeadingAddr) {
  7013. if (FullLeadingAddr) {
  7014. if (MachOOF->is64Bit())
  7015. outs() << format("%016" PRIx64, PC);
  7016. else
  7017. outs() << format("%08" PRIx64, PC);
  7018. } else {
  7019. outs() << format("%8" PRIx64 ":", PC);
  7020. }
  7021. }
  7022. if (!NoShowRawInsn || Arch == Triple::arm)
  7023. outs() << "\t";
  7024. if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, Size))
  7025. continue;
  7026. SmallVector<char, 64> AnnotationsBytes;
  7027. raw_svector_ostream Annotations(AnnotationsBytes);
  7028. bool gotInst;
  7029. if (UseThumbTarget)
  7030. gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
  7031. PC, Annotations);
  7032. else
  7033. gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
  7034. Annotations);
  7035. if (gotInst) {
  7036. if (!NoShowRawInsn || Arch == Triple::arm) {
  7037. dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
  7038. }
  7039. formatted_raw_ostream FormattedOS(outs());
  7040. StringRef AnnotationsStr = Annotations.str();
  7041. if (UseThumbTarget)
  7042. ThumbIP->printInst(&Inst, PC, AnnotationsStr, *ThumbSTI,
  7043. FormattedOS);
  7044. else
  7045. IP->printInst(&Inst, PC, AnnotationsStr, *STI, FormattedOS);
  7046. emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
  7047. // Print debug info.
  7048. if (diContext) {
  7049. DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
  7050. // Print valid line info if it changed.
  7051. if (dli != lastLine && dli.Line != 0)
  7052. outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
  7053. << dli.Column;
  7054. lastLine = dli;
  7055. }
  7056. outs() << "\n";
  7057. } else {
  7058. if (MachOOF->getArchTriple().isX86()) {
  7059. outs() << format("\t.byte 0x%02x #bad opcode\n",
  7060. *(Bytes.data() + Index) & 0xff);
  7061. Size = 1; // skip exactly one illegible byte and move on.
  7062. } else if (Arch == Triple::aarch64 ||
  7063. (Arch == Triple::arm && !IsThumb)) {
  7064. uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
  7065. (*(Bytes.data() + Index + 1) & 0xff) << 8 |
  7066. (*(Bytes.data() + Index + 2) & 0xff) << 16 |
  7067. (*(Bytes.data() + Index + 3) & 0xff) << 24;
  7068. outs() << format("\t.long\t0x%08x\n", opcode);
  7069. Size = 4;
  7070. } else if (Arch == Triple::arm) {
  7071. assert(IsThumb && "ARM mode should have been dealt with above");
  7072. uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
  7073. (*(Bytes.data() + Index + 1) & 0xff) << 8;
  7074. outs() << format("\t.short\t0x%04x\n", opcode);
  7075. Size = 2;
  7076. } else{
  7077. WithColor::warning(errs(), "llvm-objdump")
  7078. << "invalid instruction encoding\n";
  7079. if (Size == 0)
  7080. Size = 1; // skip illegible bytes
  7081. }
  7082. }
  7083. }
  7084. // Now that we are done disassembled the first symbol set the bool that
  7085. // were doing this to false.
  7086. FirstSymbol = false;
  7087. }
  7088. if (!symbolTableWorked) {
  7089. // Reading the symbol table didn't work, disassemble the whole section.
  7090. uint64_t SectAddress = Sections[SectIdx].getAddress();
  7091. uint64_t SectSize = Sections[SectIdx].getSize();
  7092. uint64_t InstSize;
  7093. for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
  7094. MCInst Inst;
  7095. uint64_t PC = SectAddress + Index;
  7096. if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, InstSize))
  7097. continue;
  7098. SmallVector<char, 64> AnnotationsBytes;
  7099. raw_svector_ostream Annotations(AnnotationsBytes);
  7100. if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
  7101. Annotations)) {
  7102. if (!NoLeadingAddr) {
  7103. if (FullLeadingAddr) {
  7104. if (MachOOF->is64Bit())
  7105. outs() << format("%016" PRIx64, PC);
  7106. else
  7107. outs() << format("%08" PRIx64, PC);
  7108. } else {
  7109. outs() << format("%8" PRIx64 ":", PC);
  7110. }
  7111. }
  7112. if (!NoShowRawInsn || Arch == Triple::arm) {
  7113. outs() << "\t";
  7114. dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
  7115. }
  7116. StringRef AnnotationsStr = Annotations.str();
  7117. IP->printInst(&Inst, PC, AnnotationsStr, *STI, outs());
  7118. outs() << "\n";
  7119. } else {
  7120. if (MachOOF->getArchTriple().isX86()) {
  7121. outs() << format("\t.byte 0x%02x #bad opcode\n",
  7122. *(Bytes.data() + Index) & 0xff);
  7123. InstSize = 1; // skip exactly one illegible byte and move on.
  7124. } else {
  7125. WithColor::warning(errs(), "llvm-objdump")
  7126. << "invalid instruction encoding\n";
  7127. if (InstSize == 0)
  7128. InstSize = 1; // skip illegible bytes
  7129. }
  7130. }
  7131. }
  7132. }
  7133. // The TripleName's need to be reset if we are called again for a different
  7134. // architecture.
  7135. TripleName = "";
  7136. ThumbTripleName = "";
  7137. if (SymbolizerInfo.demangled_name != nullptr)
  7138. free(SymbolizerInfo.demangled_name);
  7139. if (ThumbSymbolizerInfo.demangled_name != nullptr)
  7140. free(ThumbSymbolizerInfo.demangled_name);
  7141. }
  7142. }
  7143. //===----------------------------------------------------------------------===//
  7144. // __compact_unwind section dumping
  7145. //===----------------------------------------------------------------------===//
  7146. namespace {
  7147. template <typename T>
  7148. static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
  7149. using llvm::support::little;
  7150. using llvm::support::unaligned;
  7151. if (Offset + sizeof(T) > Contents.size()) {
  7152. outs() << "warning: attempt to read past end of buffer\n";
  7153. return T();
  7154. }
  7155. uint64_t Val =
  7156. support::endian::read<T, little, unaligned>(Contents.data() + Offset);
  7157. return Val;
  7158. }
  7159. template <typename T>
  7160. static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
  7161. T Val = read<T>(Contents, Offset);
  7162. Offset += sizeof(T);
  7163. return Val;
  7164. }
  7165. struct CompactUnwindEntry {
  7166. uint32_t OffsetInSection;
  7167. uint64_t FunctionAddr;
  7168. uint32_t Length;
  7169. uint32_t CompactEncoding;
  7170. uint64_t PersonalityAddr;
  7171. uint64_t LSDAAddr;
  7172. RelocationRef FunctionReloc;
  7173. RelocationRef PersonalityReloc;
  7174. RelocationRef LSDAReloc;
  7175. CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
  7176. : OffsetInSection(Offset) {
  7177. if (Is64)
  7178. read<uint64_t>(Contents, Offset);
  7179. else
  7180. read<uint32_t>(Contents, Offset);
  7181. }
  7182. private:
  7183. template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
  7184. FunctionAddr = readNext<UIntPtr>(Contents, Offset);
  7185. Length = readNext<uint32_t>(Contents, Offset);
  7186. CompactEncoding = readNext<uint32_t>(Contents, Offset);
  7187. PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
  7188. LSDAAddr = readNext<UIntPtr>(Contents, Offset);
  7189. }
  7190. };
  7191. }
  7192. /// Given a relocation from __compact_unwind, consisting of the RelocationRef
  7193. /// and data being relocated, determine the best base Name and Addend to use for
  7194. /// display purposes.
  7195. ///
  7196. /// 1. An Extern relocation will directly reference a symbol (and the data is
  7197. /// then already an addend), so use that.
  7198. /// 2. Otherwise the data is an offset in the object file's layout; try to find
  7199. // a symbol before it in the same section, and use the offset from there.
  7200. /// 3. Finally, if all that fails, fall back to an offset from the start of the
  7201. /// referenced section.
  7202. static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
  7203. std::map<uint64_t, SymbolRef> &Symbols,
  7204. const RelocationRef &Reloc, uint64_t Addr,
  7205. StringRef &Name, uint64_t &Addend) {
  7206. if (Reloc.getSymbol() != Obj->symbol_end()) {
  7207. Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
  7208. Addend = Addr;
  7209. return;
  7210. }
  7211. auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
  7212. SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
  7213. uint64_t SectionAddr = RelocSection.getAddress();
  7214. auto Sym = Symbols.upper_bound(Addr);
  7215. if (Sym == Symbols.begin()) {
  7216. // The first symbol in the object is after this reference, the best we can
  7217. // do is section-relative notation.
  7218. if (Expected<StringRef> NameOrErr = RelocSection.getName())
  7219. Name = *NameOrErr;
  7220. else
  7221. consumeError(NameOrErr.takeError());
  7222. Addend = Addr - SectionAddr;
  7223. return;
  7224. }
  7225. // Go back one so that SymbolAddress <= Addr.
  7226. --Sym;
  7227. section_iterator SymSection =
  7228. unwrapOrError(Sym->second.getSection(), Obj->getFileName());
  7229. if (RelocSection == *SymSection) {
  7230. // There's a valid symbol in the same section before this reference.
  7231. Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
  7232. Addend = Addr - Sym->first;
  7233. return;
  7234. }
  7235. // There is a symbol before this reference, but it's in a different
  7236. // section. Probably not helpful to mention it, so use the section name.
  7237. if (Expected<StringRef> NameOrErr = RelocSection.getName())
  7238. Name = *NameOrErr;
  7239. else
  7240. consumeError(NameOrErr.takeError());
  7241. Addend = Addr - SectionAddr;
  7242. }
  7243. static void printUnwindRelocDest(const MachOObjectFile *Obj,
  7244. std::map<uint64_t, SymbolRef> &Symbols,
  7245. const RelocationRef &Reloc, uint64_t Addr) {
  7246. StringRef Name;
  7247. uint64_t Addend;
  7248. if (!Reloc.getObject())
  7249. return;
  7250. findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
  7251. outs() << Name;
  7252. if (Addend)
  7253. outs() << " + " << format("0x%" PRIx64, Addend);
  7254. }
  7255. static void
  7256. printMachOCompactUnwindSection(const MachOObjectFile *Obj,
  7257. std::map<uint64_t, SymbolRef> &Symbols,
  7258. const SectionRef &CompactUnwind) {
  7259. if (!Obj->isLittleEndian()) {
  7260. outs() << "Skipping big-endian __compact_unwind section\n";
  7261. return;
  7262. }
  7263. bool Is64 = Obj->is64Bit();
  7264. uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
  7265. uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
  7266. StringRef Contents =
  7267. unwrapOrError(CompactUnwind.getContents(), Obj->getFileName());
  7268. SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
  7269. // First populate the initial raw offsets, encodings and so on from the entry.
  7270. for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
  7271. CompactUnwindEntry Entry(Contents, Offset, Is64);
  7272. CompactUnwinds.push_back(Entry);
  7273. }
  7274. // Next we need to look at the relocations to find out what objects are
  7275. // actually being referred to.
  7276. for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
  7277. uint64_t RelocAddress = Reloc.getOffset();
  7278. uint32_t EntryIdx = RelocAddress / EntrySize;
  7279. uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
  7280. CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
  7281. if (OffsetInEntry == 0)
  7282. Entry.FunctionReloc = Reloc;
  7283. else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
  7284. Entry.PersonalityReloc = Reloc;
  7285. else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
  7286. Entry.LSDAReloc = Reloc;
  7287. else {
  7288. outs() << "Invalid relocation in __compact_unwind section\n";
  7289. return;
  7290. }
  7291. }
  7292. // Finally, we're ready to print the data we've gathered.
  7293. outs() << "Contents of __compact_unwind section:\n";
  7294. for (auto &Entry : CompactUnwinds) {
  7295. outs() << " Entry at offset "
  7296. << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
  7297. // 1. Start of the region this entry applies to.
  7298. outs() << " start: " << format("0x%" PRIx64,
  7299. Entry.FunctionAddr) << ' ';
  7300. printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
  7301. outs() << '\n';
  7302. // 2. Length of the region this entry applies to.
  7303. outs() << " length: " << format("0x%" PRIx32, Entry.Length)
  7304. << '\n';
  7305. // 3. The 32-bit compact encoding.
  7306. outs() << " compact encoding: "
  7307. << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
  7308. // 4. The personality function, if present.
  7309. if (Entry.PersonalityReloc.getObject()) {
  7310. outs() << " personality function: "
  7311. << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
  7312. printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
  7313. Entry.PersonalityAddr);
  7314. outs() << '\n';
  7315. }
  7316. // 5. This entry's language-specific data area.
  7317. if (Entry.LSDAReloc.getObject()) {
  7318. outs() << " LSDA: " << format("0x%" PRIx64,
  7319. Entry.LSDAAddr) << ' ';
  7320. printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
  7321. outs() << '\n';
  7322. }
  7323. }
  7324. }
  7325. //===----------------------------------------------------------------------===//
  7326. // __unwind_info section dumping
  7327. //===----------------------------------------------------------------------===//
  7328. static void printRegularSecondLevelUnwindPage(StringRef PageData) {
  7329. ptrdiff_t Pos = 0;
  7330. uint32_t Kind = readNext<uint32_t>(PageData, Pos);
  7331. (void)Kind;
  7332. assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
  7333. uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
  7334. uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
  7335. Pos = EntriesStart;
  7336. for (unsigned i = 0; i < NumEntries; ++i) {
  7337. uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
  7338. uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
  7339. outs() << " [" << i << "]: "
  7340. << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
  7341. << ", "
  7342. << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
  7343. }
  7344. }
  7345. static void printCompressedSecondLevelUnwindPage(
  7346. StringRef PageData, uint32_t FunctionBase,
  7347. const SmallVectorImpl<uint32_t> &CommonEncodings) {
  7348. ptrdiff_t Pos = 0;
  7349. uint32_t Kind = readNext<uint32_t>(PageData, Pos);
  7350. (void)Kind;
  7351. assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
  7352. uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
  7353. uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
  7354. uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
  7355. readNext<uint16_t>(PageData, Pos);
  7356. StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
  7357. Pos = EntriesStart;
  7358. for (unsigned i = 0; i < NumEntries; ++i) {
  7359. uint32_t Entry = readNext<uint32_t>(PageData, Pos);
  7360. uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
  7361. uint32_t EncodingIdx = Entry >> 24;
  7362. uint32_t Encoding;
  7363. if (EncodingIdx < CommonEncodings.size())
  7364. Encoding = CommonEncodings[EncodingIdx];
  7365. else
  7366. Encoding = read<uint32_t>(PageEncodings,
  7367. sizeof(uint32_t) *
  7368. (EncodingIdx - CommonEncodings.size()));
  7369. outs() << " [" << i << "]: "
  7370. << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
  7371. << ", "
  7372. << "encoding[" << EncodingIdx
  7373. << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
  7374. }
  7375. }
  7376. static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
  7377. std::map<uint64_t, SymbolRef> &Symbols,
  7378. const SectionRef &UnwindInfo) {
  7379. if (!Obj->isLittleEndian()) {
  7380. outs() << "Skipping big-endian __unwind_info section\n";
  7381. return;
  7382. }
  7383. outs() << "Contents of __unwind_info section:\n";
  7384. StringRef Contents =
  7385. unwrapOrError(UnwindInfo.getContents(), Obj->getFileName());
  7386. ptrdiff_t Pos = 0;
  7387. //===----------------------------------
  7388. // Section header
  7389. //===----------------------------------
  7390. uint32_t Version = readNext<uint32_t>(Contents, Pos);
  7391. outs() << " Version: "
  7392. << format("0x%" PRIx32, Version) << '\n';
  7393. if (Version != 1) {
  7394. outs() << " Skipping section with unknown version\n";
  7395. return;
  7396. }
  7397. uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
  7398. outs() << " Common encodings array section offset: "
  7399. << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
  7400. uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
  7401. outs() << " Number of common encodings in array: "
  7402. << format("0x%" PRIx32, NumCommonEncodings) << '\n';
  7403. uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
  7404. outs() << " Personality function array section offset: "
  7405. << format("0x%" PRIx32, PersonalitiesStart) << '\n';
  7406. uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
  7407. outs() << " Number of personality functions in array: "
  7408. << format("0x%" PRIx32, NumPersonalities) << '\n';
  7409. uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
  7410. outs() << " Index array section offset: "
  7411. << format("0x%" PRIx32, IndicesStart) << '\n';
  7412. uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
  7413. outs() << " Number of indices in array: "
  7414. << format("0x%" PRIx32, NumIndices) << '\n';
  7415. //===----------------------------------
  7416. // A shared list of common encodings
  7417. //===----------------------------------
  7418. // These occupy indices in the range [0, N] whenever an encoding is referenced
  7419. // from a compressed 2nd level index table. In practice the linker only
  7420. // creates ~128 of these, so that indices are available to embed encodings in
  7421. // the 2nd level index.
  7422. SmallVector<uint32_t, 64> CommonEncodings;
  7423. outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
  7424. Pos = CommonEncodingsStart;
  7425. for (unsigned i = 0; i < NumCommonEncodings; ++i) {
  7426. uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
  7427. CommonEncodings.push_back(Encoding);
  7428. outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
  7429. << '\n';
  7430. }
  7431. //===----------------------------------
  7432. // Personality functions used in this executable
  7433. //===----------------------------------
  7434. // There should be only a handful of these (one per source language,
  7435. // roughly). Particularly since they only get 2 bits in the compact encoding.
  7436. outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
  7437. Pos = PersonalitiesStart;
  7438. for (unsigned i = 0; i < NumPersonalities; ++i) {
  7439. uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
  7440. outs() << " personality[" << i + 1
  7441. << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
  7442. }
  7443. //===----------------------------------
  7444. // The level 1 index entries
  7445. //===----------------------------------
  7446. // These specify an approximate place to start searching for the more detailed
  7447. // information, sorted by PC.
  7448. struct IndexEntry {
  7449. uint32_t FunctionOffset;
  7450. uint32_t SecondLevelPageStart;
  7451. uint32_t LSDAStart;
  7452. };
  7453. SmallVector<IndexEntry, 4> IndexEntries;
  7454. outs() << " Top level indices: (count = " << NumIndices << ")\n";
  7455. Pos = IndicesStart;
  7456. for (unsigned i = 0; i < NumIndices; ++i) {
  7457. IndexEntry Entry;
  7458. Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
  7459. Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
  7460. Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
  7461. IndexEntries.push_back(Entry);
  7462. outs() << " [" << i << "]: "
  7463. << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
  7464. << ", "
  7465. << "2nd level page offset="
  7466. << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
  7467. << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
  7468. }
  7469. //===----------------------------------
  7470. // Next come the LSDA tables
  7471. //===----------------------------------
  7472. // The LSDA layout is rather implicit: it's a contiguous array of entries from
  7473. // the first top-level index's LSDAOffset to the last (sentinel).
  7474. outs() << " LSDA descriptors:\n";
  7475. Pos = IndexEntries[0].LSDAStart;
  7476. const uint32_t LSDASize = 2 * sizeof(uint32_t);
  7477. int NumLSDAs =
  7478. (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
  7479. for (int i = 0; i < NumLSDAs; ++i) {
  7480. uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
  7481. uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
  7482. outs() << " [" << i << "]: "
  7483. << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
  7484. << ", "
  7485. << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
  7486. }
  7487. //===----------------------------------
  7488. // Finally, the 2nd level indices
  7489. //===----------------------------------
  7490. // Generally these are 4K in size, and have 2 possible forms:
  7491. // + Regular stores up to 511 entries with disparate encodings
  7492. // + Compressed stores up to 1021 entries if few enough compact encoding
  7493. // values are used.
  7494. outs() << " Second level indices:\n";
  7495. for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
  7496. // The final sentinel top-level index has no associated 2nd level page
  7497. if (IndexEntries[i].SecondLevelPageStart == 0)
  7498. break;
  7499. outs() << " Second level index[" << i << "]: "
  7500. << "offset in section="
  7501. << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
  7502. << ", "
  7503. << "base function offset="
  7504. << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
  7505. Pos = IndexEntries[i].SecondLevelPageStart;
  7506. if (Pos + sizeof(uint32_t) > Contents.size()) {
  7507. outs() << "warning: invalid offset for second level page: " << Pos << '\n';
  7508. continue;
  7509. }
  7510. uint32_t Kind =
  7511. *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
  7512. if (Kind == 2)
  7513. printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
  7514. else if (Kind == 3)
  7515. printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
  7516. IndexEntries[i].FunctionOffset,
  7517. CommonEncodings);
  7518. else
  7519. outs() << " Skipping 2nd level page with unknown kind " << Kind
  7520. << '\n';
  7521. }
  7522. }
  7523. void objdump::printMachOUnwindInfo(const MachOObjectFile *Obj) {
  7524. std::map<uint64_t, SymbolRef> Symbols;
  7525. for (const SymbolRef &SymRef : Obj->symbols()) {
  7526. // Discard any undefined or absolute symbols. They're not going to take part
  7527. // in the convenience lookup for unwind info and just take up resources.
  7528. auto SectOrErr = SymRef.getSection();
  7529. if (!SectOrErr) {
  7530. // TODO: Actually report errors helpfully.
  7531. consumeError(SectOrErr.takeError());
  7532. continue;
  7533. }
  7534. section_iterator Section = *SectOrErr;
  7535. if (Section == Obj->section_end())
  7536. continue;
  7537. uint64_t Addr = cantFail(SymRef.getValue());
  7538. Symbols.insert(std::make_pair(Addr, SymRef));
  7539. }
  7540. for (const SectionRef &Section : Obj->sections()) {
  7541. StringRef SectName;
  7542. if (Expected<StringRef> NameOrErr = Section.getName())
  7543. SectName = *NameOrErr;
  7544. else
  7545. consumeError(NameOrErr.takeError());
  7546. if (SectName == "__compact_unwind")
  7547. printMachOCompactUnwindSection(Obj, Symbols, Section);
  7548. else if (SectName == "__unwind_info")
  7549. printMachOUnwindInfoSection(Obj, Symbols, Section);
  7550. }
  7551. }
  7552. static void PrintMachHeader(uint32_t magic, uint32_t cputype,
  7553. uint32_t cpusubtype, uint32_t filetype,
  7554. uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
  7555. bool verbose) {
  7556. outs() << "Mach header\n";
  7557. outs() << " magic cputype cpusubtype caps filetype ncmds "
  7558. "sizeofcmds flags\n";
  7559. if (verbose) {
  7560. if (magic == MachO::MH_MAGIC)
  7561. outs() << " MH_MAGIC";
  7562. else if (magic == MachO::MH_MAGIC_64)
  7563. outs() << "MH_MAGIC_64";
  7564. else
  7565. outs() << format(" 0x%08" PRIx32, magic);
  7566. switch (cputype) {
  7567. case MachO::CPU_TYPE_I386:
  7568. outs() << " I386";
  7569. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7570. case MachO::CPU_SUBTYPE_I386_ALL:
  7571. outs() << " ALL";
  7572. break;
  7573. default:
  7574. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7575. break;
  7576. }
  7577. break;
  7578. case MachO::CPU_TYPE_X86_64:
  7579. outs() << " X86_64";
  7580. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7581. case MachO::CPU_SUBTYPE_X86_64_ALL:
  7582. outs() << " ALL";
  7583. break;
  7584. case MachO::CPU_SUBTYPE_X86_64_H:
  7585. outs() << " Haswell";
  7586. break;
  7587. default:
  7588. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7589. break;
  7590. }
  7591. break;
  7592. case MachO::CPU_TYPE_ARM:
  7593. outs() << " ARM";
  7594. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7595. case MachO::CPU_SUBTYPE_ARM_ALL:
  7596. outs() << " ALL";
  7597. break;
  7598. case MachO::CPU_SUBTYPE_ARM_V4T:
  7599. outs() << " V4T";
  7600. break;
  7601. case MachO::CPU_SUBTYPE_ARM_V5TEJ:
  7602. outs() << " V5TEJ";
  7603. break;
  7604. case MachO::CPU_SUBTYPE_ARM_XSCALE:
  7605. outs() << " XSCALE";
  7606. break;
  7607. case MachO::CPU_SUBTYPE_ARM_V6:
  7608. outs() << " V6";
  7609. break;
  7610. case MachO::CPU_SUBTYPE_ARM_V6M:
  7611. outs() << " V6M";
  7612. break;
  7613. case MachO::CPU_SUBTYPE_ARM_V7:
  7614. outs() << " V7";
  7615. break;
  7616. case MachO::CPU_SUBTYPE_ARM_V7EM:
  7617. outs() << " V7EM";
  7618. break;
  7619. case MachO::CPU_SUBTYPE_ARM_V7K:
  7620. outs() << " V7K";
  7621. break;
  7622. case MachO::CPU_SUBTYPE_ARM_V7M:
  7623. outs() << " V7M";
  7624. break;
  7625. case MachO::CPU_SUBTYPE_ARM_V7S:
  7626. outs() << " V7S";
  7627. break;
  7628. default:
  7629. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7630. break;
  7631. }
  7632. break;
  7633. case MachO::CPU_TYPE_ARM64:
  7634. outs() << " ARM64";
  7635. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7636. case MachO::CPU_SUBTYPE_ARM64_ALL:
  7637. outs() << " ALL";
  7638. break;
  7639. case MachO::CPU_SUBTYPE_ARM64_V8:
  7640. outs() << " V8";
  7641. break;
  7642. case MachO::CPU_SUBTYPE_ARM64E:
  7643. outs() << " E";
  7644. break;
  7645. default:
  7646. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7647. break;
  7648. }
  7649. break;
  7650. case MachO::CPU_TYPE_ARM64_32:
  7651. outs() << " ARM64_32";
  7652. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7653. case MachO::CPU_SUBTYPE_ARM64_32_V8:
  7654. outs() << " V8";
  7655. break;
  7656. default:
  7657. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7658. break;
  7659. }
  7660. break;
  7661. case MachO::CPU_TYPE_POWERPC:
  7662. outs() << " PPC";
  7663. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7664. case MachO::CPU_SUBTYPE_POWERPC_ALL:
  7665. outs() << " ALL";
  7666. break;
  7667. default:
  7668. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7669. break;
  7670. }
  7671. break;
  7672. case MachO::CPU_TYPE_POWERPC64:
  7673. outs() << " PPC64";
  7674. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7675. case MachO::CPU_SUBTYPE_POWERPC_ALL:
  7676. outs() << " ALL";
  7677. break;
  7678. default:
  7679. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7680. break;
  7681. }
  7682. break;
  7683. default:
  7684. outs() << format(" %7d", cputype);
  7685. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7686. break;
  7687. }
  7688. if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
  7689. outs() << " LIB64";
  7690. } else {
  7691. outs() << format(" 0x%02" PRIx32,
  7692. (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
  7693. }
  7694. switch (filetype) {
  7695. case MachO::MH_OBJECT:
  7696. outs() << " OBJECT";
  7697. break;
  7698. case MachO::MH_EXECUTE:
  7699. outs() << " EXECUTE";
  7700. break;
  7701. case MachO::MH_FVMLIB:
  7702. outs() << " FVMLIB";
  7703. break;
  7704. case MachO::MH_CORE:
  7705. outs() << " CORE";
  7706. break;
  7707. case MachO::MH_PRELOAD:
  7708. outs() << " PRELOAD";
  7709. break;
  7710. case MachO::MH_DYLIB:
  7711. outs() << " DYLIB";
  7712. break;
  7713. case MachO::MH_DYLIB_STUB:
  7714. outs() << " DYLIB_STUB";
  7715. break;
  7716. case MachO::MH_DYLINKER:
  7717. outs() << " DYLINKER";
  7718. break;
  7719. case MachO::MH_BUNDLE:
  7720. outs() << " BUNDLE";
  7721. break;
  7722. case MachO::MH_DSYM:
  7723. outs() << " DSYM";
  7724. break;
  7725. case MachO::MH_KEXT_BUNDLE:
  7726. outs() << " KEXTBUNDLE";
  7727. break;
  7728. default:
  7729. outs() << format(" %10u", filetype);
  7730. break;
  7731. }
  7732. outs() << format(" %5u", ncmds);
  7733. outs() << format(" %10u", sizeofcmds);
  7734. uint32_t f = flags;
  7735. if (f & MachO::MH_NOUNDEFS) {
  7736. outs() << " NOUNDEFS";
  7737. f &= ~MachO::MH_NOUNDEFS;
  7738. }
  7739. if (f & MachO::MH_INCRLINK) {
  7740. outs() << " INCRLINK";
  7741. f &= ~MachO::MH_INCRLINK;
  7742. }
  7743. if (f & MachO::MH_DYLDLINK) {
  7744. outs() << " DYLDLINK";
  7745. f &= ~MachO::MH_DYLDLINK;
  7746. }
  7747. if (f & MachO::MH_BINDATLOAD) {
  7748. outs() << " BINDATLOAD";
  7749. f &= ~MachO::MH_BINDATLOAD;
  7750. }
  7751. if (f & MachO::MH_PREBOUND) {
  7752. outs() << " PREBOUND";
  7753. f &= ~MachO::MH_PREBOUND;
  7754. }
  7755. if (f & MachO::MH_SPLIT_SEGS) {
  7756. outs() << " SPLIT_SEGS";
  7757. f &= ~MachO::MH_SPLIT_SEGS;
  7758. }
  7759. if (f & MachO::MH_LAZY_INIT) {
  7760. outs() << " LAZY_INIT";
  7761. f &= ~MachO::MH_LAZY_INIT;
  7762. }
  7763. if (f & MachO::MH_TWOLEVEL) {
  7764. outs() << " TWOLEVEL";
  7765. f &= ~MachO::MH_TWOLEVEL;
  7766. }
  7767. if (f & MachO::MH_FORCE_FLAT) {
  7768. outs() << " FORCE_FLAT";
  7769. f &= ~MachO::MH_FORCE_FLAT;
  7770. }
  7771. if (f & MachO::MH_NOMULTIDEFS) {
  7772. outs() << " NOMULTIDEFS";
  7773. f &= ~MachO::MH_NOMULTIDEFS;
  7774. }
  7775. if (f & MachO::MH_NOFIXPREBINDING) {
  7776. outs() << " NOFIXPREBINDING";
  7777. f &= ~MachO::MH_NOFIXPREBINDING;
  7778. }
  7779. if (f & MachO::MH_PREBINDABLE) {
  7780. outs() << " PREBINDABLE";
  7781. f &= ~MachO::MH_PREBINDABLE;
  7782. }
  7783. if (f & MachO::MH_ALLMODSBOUND) {
  7784. outs() << " ALLMODSBOUND";
  7785. f &= ~MachO::MH_ALLMODSBOUND;
  7786. }
  7787. if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
  7788. outs() << " SUBSECTIONS_VIA_SYMBOLS";
  7789. f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
  7790. }
  7791. if (f & MachO::MH_CANONICAL) {
  7792. outs() << " CANONICAL";
  7793. f &= ~MachO::MH_CANONICAL;
  7794. }
  7795. if (f & MachO::MH_WEAK_DEFINES) {
  7796. outs() << " WEAK_DEFINES";
  7797. f &= ~MachO::MH_WEAK_DEFINES;
  7798. }
  7799. if (f & MachO::MH_BINDS_TO_WEAK) {
  7800. outs() << " BINDS_TO_WEAK";
  7801. f &= ~MachO::MH_BINDS_TO_WEAK;
  7802. }
  7803. if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
  7804. outs() << " ALLOW_STACK_EXECUTION";
  7805. f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
  7806. }
  7807. if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
  7808. outs() << " DEAD_STRIPPABLE_DYLIB";
  7809. f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
  7810. }
  7811. if (f & MachO::MH_PIE) {
  7812. outs() << " PIE";
  7813. f &= ~MachO::MH_PIE;
  7814. }
  7815. if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
  7816. outs() << " NO_REEXPORTED_DYLIBS";
  7817. f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
  7818. }
  7819. if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
  7820. outs() << " MH_HAS_TLV_DESCRIPTORS";
  7821. f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
  7822. }
  7823. if (f & MachO::MH_NO_HEAP_EXECUTION) {
  7824. outs() << " MH_NO_HEAP_EXECUTION";
  7825. f &= ~MachO::MH_NO_HEAP_EXECUTION;
  7826. }
  7827. if (f & MachO::MH_APP_EXTENSION_SAFE) {
  7828. outs() << " APP_EXTENSION_SAFE";
  7829. f &= ~MachO::MH_APP_EXTENSION_SAFE;
  7830. }
  7831. if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
  7832. outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
  7833. f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
  7834. }
  7835. if (f != 0 || flags == 0)
  7836. outs() << format(" 0x%08" PRIx32, f);
  7837. } else {
  7838. outs() << format(" 0x%08" PRIx32, magic);
  7839. outs() << format(" %7d", cputype);
  7840. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7841. outs() << format(" 0x%02" PRIx32,
  7842. (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
  7843. outs() << format(" %10u", filetype);
  7844. outs() << format(" %5u", ncmds);
  7845. outs() << format(" %10u", sizeofcmds);
  7846. outs() << format(" 0x%08" PRIx32, flags);
  7847. }
  7848. outs() << "\n";
  7849. }
  7850. static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
  7851. StringRef SegName, uint64_t vmaddr,
  7852. uint64_t vmsize, uint64_t fileoff,
  7853. uint64_t filesize, uint32_t maxprot,
  7854. uint32_t initprot, uint32_t nsects,
  7855. uint32_t flags, uint32_t object_size,
  7856. bool verbose) {
  7857. uint64_t expected_cmdsize;
  7858. if (cmd == MachO::LC_SEGMENT) {
  7859. outs() << " cmd LC_SEGMENT\n";
  7860. expected_cmdsize = nsects;
  7861. expected_cmdsize *= sizeof(struct MachO::section);
  7862. expected_cmdsize += sizeof(struct MachO::segment_command);
  7863. } else {
  7864. outs() << " cmd LC_SEGMENT_64\n";
  7865. expected_cmdsize = nsects;
  7866. expected_cmdsize *= sizeof(struct MachO::section_64);
  7867. expected_cmdsize += sizeof(struct MachO::segment_command_64);
  7868. }
  7869. outs() << " cmdsize " << cmdsize;
  7870. if (cmdsize != expected_cmdsize)
  7871. outs() << " Inconsistent size\n";
  7872. else
  7873. outs() << "\n";
  7874. outs() << " segname " << SegName << "\n";
  7875. if (cmd == MachO::LC_SEGMENT_64) {
  7876. outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
  7877. outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
  7878. } else {
  7879. outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
  7880. outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
  7881. }
  7882. outs() << " fileoff " << fileoff;
  7883. if (fileoff > object_size)
  7884. outs() << " (past end of file)\n";
  7885. else
  7886. outs() << "\n";
  7887. outs() << " filesize " << filesize;
  7888. if (fileoff + filesize > object_size)
  7889. outs() << " (past end of file)\n";
  7890. else
  7891. outs() << "\n";
  7892. if (verbose) {
  7893. if ((maxprot &
  7894. ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
  7895. MachO::VM_PROT_EXECUTE)) != 0)
  7896. outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
  7897. else {
  7898. outs() << " maxprot ";
  7899. outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
  7900. outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
  7901. outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
  7902. }
  7903. if ((initprot &
  7904. ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
  7905. MachO::VM_PROT_EXECUTE)) != 0)
  7906. outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
  7907. else {
  7908. outs() << " initprot ";
  7909. outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
  7910. outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
  7911. outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
  7912. }
  7913. } else {
  7914. outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
  7915. outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
  7916. }
  7917. outs() << " nsects " << nsects << "\n";
  7918. if (verbose) {
  7919. outs() << " flags";
  7920. if (flags == 0)
  7921. outs() << " (none)\n";
  7922. else {
  7923. if (flags & MachO::SG_HIGHVM) {
  7924. outs() << " HIGHVM";
  7925. flags &= ~MachO::SG_HIGHVM;
  7926. }
  7927. if (flags & MachO::SG_FVMLIB) {
  7928. outs() << " FVMLIB";
  7929. flags &= ~MachO::SG_FVMLIB;
  7930. }
  7931. if (flags & MachO::SG_NORELOC) {
  7932. outs() << " NORELOC";
  7933. flags &= ~MachO::SG_NORELOC;
  7934. }
  7935. if (flags & MachO::SG_PROTECTED_VERSION_1) {
  7936. outs() << " PROTECTED_VERSION_1";
  7937. flags &= ~MachO::SG_PROTECTED_VERSION_1;
  7938. }
  7939. if (flags)
  7940. outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
  7941. else
  7942. outs() << "\n";
  7943. }
  7944. } else {
  7945. outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
  7946. }
  7947. }
  7948. static void PrintSection(const char *sectname, const char *segname,
  7949. uint64_t addr, uint64_t size, uint32_t offset,
  7950. uint32_t align, uint32_t reloff, uint32_t nreloc,
  7951. uint32_t flags, uint32_t reserved1, uint32_t reserved2,
  7952. uint32_t cmd, const char *sg_segname,
  7953. uint32_t filetype, uint32_t object_size,
  7954. bool verbose) {
  7955. outs() << "Section\n";
  7956. outs() << " sectname " << format("%.16s\n", sectname);
  7957. outs() << " segname " << format("%.16s", segname);
  7958. if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
  7959. outs() << " (does not match segment)\n";
  7960. else
  7961. outs() << "\n";
  7962. if (cmd == MachO::LC_SEGMENT_64) {
  7963. outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
  7964. outs() << " size " << format("0x%016" PRIx64, size);
  7965. } else {
  7966. outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
  7967. outs() << " size " << format("0x%08" PRIx64, size);
  7968. }
  7969. if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
  7970. outs() << " (past end of file)\n";
  7971. else
  7972. outs() << "\n";
  7973. outs() << " offset " << offset;
  7974. if (offset > object_size)
  7975. outs() << " (past end of file)\n";
  7976. else
  7977. outs() << "\n";
  7978. uint32_t align_shifted = 1 << align;
  7979. outs() << " align 2^" << align << " (" << align_shifted << ")\n";
  7980. outs() << " reloff " << reloff;
  7981. if (reloff > object_size)
  7982. outs() << " (past end of file)\n";
  7983. else
  7984. outs() << "\n";
  7985. outs() << " nreloc " << nreloc;
  7986. if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
  7987. outs() << " (past end of file)\n";
  7988. else
  7989. outs() << "\n";
  7990. uint32_t section_type = flags & MachO::SECTION_TYPE;
  7991. if (verbose) {
  7992. outs() << " type";
  7993. if (section_type == MachO::S_REGULAR)
  7994. outs() << " S_REGULAR\n";
  7995. else if (section_type == MachO::S_ZEROFILL)
  7996. outs() << " S_ZEROFILL\n";
  7997. else if (section_type == MachO::S_CSTRING_LITERALS)
  7998. outs() << " S_CSTRING_LITERALS\n";
  7999. else if (section_type == MachO::S_4BYTE_LITERALS)
  8000. outs() << " S_4BYTE_LITERALS\n";
  8001. else if (section_type == MachO::S_8BYTE_LITERALS)
  8002. outs() << " S_8BYTE_LITERALS\n";
  8003. else if (section_type == MachO::S_16BYTE_LITERALS)
  8004. outs() << " S_16BYTE_LITERALS\n";
  8005. else if (section_type == MachO::S_LITERAL_POINTERS)
  8006. outs() << " S_LITERAL_POINTERS\n";
  8007. else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
  8008. outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
  8009. else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
  8010. outs() << " S_LAZY_SYMBOL_POINTERS\n";
  8011. else if (section_type == MachO::S_SYMBOL_STUBS)
  8012. outs() << " S_SYMBOL_STUBS\n";
  8013. else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
  8014. outs() << " S_MOD_INIT_FUNC_POINTERS\n";
  8015. else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
  8016. outs() << " S_MOD_TERM_FUNC_POINTERS\n";
  8017. else if (section_type == MachO::S_COALESCED)
  8018. outs() << " S_COALESCED\n";
  8019. else if (section_type == MachO::S_INTERPOSING)
  8020. outs() << " S_INTERPOSING\n";
  8021. else if (section_type == MachO::S_DTRACE_DOF)
  8022. outs() << " S_DTRACE_DOF\n";
  8023. else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
  8024. outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
  8025. else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
  8026. outs() << " S_THREAD_LOCAL_REGULAR\n";
  8027. else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
  8028. outs() << " S_THREAD_LOCAL_ZEROFILL\n";
  8029. else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
  8030. outs() << " S_THREAD_LOCAL_VARIABLES\n";
  8031. else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
  8032. outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
  8033. else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
  8034. outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
  8035. else
  8036. outs() << format("0x%08" PRIx32, section_type) << "\n";
  8037. outs() << "attributes";
  8038. uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
  8039. if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
  8040. outs() << " PURE_INSTRUCTIONS";
  8041. if (section_attributes & MachO::S_ATTR_NO_TOC)
  8042. outs() << " NO_TOC";
  8043. if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
  8044. outs() << " STRIP_STATIC_SYMS";
  8045. if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
  8046. outs() << " NO_DEAD_STRIP";
  8047. if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
  8048. outs() << " LIVE_SUPPORT";
  8049. if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
  8050. outs() << " SELF_MODIFYING_CODE";
  8051. if (section_attributes & MachO::S_ATTR_DEBUG)
  8052. outs() << " DEBUG";
  8053. if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
  8054. outs() << " SOME_INSTRUCTIONS";
  8055. if (section_attributes & MachO::S_ATTR_EXT_RELOC)
  8056. outs() << " EXT_RELOC";
  8057. if (section_attributes & MachO::S_ATTR_LOC_RELOC)
  8058. outs() << " LOC_RELOC";
  8059. if (section_attributes == 0)
  8060. outs() << " (none)";
  8061. outs() << "\n";
  8062. } else
  8063. outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
  8064. outs() << " reserved1 " << reserved1;
  8065. if (section_type == MachO::S_SYMBOL_STUBS ||
  8066. section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
  8067. section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
  8068. section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
  8069. section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
  8070. outs() << " (index into indirect symbol table)\n";
  8071. else
  8072. outs() << "\n";
  8073. outs() << " reserved2 " << reserved2;
  8074. if (section_type == MachO::S_SYMBOL_STUBS)
  8075. outs() << " (size of stubs)\n";
  8076. else
  8077. outs() << "\n";
  8078. }
  8079. static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
  8080. uint32_t object_size) {
  8081. outs() << " cmd LC_SYMTAB\n";
  8082. outs() << " cmdsize " << st.cmdsize;
  8083. if (st.cmdsize != sizeof(struct MachO::symtab_command))
  8084. outs() << " Incorrect size\n";
  8085. else
  8086. outs() << "\n";
  8087. outs() << " symoff " << st.symoff;
  8088. if (st.symoff > object_size)
  8089. outs() << " (past end of file)\n";
  8090. else
  8091. outs() << "\n";
  8092. outs() << " nsyms " << st.nsyms;
  8093. uint64_t big_size;
  8094. if (Is64Bit) {
  8095. big_size = st.nsyms;
  8096. big_size *= sizeof(struct MachO::nlist_64);
  8097. big_size += st.symoff;
  8098. if (big_size > object_size)
  8099. outs() << " (past end of file)\n";
  8100. else
  8101. outs() << "\n";
  8102. } else {
  8103. big_size = st.nsyms;
  8104. big_size *= sizeof(struct MachO::nlist);
  8105. big_size += st.symoff;
  8106. if (big_size > object_size)
  8107. outs() << " (past end of file)\n";
  8108. else
  8109. outs() << "\n";
  8110. }
  8111. outs() << " stroff " << st.stroff;
  8112. if (st.stroff > object_size)
  8113. outs() << " (past end of file)\n";
  8114. else
  8115. outs() << "\n";
  8116. outs() << " strsize " << st.strsize;
  8117. big_size = st.stroff;
  8118. big_size += st.strsize;
  8119. if (big_size > object_size)
  8120. outs() << " (past end of file)\n";
  8121. else
  8122. outs() << "\n";
  8123. }
  8124. static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
  8125. uint32_t nsyms, uint32_t object_size,
  8126. bool Is64Bit) {
  8127. outs() << " cmd LC_DYSYMTAB\n";
  8128. outs() << " cmdsize " << dyst.cmdsize;
  8129. if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
  8130. outs() << " Incorrect size\n";
  8131. else
  8132. outs() << "\n";
  8133. outs() << " ilocalsym " << dyst.ilocalsym;
  8134. if (dyst.ilocalsym > nsyms)
  8135. outs() << " (greater than the number of symbols)\n";
  8136. else
  8137. outs() << "\n";
  8138. outs() << " nlocalsym " << dyst.nlocalsym;
  8139. uint64_t big_size;
  8140. big_size = dyst.ilocalsym;
  8141. big_size += dyst.nlocalsym;
  8142. if (big_size > nsyms)
  8143. outs() << " (past the end of the symbol table)\n";
  8144. else
  8145. outs() << "\n";
  8146. outs() << " iextdefsym " << dyst.iextdefsym;
  8147. if (dyst.iextdefsym > nsyms)
  8148. outs() << " (greater than the number of symbols)\n";
  8149. else
  8150. outs() << "\n";
  8151. outs() << " nextdefsym " << dyst.nextdefsym;
  8152. big_size = dyst.iextdefsym;
  8153. big_size += dyst.nextdefsym;
  8154. if (big_size > nsyms)
  8155. outs() << " (past the end of the symbol table)\n";
  8156. else
  8157. outs() << "\n";
  8158. outs() << " iundefsym " << dyst.iundefsym;
  8159. if (dyst.iundefsym > nsyms)
  8160. outs() << " (greater than the number of symbols)\n";
  8161. else
  8162. outs() << "\n";
  8163. outs() << " nundefsym " << dyst.nundefsym;
  8164. big_size = dyst.iundefsym;
  8165. big_size += dyst.nundefsym;
  8166. if (big_size > nsyms)
  8167. outs() << " (past the end of the symbol table)\n";
  8168. else
  8169. outs() << "\n";
  8170. outs() << " tocoff " << dyst.tocoff;
  8171. if (dyst.tocoff > object_size)
  8172. outs() << " (past end of file)\n";
  8173. else
  8174. outs() << "\n";
  8175. outs() << " ntoc " << dyst.ntoc;
  8176. big_size = dyst.ntoc;
  8177. big_size *= sizeof(struct MachO::dylib_table_of_contents);
  8178. big_size += dyst.tocoff;
  8179. if (big_size > object_size)
  8180. outs() << " (past end of file)\n";
  8181. else
  8182. outs() << "\n";
  8183. outs() << " modtaboff " << dyst.modtaboff;
  8184. if (dyst.modtaboff > object_size)
  8185. outs() << " (past end of file)\n";
  8186. else
  8187. outs() << "\n";
  8188. outs() << " nmodtab " << dyst.nmodtab;
  8189. uint64_t modtabend;
  8190. if (Is64Bit) {
  8191. modtabend = dyst.nmodtab;
  8192. modtabend *= sizeof(struct MachO::dylib_module_64);
  8193. modtabend += dyst.modtaboff;
  8194. } else {
  8195. modtabend = dyst.nmodtab;
  8196. modtabend *= sizeof(struct MachO::dylib_module);
  8197. modtabend += dyst.modtaboff;
  8198. }
  8199. if (modtabend > object_size)
  8200. outs() << " (past end of file)\n";
  8201. else
  8202. outs() << "\n";
  8203. outs() << " extrefsymoff " << dyst.extrefsymoff;
  8204. if (dyst.extrefsymoff > object_size)
  8205. outs() << " (past end of file)\n";
  8206. else
  8207. outs() << "\n";
  8208. outs() << " nextrefsyms " << dyst.nextrefsyms;
  8209. big_size = dyst.nextrefsyms;
  8210. big_size *= sizeof(struct MachO::dylib_reference);
  8211. big_size += dyst.extrefsymoff;
  8212. if (big_size > object_size)
  8213. outs() << " (past end of file)\n";
  8214. else
  8215. outs() << "\n";
  8216. outs() << " indirectsymoff " << dyst.indirectsymoff;
  8217. if (dyst.indirectsymoff > object_size)
  8218. outs() << " (past end of file)\n";
  8219. else
  8220. outs() << "\n";
  8221. outs() << " nindirectsyms " << dyst.nindirectsyms;
  8222. big_size = dyst.nindirectsyms;
  8223. big_size *= sizeof(uint32_t);
  8224. big_size += dyst.indirectsymoff;
  8225. if (big_size > object_size)
  8226. outs() << " (past end of file)\n";
  8227. else
  8228. outs() << "\n";
  8229. outs() << " extreloff " << dyst.extreloff;
  8230. if (dyst.extreloff > object_size)
  8231. outs() << " (past end of file)\n";
  8232. else
  8233. outs() << "\n";
  8234. outs() << " nextrel " << dyst.nextrel;
  8235. big_size = dyst.nextrel;
  8236. big_size *= sizeof(struct MachO::relocation_info);
  8237. big_size += dyst.extreloff;
  8238. if (big_size > object_size)
  8239. outs() << " (past end of file)\n";
  8240. else
  8241. outs() << "\n";
  8242. outs() << " locreloff " << dyst.locreloff;
  8243. if (dyst.locreloff > object_size)
  8244. outs() << " (past end of file)\n";
  8245. else
  8246. outs() << "\n";
  8247. outs() << " nlocrel " << dyst.nlocrel;
  8248. big_size = dyst.nlocrel;
  8249. big_size *= sizeof(struct MachO::relocation_info);
  8250. big_size += dyst.locreloff;
  8251. if (big_size > object_size)
  8252. outs() << " (past end of file)\n";
  8253. else
  8254. outs() << "\n";
  8255. }
  8256. static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
  8257. uint32_t object_size) {
  8258. if (dc.cmd == MachO::LC_DYLD_INFO)
  8259. outs() << " cmd LC_DYLD_INFO\n";
  8260. else
  8261. outs() << " cmd LC_DYLD_INFO_ONLY\n";
  8262. outs() << " cmdsize " << dc.cmdsize;
  8263. if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
  8264. outs() << " Incorrect size\n";
  8265. else
  8266. outs() << "\n";
  8267. outs() << " rebase_off " << dc.rebase_off;
  8268. if (dc.rebase_off > object_size)
  8269. outs() << " (past end of file)\n";
  8270. else
  8271. outs() << "\n";
  8272. outs() << " rebase_size " << dc.rebase_size;
  8273. uint64_t big_size;
  8274. big_size = dc.rebase_off;
  8275. big_size += dc.rebase_size;
  8276. if (big_size > object_size)
  8277. outs() << " (past end of file)\n";
  8278. else
  8279. outs() << "\n";
  8280. outs() << " bind_off " << dc.bind_off;
  8281. if (dc.bind_off > object_size)
  8282. outs() << " (past end of file)\n";
  8283. else
  8284. outs() << "\n";
  8285. outs() << " bind_size " << dc.bind_size;
  8286. big_size = dc.bind_off;
  8287. big_size += dc.bind_size;
  8288. if (big_size > object_size)
  8289. outs() << " (past end of file)\n";
  8290. else
  8291. outs() << "\n";
  8292. outs() << " weak_bind_off " << dc.weak_bind_off;
  8293. if (dc.weak_bind_off > object_size)
  8294. outs() << " (past end of file)\n";
  8295. else
  8296. outs() << "\n";
  8297. outs() << " weak_bind_size " << dc.weak_bind_size;
  8298. big_size = dc.weak_bind_off;
  8299. big_size += dc.weak_bind_size;
  8300. if (big_size > object_size)
  8301. outs() << " (past end of file)\n";
  8302. else
  8303. outs() << "\n";
  8304. outs() << " lazy_bind_off " << dc.lazy_bind_off;
  8305. if (dc.lazy_bind_off > object_size)
  8306. outs() << " (past end of file)\n";
  8307. else
  8308. outs() << "\n";
  8309. outs() << " lazy_bind_size " << dc.lazy_bind_size;
  8310. big_size = dc.lazy_bind_off;
  8311. big_size += dc.lazy_bind_size;
  8312. if (big_size > object_size)
  8313. outs() << " (past end of file)\n";
  8314. else
  8315. outs() << "\n";
  8316. outs() << " export_off " << dc.export_off;
  8317. if (dc.export_off > object_size)
  8318. outs() << " (past end of file)\n";
  8319. else
  8320. outs() << "\n";
  8321. outs() << " export_size " << dc.export_size;
  8322. big_size = dc.export_off;
  8323. big_size += dc.export_size;
  8324. if (big_size > object_size)
  8325. outs() << " (past end of file)\n";
  8326. else
  8327. outs() << "\n";
  8328. }
  8329. static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
  8330. const char *Ptr) {
  8331. if (dyld.cmd == MachO::LC_ID_DYLINKER)
  8332. outs() << " cmd LC_ID_DYLINKER\n";
  8333. else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
  8334. outs() << " cmd LC_LOAD_DYLINKER\n";
  8335. else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
  8336. outs() << " cmd LC_DYLD_ENVIRONMENT\n";
  8337. else
  8338. outs() << " cmd ?(" << dyld.cmd << ")\n";
  8339. outs() << " cmdsize " << dyld.cmdsize;
  8340. if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
  8341. outs() << " Incorrect size\n";
  8342. else
  8343. outs() << "\n";
  8344. if (dyld.name >= dyld.cmdsize)
  8345. outs() << " name ?(bad offset " << dyld.name << ")\n";
  8346. else {
  8347. const char *P = (const char *)(Ptr) + dyld.name;
  8348. outs() << " name " << P << " (offset " << dyld.name << ")\n";
  8349. }
  8350. }
  8351. static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
  8352. outs() << " cmd LC_UUID\n";
  8353. outs() << " cmdsize " << uuid.cmdsize;
  8354. if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
  8355. outs() << " Incorrect size\n";
  8356. else
  8357. outs() << "\n";
  8358. outs() << " uuid ";
  8359. for (int i = 0; i < 16; ++i) {
  8360. outs() << format("%02" PRIX32, uuid.uuid[i]);
  8361. if (i == 3 || i == 5 || i == 7 || i == 9)
  8362. outs() << "-";
  8363. }
  8364. outs() << "\n";
  8365. }
  8366. static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
  8367. outs() << " cmd LC_RPATH\n";
  8368. outs() << " cmdsize " << rpath.cmdsize;
  8369. if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
  8370. outs() << " Incorrect size\n";
  8371. else
  8372. outs() << "\n";
  8373. if (rpath.path >= rpath.cmdsize)
  8374. outs() << " path ?(bad offset " << rpath.path << ")\n";
  8375. else {
  8376. const char *P = (const char *)(Ptr) + rpath.path;
  8377. outs() << " path " << P << " (offset " << rpath.path << ")\n";
  8378. }
  8379. }
  8380. static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
  8381. StringRef LoadCmdName;
  8382. switch (vd.cmd) {
  8383. case MachO::LC_VERSION_MIN_MACOSX:
  8384. LoadCmdName = "LC_VERSION_MIN_MACOSX";
  8385. break;
  8386. case MachO::LC_VERSION_MIN_IPHONEOS:
  8387. LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
  8388. break;
  8389. case MachO::LC_VERSION_MIN_TVOS:
  8390. LoadCmdName = "LC_VERSION_MIN_TVOS";
  8391. break;
  8392. case MachO::LC_VERSION_MIN_WATCHOS:
  8393. LoadCmdName = "LC_VERSION_MIN_WATCHOS";
  8394. break;
  8395. default:
  8396. llvm_unreachable("Unknown version min load command");
  8397. }
  8398. outs() << " cmd " << LoadCmdName << '\n';
  8399. outs() << " cmdsize " << vd.cmdsize;
  8400. if (vd.cmdsize != sizeof(struct MachO::version_min_command))
  8401. outs() << " Incorrect size\n";
  8402. else
  8403. outs() << "\n";
  8404. outs() << " version "
  8405. << MachOObjectFile::getVersionMinMajor(vd, false) << "."
  8406. << MachOObjectFile::getVersionMinMinor(vd, false);
  8407. uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
  8408. if (Update != 0)
  8409. outs() << "." << Update;
  8410. outs() << "\n";
  8411. if (vd.sdk == 0)
  8412. outs() << " sdk n/a";
  8413. else {
  8414. outs() << " sdk "
  8415. << MachOObjectFile::getVersionMinMajor(vd, true) << "."
  8416. << MachOObjectFile::getVersionMinMinor(vd, true);
  8417. }
  8418. Update = MachOObjectFile::getVersionMinUpdate(vd, true);
  8419. if (Update != 0)
  8420. outs() << "." << Update;
  8421. outs() << "\n";
  8422. }
  8423. static void PrintNoteLoadCommand(MachO::note_command Nt) {
  8424. outs() << " cmd LC_NOTE\n";
  8425. outs() << " cmdsize " << Nt.cmdsize;
  8426. if (Nt.cmdsize != sizeof(struct MachO::note_command))
  8427. outs() << " Incorrect size\n";
  8428. else
  8429. outs() << "\n";
  8430. const char *d = Nt.data_owner;
  8431. outs() << "data_owner " << format("%.16s\n", d);
  8432. outs() << " offset " << Nt.offset << "\n";
  8433. outs() << " size " << Nt.size << "\n";
  8434. }
  8435. static void PrintBuildToolVersion(MachO::build_tool_version bv) {
  8436. outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
  8437. outs() << " version " << MachOObjectFile::getVersionString(bv.version)
  8438. << "\n";
  8439. }
  8440. static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
  8441. MachO::build_version_command bd) {
  8442. outs() << " cmd LC_BUILD_VERSION\n";
  8443. outs() << " cmdsize " << bd.cmdsize;
  8444. if (bd.cmdsize !=
  8445. sizeof(struct MachO::build_version_command) +
  8446. bd.ntools * sizeof(struct MachO::build_tool_version))
  8447. outs() << " Incorrect size\n";
  8448. else
  8449. outs() << "\n";
  8450. outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
  8451. << "\n";
  8452. if (bd.sdk)
  8453. outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
  8454. << "\n";
  8455. else
  8456. outs() << " sdk n/a\n";
  8457. outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
  8458. << "\n";
  8459. outs() << " ntools " << bd.ntools << "\n";
  8460. for (unsigned i = 0; i < bd.ntools; ++i) {
  8461. MachO::build_tool_version bv = obj->getBuildToolVersion(i);
  8462. PrintBuildToolVersion(bv);
  8463. }
  8464. }
  8465. static void PrintSourceVersionCommand(MachO::source_version_command sd) {
  8466. outs() << " cmd LC_SOURCE_VERSION\n";
  8467. outs() << " cmdsize " << sd.cmdsize;
  8468. if (sd.cmdsize != sizeof(struct MachO::source_version_command))
  8469. outs() << " Incorrect size\n";
  8470. else
  8471. outs() << "\n";
  8472. uint64_t a = (sd.version >> 40) & 0xffffff;
  8473. uint64_t b = (sd.version >> 30) & 0x3ff;
  8474. uint64_t c = (sd.version >> 20) & 0x3ff;
  8475. uint64_t d = (sd.version >> 10) & 0x3ff;
  8476. uint64_t e = sd.version & 0x3ff;
  8477. outs() << " version " << a << "." << b;
  8478. if (e != 0)
  8479. outs() << "." << c << "." << d << "." << e;
  8480. else if (d != 0)
  8481. outs() << "." << c << "." << d;
  8482. else if (c != 0)
  8483. outs() << "." << c;
  8484. outs() << "\n";
  8485. }
  8486. static void PrintEntryPointCommand(MachO::entry_point_command ep) {
  8487. outs() << " cmd LC_MAIN\n";
  8488. outs() << " cmdsize " << ep.cmdsize;
  8489. if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
  8490. outs() << " Incorrect size\n";
  8491. else
  8492. outs() << "\n";
  8493. outs() << " entryoff " << ep.entryoff << "\n";
  8494. outs() << " stacksize " << ep.stacksize << "\n";
  8495. }
  8496. static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
  8497. uint32_t object_size) {
  8498. outs() << " cmd LC_ENCRYPTION_INFO\n";
  8499. outs() << " cmdsize " << ec.cmdsize;
  8500. if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
  8501. outs() << " Incorrect size\n";
  8502. else
  8503. outs() << "\n";
  8504. outs() << " cryptoff " << ec.cryptoff;
  8505. if (ec.cryptoff > object_size)
  8506. outs() << " (past end of file)\n";
  8507. else
  8508. outs() << "\n";
  8509. outs() << " cryptsize " << ec.cryptsize;
  8510. if (ec.cryptsize > object_size)
  8511. outs() << " (past end of file)\n";
  8512. else
  8513. outs() << "\n";
  8514. outs() << " cryptid " << ec.cryptid << "\n";
  8515. }
  8516. static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
  8517. uint32_t object_size) {
  8518. outs() << " cmd LC_ENCRYPTION_INFO_64\n";
  8519. outs() << " cmdsize " << ec.cmdsize;
  8520. if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
  8521. outs() << " Incorrect size\n";
  8522. else
  8523. outs() << "\n";
  8524. outs() << " cryptoff " << ec.cryptoff;
  8525. if (ec.cryptoff > object_size)
  8526. outs() << " (past end of file)\n";
  8527. else
  8528. outs() << "\n";
  8529. outs() << " cryptsize " << ec.cryptsize;
  8530. if (ec.cryptsize > object_size)
  8531. outs() << " (past end of file)\n";
  8532. else
  8533. outs() << "\n";
  8534. outs() << " cryptid " << ec.cryptid << "\n";
  8535. outs() << " pad " << ec.pad << "\n";
  8536. }
  8537. static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
  8538. const char *Ptr) {
  8539. outs() << " cmd LC_LINKER_OPTION\n";
  8540. outs() << " cmdsize " << lo.cmdsize;
  8541. if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
  8542. outs() << " Incorrect size\n";
  8543. else
  8544. outs() << "\n";
  8545. outs() << " count " << lo.count << "\n";
  8546. const char *string = Ptr + sizeof(struct MachO::linker_option_command);
  8547. uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
  8548. uint32_t i = 0;
  8549. while (left > 0) {
  8550. while (*string == '\0' && left > 0) {
  8551. string++;
  8552. left--;
  8553. }
  8554. if (left > 0) {
  8555. i++;
  8556. outs() << " string #" << i << " " << format("%.*s\n", left, string);
  8557. uint32_t NullPos = StringRef(string, left).find('\0');
  8558. uint32_t len = std::min(NullPos, left) + 1;
  8559. string += len;
  8560. left -= len;
  8561. }
  8562. }
  8563. if (lo.count != i)
  8564. outs() << " count " << lo.count << " does not match number of strings "
  8565. << i << "\n";
  8566. }
  8567. static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
  8568. const char *Ptr) {
  8569. outs() << " cmd LC_SUB_FRAMEWORK\n";
  8570. outs() << " cmdsize " << sub.cmdsize;
  8571. if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
  8572. outs() << " Incorrect size\n";
  8573. else
  8574. outs() << "\n";
  8575. if (sub.umbrella < sub.cmdsize) {
  8576. const char *P = Ptr + sub.umbrella;
  8577. outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
  8578. } else {
  8579. outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
  8580. }
  8581. }
  8582. static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
  8583. const char *Ptr) {
  8584. outs() << " cmd LC_SUB_UMBRELLA\n";
  8585. outs() << " cmdsize " << sub.cmdsize;
  8586. if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
  8587. outs() << " Incorrect size\n";
  8588. else
  8589. outs() << "\n";
  8590. if (sub.sub_umbrella < sub.cmdsize) {
  8591. const char *P = Ptr + sub.sub_umbrella;
  8592. outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
  8593. } else {
  8594. outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
  8595. }
  8596. }
  8597. static void PrintSubLibraryCommand(MachO::sub_library_command sub,
  8598. const char *Ptr) {
  8599. outs() << " cmd LC_SUB_LIBRARY\n";
  8600. outs() << " cmdsize " << sub.cmdsize;
  8601. if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
  8602. outs() << " Incorrect size\n";
  8603. else
  8604. outs() << "\n";
  8605. if (sub.sub_library < sub.cmdsize) {
  8606. const char *P = Ptr + sub.sub_library;
  8607. outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
  8608. } else {
  8609. outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
  8610. }
  8611. }
  8612. static void PrintSubClientCommand(MachO::sub_client_command sub,
  8613. const char *Ptr) {
  8614. outs() << " cmd LC_SUB_CLIENT\n";
  8615. outs() << " cmdsize " << sub.cmdsize;
  8616. if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
  8617. outs() << " Incorrect size\n";
  8618. else
  8619. outs() << "\n";
  8620. if (sub.client < sub.cmdsize) {
  8621. const char *P = Ptr + sub.client;
  8622. outs() << " client " << P << " (offset " << sub.client << ")\n";
  8623. } else {
  8624. outs() << " client ?(bad offset " << sub.client << ")\n";
  8625. }
  8626. }
  8627. static void PrintRoutinesCommand(MachO::routines_command r) {
  8628. outs() << " cmd LC_ROUTINES\n";
  8629. outs() << " cmdsize " << r.cmdsize;
  8630. if (r.cmdsize != sizeof(struct MachO::routines_command))
  8631. outs() << " Incorrect size\n";
  8632. else
  8633. outs() << "\n";
  8634. outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
  8635. outs() << " init_module " << r.init_module << "\n";
  8636. outs() << " reserved1 " << r.reserved1 << "\n";
  8637. outs() << " reserved2 " << r.reserved2 << "\n";
  8638. outs() << " reserved3 " << r.reserved3 << "\n";
  8639. outs() << " reserved4 " << r.reserved4 << "\n";
  8640. outs() << " reserved5 " << r.reserved5 << "\n";
  8641. outs() << " reserved6 " << r.reserved6 << "\n";
  8642. }
  8643. static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
  8644. outs() << " cmd LC_ROUTINES_64\n";
  8645. outs() << " cmdsize " << r.cmdsize;
  8646. if (r.cmdsize != sizeof(struct MachO::routines_command_64))
  8647. outs() << " Incorrect size\n";
  8648. else
  8649. outs() << "\n";
  8650. outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
  8651. outs() << " init_module " << r.init_module << "\n";
  8652. outs() << " reserved1 " << r.reserved1 << "\n";
  8653. outs() << " reserved2 " << r.reserved2 << "\n";
  8654. outs() << " reserved3 " << r.reserved3 << "\n";
  8655. outs() << " reserved4 " << r.reserved4 << "\n";
  8656. outs() << " reserved5 " << r.reserved5 << "\n";
  8657. outs() << " reserved6 " << r.reserved6 << "\n";
  8658. }
  8659. static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
  8660. outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
  8661. outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
  8662. outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
  8663. outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
  8664. outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
  8665. outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
  8666. outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
  8667. outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
  8668. outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
  8669. outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
  8670. outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
  8671. outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
  8672. outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
  8673. outs() << " es " << format("0x%08" PRIx32, cpu32.es);
  8674. outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
  8675. outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
  8676. }
  8677. static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
  8678. outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
  8679. outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
  8680. outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
  8681. outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
  8682. outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
  8683. outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
  8684. outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
  8685. outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
  8686. outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
  8687. outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
  8688. outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
  8689. outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
  8690. outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
  8691. outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
  8692. outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
  8693. outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
  8694. outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
  8695. outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
  8696. outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
  8697. outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
  8698. outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
  8699. }
  8700. static void Print_mmst_reg(MachO::mmst_reg_t &r) {
  8701. uint32_t f;
  8702. outs() << "\t mmst_reg ";
  8703. for (f = 0; f < 10; f++)
  8704. outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
  8705. outs() << "\n";
  8706. outs() << "\t mmst_rsrv ";
  8707. for (f = 0; f < 6; f++)
  8708. outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
  8709. outs() << "\n";
  8710. }
  8711. static void Print_xmm_reg(MachO::xmm_reg_t &r) {
  8712. uint32_t f;
  8713. outs() << "\t xmm_reg ";
  8714. for (f = 0; f < 16; f++)
  8715. outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
  8716. outs() << "\n";
  8717. }
  8718. static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
  8719. outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
  8720. outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
  8721. outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
  8722. outs() << " denorm " << fpu.fpu_fcw.denorm;
  8723. outs() << " zdiv " << fpu.fpu_fcw.zdiv;
  8724. outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
  8725. outs() << " undfl " << fpu.fpu_fcw.undfl;
  8726. outs() << " precis " << fpu.fpu_fcw.precis << "\n";
  8727. outs() << "\t\t pc ";
  8728. if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
  8729. outs() << "FP_PREC_24B ";
  8730. else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
  8731. outs() << "FP_PREC_53B ";
  8732. else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
  8733. outs() << "FP_PREC_64B ";
  8734. else
  8735. outs() << fpu.fpu_fcw.pc << " ";
  8736. outs() << "rc ";
  8737. if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
  8738. outs() << "FP_RND_NEAR ";
  8739. else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
  8740. outs() << "FP_RND_DOWN ";
  8741. else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
  8742. outs() << "FP_RND_UP ";
  8743. else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
  8744. outs() << "FP_CHOP ";
  8745. outs() << "\n";
  8746. outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
  8747. outs() << " denorm " << fpu.fpu_fsw.denorm;
  8748. outs() << " zdiv " << fpu.fpu_fsw.zdiv;
  8749. outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
  8750. outs() << " undfl " << fpu.fpu_fsw.undfl;
  8751. outs() << " precis " << fpu.fpu_fsw.precis;
  8752. outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
  8753. outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
  8754. outs() << " c0 " << fpu.fpu_fsw.c0;
  8755. outs() << " c1 " << fpu.fpu_fsw.c1;
  8756. outs() << " c2 " << fpu.fpu_fsw.c2;
  8757. outs() << " tos " << fpu.fpu_fsw.tos;
  8758. outs() << " c3 " << fpu.fpu_fsw.c3;
  8759. outs() << " busy " << fpu.fpu_fsw.busy << "\n";
  8760. outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
  8761. outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
  8762. outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
  8763. outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
  8764. outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
  8765. outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
  8766. outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
  8767. outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
  8768. outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
  8769. outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
  8770. outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
  8771. outs() << "\n";
  8772. outs() << "\t fpu_stmm0:\n";
  8773. Print_mmst_reg(fpu.fpu_stmm0);
  8774. outs() << "\t fpu_stmm1:\n";
  8775. Print_mmst_reg(fpu.fpu_stmm1);
  8776. outs() << "\t fpu_stmm2:\n";
  8777. Print_mmst_reg(fpu.fpu_stmm2);
  8778. outs() << "\t fpu_stmm3:\n";
  8779. Print_mmst_reg(fpu.fpu_stmm3);
  8780. outs() << "\t fpu_stmm4:\n";
  8781. Print_mmst_reg(fpu.fpu_stmm4);
  8782. outs() << "\t fpu_stmm5:\n";
  8783. Print_mmst_reg(fpu.fpu_stmm5);
  8784. outs() << "\t fpu_stmm6:\n";
  8785. Print_mmst_reg(fpu.fpu_stmm6);
  8786. outs() << "\t fpu_stmm7:\n";
  8787. Print_mmst_reg(fpu.fpu_stmm7);
  8788. outs() << "\t fpu_xmm0:\n";
  8789. Print_xmm_reg(fpu.fpu_xmm0);
  8790. outs() << "\t fpu_xmm1:\n";
  8791. Print_xmm_reg(fpu.fpu_xmm1);
  8792. outs() << "\t fpu_xmm2:\n";
  8793. Print_xmm_reg(fpu.fpu_xmm2);
  8794. outs() << "\t fpu_xmm3:\n";
  8795. Print_xmm_reg(fpu.fpu_xmm3);
  8796. outs() << "\t fpu_xmm4:\n";
  8797. Print_xmm_reg(fpu.fpu_xmm4);
  8798. outs() << "\t fpu_xmm5:\n";
  8799. Print_xmm_reg(fpu.fpu_xmm5);
  8800. outs() << "\t fpu_xmm6:\n";
  8801. Print_xmm_reg(fpu.fpu_xmm6);
  8802. outs() << "\t fpu_xmm7:\n";
  8803. Print_xmm_reg(fpu.fpu_xmm7);
  8804. outs() << "\t fpu_xmm8:\n";
  8805. Print_xmm_reg(fpu.fpu_xmm8);
  8806. outs() << "\t fpu_xmm9:\n";
  8807. Print_xmm_reg(fpu.fpu_xmm9);
  8808. outs() << "\t fpu_xmm10:\n";
  8809. Print_xmm_reg(fpu.fpu_xmm10);
  8810. outs() << "\t fpu_xmm11:\n";
  8811. Print_xmm_reg(fpu.fpu_xmm11);
  8812. outs() << "\t fpu_xmm12:\n";
  8813. Print_xmm_reg(fpu.fpu_xmm12);
  8814. outs() << "\t fpu_xmm13:\n";
  8815. Print_xmm_reg(fpu.fpu_xmm13);
  8816. outs() << "\t fpu_xmm14:\n";
  8817. Print_xmm_reg(fpu.fpu_xmm14);
  8818. outs() << "\t fpu_xmm15:\n";
  8819. Print_xmm_reg(fpu.fpu_xmm15);
  8820. outs() << "\t fpu_rsrv4:\n";
  8821. for (uint32_t f = 0; f < 6; f++) {
  8822. outs() << "\t ";
  8823. for (uint32_t g = 0; g < 16; g++)
  8824. outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
  8825. outs() << "\n";
  8826. }
  8827. outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
  8828. outs() << "\n";
  8829. }
  8830. static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
  8831. outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
  8832. outs() << " err " << format("0x%08" PRIx32, exc64.err);
  8833. outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
  8834. }
  8835. static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
  8836. outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
  8837. outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
  8838. outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
  8839. outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
  8840. outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
  8841. outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
  8842. outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
  8843. outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
  8844. outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
  8845. outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
  8846. outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
  8847. outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
  8848. outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
  8849. outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
  8850. outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
  8851. outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
  8852. outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
  8853. }
  8854. static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
  8855. outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
  8856. outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
  8857. outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
  8858. outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
  8859. outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
  8860. outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
  8861. outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
  8862. outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
  8863. outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
  8864. outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
  8865. outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
  8866. outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
  8867. outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
  8868. outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
  8869. outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
  8870. outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
  8871. outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
  8872. outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
  8873. outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
  8874. outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
  8875. outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
  8876. outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
  8877. outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
  8878. outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
  8879. outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
  8880. outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
  8881. outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
  8882. outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
  8883. outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
  8884. outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
  8885. outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
  8886. outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
  8887. outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
  8888. outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
  8889. }
  8890. static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
  8891. bool isLittleEndian, uint32_t cputype) {
  8892. if (t.cmd == MachO::LC_THREAD)
  8893. outs() << " cmd LC_THREAD\n";
  8894. else if (t.cmd == MachO::LC_UNIXTHREAD)
  8895. outs() << " cmd LC_UNIXTHREAD\n";
  8896. else
  8897. outs() << " cmd " << t.cmd << " (unknown)\n";
  8898. outs() << " cmdsize " << t.cmdsize;
  8899. if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
  8900. outs() << " Incorrect size\n";
  8901. else
  8902. outs() << "\n";
  8903. const char *begin = Ptr + sizeof(struct MachO::thread_command);
  8904. const char *end = Ptr + t.cmdsize;
  8905. uint32_t flavor, count, left;
  8906. if (cputype == MachO::CPU_TYPE_I386) {
  8907. while (begin < end) {
  8908. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  8909. memcpy((char *)&flavor, begin, sizeof(uint32_t));
  8910. begin += sizeof(uint32_t);
  8911. } else {
  8912. flavor = 0;
  8913. begin = end;
  8914. }
  8915. if (isLittleEndian != sys::IsLittleEndianHost)
  8916. sys::swapByteOrder(flavor);
  8917. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  8918. memcpy((char *)&count, begin, sizeof(uint32_t));
  8919. begin += sizeof(uint32_t);
  8920. } else {
  8921. count = 0;
  8922. begin = end;
  8923. }
  8924. if (isLittleEndian != sys::IsLittleEndianHost)
  8925. sys::swapByteOrder(count);
  8926. if (flavor == MachO::x86_THREAD_STATE32) {
  8927. outs() << " flavor i386_THREAD_STATE\n";
  8928. if (count == MachO::x86_THREAD_STATE32_COUNT)
  8929. outs() << " count i386_THREAD_STATE_COUNT\n";
  8930. else
  8931. outs() << " count " << count
  8932. << " (not x86_THREAD_STATE32_COUNT)\n";
  8933. MachO::x86_thread_state32_t cpu32;
  8934. left = end - begin;
  8935. if (left >= sizeof(MachO::x86_thread_state32_t)) {
  8936. memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
  8937. begin += sizeof(MachO::x86_thread_state32_t);
  8938. } else {
  8939. memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
  8940. memcpy(&cpu32, begin, left);
  8941. begin += left;
  8942. }
  8943. if (isLittleEndian != sys::IsLittleEndianHost)
  8944. swapStruct(cpu32);
  8945. Print_x86_thread_state32_t(cpu32);
  8946. } else if (flavor == MachO::x86_THREAD_STATE) {
  8947. outs() << " flavor x86_THREAD_STATE\n";
  8948. if (count == MachO::x86_THREAD_STATE_COUNT)
  8949. outs() << " count x86_THREAD_STATE_COUNT\n";
  8950. else
  8951. outs() << " count " << count
  8952. << " (not x86_THREAD_STATE_COUNT)\n";
  8953. struct MachO::x86_thread_state_t ts;
  8954. left = end - begin;
  8955. if (left >= sizeof(MachO::x86_thread_state_t)) {
  8956. memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
  8957. begin += sizeof(MachO::x86_thread_state_t);
  8958. } else {
  8959. memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
  8960. memcpy(&ts, begin, left);
  8961. begin += left;
  8962. }
  8963. if (isLittleEndian != sys::IsLittleEndianHost)
  8964. swapStruct(ts);
  8965. if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
  8966. outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
  8967. if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
  8968. outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
  8969. else
  8970. outs() << "tsh.count " << ts.tsh.count
  8971. << " (not x86_THREAD_STATE32_COUNT\n";
  8972. Print_x86_thread_state32_t(ts.uts.ts32);
  8973. } else {
  8974. outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
  8975. << ts.tsh.count << "\n";
  8976. }
  8977. } else {
  8978. outs() << " flavor " << flavor << " (unknown)\n";
  8979. outs() << " count " << count << "\n";
  8980. outs() << " state (unknown)\n";
  8981. begin += count * sizeof(uint32_t);
  8982. }
  8983. }
  8984. } else if (cputype == MachO::CPU_TYPE_X86_64) {
  8985. while (begin < end) {
  8986. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  8987. memcpy((char *)&flavor, begin, sizeof(uint32_t));
  8988. begin += sizeof(uint32_t);
  8989. } else {
  8990. flavor = 0;
  8991. begin = end;
  8992. }
  8993. if (isLittleEndian != sys::IsLittleEndianHost)
  8994. sys::swapByteOrder(flavor);
  8995. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  8996. memcpy((char *)&count, begin, sizeof(uint32_t));
  8997. begin += sizeof(uint32_t);
  8998. } else {
  8999. count = 0;
  9000. begin = end;
  9001. }
  9002. if (isLittleEndian != sys::IsLittleEndianHost)
  9003. sys::swapByteOrder(count);
  9004. if (flavor == MachO::x86_THREAD_STATE64) {
  9005. outs() << " flavor x86_THREAD_STATE64\n";
  9006. if (count == MachO::x86_THREAD_STATE64_COUNT)
  9007. outs() << " count x86_THREAD_STATE64_COUNT\n";
  9008. else
  9009. outs() << " count " << count
  9010. << " (not x86_THREAD_STATE64_COUNT)\n";
  9011. MachO::x86_thread_state64_t cpu64;
  9012. left = end - begin;
  9013. if (left >= sizeof(MachO::x86_thread_state64_t)) {
  9014. memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
  9015. begin += sizeof(MachO::x86_thread_state64_t);
  9016. } else {
  9017. memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
  9018. memcpy(&cpu64, begin, left);
  9019. begin += left;
  9020. }
  9021. if (isLittleEndian != sys::IsLittleEndianHost)
  9022. swapStruct(cpu64);
  9023. Print_x86_thread_state64_t(cpu64);
  9024. } else if (flavor == MachO::x86_THREAD_STATE) {
  9025. outs() << " flavor x86_THREAD_STATE\n";
  9026. if (count == MachO::x86_THREAD_STATE_COUNT)
  9027. outs() << " count x86_THREAD_STATE_COUNT\n";
  9028. else
  9029. outs() << " count " << count
  9030. << " (not x86_THREAD_STATE_COUNT)\n";
  9031. struct MachO::x86_thread_state_t ts;
  9032. left = end - begin;
  9033. if (left >= sizeof(MachO::x86_thread_state_t)) {
  9034. memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
  9035. begin += sizeof(MachO::x86_thread_state_t);
  9036. } else {
  9037. memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
  9038. memcpy(&ts, begin, left);
  9039. begin += left;
  9040. }
  9041. if (isLittleEndian != sys::IsLittleEndianHost)
  9042. swapStruct(ts);
  9043. if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
  9044. outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
  9045. if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
  9046. outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
  9047. else
  9048. outs() << "tsh.count " << ts.tsh.count
  9049. << " (not x86_THREAD_STATE64_COUNT\n";
  9050. Print_x86_thread_state64_t(ts.uts.ts64);
  9051. } else {
  9052. outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
  9053. << ts.tsh.count << "\n";
  9054. }
  9055. } else if (flavor == MachO::x86_FLOAT_STATE) {
  9056. outs() << " flavor x86_FLOAT_STATE\n";
  9057. if (count == MachO::x86_FLOAT_STATE_COUNT)
  9058. outs() << " count x86_FLOAT_STATE_COUNT\n";
  9059. else
  9060. outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
  9061. struct MachO::x86_float_state_t fs;
  9062. left = end - begin;
  9063. if (left >= sizeof(MachO::x86_float_state_t)) {
  9064. memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
  9065. begin += sizeof(MachO::x86_float_state_t);
  9066. } else {
  9067. memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
  9068. memcpy(&fs, begin, left);
  9069. begin += left;
  9070. }
  9071. if (isLittleEndian != sys::IsLittleEndianHost)
  9072. swapStruct(fs);
  9073. if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
  9074. outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
  9075. if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
  9076. outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
  9077. else
  9078. outs() << "fsh.count " << fs.fsh.count
  9079. << " (not x86_FLOAT_STATE64_COUNT\n";
  9080. Print_x86_float_state_t(fs.ufs.fs64);
  9081. } else {
  9082. outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
  9083. << fs.fsh.count << "\n";
  9084. }
  9085. } else if (flavor == MachO::x86_EXCEPTION_STATE) {
  9086. outs() << " flavor x86_EXCEPTION_STATE\n";
  9087. if (count == MachO::x86_EXCEPTION_STATE_COUNT)
  9088. outs() << " count x86_EXCEPTION_STATE_COUNT\n";
  9089. else
  9090. outs() << " count " << count
  9091. << " (not x86_EXCEPTION_STATE_COUNT)\n";
  9092. struct MachO::x86_exception_state_t es;
  9093. left = end - begin;
  9094. if (left >= sizeof(MachO::x86_exception_state_t)) {
  9095. memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
  9096. begin += sizeof(MachO::x86_exception_state_t);
  9097. } else {
  9098. memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
  9099. memcpy(&es, begin, left);
  9100. begin += left;
  9101. }
  9102. if (isLittleEndian != sys::IsLittleEndianHost)
  9103. swapStruct(es);
  9104. if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
  9105. outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
  9106. if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
  9107. outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
  9108. else
  9109. outs() << "\t esh.count " << es.esh.count
  9110. << " (not x86_EXCEPTION_STATE64_COUNT\n";
  9111. Print_x86_exception_state_t(es.ues.es64);
  9112. } else {
  9113. outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
  9114. << es.esh.count << "\n";
  9115. }
  9116. } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
  9117. outs() << " flavor x86_EXCEPTION_STATE64\n";
  9118. if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
  9119. outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
  9120. else
  9121. outs() << " count " << count
  9122. << " (not x86_EXCEPTION_STATE64_COUNT)\n";
  9123. struct MachO::x86_exception_state64_t es64;
  9124. left = end - begin;
  9125. if (left >= sizeof(MachO::x86_exception_state64_t)) {
  9126. memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
  9127. begin += sizeof(MachO::x86_exception_state64_t);
  9128. } else {
  9129. memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
  9130. memcpy(&es64, begin, left);
  9131. begin += left;
  9132. }
  9133. if (isLittleEndian != sys::IsLittleEndianHost)
  9134. swapStruct(es64);
  9135. Print_x86_exception_state_t(es64);
  9136. } else {
  9137. outs() << " flavor " << flavor << " (unknown)\n";
  9138. outs() << " count " << count << "\n";
  9139. outs() << " state (unknown)\n";
  9140. begin += count * sizeof(uint32_t);
  9141. }
  9142. }
  9143. } else if (cputype == MachO::CPU_TYPE_ARM) {
  9144. while (begin < end) {
  9145. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9146. memcpy((char *)&flavor, begin, sizeof(uint32_t));
  9147. begin += sizeof(uint32_t);
  9148. } else {
  9149. flavor = 0;
  9150. begin = end;
  9151. }
  9152. if (isLittleEndian != sys::IsLittleEndianHost)
  9153. sys::swapByteOrder(flavor);
  9154. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9155. memcpy((char *)&count, begin, sizeof(uint32_t));
  9156. begin += sizeof(uint32_t);
  9157. } else {
  9158. count = 0;
  9159. begin = end;
  9160. }
  9161. if (isLittleEndian != sys::IsLittleEndianHost)
  9162. sys::swapByteOrder(count);
  9163. if (flavor == MachO::ARM_THREAD_STATE) {
  9164. outs() << " flavor ARM_THREAD_STATE\n";
  9165. if (count == MachO::ARM_THREAD_STATE_COUNT)
  9166. outs() << " count ARM_THREAD_STATE_COUNT\n";
  9167. else
  9168. outs() << " count " << count
  9169. << " (not ARM_THREAD_STATE_COUNT)\n";
  9170. MachO::arm_thread_state32_t cpu32;
  9171. left = end - begin;
  9172. if (left >= sizeof(MachO::arm_thread_state32_t)) {
  9173. memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
  9174. begin += sizeof(MachO::arm_thread_state32_t);
  9175. } else {
  9176. memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
  9177. memcpy(&cpu32, begin, left);
  9178. begin += left;
  9179. }
  9180. if (isLittleEndian != sys::IsLittleEndianHost)
  9181. swapStruct(cpu32);
  9182. Print_arm_thread_state32_t(cpu32);
  9183. } else {
  9184. outs() << " flavor " << flavor << " (unknown)\n";
  9185. outs() << " count " << count << "\n";
  9186. outs() << " state (unknown)\n";
  9187. begin += count * sizeof(uint32_t);
  9188. }
  9189. }
  9190. } else if (cputype == MachO::CPU_TYPE_ARM64 ||
  9191. cputype == MachO::CPU_TYPE_ARM64_32) {
  9192. while (begin < end) {
  9193. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9194. memcpy((char *)&flavor, begin, sizeof(uint32_t));
  9195. begin += sizeof(uint32_t);
  9196. } else {
  9197. flavor = 0;
  9198. begin = end;
  9199. }
  9200. if (isLittleEndian != sys::IsLittleEndianHost)
  9201. sys::swapByteOrder(flavor);
  9202. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9203. memcpy((char *)&count, begin, sizeof(uint32_t));
  9204. begin += sizeof(uint32_t);
  9205. } else {
  9206. count = 0;
  9207. begin = end;
  9208. }
  9209. if (isLittleEndian != sys::IsLittleEndianHost)
  9210. sys::swapByteOrder(count);
  9211. if (flavor == MachO::ARM_THREAD_STATE64) {
  9212. outs() << " flavor ARM_THREAD_STATE64\n";
  9213. if (count == MachO::ARM_THREAD_STATE64_COUNT)
  9214. outs() << " count ARM_THREAD_STATE64_COUNT\n";
  9215. else
  9216. outs() << " count " << count
  9217. << " (not ARM_THREAD_STATE64_COUNT)\n";
  9218. MachO::arm_thread_state64_t cpu64;
  9219. left = end - begin;
  9220. if (left >= sizeof(MachO::arm_thread_state64_t)) {
  9221. memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
  9222. begin += sizeof(MachO::arm_thread_state64_t);
  9223. } else {
  9224. memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
  9225. memcpy(&cpu64, begin, left);
  9226. begin += left;
  9227. }
  9228. if (isLittleEndian != sys::IsLittleEndianHost)
  9229. swapStruct(cpu64);
  9230. Print_arm_thread_state64_t(cpu64);
  9231. } else {
  9232. outs() << " flavor " << flavor << " (unknown)\n";
  9233. outs() << " count " << count << "\n";
  9234. outs() << " state (unknown)\n";
  9235. begin += count * sizeof(uint32_t);
  9236. }
  9237. }
  9238. } else {
  9239. while (begin < end) {
  9240. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9241. memcpy((char *)&flavor, begin, sizeof(uint32_t));
  9242. begin += sizeof(uint32_t);
  9243. } else {
  9244. flavor = 0;
  9245. begin = end;
  9246. }
  9247. if (isLittleEndian != sys::IsLittleEndianHost)
  9248. sys::swapByteOrder(flavor);
  9249. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9250. memcpy((char *)&count, begin, sizeof(uint32_t));
  9251. begin += sizeof(uint32_t);
  9252. } else {
  9253. count = 0;
  9254. begin = end;
  9255. }
  9256. if (isLittleEndian != sys::IsLittleEndianHost)
  9257. sys::swapByteOrder(count);
  9258. outs() << " flavor " << flavor << "\n";
  9259. outs() << " count " << count << "\n";
  9260. outs() << " state (Unknown cputype/cpusubtype)\n";
  9261. begin += count * sizeof(uint32_t);
  9262. }
  9263. }
  9264. }
  9265. static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
  9266. if (dl.cmd == MachO::LC_ID_DYLIB)
  9267. outs() << " cmd LC_ID_DYLIB\n";
  9268. else if (dl.cmd == MachO::LC_LOAD_DYLIB)
  9269. outs() << " cmd LC_LOAD_DYLIB\n";
  9270. else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
  9271. outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
  9272. else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
  9273. outs() << " cmd LC_REEXPORT_DYLIB\n";
  9274. else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
  9275. outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
  9276. else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
  9277. outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
  9278. else
  9279. outs() << " cmd " << dl.cmd << " (unknown)\n";
  9280. outs() << " cmdsize " << dl.cmdsize;
  9281. if (dl.cmdsize < sizeof(struct MachO::dylib_command))
  9282. outs() << " Incorrect size\n";
  9283. else
  9284. outs() << "\n";
  9285. if (dl.dylib.name < dl.cmdsize) {
  9286. const char *P = (const char *)(Ptr) + dl.dylib.name;
  9287. outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
  9288. } else {
  9289. outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
  9290. }
  9291. outs() << " time stamp " << dl.dylib.timestamp << " ";
  9292. time_t t = dl.dylib.timestamp;
  9293. outs() << ctime(&t);
  9294. outs() << " current version ";
  9295. if (dl.dylib.current_version == 0xffffffff)
  9296. outs() << "n/a\n";
  9297. else
  9298. outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
  9299. << ((dl.dylib.current_version >> 8) & 0xff) << "."
  9300. << (dl.dylib.current_version & 0xff) << "\n";
  9301. outs() << "compatibility version ";
  9302. if (dl.dylib.compatibility_version == 0xffffffff)
  9303. outs() << "n/a\n";
  9304. else
  9305. outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
  9306. << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
  9307. << (dl.dylib.compatibility_version & 0xff) << "\n";
  9308. }
  9309. static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
  9310. uint32_t object_size) {
  9311. if (ld.cmd == MachO::LC_CODE_SIGNATURE)
  9312. outs() << " cmd LC_CODE_SIGNATURE\n";
  9313. else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
  9314. outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
  9315. else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
  9316. outs() << " cmd LC_FUNCTION_STARTS\n";
  9317. else if (ld.cmd == MachO::LC_DATA_IN_CODE)
  9318. outs() << " cmd LC_DATA_IN_CODE\n";
  9319. else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
  9320. outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
  9321. else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
  9322. outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
  9323. else
  9324. outs() << " cmd " << ld.cmd << " (?)\n";
  9325. outs() << " cmdsize " << ld.cmdsize;
  9326. if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
  9327. outs() << " Incorrect size\n";
  9328. else
  9329. outs() << "\n";
  9330. outs() << " dataoff " << ld.dataoff;
  9331. if (ld.dataoff > object_size)
  9332. outs() << " (past end of file)\n";
  9333. else
  9334. outs() << "\n";
  9335. outs() << " datasize " << ld.datasize;
  9336. uint64_t big_size = ld.dataoff;
  9337. big_size += ld.datasize;
  9338. if (big_size > object_size)
  9339. outs() << " (past end of file)\n";
  9340. else
  9341. outs() << "\n";
  9342. }
  9343. static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
  9344. uint32_t cputype, bool verbose) {
  9345. StringRef Buf = Obj->getData();
  9346. unsigned Index = 0;
  9347. for (const auto &Command : Obj->load_commands()) {
  9348. outs() << "Load command " << Index++ << "\n";
  9349. if (Command.C.cmd == MachO::LC_SEGMENT) {
  9350. MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
  9351. const char *sg_segname = SLC.segname;
  9352. PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
  9353. SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
  9354. SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
  9355. verbose);
  9356. for (unsigned j = 0; j < SLC.nsects; j++) {
  9357. MachO::section S = Obj->getSection(Command, j);
  9358. PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
  9359. S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
  9360. SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
  9361. }
  9362. } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
  9363. MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
  9364. const char *sg_segname = SLC_64.segname;
  9365. PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
  9366. SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
  9367. SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
  9368. SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
  9369. for (unsigned j = 0; j < SLC_64.nsects; j++) {
  9370. MachO::section_64 S_64 = Obj->getSection64(Command, j);
  9371. PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
  9372. S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
  9373. S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
  9374. sg_segname, filetype, Buf.size(), verbose);
  9375. }
  9376. } else if (Command.C.cmd == MachO::LC_SYMTAB) {
  9377. MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
  9378. PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
  9379. } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
  9380. MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
  9381. MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
  9382. PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
  9383. Obj->is64Bit());
  9384. } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
  9385. Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
  9386. MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
  9387. PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
  9388. } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
  9389. Command.C.cmd == MachO::LC_ID_DYLINKER ||
  9390. Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
  9391. MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
  9392. PrintDyldLoadCommand(Dyld, Command.Ptr);
  9393. } else if (Command.C.cmd == MachO::LC_UUID) {
  9394. MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
  9395. PrintUuidLoadCommand(Uuid);
  9396. } else if (Command.C.cmd == MachO::LC_RPATH) {
  9397. MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
  9398. PrintRpathLoadCommand(Rpath, Command.Ptr);
  9399. } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
  9400. Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
  9401. Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
  9402. Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
  9403. MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
  9404. PrintVersionMinLoadCommand(Vd);
  9405. } else if (Command.C.cmd == MachO::LC_NOTE) {
  9406. MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
  9407. PrintNoteLoadCommand(Nt);
  9408. } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
  9409. MachO::build_version_command Bv =
  9410. Obj->getBuildVersionLoadCommand(Command);
  9411. PrintBuildVersionLoadCommand(Obj, Bv);
  9412. } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
  9413. MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
  9414. PrintSourceVersionCommand(Sd);
  9415. } else if (Command.C.cmd == MachO::LC_MAIN) {
  9416. MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
  9417. PrintEntryPointCommand(Ep);
  9418. } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
  9419. MachO::encryption_info_command Ei =
  9420. Obj->getEncryptionInfoCommand(Command);
  9421. PrintEncryptionInfoCommand(Ei, Buf.size());
  9422. } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
  9423. MachO::encryption_info_command_64 Ei =
  9424. Obj->getEncryptionInfoCommand64(Command);
  9425. PrintEncryptionInfoCommand64(Ei, Buf.size());
  9426. } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
  9427. MachO::linker_option_command Lo =
  9428. Obj->getLinkerOptionLoadCommand(Command);
  9429. PrintLinkerOptionCommand(Lo, Command.Ptr);
  9430. } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
  9431. MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
  9432. PrintSubFrameworkCommand(Sf, Command.Ptr);
  9433. } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
  9434. MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
  9435. PrintSubUmbrellaCommand(Sf, Command.Ptr);
  9436. } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
  9437. MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
  9438. PrintSubLibraryCommand(Sl, Command.Ptr);
  9439. } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
  9440. MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
  9441. PrintSubClientCommand(Sc, Command.Ptr);
  9442. } else if (Command.C.cmd == MachO::LC_ROUTINES) {
  9443. MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
  9444. PrintRoutinesCommand(Rc);
  9445. } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
  9446. MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
  9447. PrintRoutinesCommand64(Rc);
  9448. } else if (Command.C.cmd == MachO::LC_THREAD ||
  9449. Command.C.cmd == MachO::LC_UNIXTHREAD) {
  9450. MachO::thread_command Tc = Obj->getThreadCommand(Command);
  9451. PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
  9452. } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
  9453. Command.C.cmd == MachO::LC_ID_DYLIB ||
  9454. Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
  9455. Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
  9456. Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
  9457. Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
  9458. MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
  9459. PrintDylibCommand(Dl, Command.Ptr);
  9460. } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
  9461. Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
  9462. Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
  9463. Command.C.cmd == MachO::LC_DATA_IN_CODE ||
  9464. Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
  9465. Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
  9466. MachO::linkedit_data_command Ld =
  9467. Obj->getLinkeditDataLoadCommand(Command);
  9468. PrintLinkEditDataCommand(Ld, Buf.size());
  9469. } else {
  9470. outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
  9471. << ")\n";
  9472. outs() << " cmdsize " << Command.C.cmdsize << "\n";
  9473. // TODO: get and print the raw bytes of the load command.
  9474. }
  9475. // TODO: print all the other kinds of load commands.
  9476. }
  9477. }
  9478. static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
  9479. if (Obj->is64Bit()) {
  9480. MachO::mach_header_64 H_64;
  9481. H_64 = Obj->getHeader64();
  9482. PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
  9483. H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
  9484. } else {
  9485. MachO::mach_header H;
  9486. H = Obj->getHeader();
  9487. PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
  9488. H.sizeofcmds, H.flags, verbose);
  9489. }
  9490. }
  9491. void objdump::printMachOFileHeader(const object::ObjectFile *Obj) {
  9492. const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
  9493. PrintMachHeader(file, !NonVerbose);
  9494. }
  9495. void objdump::printMachOLoadCommands(const object::ObjectFile *Obj) {
  9496. const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
  9497. uint32_t filetype = 0;
  9498. uint32_t cputype = 0;
  9499. if (file->is64Bit()) {
  9500. MachO::mach_header_64 H_64;
  9501. H_64 = file->getHeader64();
  9502. filetype = H_64.filetype;
  9503. cputype = H_64.cputype;
  9504. } else {
  9505. MachO::mach_header H;
  9506. H = file->getHeader();
  9507. filetype = H.filetype;
  9508. cputype = H.cputype;
  9509. }
  9510. PrintLoadCommands(file, filetype, cputype, !NonVerbose);
  9511. }
  9512. //===----------------------------------------------------------------------===//
  9513. // export trie dumping
  9514. //===----------------------------------------------------------------------===//
  9515. static void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
  9516. uint64_t BaseSegmentAddress = 0;
  9517. for (const auto &Command : Obj->load_commands()) {
  9518. if (Command.C.cmd == MachO::LC_SEGMENT) {
  9519. MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
  9520. if (Seg.fileoff == 0 && Seg.filesize != 0) {
  9521. BaseSegmentAddress = Seg.vmaddr;
  9522. break;
  9523. }
  9524. } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
  9525. MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
  9526. if (Seg.fileoff == 0 && Seg.filesize != 0) {
  9527. BaseSegmentAddress = Seg.vmaddr;
  9528. break;
  9529. }
  9530. }
  9531. }
  9532. Error Err = Error::success();
  9533. for (const object::ExportEntry &Entry : Obj->exports(Err)) {
  9534. uint64_t Flags = Entry.flags();
  9535. bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
  9536. bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
  9537. bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
  9538. MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
  9539. bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
  9540. MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
  9541. bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
  9542. if (ReExport)
  9543. outs() << "[re-export] ";
  9544. else
  9545. outs() << format("0x%08llX ",
  9546. Entry.address() + BaseSegmentAddress);
  9547. outs() << Entry.name();
  9548. if (WeakDef || ThreadLocal || Resolver || Abs) {
  9549. bool NeedsComma = false;
  9550. outs() << " [";
  9551. if (WeakDef) {
  9552. outs() << "weak_def";
  9553. NeedsComma = true;
  9554. }
  9555. if (ThreadLocal) {
  9556. if (NeedsComma)
  9557. outs() << ", ";
  9558. outs() << "per-thread";
  9559. NeedsComma = true;
  9560. }
  9561. if (Abs) {
  9562. if (NeedsComma)
  9563. outs() << ", ";
  9564. outs() << "absolute";
  9565. NeedsComma = true;
  9566. }
  9567. if (Resolver) {
  9568. if (NeedsComma)
  9569. outs() << ", ";
  9570. outs() << format("resolver=0x%08llX", Entry.other());
  9571. NeedsComma = true;
  9572. }
  9573. outs() << "]";
  9574. }
  9575. if (ReExport) {
  9576. StringRef DylibName = "unknown";
  9577. int Ordinal = Entry.other() - 1;
  9578. Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
  9579. if (Entry.otherName().empty())
  9580. outs() << " (from " << DylibName << ")";
  9581. else
  9582. outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
  9583. }
  9584. outs() << "\n";
  9585. }
  9586. if (Err)
  9587. reportError(std::move(Err), Obj->getFileName());
  9588. }
  9589. //===----------------------------------------------------------------------===//
  9590. // rebase table dumping
  9591. //===----------------------------------------------------------------------===//
  9592. static void printMachORebaseTable(object::MachOObjectFile *Obj) {
  9593. outs() << "segment section address type\n";
  9594. Error Err = Error::success();
  9595. for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
  9596. StringRef SegmentName = Entry.segmentName();
  9597. StringRef SectionName = Entry.sectionName();
  9598. uint64_t Address = Entry.address();
  9599. // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
  9600. outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
  9601. SegmentName.str().c_str(), SectionName.str().c_str(),
  9602. Address, Entry.typeName().str().c_str());
  9603. }
  9604. if (Err)
  9605. reportError(std::move(Err), Obj->getFileName());
  9606. }
  9607. static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
  9608. StringRef DylibName;
  9609. switch (Ordinal) {
  9610. case MachO::BIND_SPECIAL_DYLIB_SELF:
  9611. return "this-image";
  9612. case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
  9613. return "main-executable";
  9614. case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
  9615. return "flat-namespace";
  9616. default:
  9617. if (Ordinal > 0) {
  9618. std::error_code EC =
  9619. Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
  9620. if (EC)
  9621. return "<<bad library ordinal>>";
  9622. return DylibName;
  9623. }
  9624. }
  9625. return "<<unknown special ordinal>>";
  9626. }
  9627. //===----------------------------------------------------------------------===//
  9628. // bind table dumping
  9629. //===----------------------------------------------------------------------===//
  9630. static void printMachOBindTable(object::MachOObjectFile *Obj) {
  9631. // Build table of sections so names can used in final output.
  9632. outs() << "segment section address type "
  9633. "addend dylib symbol\n";
  9634. Error Err = Error::success();
  9635. for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
  9636. StringRef SegmentName = Entry.segmentName();
  9637. StringRef SectionName = Entry.sectionName();
  9638. uint64_t Address = Entry.address();
  9639. // Table lines look like:
  9640. // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
  9641. StringRef Attr;
  9642. if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
  9643. Attr = " (weak_import)";
  9644. outs() << left_justify(SegmentName, 8) << " "
  9645. << left_justify(SectionName, 18) << " "
  9646. << format_hex(Address, 10, true) << " "
  9647. << left_justify(Entry.typeName(), 8) << " "
  9648. << format_decimal(Entry.addend(), 8) << " "
  9649. << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
  9650. << Entry.symbolName() << Attr << "\n";
  9651. }
  9652. if (Err)
  9653. reportError(std::move(Err), Obj->getFileName());
  9654. }
  9655. //===----------------------------------------------------------------------===//
  9656. // lazy bind table dumping
  9657. //===----------------------------------------------------------------------===//
  9658. static void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
  9659. outs() << "segment section address "
  9660. "dylib symbol\n";
  9661. Error Err = Error::success();
  9662. for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
  9663. StringRef SegmentName = Entry.segmentName();
  9664. StringRef SectionName = Entry.sectionName();
  9665. uint64_t Address = Entry.address();
  9666. // Table lines look like:
  9667. // __DATA __got 0x00012010 libSystem ___stack_chk_guard
  9668. outs() << left_justify(SegmentName, 8) << " "
  9669. << left_justify(SectionName, 18) << " "
  9670. << format_hex(Address, 10, true) << " "
  9671. << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
  9672. << Entry.symbolName() << "\n";
  9673. }
  9674. if (Err)
  9675. reportError(std::move(Err), Obj->getFileName());
  9676. }
  9677. //===----------------------------------------------------------------------===//
  9678. // weak bind table dumping
  9679. //===----------------------------------------------------------------------===//
  9680. static void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
  9681. outs() << "segment section address "
  9682. "type addend symbol\n";
  9683. Error Err = Error::success();
  9684. for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
  9685. // Strong symbols don't have a location to update.
  9686. if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
  9687. outs() << " strong "
  9688. << Entry.symbolName() << "\n";
  9689. continue;
  9690. }
  9691. StringRef SegmentName = Entry.segmentName();
  9692. StringRef SectionName = Entry.sectionName();
  9693. uint64_t Address = Entry.address();
  9694. // Table lines look like:
  9695. // __DATA __data 0x00001000 pointer 0 _foo
  9696. outs() << left_justify(SegmentName, 8) << " "
  9697. << left_justify(SectionName, 18) << " "
  9698. << format_hex(Address, 10, true) << " "
  9699. << left_justify(Entry.typeName(), 8) << " "
  9700. << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
  9701. << "\n";
  9702. }
  9703. if (Err)
  9704. reportError(std::move(Err), Obj->getFileName());
  9705. }
  9706. // get_dyld_bind_info_symbolname() is used for disassembly and passed an
  9707. // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
  9708. // information for that address. If the address is found its binding symbol
  9709. // name is returned. If not nullptr is returned.
  9710. static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
  9711. struct DisassembleInfo *info) {
  9712. if (info->bindtable == nullptr) {
  9713. info->bindtable = std::make_unique<SymbolAddressMap>();
  9714. Error Err = Error::success();
  9715. for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
  9716. uint64_t Address = Entry.address();
  9717. StringRef name = Entry.symbolName();
  9718. if (!name.empty())
  9719. (*info->bindtable)[Address] = name;
  9720. }
  9721. if (Err)
  9722. reportError(std::move(Err), info->O->getFileName());
  9723. }
  9724. auto name = info->bindtable->lookup(ReferenceValue);
  9725. return !name.empty() ? name.data() : nullptr;
  9726. }
  9727. void objdump::printLazyBindTable(ObjectFile *o) {
  9728. outs() << "Lazy bind table:\n";
  9729. if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  9730. printMachOLazyBindTable(MachO);
  9731. else
  9732. WithColor::error()
  9733. << "This operation is only currently supported "
  9734. "for Mach-O executable files.\n";
  9735. }
  9736. void objdump::printWeakBindTable(ObjectFile *o) {
  9737. outs() << "Weak bind table:\n";
  9738. if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  9739. printMachOWeakBindTable(MachO);
  9740. else
  9741. WithColor::error()
  9742. << "This operation is only currently supported "
  9743. "for Mach-O executable files.\n";
  9744. }
  9745. void objdump::printExportsTrie(const ObjectFile *o) {
  9746. outs() << "Exports trie:\n";
  9747. if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  9748. printMachOExportsTrie(MachO);
  9749. else
  9750. WithColor::error()
  9751. << "This operation is only currently supported "
  9752. "for Mach-O executable files.\n";
  9753. }
  9754. void objdump::printRebaseTable(ObjectFile *o) {
  9755. outs() << "Rebase table:\n";
  9756. if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  9757. printMachORebaseTable(MachO);
  9758. else
  9759. WithColor::error()
  9760. << "This operation is only currently supported "
  9761. "for Mach-O executable files.\n";
  9762. }
  9763. void objdump::printBindTable(ObjectFile *o) {
  9764. outs() << "Bind table:\n";
  9765. if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  9766. printMachOBindTable(MachO);
  9767. else
  9768. WithColor::error()
  9769. << "This operation is only currently supported "
  9770. "for Mach-O executable files.\n";
  9771. }