MachODump.cpp 380 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513
  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 "llvm-objdump.h"
  13. #include "llvm-c/Disassembler.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/StringExtras.h"
  16. #include "llvm/ADT/Triple.h"
  17. #include "llvm/BinaryFormat/MachO.h"
  18. #include "llvm/Config/config.h"
  19. #include "llvm/DebugInfo/DIContext.h"
  20. #include "llvm/DebugInfo/DWARF/DWARFContext.h"
  21. #include "llvm/Demangle/Demangle.h"
  22. #include "llvm/MC/MCAsmInfo.h"
  23. #include "llvm/MC/MCContext.h"
  24. #include "llvm/MC/MCDisassembler/MCDisassembler.h"
  25. #include "llvm/MC/MCInst.h"
  26. #include "llvm/MC/MCInstPrinter.h"
  27. #include "llvm/MC/MCInstrDesc.h"
  28. #include "llvm/MC/MCInstrInfo.h"
  29. #include "llvm/MC/MCRegisterInfo.h"
  30. #include "llvm/MC/MCSubtargetInfo.h"
  31. #include "llvm/Object/MachO.h"
  32. #include "llvm/Object/MachOUniversal.h"
  33. #include "llvm/Support/Casting.h"
  34. #include "llvm/Support/CommandLine.h"
  35. #include "llvm/Support/Debug.h"
  36. #include "llvm/Support/Endian.h"
  37. #include "llvm/Support/Format.h"
  38. #include "llvm/Support/FormattedStream.h"
  39. #include "llvm/Support/GraphWriter.h"
  40. #include "llvm/Support/LEB128.h"
  41. #include "llvm/Support/MemoryBuffer.h"
  42. #include "llvm/Support/TargetRegistry.h"
  43. #include "llvm/Support/TargetSelect.h"
  44. #include "llvm/Support/ToolOutputFile.h"
  45. #include "llvm/Support/WithColor.h"
  46. #include "llvm/Support/raw_ostream.h"
  47. #include <algorithm>
  48. #include <cstring>
  49. #include <system_error>
  50. #ifdef HAVE_LIBXAR
  51. extern "C" {
  52. #include <xar/xar.h>
  53. }
  54. #endif
  55. using namespace llvm::object;
  56. namespace llvm {
  57. cl::OptionCategory MachOCat("llvm-objdump MachO Specific Options");
  58. extern cl::opt<bool> ArchiveHeaders;
  59. extern cl::opt<bool> Disassemble;
  60. extern cl::opt<bool> DisassembleAll;
  61. extern cl::opt<DIDumpType> DwarfDumpType;
  62. extern cl::list<std::string> FilterSections;
  63. extern cl::list<std::string> MAttrs;
  64. extern cl::opt<std::string> MCPU;
  65. extern cl::opt<bool> NoShowRawInsn;
  66. extern cl::opt<bool> NoLeadingAddr;
  67. extern cl::opt<bool> PrintImmHex;
  68. extern cl::opt<bool> PrivateHeaders;
  69. extern cl::opt<bool> Relocations;
  70. extern cl::opt<bool> SectionHeaders;
  71. extern cl::opt<bool> SectionContents;
  72. extern cl::opt<bool> SymbolTable;
  73. extern cl::opt<std::string> TripleName;
  74. extern cl::opt<bool> UnwindInfo;
  75. cl::opt<bool>
  76. FirstPrivateHeader("private-header",
  77. cl::desc("Display only the first format specific file "
  78. "header"),
  79. cl::cat(MachOCat));
  80. cl::opt<bool> ExportsTrie("exports-trie",
  81. cl::desc("Display mach-o exported symbols"),
  82. cl::cat(MachOCat));
  83. cl::opt<bool> Rebase("rebase", cl::desc("Display mach-o rebasing info"),
  84. cl::cat(MachOCat));
  85. cl::opt<bool> Bind("bind", cl::desc("Display mach-o binding info"),
  86. cl::cat(MachOCat));
  87. cl::opt<bool> LazyBind("lazy-bind",
  88. cl::desc("Display mach-o lazy binding info"),
  89. cl::cat(MachOCat));
  90. cl::opt<bool> WeakBind("weak-bind",
  91. cl::desc("Display mach-o weak binding info"),
  92. cl::cat(MachOCat));
  93. static cl::opt<bool>
  94. UseDbg("g", cl::Grouping,
  95. cl::desc("Print line information from debug info if available"),
  96. cl::cat(MachOCat));
  97. static cl::opt<std::string> DSYMFile("dsym",
  98. cl::desc("Use .dSYM file for debug info"),
  99. cl::cat(MachOCat));
  100. static cl::opt<bool> FullLeadingAddr("full-leading-addr",
  101. cl::desc("Print full leading address"),
  102. cl::cat(MachOCat));
  103. static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
  104. cl::desc("Print no leading headers"),
  105. cl::cat(MachOCat));
  106. cl::opt<bool> UniversalHeaders("universal-headers",
  107. cl::desc("Print Mach-O universal headers "
  108. "(requires -macho)"),
  109. cl::cat(MachOCat));
  110. cl::opt<bool>
  111. ArchiveMemberOffsets("archive-member-offsets",
  112. cl::desc("Print the offset to each archive member for "
  113. "Mach-O archives (requires -macho and "
  114. "-archive-headers)"),
  115. cl::cat(MachOCat));
  116. cl::opt<bool> IndirectSymbols("indirect-symbols",
  117. cl::desc("Print indirect symbol table for Mach-O "
  118. "objects (requires -macho)"),
  119. cl::cat(MachOCat));
  120. cl::opt<bool>
  121. DataInCode("data-in-code",
  122. cl::desc("Print the data in code table for Mach-O objects "
  123. "(requires -macho)"),
  124. cl::cat(MachOCat));
  125. cl::opt<bool> LinkOptHints("link-opt-hints",
  126. cl::desc("Print the linker optimization hints for "
  127. "Mach-O objects (requires -macho)"),
  128. cl::cat(MachOCat));
  129. cl::opt<bool> InfoPlist("info-plist",
  130. cl::desc("Print the info plist section as strings for "
  131. "Mach-O objects (requires -macho)"),
  132. cl::cat(MachOCat));
  133. cl::opt<bool> DylibsUsed("dylibs-used",
  134. cl::desc("Print the shared libraries used for linked "
  135. "Mach-O files (requires -macho)"),
  136. cl::cat(MachOCat));
  137. cl::opt<bool>
  138. DylibId("dylib-id",
  139. cl::desc("Print the shared library's id for the dylib Mach-O "
  140. "file (requires -macho)"),
  141. cl::cat(MachOCat));
  142. cl::opt<bool>
  143. NonVerbose("non-verbose",
  144. cl::desc("Print the info for Mach-O objects in "
  145. "non-verbose or numeric form (requires -macho)"),
  146. cl::cat(MachOCat));
  147. cl::opt<bool>
  148. ObjcMetaData("objc-meta-data",
  149. cl::desc("Print the Objective-C runtime meta data for "
  150. "Mach-O files (requires -macho)"),
  151. cl::cat(MachOCat));
  152. cl::opt<std::string> DisSymName(
  153. "dis-symname",
  154. cl::desc("disassemble just this symbol's instructions (requires -macho)"),
  155. cl::cat(MachOCat));
  156. static cl::opt<bool> NoSymbolicOperands(
  157. "no-symbolic-operands",
  158. cl::desc("do not symbolic operands when disassembling (requires -macho)"),
  159. cl::cat(MachOCat));
  160. static cl::list<std::string>
  161. ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
  162. cl::ZeroOrMore, cl::cat(MachOCat));
  163. bool ArchAll = false;
  164. static std::string ThumbTripleName;
  165. static const Target *GetTarget(const MachOObjectFile *MachOObj,
  166. const char **McpuDefault,
  167. const Target **ThumbTarget) {
  168. // Figure out the target triple.
  169. Triple TT(TripleName);
  170. if (TripleName.empty()) {
  171. TT = MachOObj->getArchTriple(McpuDefault);
  172. TripleName = TT.str();
  173. }
  174. if (TT.getArch() == Triple::arm) {
  175. // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
  176. // that support ARM are also capable of Thumb mode.
  177. Triple ThumbTriple = TT;
  178. std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
  179. ThumbTriple.setArchName(ThumbName);
  180. ThumbTripleName = ThumbTriple.str();
  181. }
  182. // Get the target specific parser.
  183. std::string Error;
  184. const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
  185. if (TheTarget && ThumbTripleName.empty())
  186. return TheTarget;
  187. *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
  188. if (*ThumbTarget)
  189. return TheTarget;
  190. WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
  191. if (!TheTarget)
  192. errs() << TripleName;
  193. else
  194. errs() << ThumbTripleName;
  195. errs() << "', see --version and --triple.\n";
  196. return nullptr;
  197. }
  198. struct SymbolSorter {
  199. bool operator()(const SymbolRef &A, const SymbolRef &B) {
  200. Expected<SymbolRef::Type> ATypeOrErr = A.getType();
  201. if (!ATypeOrErr)
  202. reportError(ATypeOrErr.takeError(), A.getObject()->getFileName());
  203. SymbolRef::Type AType = *ATypeOrErr;
  204. Expected<SymbolRef::Type> BTypeOrErr = B.getType();
  205. if (!BTypeOrErr)
  206. reportError(BTypeOrErr.takeError(), B.getObject()->getFileName());
  207. SymbolRef::Type BType = *BTypeOrErr;
  208. uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
  209. uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
  210. return AAddr < BAddr;
  211. }
  212. };
  213. // Types for the storted data in code table that is built before disassembly
  214. // and the predicate function to sort them.
  215. typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
  216. typedef std::vector<DiceTableEntry> DiceTable;
  217. typedef DiceTable::iterator dice_table_iterator;
  218. #ifdef HAVE_LIBXAR
  219. namespace {
  220. struct ScopedXarFile {
  221. xar_t xar;
  222. ScopedXarFile(const char *filename, int32_t flags)
  223. : xar(xar_open(filename, flags)) {}
  224. ~ScopedXarFile() {
  225. if (xar)
  226. xar_close(xar);
  227. }
  228. ScopedXarFile(const ScopedXarFile &) = delete;
  229. ScopedXarFile &operator=(const ScopedXarFile &) = delete;
  230. operator xar_t() { return xar; }
  231. };
  232. struct ScopedXarIter {
  233. xar_iter_t iter;
  234. ScopedXarIter() : iter(xar_iter_new()) {}
  235. ~ScopedXarIter() {
  236. if (iter)
  237. xar_iter_free(iter);
  238. }
  239. ScopedXarIter(const ScopedXarIter &) = delete;
  240. ScopedXarIter &operator=(const ScopedXarIter &) = delete;
  241. operator xar_iter_t() { return iter; }
  242. };
  243. } // namespace
  244. #endif // defined(HAVE_LIBXAR)
  245. // This is used to search for a data in code table entry for the PC being
  246. // disassembled. The j parameter has the PC in j.first. A single data in code
  247. // table entry can cover many bytes for each of its Kind's. So if the offset,
  248. // aka the i.first value, of the data in code table entry plus its Length
  249. // covers the PC being searched for this will return true. If not it will
  250. // return false.
  251. static bool compareDiceTableEntries(const DiceTableEntry &i,
  252. const DiceTableEntry &j) {
  253. uint16_t Length;
  254. i.second.getLength(Length);
  255. return j.first >= i.first && j.first < i.first + Length;
  256. }
  257. static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
  258. unsigned short Kind) {
  259. uint32_t Value, Size = 1;
  260. switch (Kind) {
  261. default:
  262. case MachO::DICE_KIND_DATA:
  263. if (Length >= 4) {
  264. if (!NoShowRawInsn)
  265. dumpBytes(makeArrayRef(bytes, 4), outs());
  266. Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
  267. outs() << "\t.long " << Value;
  268. Size = 4;
  269. } else if (Length >= 2) {
  270. if (!NoShowRawInsn)
  271. dumpBytes(makeArrayRef(bytes, 2), outs());
  272. Value = bytes[1] << 8 | bytes[0];
  273. outs() << "\t.short " << Value;
  274. Size = 2;
  275. } else {
  276. if (!NoShowRawInsn)
  277. dumpBytes(makeArrayRef(bytes, 2), outs());
  278. Value = bytes[0];
  279. outs() << "\t.byte " << Value;
  280. Size = 1;
  281. }
  282. if (Kind == MachO::DICE_KIND_DATA)
  283. outs() << "\t@ KIND_DATA\n";
  284. else
  285. outs() << "\t@ data in code kind = " << Kind << "\n";
  286. break;
  287. case MachO::DICE_KIND_JUMP_TABLE8:
  288. if (!NoShowRawInsn)
  289. dumpBytes(makeArrayRef(bytes, 1), outs());
  290. Value = bytes[0];
  291. outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
  292. Size = 1;
  293. break;
  294. case MachO::DICE_KIND_JUMP_TABLE16:
  295. if (!NoShowRawInsn)
  296. dumpBytes(makeArrayRef(bytes, 2), outs());
  297. Value = bytes[1] << 8 | bytes[0];
  298. outs() << "\t.short " << format("%5u", Value & 0xffff)
  299. << "\t@ KIND_JUMP_TABLE16\n";
  300. Size = 2;
  301. break;
  302. case MachO::DICE_KIND_JUMP_TABLE32:
  303. case MachO::DICE_KIND_ABS_JUMP_TABLE32:
  304. if (!NoShowRawInsn)
  305. dumpBytes(makeArrayRef(bytes, 4), outs());
  306. Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
  307. outs() << "\t.long " << Value;
  308. if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
  309. outs() << "\t@ KIND_JUMP_TABLE32\n";
  310. else
  311. outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
  312. Size = 4;
  313. break;
  314. }
  315. return Size;
  316. }
  317. static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
  318. std::vector<SectionRef> &Sections,
  319. std::vector<SymbolRef> &Symbols,
  320. SmallVectorImpl<uint64_t> &FoundFns,
  321. uint64_t &BaseSegmentAddress) {
  322. const StringRef FileName = MachOObj->getFileName();
  323. for (const SymbolRef &Symbol : MachOObj->symbols()) {
  324. StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
  325. if (!SymName.startswith("ltmp"))
  326. Symbols.push_back(Symbol);
  327. }
  328. for (const SectionRef &Section : MachOObj->sections())
  329. Sections.push_back(Section);
  330. bool BaseSegmentAddressSet = false;
  331. for (const auto &Command : MachOObj->load_commands()) {
  332. if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
  333. // We found a function starts segment, parse the addresses for later
  334. // consumption.
  335. MachO::linkedit_data_command LLC =
  336. MachOObj->getLinkeditDataLoadCommand(Command);
  337. MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
  338. } else if (Command.C.cmd == MachO::LC_SEGMENT) {
  339. MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
  340. StringRef SegName = SLC.segname;
  341. if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
  342. BaseSegmentAddressSet = true;
  343. BaseSegmentAddress = SLC.vmaddr;
  344. }
  345. } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
  346. MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(Command);
  347. StringRef SegName = SLC.segname;
  348. if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
  349. BaseSegmentAddressSet = true;
  350. BaseSegmentAddress = SLC.vmaddr;
  351. }
  352. }
  353. }
  354. }
  355. static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes,
  356. DiceTable &Dices, uint64_t &InstSize) {
  357. // Check the data in code table here to see if this is data not an
  358. // instruction to be disassembled.
  359. DiceTable Dice;
  360. Dice.push_back(std::make_pair(PC, DiceRef()));
  361. dice_table_iterator DTI =
  362. std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
  363. compareDiceTableEntries);
  364. if (DTI != Dices.end()) {
  365. uint16_t Length;
  366. DTI->second.getLength(Length);
  367. uint16_t Kind;
  368. DTI->second.getKind(Kind);
  369. InstSize = DumpDataInCode(bytes, Length, Kind);
  370. if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
  371. (PC == (DTI->first + Length - 1)) && (Length & 1))
  372. InstSize++;
  373. return true;
  374. }
  375. return false;
  376. }
  377. static void printRelocationTargetName(const MachOObjectFile *O,
  378. const MachO::any_relocation_info &RE,
  379. raw_string_ostream &Fmt) {
  380. // Target of a scattered relocation is an address. In the interest of
  381. // generating pretty output, scan through the symbol table looking for a
  382. // symbol that aligns with that address. If we find one, print it.
  383. // Otherwise, we just print the hex address of the target.
  384. const StringRef FileName = O->getFileName();
  385. if (O->isRelocationScattered(RE)) {
  386. uint32_t Val = O->getPlainRelocationSymbolNum(RE);
  387. for (const SymbolRef &Symbol : O->symbols()) {
  388. uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
  389. if (Addr != Val)
  390. continue;
  391. Fmt << unwrapOrError(Symbol.getName(), FileName);
  392. return;
  393. }
  394. // If we couldn't find a symbol that this relocation refers to, try
  395. // to find a section beginning instead.
  396. for (const SectionRef &Section : ToolSectionFilter(*O)) {
  397. uint64_t Addr = Section.getAddress();
  398. if (Addr != Val)
  399. continue;
  400. StringRef NameOrErr = unwrapOrError(Section.getName(), O->getFileName());
  401. Fmt << NameOrErr;
  402. return;
  403. }
  404. Fmt << format("0x%x", Val);
  405. return;
  406. }
  407. StringRef S;
  408. bool isExtern = O->getPlainRelocationExternal(RE);
  409. uint64_t Val = O->getPlainRelocationSymbolNum(RE);
  410. if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
  411. Fmt << format("0x%0" PRIx64, Val);
  412. return;
  413. }
  414. if (isExtern) {
  415. symbol_iterator SI = O->symbol_begin();
  416. advance(SI, Val);
  417. S = unwrapOrError(SI->getName(), FileName);
  418. } else {
  419. section_iterator SI = O->section_begin();
  420. // Adjust for the fact that sections are 1-indexed.
  421. if (Val == 0) {
  422. Fmt << "0 (?,?)";
  423. return;
  424. }
  425. uint32_t I = Val - 1;
  426. while (I != 0 && SI != O->section_end()) {
  427. --I;
  428. advance(SI, 1);
  429. }
  430. if (SI == O->section_end()) {
  431. Fmt << Val << " (?,?)";
  432. } else {
  433. if (Expected<StringRef> NameOrErr = SI->getName())
  434. S = *NameOrErr;
  435. else
  436. consumeError(NameOrErr.takeError());
  437. }
  438. }
  439. Fmt << S;
  440. }
  441. Error getMachORelocationValueString(const MachOObjectFile *Obj,
  442. const RelocationRef &RelRef,
  443. SmallVectorImpl<char> &Result) {
  444. DataRefImpl Rel = RelRef.getRawDataRefImpl();
  445. MachO::any_relocation_info RE = Obj->getRelocation(Rel);
  446. unsigned Arch = Obj->getArch();
  447. std::string FmtBuf;
  448. raw_string_ostream Fmt(FmtBuf);
  449. unsigned Type = Obj->getAnyRelocationType(RE);
  450. bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
  451. // Determine any addends that should be displayed with the relocation.
  452. // These require decoding the relocation type, which is triple-specific.
  453. // X86_64 has entirely custom relocation types.
  454. if (Arch == Triple::x86_64) {
  455. switch (Type) {
  456. case MachO::X86_64_RELOC_GOT_LOAD:
  457. case MachO::X86_64_RELOC_GOT: {
  458. printRelocationTargetName(Obj, RE, Fmt);
  459. Fmt << "@GOT";
  460. if (IsPCRel)
  461. Fmt << "PCREL";
  462. break;
  463. }
  464. case MachO::X86_64_RELOC_SUBTRACTOR: {
  465. DataRefImpl RelNext = Rel;
  466. Obj->moveRelocationNext(RelNext);
  467. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  468. // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
  469. // X86_64_RELOC_UNSIGNED.
  470. // NOTE: Scattered relocations don't exist on x86_64.
  471. unsigned RType = Obj->getAnyRelocationType(RENext);
  472. if (RType != MachO::X86_64_RELOC_UNSIGNED)
  473. reportError(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
  474. "X86_64_RELOC_SUBTRACTOR.");
  475. // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
  476. // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
  477. printRelocationTargetName(Obj, RENext, Fmt);
  478. Fmt << "-";
  479. printRelocationTargetName(Obj, RE, Fmt);
  480. break;
  481. }
  482. case MachO::X86_64_RELOC_TLV:
  483. printRelocationTargetName(Obj, RE, Fmt);
  484. Fmt << "@TLV";
  485. if (IsPCRel)
  486. Fmt << "P";
  487. break;
  488. case MachO::X86_64_RELOC_SIGNED_1:
  489. printRelocationTargetName(Obj, RE, Fmt);
  490. Fmt << "-1";
  491. break;
  492. case MachO::X86_64_RELOC_SIGNED_2:
  493. printRelocationTargetName(Obj, RE, Fmt);
  494. Fmt << "-2";
  495. break;
  496. case MachO::X86_64_RELOC_SIGNED_4:
  497. printRelocationTargetName(Obj, RE, Fmt);
  498. Fmt << "-4";
  499. break;
  500. default:
  501. printRelocationTargetName(Obj, RE, Fmt);
  502. break;
  503. }
  504. // X86 and ARM share some relocation types in common.
  505. } else if (Arch == Triple::x86 || Arch == Triple::arm ||
  506. Arch == Triple::ppc) {
  507. // Generic relocation types...
  508. switch (Type) {
  509. case MachO::GENERIC_RELOC_PAIR: // prints no info
  510. return Error::success();
  511. case MachO::GENERIC_RELOC_SECTDIFF: {
  512. DataRefImpl RelNext = Rel;
  513. Obj->moveRelocationNext(RelNext);
  514. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  515. // X86 sect diff's must be followed by a relocation of type
  516. // GENERIC_RELOC_PAIR.
  517. unsigned RType = Obj->getAnyRelocationType(RENext);
  518. if (RType != MachO::GENERIC_RELOC_PAIR)
  519. reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
  520. "GENERIC_RELOC_SECTDIFF.");
  521. printRelocationTargetName(Obj, RE, Fmt);
  522. Fmt << "-";
  523. printRelocationTargetName(Obj, RENext, Fmt);
  524. break;
  525. }
  526. }
  527. if (Arch == Triple::x86 || Arch == Triple::ppc) {
  528. switch (Type) {
  529. case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
  530. DataRefImpl RelNext = Rel;
  531. Obj->moveRelocationNext(RelNext);
  532. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  533. // X86 sect diff's must be followed by a relocation of type
  534. // GENERIC_RELOC_PAIR.
  535. unsigned RType = Obj->getAnyRelocationType(RENext);
  536. if (RType != MachO::GENERIC_RELOC_PAIR)
  537. reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
  538. "GENERIC_RELOC_LOCAL_SECTDIFF.");
  539. printRelocationTargetName(Obj, RE, Fmt);
  540. Fmt << "-";
  541. printRelocationTargetName(Obj, RENext, Fmt);
  542. break;
  543. }
  544. case MachO::GENERIC_RELOC_TLV: {
  545. printRelocationTargetName(Obj, RE, Fmt);
  546. Fmt << "@TLV";
  547. if (IsPCRel)
  548. Fmt << "P";
  549. break;
  550. }
  551. default:
  552. printRelocationTargetName(Obj, RE, Fmt);
  553. }
  554. } else { // ARM-specific relocations
  555. switch (Type) {
  556. case MachO::ARM_RELOC_HALF:
  557. case MachO::ARM_RELOC_HALF_SECTDIFF: {
  558. // Half relocations steal a bit from the length field to encode
  559. // whether this is an upper16 or a lower16 relocation.
  560. bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
  561. if (isUpper)
  562. Fmt << ":upper16:(";
  563. else
  564. Fmt << ":lower16:(";
  565. printRelocationTargetName(Obj, RE, Fmt);
  566. DataRefImpl RelNext = Rel;
  567. Obj->moveRelocationNext(RelNext);
  568. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  569. // ARM half relocs must be followed by a relocation of type
  570. // ARM_RELOC_PAIR.
  571. unsigned RType = Obj->getAnyRelocationType(RENext);
  572. if (RType != MachO::ARM_RELOC_PAIR)
  573. reportError(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
  574. "ARM_RELOC_HALF");
  575. // NOTE: The half of the target virtual address is stashed in the
  576. // address field of the secondary relocation, but we can't reverse
  577. // engineer the constant offset from it without decoding the movw/movt
  578. // instruction to find the other half in its immediate field.
  579. // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
  580. // symbol/section pointer of the follow-on relocation.
  581. if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
  582. Fmt << "-";
  583. printRelocationTargetName(Obj, RENext, Fmt);
  584. }
  585. Fmt << ")";
  586. break;
  587. }
  588. default: {
  589. printRelocationTargetName(Obj, RE, Fmt);
  590. }
  591. }
  592. }
  593. } else
  594. printRelocationTargetName(Obj, RE, Fmt);
  595. Fmt.flush();
  596. Result.append(FmtBuf.begin(), FmtBuf.end());
  597. return Error::success();
  598. }
  599. static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
  600. uint32_t n, uint32_t count,
  601. uint32_t stride, uint64_t addr) {
  602. MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
  603. uint32_t nindirectsyms = Dysymtab.nindirectsyms;
  604. if (n > nindirectsyms)
  605. outs() << " (entries start past the end of the indirect symbol "
  606. "table) (reserved1 field greater than the table size)";
  607. else if (n + count > nindirectsyms)
  608. outs() << " (entries extends past the end of the indirect symbol "
  609. "table)";
  610. outs() << "\n";
  611. uint32_t cputype = O->getHeader().cputype;
  612. if (cputype & MachO::CPU_ARCH_ABI64)
  613. outs() << "address index";
  614. else
  615. outs() << "address index";
  616. if (verbose)
  617. outs() << " name\n";
  618. else
  619. outs() << "\n";
  620. for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
  621. if (cputype & MachO::CPU_ARCH_ABI64)
  622. outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
  623. else
  624. outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
  625. MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
  626. uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
  627. if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
  628. outs() << "LOCAL\n";
  629. continue;
  630. }
  631. if (indirect_symbol ==
  632. (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
  633. outs() << "LOCAL ABSOLUTE\n";
  634. continue;
  635. }
  636. if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
  637. outs() << "ABSOLUTE\n";
  638. continue;
  639. }
  640. outs() << format("%5u ", indirect_symbol);
  641. if (verbose) {
  642. MachO::symtab_command Symtab = O->getSymtabLoadCommand();
  643. if (indirect_symbol < Symtab.nsyms) {
  644. symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
  645. SymbolRef Symbol = *Sym;
  646. outs() << unwrapOrError(Symbol.getName(), O->getFileName());
  647. } else {
  648. outs() << "?";
  649. }
  650. }
  651. outs() << "\n";
  652. }
  653. }
  654. static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
  655. for (const auto &Load : O->load_commands()) {
  656. if (Load.C.cmd == MachO::LC_SEGMENT_64) {
  657. MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
  658. for (unsigned J = 0; J < Seg.nsects; ++J) {
  659. MachO::section_64 Sec = O->getSection64(Load, J);
  660. uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
  661. if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
  662. section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
  663. section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
  664. section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
  665. section_type == MachO::S_SYMBOL_STUBS) {
  666. uint32_t stride;
  667. if (section_type == MachO::S_SYMBOL_STUBS)
  668. stride = Sec.reserved2;
  669. else
  670. stride = 8;
  671. if (stride == 0) {
  672. outs() << "Can't print indirect symbols for (" << Sec.segname << ","
  673. << Sec.sectname << ") "
  674. << "(size of stubs in reserved2 field is zero)\n";
  675. continue;
  676. }
  677. uint32_t count = Sec.size / stride;
  678. outs() << "Indirect symbols for (" << Sec.segname << ","
  679. << Sec.sectname << ") " << count << " entries";
  680. uint32_t n = Sec.reserved1;
  681. PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
  682. }
  683. }
  684. } else if (Load.C.cmd == MachO::LC_SEGMENT) {
  685. MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
  686. for (unsigned J = 0; J < Seg.nsects; ++J) {
  687. MachO::section Sec = O->getSection(Load, J);
  688. uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
  689. if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
  690. section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
  691. section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
  692. section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
  693. section_type == MachO::S_SYMBOL_STUBS) {
  694. uint32_t stride;
  695. if (section_type == MachO::S_SYMBOL_STUBS)
  696. stride = Sec.reserved2;
  697. else
  698. stride = 4;
  699. if (stride == 0) {
  700. outs() << "Can't print indirect symbols for (" << Sec.segname << ","
  701. << Sec.sectname << ") "
  702. << "(size of stubs in reserved2 field is zero)\n";
  703. continue;
  704. }
  705. uint32_t count = Sec.size / stride;
  706. outs() << "Indirect symbols for (" << Sec.segname << ","
  707. << Sec.sectname << ") " << count << " entries";
  708. uint32_t n = Sec.reserved1;
  709. PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
  710. }
  711. }
  712. }
  713. }
  714. }
  715. static void PrintRType(const uint64_t cputype, const unsigned r_type) {
  716. static char const *generic_r_types[] = {
  717. "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
  718. " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
  719. " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
  720. };
  721. static char const *x86_64_r_types[] = {
  722. "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
  723. "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
  724. " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
  725. };
  726. static char const *arm_r_types[] = {
  727. "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
  728. "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
  729. " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
  730. };
  731. static char const *arm64_r_types[] = {
  732. "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
  733. "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
  734. "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
  735. };
  736. if (r_type > 0xf){
  737. outs() << format("%-7u", r_type) << " ";
  738. return;
  739. }
  740. switch (cputype) {
  741. case MachO::CPU_TYPE_I386:
  742. outs() << generic_r_types[r_type];
  743. break;
  744. case MachO::CPU_TYPE_X86_64:
  745. outs() << x86_64_r_types[r_type];
  746. break;
  747. case MachO::CPU_TYPE_ARM:
  748. outs() << arm_r_types[r_type];
  749. break;
  750. case MachO::CPU_TYPE_ARM64:
  751. case MachO::CPU_TYPE_ARM64_32:
  752. outs() << arm64_r_types[r_type];
  753. break;
  754. default:
  755. outs() << format("%-7u ", r_type);
  756. }
  757. }
  758. static void PrintRLength(const uint64_t cputype, const unsigned r_type,
  759. const unsigned r_length, const bool previous_arm_half){
  760. if (cputype == MachO::CPU_TYPE_ARM &&
  761. (r_type == MachO::ARM_RELOC_HALF ||
  762. r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
  763. if ((r_length & 0x1) == 0)
  764. outs() << "lo/";
  765. else
  766. outs() << "hi/";
  767. if ((r_length & 0x1) == 0)
  768. outs() << "arm ";
  769. else
  770. outs() << "thm ";
  771. } else {
  772. switch (r_length) {
  773. case 0:
  774. outs() << "byte ";
  775. break;
  776. case 1:
  777. outs() << "word ";
  778. break;
  779. case 2:
  780. outs() << "long ";
  781. break;
  782. case 3:
  783. if (cputype == MachO::CPU_TYPE_X86_64)
  784. outs() << "quad ";
  785. else
  786. outs() << format("?(%2d) ", r_length);
  787. break;
  788. default:
  789. outs() << format("?(%2d) ", r_length);
  790. }
  791. }
  792. }
  793. static void PrintRelocationEntries(const MachOObjectFile *O,
  794. const relocation_iterator Begin,
  795. const relocation_iterator End,
  796. const uint64_t cputype,
  797. const bool verbose) {
  798. const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
  799. bool previous_arm_half = false;
  800. bool previous_sectdiff = false;
  801. uint32_t sectdiff_r_type = 0;
  802. for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
  803. const DataRefImpl Rel = Reloc->getRawDataRefImpl();
  804. const MachO::any_relocation_info RE = O->getRelocation(Rel);
  805. const unsigned r_type = O->getAnyRelocationType(RE);
  806. const bool r_scattered = O->isRelocationScattered(RE);
  807. const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
  808. const unsigned r_length = O->getAnyRelocationLength(RE);
  809. const unsigned r_address = O->getAnyRelocationAddress(RE);
  810. const bool r_extern = (r_scattered ? false :
  811. O->getPlainRelocationExternal(RE));
  812. const uint32_t r_value = (r_scattered ?
  813. O->getScatteredRelocationValue(RE) : 0);
  814. const unsigned r_symbolnum = (r_scattered ? 0 :
  815. O->getPlainRelocationSymbolNum(RE));
  816. if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
  817. if (verbose) {
  818. // scattered: address
  819. if ((cputype == MachO::CPU_TYPE_I386 &&
  820. r_type == MachO::GENERIC_RELOC_PAIR) ||
  821. (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
  822. outs() << " ";
  823. else
  824. outs() << format("%08x ", (unsigned int)r_address);
  825. // scattered: pcrel
  826. if (r_pcrel)
  827. outs() << "True ";
  828. else
  829. outs() << "False ";
  830. // scattered: length
  831. PrintRLength(cputype, r_type, r_length, previous_arm_half);
  832. // scattered: extern & type
  833. outs() << "n/a ";
  834. PrintRType(cputype, r_type);
  835. // scattered: scattered & value
  836. outs() << format("True 0x%08x", (unsigned int)r_value);
  837. if (previous_sectdiff == false) {
  838. if ((cputype == MachO::CPU_TYPE_ARM &&
  839. r_type == MachO::ARM_RELOC_PAIR))
  840. outs() << format(" half = 0x%04x ", (unsigned int)r_address);
  841. } else if (cputype == MachO::CPU_TYPE_ARM &&
  842. sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
  843. outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
  844. if ((cputype == MachO::CPU_TYPE_I386 &&
  845. (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
  846. r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
  847. (cputype == MachO::CPU_TYPE_ARM &&
  848. (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
  849. sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
  850. sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
  851. previous_sectdiff = true;
  852. sectdiff_r_type = r_type;
  853. } else {
  854. previous_sectdiff = false;
  855. sectdiff_r_type = 0;
  856. }
  857. if (cputype == MachO::CPU_TYPE_ARM &&
  858. (r_type == MachO::ARM_RELOC_HALF ||
  859. r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
  860. previous_arm_half = true;
  861. else
  862. previous_arm_half = false;
  863. outs() << "\n";
  864. }
  865. else {
  866. // scattered: address pcrel length extern type scattered value
  867. outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
  868. (unsigned int)r_address, r_pcrel, r_length, r_type,
  869. (unsigned int)r_value);
  870. }
  871. }
  872. else {
  873. if (verbose) {
  874. // plain: address
  875. if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
  876. outs() << " ";
  877. else
  878. outs() << format("%08x ", (unsigned int)r_address);
  879. // plain: pcrel
  880. if (r_pcrel)
  881. outs() << "True ";
  882. else
  883. outs() << "False ";
  884. // plain: length
  885. PrintRLength(cputype, r_type, r_length, previous_arm_half);
  886. if (r_extern) {
  887. // plain: extern & type & scattered
  888. outs() << "True ";
  889. PrintRType(cputype, r_type);
  890. outs() << "False ";
  891. // plain: symbolnum/value
  892. if (r_symbolnum > Symtab.nsyms)
  893. outs() << format("?(%d)\n", r_symbolnum);
  894. else {
  895. SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
  896. Expected<StringRef> SymNameNext = Symbol.getName();
  897. const char *name = NULL;
  898. if (SymNameNext)
  899. name = SymNameNext->data();
  900. if (name == NULL)
  901. outs() << format("?(%d)\n", r_symbolnum);
  902. else
  903. outs() << name << "\n";
  904. }
  905. }
  906. else {
  907. // plain: extern & type & scattered
  908. outs() << "False ";
  909. PrintRType(cputype, r_type);
  910. outs() << "False ";
  911. // plain: symbolnum/value
  912. if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
  913. outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
  914. else if ((cputype == MachO::CPU_TYPE_ARM64 ||
  915. cputype == MachO::CPU_TYPE_ARM64_32) &&
  916. r_type == MachO::ARM64_RELOC_ADDEND)
  917. outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
  918. else {
  919. outs() << format("%d ", r_symbolnum);
  920. if (r_symbolnum == MachO::R_ABS)
  921. outs() << "R_ABS\n";
  922. else {
  923. // in this case, r_symbolnum is actually a 1-based section number
  924. uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
  925. if (r_symbolnum > 0 && r_symbolnum <= nsects) {
  926. object::DataRefImpl DRI;
  927. DRI.d.a = r_symbolnum-1;
  928. StringRef SegName = O->getSectionFinalSegmentName(DRI);
  929. if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
  930. outs() << "(" << SegName << "," << *NameOrErr << ")\n";
  931. else
  932. outs() << "(?,?)\n";
  933. }
  934. else {
  935. outs() << "(?,?)\n";
  936. }
  937. }
  938. }
  939. }
  940. if (cputype == MachO::CPU_TYPE_ARM &&
  941. (r_type == MachO::ARM_RELOC_HALF ||
  942. r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
  943. previous_arm_half = true;
  944. else
  945. previous_arm_half = false;
  946. }
  947. else {
  948. // plain: address pcrel length extern type scattered symbolnum/section
  949. outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
  950. (unsigned int)r_address, r_pcrel, r_length, r_extern,
  951. r_type, r_symbolnum);
  952. }
  953. }
  954. }
  955. }
  956. static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
  957. const uint64_t cputype = O->getHeader().cputype;
  958. const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
  959. if (Dysymtab.nextrel != 0) {
  960. outs() << "External relocation information " << Dysymtab.nextrel
  961. << " entries";
  962. outs() << "\naddress pcrel length extern type scattered "
  963. "symbolnum/value\n";
  964. PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
  965. verbose);
  966. }
  967. if (Dysymtab.nlocrel != 0) {
  968. outs() << format("Local relocation information %u entries",
  969. Dysymtab.nlocrel);
  970. outs() << "\naddress pcrel length extern type scattered "
  971. "symbolnum/value\n";
  972. PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
  973. verbose);
  974. }
  975. for (const auto &Load : O->load_commands()) {
  976. if (Load.C.cmd == MachO::LC_SEGMENT_64) {
  977. const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
  978. for (unsigned J = 0; J < Seg.nsects; ++J) {
  979. const MachO::section_64 Sec = O->getSection64(Load, J);
  980. if (Sec.nreloc != 0) {
  981. DataRefImpl DRI;
  982. DRI.d.a = J;
  983. const StringRef SegName = O->getSectionFinalSegmentName(DRI);
  984. if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
  985. outs() << "Relocation information (" << SegName << "," << *NameOrErr
  986. << format(") %u entries", Sec.nreloc);
  987. else
  988. outs() << "Relocation information (" << SegName << ",?) "
  989. << format("%u entries", Sec.nreloc);
  990. outs() << "\naddress pcrel length extern type scattered "
  991. "symbolnum/value\n";
  992. PrintRelocationEntries(O, O->section_rel_begin(DRI),
  993. O->section_rel_end(DRI), cputype, verbose);
  994. }
  995. }
  996. } else if (Load.C.cmd == MachO::LC_SEGMENT) {
  997. const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
  998. for (unsigned J = 0; J < Seg.nsects; ++J) {
  999. const MachO::section Sec = O->getSection(Load, J);
  1000. if (Sec.nreloc != 0) {
  1001. DataRefImpl DRI;
  1002. DRI.d.a = J;
  1003. const StringRef SegName = O->getSectionFinalSegmentName(DRI);
  1004. if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
  1005. outs() << "Relocation information (" << SegName << "," << *NameOrErr
  1006. << format(") %u entries", Sec.nreloc);
  1007. else
  1008. outs() << "Relocation information (" << SegName << ",?) "
  1009. << format("%u entries", Sec.nreloc);
  1010. outs() << "\naddress pcrel length extern type scattered "
  1011. "symbolnum/value\n";
  1012. PrintRelocationEntries(O, O->section_rel_begin(DRI),
  1013. O->section_rel_end(DRI), cputype, verbose);
  1014. }
  1015. }
  1016. }
  1017. }
  1018. }
  1019. static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
  1020. MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
  1021. uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
  1022. outs() << "Data in code table (" << nentries << " entries)\n";
  1023. outs() << "offset length kind\n";
  1024. for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
  1025. ++DI) {
  1026. uint32_t Offset;
  1027. DI->getOffset(Offset);
  1028. outs() << format("0x%08" PRIx32, Offset) << " ";
  1029. uint16_t Length;
  1030. DI->getLength(Length);
  1031. outs() << format("%6u", Length) << " ";
  1032. uint16_t Kind;
  1033. DI->getKind(Kind);
  1034. if (verbose) {
  1035. switch (Kind) {
  1036. case MachO::DICE_KIND_DATA:
  1037. outs() << "DATA";
  1038. break;
  1039. case MachO::DICE_KIND_JUMP_TABLE8:
  1040. outs() << "JUMP_TABLE8";
  1041. break;
  1042. case MachO::DICE_KIND_JUMP_TABLE16:
  1043. outs() << "JUMP_TABLE16";
  1044. break;
  1045. case MachO::DICE_KIND_JUMP_TABLE32:
  1046. outs() << "JUMP_TABLE32";
  1047. break;
  1048. case MachO::DICE_KIND_ABS_JUMP_TABLE32:
  1049. outs() << "ABS_JUMP_TABLE32";
  1050. break;
  1051. default:
  1052. outs() << format("0x%04" PRIx32, Kind);
  1053. break;
  1054. }
  1055. } else
  1056. outs() << format("0x%04" PRIx32, Kind);
  1057. outs() << "\n";
  1058. }
  1059. }
  1060. static void PrintLinkOptHints(MachOObjectFile *O) {
  1061. MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
  1062. const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
  1063. uint32_t nloh = LohLC.datasize;
  1064. outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
  1065. for (uint32_t i = 0; i < nloh;) {
  1066. unsigned n;
  1067. uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
  1068. i += n;
  1069. outs() << " identifier " << identifier << " ";
  1070. if (i >= nloh)
  1071. return;
  1072. switch (identifier) {
  1073. case 1:
  1074. outs() << "AdrpAdrp\n";
  1075. break;
  1076. case 2:
  1077. outs() << "AdrpLdr\n";
  1078. break;
  1079. case 3:
  1080. outs() << "AdrpAddLdr\n";
  1081. break;
  1082. case 4:
  1083. outs() << "AdrpLdrGotLdr\n";
  1084. break;
  1085. case 5:
  1086. outs() << "AdrpAddStr\n";
  1087. break;
  1088. case 6:
  1089. outs() << "AdrpLdrGotStr\n";
  1090. break;
  1091. case 7:
  1092. outs() << "AdrpAdd\n";
  1093. break;
  1094. case 8:
  1095. outs() << "AdrpLdrGot\n";
  1096. break;
  1097. default:
  1098. outs() << "Unknown identifier value\n";
  1099. break;
  1100. }
  1101. uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
  1102. i += n;
  1103. outs() << " narguments " << narguments << "\n";
  1104. if (i >= nloh)
  1105. return;
  1106. for (uint32_t j = 0; j < narguments; j++) {
  1107. uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
  1108. i += n;
  1109. outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
  1110. if (i >= nloh)
  1111. return;
  1112. }
  1113. }
  1114. }
  1115. static void PrintDylibs(MachOObjectFile *O, bool JustId) {
  1116. unsigned Index = 0;
  1117. for (const auto &Load : O->load_commands()) {
  1118. if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
  1119. (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
  1120. Load.C.cmd == MachO::LC_LOAD_DYLIB ||
  1121. Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
  1122. Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
  1123. Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
  1124. Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
  1125. MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
  1126. if (dl.dylib.name < dl.cmdsize) {
  1127. const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
  1128. if (JustId)
  1129. outs() << p << "\n";
  1130. else {
  1131. outs() << "\t" << p;
  1132. outs() << " (compatibility version "
  1133. << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
  1134. << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
  1135. << (dl.dylib.compatibility_version & 0xff) << ",";
  1136. outs() << " current version "
  1137. << ((dl.dylib.current_version >> 16) & 0xffff) << "."
  1138. << ((dl.dylib.current_version >> 8) & 0xff) << "."
  1139. << (dl.dylib.current_version & 0xff);
  1140. if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
  1141. outs() << ", weak";
  1142. if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
  1143. outs() << ", reexport";
  1144. if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
  1145. outs() << ", upward";
  1146. if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
  1147. outs() << ", lazy";
  1148. outs() << ")\n";
  1149. }
  1150. } else {
  1151. outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
  1152. if (Load.C.cmd == MachO::LC_ID_DYLIB)
  1153. outs() << "LC_ID_DYLIB ";
  1154. else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
  1155. outs() << "LC_LOAD_DYLIB ";
  1156. else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
  1157. outs() << "LC_LOAD_WEAK_DYLIB ";
  1158. else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
  1159. outs() << "LC_LAZY_LOAD_DYLIB ";
  1160. else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
  1161. outs() << "LC_REEXPORT_DYLIB ";
  1162. else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
  1163. outs() << "LC_LOAD_UPWARD_DYLIB ";
  1164. else
  1165. outs() << "LC_??? ";
  1166. outs() << "command " << Index++ << "\n";
  1167. }
  1168. }
  1169. }
  1170. }
  1171. typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
  1172. static void CreateSymbolAddressMap(MachOObjectFile *O,
  1173. SymbolAddressMap *AddrMap) {
  1174. // Create a map of symbol addresses to symbol names.
  1175. const StringRef FileName = O->getFileName();
  1176. for (const SymbolRef &Symbol : O->symbols()) {
  1177. SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
  1178. if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
  1179. ST == SymbolRef::ST_Other) {
  1180. uint64_t Address = Symbol.getValue();
  1181. StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
  1182. if (!SymName.startswith(".objc"))
  1183. (*AddrMap)[Address] = SymName;
  1184. }
  1185. }
  1186. }
  1187. // GuessSymbolName is passed the address of what might be a symbol and a
  1188. // pointer to the SymbolAddressMap. It returns the name of a symbol
  1189. // with that address or nullptr if no symbol is found with that address.
  1190. static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
  1191. const char *SymbolName = nullptr;
  1192. // A DenseMap can't lookup up some values.
  1193. if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
  1194. StringRef name = AddrMap->lookup(value);
  1195. if (!name.empty())
  1196. SymbolName = name.data();
  1197. }
  1198. return SymbolName;
  1199. }
  1200. static void DumpCstringChar(const char c) {
  1201. char p[2];
  1202. p[0] = c;
  1203. p[1] = '\0';
  1204. outs().write_escaped(p);
  1205. }
  1206. static void DumpCstringSection(MachOObjectFile *O, const char *sect,
  1207. uint32_t sect_size, uint64_t sect_addr,
  1208. bool print_addresses) {
  1209. for (uint32_t i = 0; i < sect_size; i++) {
  1210. if (print_addresses) {
  1211. if (O->is64Bit())
  1212. outs() << format("%016" PRIx64, sect_addr + i) << " ";
  1213. else
  1214. outs() << format("%08" PRIx64, sect_addr + i) << " ";
  1215. }
  1216. for (; i < sect_size && sect[i] != '\0'; i++)
  1217. DumpCstringChar(sect[i]);
  1218. if (i < sect_size && sect[i] == '\0')
  1219. outs() << "\n";
  1220. }
  1221. }
  1222. static void DumpLiteral4(uint32_t l, float f) {
  1223. outs() << format("0x%08" PRIx32, l);
  1224. if ((l & 0x7f800000) != 0x7f800000)
  1225. outs() << format(" (%.16e)\n", f);
  1226. else {
  1227. if (l == 0x7f800000)
  1228. outs() << " (+Infinity)\n";
  1229. else if (l == 0xff800000)
  1230. outs() << " (-Infinity)\n";
  1231. else if ((l & 0x00400000) == 0x00400000)
  1232. outs() << " (non-signaling Not-a-Number)\n";
  1233. else
  1234. outs() << " (signaling Not-a-Number)\n";
  1235. }
  1236. }
  1237. static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
  1238. uint32_t sect_size, uint64_t sect_addr,
  1239. bool print_addresses) {
  1240. for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
  1241. if (print_addresses) {
  1242. if (O->is64Bit())
  1243. outs() << format("%016" PRIx64, sect_addr + i) << " ";
  1244. else
  1245. outs() << format("%08" PRIx64, sect_addr + i) << " ";
  1246. }
  1247. float f;
  1248. memcpy(&f, sect + i, sizeof(float));
  1249. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1250. sys::swapByteOrder(f);
  1251. uint32_t l;
  1252. memcpy(&l, sect + i, sizeof(uint32_t));
  1253. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1254. sys::swapByteOrder(l);
  1255. DumpLiteral4(l, f);
  1256. }
  1257. }
  1258. static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
  1259. double d) {
  1260. outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
  1261. uint32_t Hi, Lo;
  1262. Hi = (O->isLittleEndian()) ? l1 : l0;
  1263. Lo = (O->isLittleEndian()) ? l0 : l1;
  1264. // Hi is the high word, so this is equivalent to if(isfinite(d))
  1265. if ((Hi & 0x7ff00000) != 0x7ff00000)
  1266. outs() << format(" (%.16e)\n", d);
  1267. else {
  1268. if (Hi == 0x7ff00000 && Lo == 0)
  1269. outs() << " (+Infinity)\n";
  1270. else if (Hi == 0xfff00000 && Lo == 0)
  1271. outs() << " (-Infinity)\n";
  1272. else if ((Hi & 0x00080000) == 0x00080000)
  1273. outs() << " (non-signaling Not-a-Number)\n";
  1274. else
  1275. outs() << " (signaling Not-a-Number)\n";
  1276. }
  1277. }
  1278. static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
  1279. uint32_t sect_size, uint64_t sect_addr,
  1280. bool print_addresses) {
  1281. for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
  1282. if (print_addresses) {
  1283. if (O->is64Bit())
  1284. outs() << format("%016" PRIx64, sect_addr + i) << " ";
  1285. else
  1286. outs() << format("%08" PRIx64, sect_addr + i) << " ";
  1287. }
  1288. double d;
  1289. memcpy(&d, sect + i, sizeof(double));
  1290. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1291. sys::swapByteOrder(d);
  1292. uint32_t l0, l1;
  1293. memcpy(&l0, sect + i, sizeof(uint32_t));
  1294. memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
  1295. if (O->isLittleEndian() != sys::IsLittleEndianHost) {
  1296. sys::swapByteOrder(l0);
  1297. sys::swapByteOrder(l1);
  1298. }
  1299. DumpLiteral8(O, l0, l1, d);
  1300. }
  1301. }
  1302. static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
  1303. outs() << format("0x%08" PRIx32, l0) << " ";
  1304. outs() << format("0x%08" PRIx32, l1) << " ";
  1305. outs() << format("0x%08" PRIx32, l2) << " ";
  1306. outs() << format("0x%08" PRIx32, l3) << "\n";
  1307. }
  1308. static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
  1309. uint32_t sect_size, uint64_t sect_addr,
  1310. bool print_addresses) {
  1311. for (uint32_t i = 0; i < sect_size; i += 16) {
  1312. if (print_addresses) {
  1313. if (O->is64Bit())
  1314. outs() << format("%016" PRIx64, sect_addr + i) << " ";
  1315. else
  1316. outs() << format("%08" PRIx64, sect_addr + i) << " ";
  1317. }
  1318. uint32_t l0, l1, l2, l3;
  1319. memcpy(&l0, sect + i, sizeof(uint32_t));
  1320. memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
  1321. memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
  1322. memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
  1323. if (O->isLittleEndian() != sys::IsLittleEndianHost) {
  1324. sys::swapByteOrder(l0);
  1325. sys::swapByteOrder(l1);
  1326. sys::swapByteOrder(l2);
  1327. sys::swapByteOrder(l3);
  1328. }
  1329. DumpLiteral16(l0, l1, l2, l3);
  1330. }
  1331. }
  1332. static void DumpLiteralPointerSection(MachOObjectFile *O,
  1333. const SectionRef &Section,
  1334. const char *sect, uint32_t sect_size,
  1335. uint64_t sect_addr,
  1336. bool print_addresses) {
  1337. // Collect the literal sections in this Mach-O file.
  1338. std::vector<SectionRef> LiteralSections;
  1339. for (const SectionRef &Section : O->sections()) {
  1340. DataRefImpl Ref = Section.getRawDataRefImpl();
  1341. uint32_t section_type;
  1342. if (O->is64Bit()) {
  1343. const MachO::section_64 Sec = O->getSection64(Ref);
  1344. section_type = Sec.flags & MachO::SECTION_TYPE;
  1345. } else {
  1346. const MachO::section Sec = O->getSection(Ref);
  1347. section_type = Sec.flags & MachO::SECTION_TYPE;
  1348. }
  1349. if (section_type == MachO::S_CSTRING_LITERALS ||
  1350. section_type == MachO::S_4BYTE_LITERALS ||
  1351. section_type == MachO::S_8BYTE_LITERALS ||
  1352. section_type == MachO::S_16BYTE_LITERALS)
  1353. LiteralSections.push_back(Section);
  1354. }
  1355. // Set the size of the literal pointer.
  1356. uint32_t lp_size = O->is64Bit() ? 8 : 4;
  1357. // Collect the external relocation symbols for the literal pointers.
  1358. std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
  1359. for (const RelocationRef &Reloc : Section.relocations()) {
  1360. DataRefImpl Rel;
  1361. MachO::any_relocation_info RE;
  1362. bool isExtern = false;
  1363. Rel = Reloc.getRawDataRefImpl();
  1364. RE = O->getRelocation(Rel);
  1365. isExtern = O->getPlainRelocationExternal(RE);
  1366. if (isExtern) {
  1367. uint64_t RelocOffset = Reloc.getOffset();
  1368. symbol_iterator RelocSym = Reloc.getSymbol();
  1369. Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
  1370. }
  1371. }
  1372. array_pod_sort(Relocs.begin(), Relocs.end());
  1373. // Dump each literal pointer.
  1374. for (uint32_t i = 0; i < sect_size; i += lp_size) {
  1375. if (print_addresses) {
  1376. if (O->is64Bit())
  1377. outs() << format("%016" PRIx64, sect_addr + i) << " ";
  1378. else
  1379. outs() << format("%08" PRIx64, sect_addr + i) << " ";
  1380. }
  1381. uint64_t lp;
  1382. if (O->is64Bit()) {
  1383. memcpy(&lp, sect + i, sizeof(uint64_t));
  1384. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1385. sys::swapByteOrder(lp);
  1386. } else {
  1387. uint32_t li;
  1388. memcpy(&li, sect + i, sizeof(uint32_t));
  1389. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1390. sys::swapByteOrder(li);
  1391. lp = li;
  1392. }
  1393. // First look for an external relocation entry for this literal pointer.
  1394. auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
  1395. return P.first == i;
  1396. });
  1397. if (Reloc != Relocs.end()) {
  1398. symbol_iterator RelocSym = Reloc->second;
  1399. StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
  1400. outs() << "external relocation entry for symbol:" << SymName << "\n";
  1401. continue;
  1402. }
  1403. // For local references see what the section the literal pointer points to.
  1404. auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
  1405. return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
  1406. });
  1407. if (Sect == LiteralSections.end()) {
  1408. outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
  1409. continue;
  1410. }
  1411. uint64_t SectAddress = Sect->getAddress();
  1412. uint64_t SectSize = Sect->getSize();
  1413. StringRef SectName;
  1414. Expected<StringRef> SectNameOrErr = Sect->getName();
  1415. if (SectNameOrErr)
  1416. SectName = *SectNameOrErr;
  1417. else
  1418. consumeError(SectNameOrErr.takeError());
  1419. DataRefImpl Ref = Sect->getRawDataRefImpl();
  1420. StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
  1421. outs() << SegmentName << ":" << SectName << ":";
  1422. uint32_t section_type;
  1423. if (O->is64Bit()) {
  1424. const MachO::section_64 Sec = O->getSection64(Ref);
  1425. section_type = Sec.flags & MachO::SECTION_TYPE;
  1426. } else {
  1427. const MachO::section Sec = O->getSection(Ref);
  1428. section_type = Sec.flags & MachO::SECTION_TYPE;
  1429. }
  1430. StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName());
  1431. const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
  1432. switch (section_type) {
  1433. case MachO::S_CSTRING_LITERALS:
  1434. for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
  1435. i++) {
  1436. DumpCstringChar(Contents[i]);
  1437. }
  1438. outs() << "\n";
  1439. break;
  1440. case MachO::S_4BYTE_LITERALS:
  1441. float f;
  1442. memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
  1443. uint32_t l;
  1444. memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
  1445. if (O->isLittleEndian() != sys::IsLittleEndianHost) {
  1446. sys::swapByteOrder(f);
  1447. sys::swapByteOrder(l);
  1448. }
  1449. DumpLiteral4(l, f);
  1450. break;
  1451. case MachO::S_8BYTE_LITERALS: {
  1452. double d;
  1453. memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
  1454. uint32_t l0, l1;
  1455. memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
  1456. memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
  1457. sizeof(uint32_t));
  1458. if (O->isLittleEndian() != sys::IsLittleEndianHost) {
  1459. sys::swapByteOrder(f);
  1460. sys::swapByteOrder(l0);
  1461. sys::swapByteOrder(l1);
  1462. }
  1463. DumpLiteral8(O, l0, l1, d);
  1464. break;
  1465. }
  1466. case MachO::S_16BYTE_LITERALS: {
  1467. uint32_t l0, l1, l2, l3;
  1468. memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
  1469. memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
  1470. sizeof(uint32_t));
  1471. memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
  1472. sizeof(uint32_t));
  1473. memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
  1474. sizeof(uint32_t));
  1475. if (O->isLittleEndian() != sys::IsLittleEndianHost) {
  1476. sys::swapByteOrder(l0);
  1477. sys::swapByteOrder(l1);
  1478. sys::swapByteOrder(l2);
  1479. sys::swapByteOrder(l3);
  1480. }
  1481. DumpLiteral16(l0, l1, l2, l3);
  1482. break;
  1483. }
  1484. }
  1485. }
  1486. }
  1487. static void DumpInitTermPointerSection(MachOObjectFile *O,
  1488. const SectionRef &Section,
  1489. const char *sect,
  1490. uint32_t sect_size, uint64_t sect_addr,
  1491. SymbolAddressMap *AddrMap,
  1492. bool verbose) {
  1493. uint32_t stride;
  1494. stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
  1495. // Collect the external relocation symbols for the pointers.
  1496. std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
  1497. for (const RelocationRef &Reloc : Section.relocations()) {
  1498. DataRefImpl Rel;
  1499. MachO::any_relocation_info RE;
  1500. bool isExtern = false;
  1501. Rel = Reloc.getRawDataRefImpl();
  1502. RE = O->getRelocation(Rel);
  1503. isExtern = O->getPlainRelocationExternal(RE);
  1504. if (isExtern) {
  1505. uint64_t RelocOffset = Reloc.getOffset();
  1506. symbol_iterator RelocSym = Reloc.getSymbol();
  1507. Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
  1508. }
  1509. }
  1510. array_pod_sort(Relocs.begin(), Relocs.end());
  1511. for (uint32_t i = 0; i < sect_size; i += stride) {
  1512. const char *SymbolName = nullptr;
  1513. uint64_t p;
  1514. if (O->is64Bit()) {
  1515. outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
  1516. uint64_t pointer_value;
  1517. memcpy(&pointer_value, sect + i, stride);
  1518. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1519. sys::swapByteOrder(pointer_value);
  1520. outs() << format("0x%016" PRIx64, pointer_value);
  1521. p = pointer_value;
  1522. } else {
  1523. outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
  1524. uint32_t pointer_value;
  1525. memcpy(&pointer_value, sect + i, stride);
  1526. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1527. sys::swapByteOrder(pointer_value);
  1528. outs() << format("0x%08" PRIx32, pointer_value);
  1529. p = pointer_value;
  1530. }
  1531. if (verbose) {
  1532. // First look for an external relocation entry for this pointer.
  1533. auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
  1534. return P.first == i;
  1535. });
  1536. if (Reloc != Relocs.end()) {
  1537. symbol_iterator RelocSym = Reloc->second;
  1538. outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
  1539. } else {
  1540. SymbolName = GuessSymbolName(p, AddrMap);
  1541. if (SymbolName)
  1542. outs() << " " << SymbolName;
  1543. }
  1544. }
  1545. outs() << "\n";
  1546. }
  1547. }
  1548. static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
  1549. uint32_t size, uint64_t addr) {
  1550. uint32_t cputype = O->getHeader().cputype;
  1551. if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
  1552. uint32_t j;
  1553. for (uint32_t i = 0; i < size; i += j, addr += j) {
  1554. if (O->is64Bit())
  1555. outs() << format("%016" PRIx64, addr) << "\t";
  1556. else
  1557. outs() << format("%08" PRIx64, addr) << "\t";
  1558. for (j = 0; j < 16 && i + j < size; j++) {
  1559. uint8_t byte_word = *(sect + i + j);
  1560. outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
  1561. }
  1562. outs() << "\n";
  1563. }
  1564. } else {
  1565. uint32_t j;
  1566. for (uint32_t i = 0; i < size; i += j, addr += j) {
  1567. if (O->is64Bit())
  1568. outs() << format("%016" PRIx64, addr) << "\t";
  1569. else
  1570. outs() << format("%08" PRIx64, addr) << "\t";
  1571. for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
  1572. j += sizeof(int32_t)) {
  1573. if (i + j + sizeof(int32_t) <= size) {
  1574. uint32_t long_word;
  1575. memcpy(&long_word, sect + i + j, sizeof(int32_t));
  1576. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  1577. sys::swapByteOrder(long_word);
  1578. outs() << format("%08" PRIx32, long_word) << " ";
  1579. } else {
  1580. for (uint32_t k = 0; i + j + k < size; k++) {
  1581. uint8_t byte_word = *(sect + i + j + k);
  1582. outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
  1583. }
  1584. }
  1585. }
  1586. outs() << "\n";
  1587. }
  1588. }
  1589. }
  1590. static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
  1591. StringRef DisSegName, StringRef DisSectName);
  1592. static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
  1593. uint32_t size, uint32_t addr);
  1594. #ifdef HAVE_LIBXAR
  1595. static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
  1596. uint32_t size, bool verbose,
  1597. bool PrintXarHeader, bool PrintXarFileHeaders,
  1598. std::string XarMemberName);
  1599. #endif // defined(HAVE_LIBXAR)
  1600. static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
  1601. bool verbose) {
  1602. SymbolAddressMap AddrMap;
  1603. if (verbose)
  1604. CreateSymbolAddressMap(O, &AddrMap);
  1605. for (unsigned i = 0; i < FilterSections.size(); ++i) {
  1606. StringRef DumpSection = FilterSections[i];
  1607. std::pair<StringRef, StringRef> DumpSegSectName;
  1608. DumpSegSectName = DumpSection.split(',');
  1609. StringRef DumpSegName, DumpSectName;
  1610. if (!DumpSegSectName.second.empty()) {
  1611. DumpSegName = DumpSegSectName.first;
  1612. DumpSectName = DumpSegSectName.second;
  1613. } else {
  1614. DumpSegName = "";
  1615. DumpSectName = DumpSegSectName.first;
  1616. }
  1617. for (const SectionRef &Section : O->sections()) {
  1618. StringRef SectName;
  1619. Expected<StringRef> SecNameOrErr = Section.getName();
  1620. if (SecNameOrErr)
  1621. SectName = *SecNameOrErr;
  1622. else
  1623. consumeError(SecNameOrErr.takeError());
  1624. DataRefImpl Ref = Section.getRawDataRefImpl();
  1625. StringRef SegName = O->getSectionFinalSegmentName(Ref);
  1626. if ((DumpSegName.empty() || SegName == DumpSegName) &&
  1627. (SectName == DumpSectName)) {
  1628. uint32_t section_flags;
  1629. if (O->is64Bit()) {
  1630. const MachO::section_64 Sec = O->getSection64(Ref);
  1631. section_flags = Sec.flags;
  1632. } else {
  1633. const MachO::section Sec = O->getSection(Ref);
  1634. section_flags = Sec.flags;
  1635. }
  1636. uint32_t section_type = section_flags & MachO::SECTION_TYPE;
  1637. StringRef BytesStr =
  1638. unwrapOrError(Section.getContents(), O->getFileName());
  1639. const char *sect = reinterpret_cast<const char *>(BytesStr.data());
  1640. uint32_t sect_size = BytesStr.size();
  1641. uint64_t sect_addr = Section.getAddress();
  1642. outs() << "Contents of (" << SegName << "," << SectName
  1643. << ") section\n";
  1644. if (verbose) {
  1645. if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
  1646. (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
  1647. DisassembleMachO(Filename, O, SegName, SectName);
  1648. continue;
  1649. }
  1650. if (SegName == "__TEXT" && SectName == "__info_plist") {
  1651. outs() << sect;
  1652. continue;
  1653. }
  1654. if (SegName == "__OBJC" && SectName == "__protocol") {
  1655. DumpProtocolSection(O, sect, sect_size, sect_addr);
  1656. continue;
  1657. }
  1658. #ifdef HAVE_LIBXAR
  1659. if (SegName == "__LLVM" && SectName == "__bundle") {
  1660. DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
  1661. ArchiveHeaders, "");
  1662. continue;
  1663. }
  1664. #endif // defined(HAVE_LIBXAR)
  1665. switch (section_type) {
  1666. case MachO::S_REGULAR:
  1667. DumpRawSectionContents(O, sect, sect_size, sect_addr);
  1668. break;
  1669. case MachO::S_ZEROFILL:
  1670. outs() << "zerofill section and has no contents in the file\n";
  1671. break;
  1672. case MachO::S_CSTRING_LITERALS:
  1673. DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
  1674. break;
  1675. case MachO::S_4BYTE_LITERALS:
  1676. DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
  1677. break;
  1678. case MachO::S_8BYTE_LITERALS:
  1679. DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
  1680. break;
  1681. case MachO::S_16BYTE_LITERALS:
  1682. DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
  1683. break;
  1684. case MachO::S_LITERAL_POINTERS:
  1685. DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
  1686. !NoLeadingAddr);
  1687. break;
  1688. case MachO::S_MOD_INIT_FUNC_POINTERS:
  1689. case MachO::S_MOD_TERM_FUNC_POINTERS:
  1690. DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
  1691. &AddrMap, verbose);
  1692. break;
  1693. default:
  1694. outs() << "Unknown section type ("
  1695. << format("0x%08" PRIx32, section_type) << ")\n";
  1696. DumpRawSectionContents(O, sect, sect_size, sect_addr);
  1697. break;
  1698. }
  1699. } else {
  1700. if (section_type == MachO::S_ZEROFILL)
  1701. outs() << "zerofill section and has no contents in the file\n";
  1702. else
  1703. DumpRawSectionContents(O, sect, sect_size, sect_addr);
  1704. }
  1705. }
  1706. }
  1707. }
  1708. }
  1709. static void DumpInfoPlistSectionContents(StringRef Filename,
  1710. MachOObjectFile *O) {
  1711. for (const SectionRef &Section : O->sections()) {
  1712. StringRef SectName;
  1713. Expected<StringRef> SecNameOrErr = Section.getName();
  1714. if (SecNameOrErr)
  1715. SectName = *SecNameOrErr;
  1716. else
  1717. consumeError(SecNameOrErr.takeError());
  1718. DataRefImpl Ref = Section.getRawDataRefImpl();
  1719. StringRef SegName = O->getSectionFinalSegmentName(Ref);
  1720. if (SegName == "__TEXT" && SectName == "__info_plist") {
  1721. if (!NoLeadingHeaders)
  1722. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  1723. StringRef BytesStr =
  1724. unwrapOrError(Section.getContents(), O->getFileName());
  1725. const char *sect = reinterpret_cast<const char *>(BytesStr.data());
  1726. outs() << format("%.*s", BytesStr.size(), sect) << "\n";
  1727. return;
  1728. }
  1729. }
  1730. }
  1731. // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
  1732. // and if it is and there is a list of architecture flags is specified then
  1733. // check to make sure this Mach-O file is one of those architectures or all
  1734. // architectures were specified. If not then an error is generated and this
  1735. // routine returns false. Else it returns true.
  1736. static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
  1737. auto *MachO = dyn_cast<MachOObjectFile>(O);
  1738. if (!MachO || ArchAll || ArchFlags.empty())
  1739. return true;
  1740. MachO::mach_header H;
  1741. MachO::mach_header_64 H_64;
  1742. Triple T;
  1743. const char *McpuDefault, *ArchFlag;
  1744. if (MachO->is64Bit()) {
  1745. H_64 = MachO->MachOObjectFile::getHeader64();
  1746. T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
  1747. &McpuDefault, &ArchFlag);
  1748. } else {
  1749. H = MachO->MachOObjectFile::getHeader();
  1750. T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
  1751. &McpuDefault, &ArchFlag);
  1752. }
  1753. const std::string ArchFlagName(ArchFlag);
  1754. if (none_of(ArchFlags, [&](const std::string &Name) {
  1755. return Name == ArchFlagName;
  1756. })) {
  1757. WithColor::error(errs(), "llvm-objdump")
  1758. << Filename << ": no architecture specified.\n";
  1759. return false;
  1760. }
  1761. return true;
  1762. }
  1763. static void printObjcMetaData(MachOObjectFile *O, bool verbose);
  1764. // ProcessMachO() is passed a single opened Mach-O file, which may be an
  1765. // archive member and or in a slice of a universal file. It prints the
  1766. // the file name and header info and then processes it according to the
  1767. // command line options.
  1768. static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
  1769. StringRef ArchiveMemberName = StringRef(),
  1770. StringRef ArchitectureName = StringRef()) {
  1771. // If we are doing some processing here on the Mach-O file print the header
  1772. // info. And don't print it otherwise like in the case of printing the
  1773. // UniversalHeaders or ArchiveHeaders.
  1774. if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
  1775. Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
  1776. DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
  1777. (!FilterSections.empty())) {
  1778. if (!NoLeadingHeaders) {
  1779. outs() << Name;
  1780. if (!ArchiveMemberName.empty())
  1781. outs() << '(' << ArchiveMemberName << ')';
  1782. if (!ArchitectureName.empty())
  1783. outs() << " (architecture " << ArchitectureName << ")";
  1784. outs() << ":\n";
  1785. }
  1786. }
  1787. // To use the report_error() form with an ArchiveName and FileName set
  1788. // these up based on what is passed for Name and ArchiveMemberName.
  1789. StringRef ArchiveName;
  1790. StringRef FileName;
  1791. if (!ArchiveMemberName.empty()) {
  1792. ArchiveName = Name;
  1793. FileName = ArchiveMemberName;
  1794. } else {
  1795. ArchiveName = StringRef();
  1796. FileName = Name;
  1797. }
  1798. // If we need the symbol table to do the operation then check it here to
  1799. // produce a good error message as to where the Mach-O file comes from in
  1800. // the error message.
  1801. if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
  1802. if (Error Err = MachOOF->checkSymbolTable())
  1803. reportError(std::move(Err), FileName, ArchiveName, ArchitectureName);
  1804. if (DisassembleAll) {
  1805. for (const SectionRef &Section : MachOOF->sections()) {
  1806. StringRef SectName;
  1807. if (Expected<StringRef> NameOrErr = Section.getName())
  1808. SectName = *NameOrErr;
  1809. else
  1810. consumeError(NameOrErr.takeError());
  1811. if (SectName.equals("__text")) {
  1812. DataRefImpl Ref = Section.getRawDataRefImpl();
  1813. StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
  1814. DisassembleMachO(FileName, MachOOF, SegName, SectName);
  1815. }
  1816. }
  1817. }
  1818. else if (Disassemble) {
  1819. if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
  1820. MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
  1821. DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
  1822. else
  1823. DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
  1824. }
  1825. if (IndirectSymbols)
  1826. PrintIndirectSymbols(MachOOF, !NonVerbose);
  1827. if (DataInCode)
  1828. PrintDataInCodeTable(MachOOF, !NonVerbose);
  1829. if (LinkOptHints)
  1830. PrintLinkOptHints(MachOOF);
  1831. if (Relocations)
  1832. PrintRelocations(MachOOF, !NonVerbose);
  1833. if (SectionHeaders)
  1834. printSectionHeaders(MachOOF);
  1835. if (SectionContents)
  1836. printSectionContents(MachOOF);
  1837. if (!FilterSections.empty())
  1838. DumpSectionContents(FileName, MachOOF, !NonVerbose);
  1839. if (InfoPlist)
  1840. DumpInfoPlistSectionContents(FileName, MachOOF);
  1841. if (DylibsUsed)
  1842. PrintDylibs(MachOOF, false);
  1843. if (DylibId)
  1844. PrintDylibs(MachOOF, true);
  1845. if (SymbolTable)
  1846. printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
  1847. if (UnwindInfo)
  1848. printMachOUnwindInfo(MachOOF);
  1849. if (PrivateHeaders) {
  1850. printMachOFileHeader(MachOOF);
  1851. printMachOLoadCommands(MachOOF);
  1852. }
  1853. if (FirstPrivateHeader)
  1854. printMachOFileHeader(MachOOF);
  1855. if (ObjcMetaData)
  1856. printObjcMetaData(MachOOF, !NonVerbose);
  1857. if (ExportsTrie)
  1858. printExportsTrie(MachOOF);
  1859. if (Rebase)
  1860. printRebaseTable(MachOOF);
  1861. if (Bind)
  1862. printBindTable(MachOOF);
  1863. if (LazyBind)
  1864. printLazyBindTable(MachOOF);
  1865. if (WeakBind)
  1866. printWeakBindTable(MachOOF);
  1867. if (DwarfDumpType != DIDT_Null) {
  1868. std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
  1869. // Dump the complete DWARF structure.
  1870. DIDumpOptions DumpOpts;
  1871. DumpOpts.DumpType = DwarfDumpType;
  1872. DICtx->dump(outs(), DumpOpts);
  1873. }
  1874. }
  1875. // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
  1876. static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
  1877. outs() << " cputype (" << cputype << ")\n";
  1878. outs() << " cpusubtype (" << cpusubtype << ")\n";
  1879. }
  1880. // printCPUType() helps print_fat_headers by printing the cputype and
  1881. // pusubtype (symbolically for the one's it knows about).
  1882. static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
  1883. switch (cputype) {
  1884. case MachO::CPU_TYPE_I386:
  1885. switch (cpusubtype) {
  1886. case MachO::CPU_SUBTYPE_I386_ALL:
  1887. outs() << " cputype CPU_TYPE_I386\n";
  1888. outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
  1889. break;
  1890. default:
  1891. printUnknownCPUType(cputype, cpusubtype);
  1892. break;
  1893. }
  1894. break;
  1895. case MachO::CPU_TYPE_X86_64:
  1896. switch (cpusubtype) {
  1897. case MachO::CPU_SUBTYPE_X86_64_ALL:
  1898. outs() << " cputype CPU_TYPE_X86_64\n";
  1899. outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
  1900. break;
  1901. case MachO::CPU_SUBTYPE_X86_64_H:
  1902. outs() << " cputype CPU_TYPE_X86_64\n";
  1903. outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
  1904. break;
  1905. default:
  1906. printUnknownCPUType(cputype, cpusubtype);
  1907. break;
  1908. }
  1909. break;
  1910. case MachO::CPU_TYPE_ARM:
  1911. switch (cpusubtype) {
  1912. case MachO::CPU_SUBTYPE_ARM_ALL:
  1913. outs() << " cputype CPU_TYPE_ARM\n";
  1914. outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
  1915. break;
  1916. case MachO::CPU_SUBTYPE_ARM_V4T:
  1917. outs() << " cputype CPU_TYPE_ARM\n";
  1918. outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
  1919. break;
  1920. case MachO::CPU_SUBTYPE_ARM_V5TEJ:
  1921. outs() << " cputype CPU_TYPE_ARM\n";
  1922. outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
  1923. break;
  1924. case MachO::CPU_SUBTYPE_ARM_XSCALE:
  1925. outs() << " cputype CPU_TYPE_ARM\n";
  1926. outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
  1927. break;
  1928. case MachO::CPU_SUBTYPE_ARM_V6:
  1929. outs() << " cputype CPU_TYPE_ARM\n";
  1930. outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
  1931. break;
  1932. case MachO::CPU_SUBTYPE_ARM_V6M:
  1933. outs() << " cputype CPU_TYPE_ARM\n";
  1934. outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
  1935. break;
  1936. case MachO::CPU_SUBTYPE_ARM_V7:
  1937. outs() << " cputype CPU_TYPE_ARM\n";
  1938. outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
  1939. break;
  1940. case MachO::CPU_SUBTYPE_ARM_V7EM:
  1941. outs() << " cputype CPU_TYPE_ARM\n";
  1942. outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
  1943. break;
  1944. case MachO::CPU_SUBTYPE_ARM_V7K:
  1945. outs() << " cputype CPU_TYPE_ARM\n";
  1946. outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
  1947. break;
  1948. case MachO::CPU_SUBTYPE_ARM_V7M:
  1949. outs() << " cputype CPU_TYPE_ARM\n";
  1950. outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
  1951. break;
  1952. case MachO::CPU_SUBTYPE_ARM_V7S:
  1953. outs() << " cputype CPU_TYPE_ARM\n";
  1954. outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
  1955. break;
  1956. default:
  1957. printUnknownCPUType(cputype, cpusubtype);
  1958. break;
  1959. }
  1960. break;
  1961. case MachO::CPU_TYPE_ARM64:
  1962. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  1963. case MachO::CPU_SUBTYPE_ARM64_ALL:
  1964. outs() << " cputype CPU_TYPE_ARM64\n";
  1965. outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
  1966. break;
  1967. case MachO::CPU_SUBTYPE_ARM64E:
  1968. outs() << " cputype CPU_TYPE_ARM64\n";
  1969. outs() << " cpusubtype CPU_SUBTYPE_ARM64E\n";
  1970. break;
  1971. default:
  1972. printUnknownCPUType(cputype, cpusubtype);
  1973. break;
  1974. }
  1975. break;
  1976. case MachO::CPU_TYPE_ARM64_32:
  1977. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  1978. case MachO::CPU_SUBTYPE_ARM64_32_V8:
  1979. outs() << " cputype CPU_TYPE_ARM64_32\n";
  1980. outs() << " cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
  1981. break;
  1982. default:
  1983. printUnknownCPUType(cputype, cpusubtype);
  1984. break;
  1985. }
  1986. break;
  1987. default:
  1988. printUnknownCPUType(cputype, cpusubtype);
  1989. break;
  1990. }
  1991. }
  1992. static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
  1993. bool verbose) {
  1994. outs() << "Fat headers\n";
  1995. if (verbose) {
  1996. if (UB->getMagic() == MachO::FAT_MAGIC)
  1997. outs() << "fat_magic FAT_MAGIC\n";
  1998. else // UB->getMagic() == MachO::FAT_MAGIC_64
  1999. outs() << "fat_magic FAT_MAGIC_64\n";
  2000. } else
  2001. outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
  2002. uint32_t nfat_arch = UB->getNumberOfObjects();
  2003. StringRef Buf = UB->getData();
  2004. uint64_t size = Buf.size();
  2005. uint64_t big_size = sizeof(struct MachO::fat_header) +
  2006. nfat_arch * sizeof(struct MachO::fat_arch);
  2007. outs() << "nfat_arch " << UB->getNumberOfObjects();
  2008. if (nfat_arch == 0)
  2009. outs() << " (malformed, contains zero architecture types)\n";
  2010. else if (big_size > size)
  2011. outs() << " (malformed, architectures past end of file)\n";
  2012. else
  2013. outs() << "\n";
  2014. for (uint32_t i = 0; i < nfat_arch; ++i) {
  2015. MachOUniversalBinary::ObjectForArch OFA(UB, i);
  2016. uint32_t cputype = OFA.getCPUType();
  2017. uint32_t cpusubtype = OFA.getCPUSubType();
  2018. outs() << "architecture ";
  2019. for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
  2020. MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
  2021. uint32_t other_cputype = other_OFA.getCPUType();
  2022. uint32_t other_cpusubtype = other_OFA.getCPUSubType();
  2023. if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
  2024. (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
  2025. (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
  2026. outs() << "(illegal duplicate architecture) ";
  2027. break;
  2028. }
  2029. }
  2030. if (verbose) {
  2031. outs() << OFA.getArchFlagName() << "\n";
  2032. printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  2033. } else {
  2034. outs() << i << "\n";
  2035. outs() << " cputype " << cputype << "\n";
  2036. outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
  2037. << "\n";
  2038. }
  2039. if (verbose &&
  2040. (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
  2041. outs() << " capabilities CPU_SUBTYPE_LIB64\n";
  2042. else
  2043. outs() << " capabilities "
  2044. << format("0x%" PRIx32,
  2045. (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
  2046. outs() << " offset " << OFA.getOffset();
  2047. if (OFA.getOffset() > size)
  2048. outs() << " (past end of file)";
  2049. if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
  2050. outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
  2051. outs() << "\n";
  2052. outs() << " size " << OFA.getSize();
  2053. big_size = OFA.getOffset() + OFA.getSize();
  2054. if (big_size > size)
  2055. outs() << " (past end of file)";
  2056. outs() << "\n";
  2057. outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
  2058. << ")\n";
  2059. }
  2060. }
  2061. static void printArchiveChild(StringRef Filename, const Archive::Child &C,
  2062. size_t ChildIndex, bool verbose,
  2063. bool print_offset,
  2064. StringRef ArchitectureName = StringRef()) {
  2065. if (print_offset)
  2066. outs() << C.getChildOffset() << "\t";
  2067. sys::fs::perms Mode =
  2068. unwrapOrError(C.getAccessMode(), getFileNameForError(C, ChildIndex),
  2069. Filename, ArchitectureName);
  2070. if (verbose) {
  2071. // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
  2072. // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
  2073. outs() << "-";
  2074. outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
  2075. outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
  2076. outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
  2077. outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
  2078. outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
  2079. outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
  2080. outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
  2081. outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
  2082. outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
  2083. } else {
  2084. outs() << format("0%o ", Mode);
  2085. }
  2086. outs() << format("%3d/%-3d %5" PRId64 " ",
  2087. unwrapOrError(C.getUID(), getFileNameForError(C, ChildIndex),
  2088. Filename, ArchitectureName),
  2089. unwrapOrError(C.getGID(), getFileNameForError(C, ChildIndex),
  2090. Filename, ArchitectureName),
  2091. unwrapOrError(C.getRawSize(),
  2092. getFileNameForError(C, ChildIndex), Filename,
  2093. ArchitectureName));
  2094. StringRef RawLastModified = C.getRawLastModified();
  2095. if (verbose) {
  2096. unsigned Seconds;
  2097. if (RawLastModified.getAsInteger(10, Seconds))
  2098. outs() << "(date: \"" << RawLastModified
  2099. << "\" contains non-decimal chars) ";
  2100. else {
  2101. // Since cime(3) returns a 26 character string of the form:
  2102. // "Sun Sep 16 01:03:52 1973\n\0"
  2103. // just print 24 characters.
  2104. time_t t = Seconds;
  2105. outs() << format("%.24s ", ctime(&t));
  2106. }
  2107. } else {
  2108. outs() << RawLastModified << " ";
  2109. }
  2110. if (verbose) {
  2111. Expected<StringRef> NameOrErr = C.getName();
  2112. if (!NameOrErr) {
  2113. consumeError(NameOrErr.takeError());
  2114. outs() << unwrapOrError(C.getRawName(),
  2115. getFileNameForError(C, ChildIndex), Filename,
  2116. ArchitectureName)
  2117. << "\n";
  2118. } else {
  2119. StringRef Name = NameOrErr.get();
  2120. outs() << Name << "\n";
  2121. }
  2122. } else {
  2123. outs() << unwrapOrError(C.getRawName(), getFileNameForError(C, ChildIndex),
  2124. Filename, ArchitectureName)
  2125. << "\n";
  2126. }
  2127. }
  2128. static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
  2129. bool print_offset,
  2130. StringRef ArchitectureName = StringRef()) {
  2131. Error Err = Error::success();
  2132. size_t I = 0;
  2133. for (const auto &C : A->children(Err, false))
  2134. printArchiveChild(Filename, C, I++, verbose, print_offset,
  2135. ArchitectureName);
  2136. if (Err)
  2137. reportError(std::move(Err), Filename, "", ArchitectureName);
  2138. }
  2139. static bool ValidateArchFlags() {
  2140. // Check for -arch all and verifiy the -arch flags are valid.
  2141. for (unsigned i = 0; i < ArchFlags.size(); ++i) {
  2142. if (ArchFlags[i] == "all") {
  2143. ArchAll = true;
  2144. } else {
  2145. if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
  2146. WithColor::error(errs(), "llvm-objdump")
  2147. << "unknown architecture named '" + ArchFlags[i] +
  2148. "'for the -arch option\n";
  2149. return false;
  2150. }
  2151. }
  2152. }
  2153. return true;
  2154. }
  2155. // ParseInputMachO() parses the named Mach-O file in Filename and handles the
  2156. // -arch flags selecting just those slices as specified by them and also parses
  2157. // archive files. Then for each individual Mach-O file ProcessMachO() is
  2158. // called to process the file based on the command line options.
  2159. void parseInputMachO(StringRef Filename) {
  2160. if (!ValidateArchFlags())
  2161. return;
  2162. // Attempt to open the binary.
  2163. Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
  2164. if (!BinaryOrErr) {
  2165. if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
  2166. reportError(std::move(E), Filename);
  2167. else
  2168. outs() << Filename << ": is not an object file\n";
  2169. return;
  2170. }
  2171. Binary &Bin = *BinaryOrErr.get().getBinary();
  2172. if (Archive *A = dyn_cast<Archive>(&Bin)) {
  2173. outs() << "Archive : " << Filename << "\n";
  2174. if (ArchiveHeaders)
  2175. printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
  2176. Error Err = Error::success();
  2177. unsigned I = -1;
  2178. for (auto &C : A->children(Err)) {
  2179. ++I;
  2180. Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
  2181. if (!ChildOrErr) {
  2182. if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
  2183. reportError(std::move(E), getFileNameForError(C, I), Filename);
  2184. continue;
  2185. }
  2186. if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
  2187. if (!checkMachOAndArchFlags(O, Filename))
  2188. return;
  2189. ProcessMachO(Filename, O, O->getFileName());
  2190. }
  2191. }
  2192. if (Err)
  2193. reportError(std::move(Err), Filename);
  2194. return;
  2195. }
  2196. if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
  2197. parseInputMachO(UB);
  2198. return;
  2199. }
  2200. if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
  2201. if (!checkMachOAndArchFlags(O, Filename))
  2202. return;
  2203. if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
  2204. ProcessMachO(Filename, MachOOF);
  2205. else
  2206. WithColor::error(errs(), "llvm-objdump")
  2207. << Filename << "': "
  2208. << "object is not a Mach-O file type.\n";
  2209. return;
  2210. }
  2211. llvm_unreachable("Input object can't be invalid at this point");
  2212. }
  2213. void parseInputMachO(MachOUniversalBinary *UB) {
  2214. if (!ValidateArchFlags())
  2215. return;
  2216. auto Filename = UB->getFileName();
  2217. if (UniversalHeaders)
  2218. printMachOUniversalHeaders(UB, !NonVerbose);
  2219. // If we have a list of architecture flags specified dump only those.
  2220. if (!ArchAll && !ArchFlags.empty()) {
  2221. // Look for a slice in the universal binary that matches each ArchFlag.
  2222. bool ArchFound;
  2223. for (unsigned i = 0; i < ArchFlags.size(); ++i) {
  2224. ArchFound = false;
  2225. for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
  2226. E = UB->end_objects();
  2227. I != E; ++I) {
  2228. if (ArchFlags[i] == I->getArchFlagName()) {
  2229. ArchFound = true;
  2230. Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
  2231. I->getAsObjectFile();
  2232. std::string ArchitectureName = "";
  2233. if (ArchFlags.size() > 1)
  2234. ArchitectureName = I->getArchFlagName();
  2235. if (ObjOrErr) {
  2236. ObjectFile &O = *ObjOrErr.get();
  2237. if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
  2238. ProcessMachO(Filename, MachOOF, "", ArchitectureName);
  2239. } else if (Error E = isNotObjectErrorInvalidFileType(
  2240. ObjOrErr.takeError())) {
  2241. reportError(std::move(E), "", Filename, ArchitectureName);
  2242. continue;
  2243. } else if (Expected<std::unique_ptr<Archive>> AOrErr =
  2244. I->getAsArchive()) {
  2245. std::unique_ptr<Archive> &A = *AOrErr;
  2246. outs() << "Archive : " << Filename;
  2247. if (!ArchitectureName.empty())
  2248. outs() << " (architecture " << ArchitectureName << ")";
  2249. outs() << "\n";
  2250. if (ArchiveHeaders)
  2251. printArchiveHeaders(Filename, A.get(), !NonVerbose,
  2252. ArchiveMemberOffsets, ArchitectureName);
  2253. Error Err = Error::success();
  2254. unsigned I = -1;
  2255. for (auto &C : A->children(Err)) {
  2256. ++I;
  2257. Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
  2258. if (!ChildOrErr) {
  2259. if (Error E =
  2260. isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
  2261. reportError(std::move(E), getFileNameForError(C, I), Filename,
  2262. ArchitectureName);
  2263. continue;
  2264. }
  2265. if (MachOObjectFile *O =
  2266. dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
  2267. ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
  2268. }
  2269. if (Err)
  2270. reportError(std::move(Err), Filename);
  2271. } else {
  2272. consumeError(AOrErr.takeError());
  2273. reportError(Filename,
  2274. "Mach-O universal file for architecture " +
  2275. StringRef(I->getArchFlagName()) +
  2276. " is not a Mach-O file or an archive file");
  2277. }
  2278. }
  2279. }
  2280. if (!ArchFound) {
  2281. WithColor::error(errs(), "llvm-objdump")
  2282. << "file: " + Filename + " does not contain "
  2283. << "architecture: " + ArchFlags[i] + "\n";
  2284. return;
  2285. }
  2286. }
  2287. return;
  2288. }
  2289. // No architecture flags were specified so if this contains a slice that
  2290. // matches the host architecture dump only that.
  2291. if (!ArchAll) {
  2292. for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
  2293. E = UB->end_objects();
  2294. I != E; ++I) {
  2295. if (MachOObjectFile::getHostArch().getArchName() ==
  2296. I->getArchFlagName()) {
  2297. Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
  2298. std::string ArchiveName;
  2299. ArchiveName.clear();
  2300. if (ObjOrErr) {
  2301. ObjectFile &O = *ObjOrErr.get();
  2302. if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
  2303. ProcessMachO(Filename, MachOOF);
  2304. } else if (Error E =
  2305. isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
  2306. reportError(std::move(E), Filename);
  2307. } else if (Expected<std::unique_ptr<Archive>> AOrErr =
  2308. I->getAsArchive()) {
  2309. std::unique_ptr<Archive> &A = *AOrErr;
  2310. outs() << "Archive : " << Filename << "\n";
  2311. if (ArchiveHeaders)
  2312. printArchiveHeaders(Filename, A.get(), !NonVerbose,
  2313. ArchiveMemberOffsets);
  2314. Error Err = Error::success();
  2315. unsigned I = -1;
  2316. for (auto &C : A->children(Err)) {
  2317. ++I;
  2318. Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
  2319. if (!ChildOrErr) {
  2320. if (Error E =
  2321. isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
  2322. reportError(std::move(E), getFileNameForError(C, I), Filename);
  2323. continue;
  2324. }
  2325. if (MachOObjectFile *O =
  2326. dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
  2327. ProcessMachO(Filename, O, O->getFileName());
  2328. }
  2329. if (Err)
  2330. reportError(std::move(Err), Filename);
  2331. } else {
  2332. consumeError(AOrErr.takeError());
  2333. reportError(Filename, "Mach-O universal file for architecture " +
  2334. StringRef(I->getArchFlagName()) +
  2335. " is not a Mach-O file or an archive file");
  2336. }
  2337. return;
  2338. }
  2339. }
  2340. }
  2341. // Either all architectures have been specified or none have been specified
  2342. // and this does not contain the host architecture so dump all the slices.
  2343. bool moreThanOneArch = UB->getNumberOfObjects() > 1;
  2344. for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
  2345. E = UB->end_objects();
  2346. I != E; ++I) {
  2347. Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
  2348. std::string ArchitectureName = "";
  2349. if (moreThanOneArch)
  2350. ArchitectureName = I->getArchFlagName();
  2351. if (ObjOrErr) {
  2352. ObjectFile &Obj = *ObjOrErr.get();
  2353. if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
  2354. ProcessMachO(Filename, MachOOF, "", ArchitectureName);
  2355. } else if (Error E =
  2356. isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
  2357. reportError(std::move(E), Filename, "", ArchitectureName);
  2358. } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
  2359. std::unique_ptr<Archive> &A = *AOrErr;
  2360. outs() << "Archive : " << Filename;
  2361. if (!ArchitectureName.empty())
  2362. outs() << " (architecture " << ArchitectureName << ")";
  2363. outs() << "\n";
  2364. if (ArchiveHeaders)
  2365. printArchiveHeaders(Filename, A.get(), !NonVerbose,
  2366. ArchiveMemberOffsets, ArchitectureName);
  2367. Error Err = Error::success();
  2368. unsigned I = -1;
  2369. for (auto &C : A->children(Err)) {
  2370. ++I;
  2371. Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
  2372. if (!ChildOrErr) {
  2373. if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
  2374. reportError(std::move(E), getFileNameForError(C, I), Filename,
  2375. ArchitectureName);
  2376. continue;
  2377. }
  2378. if (MachOObjectFile *O =
  2379. dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
  2380. if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
  2381. ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
  2382. ArchitectureName);
  2383. }
  2384. }
  2385. if (Err)
  2386. reportError(std::move(Err), Filename);
  2387. } else {
  2388. consumeError(AOrErr.takeError());
  2389. reportError(Filename, "Mach-O universal file for architecture " +
  2390. StringRef(I->getArchFlagName()) +
  2391. " is not a Mach-O file or an archive file");
  2392. }
  2393. }
  2394. }
  2395. // The block of info used by the Symbolizer call backs.
  2396. struct DisassembleInfo {
  2397. DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
  2398. std::vector<SectionRef> *Sections, bool verbose)
  2399. : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
  2400. bool verbose;
  2401. MachOObjectFile *O;
  2402. SectionRef S;
  2403. SymbolAddressMap *AddrMap;
  2404. std::vector<SectionRef> *Sections;
  2405. const char *class_name = nullptr;
  2406. const char *selector_name = nullptr;
  2407. std::unique_ptr<char[]> method = nullptr;
  2408. char *demangled_name = nullptr;
  2409. uint64_t adrp_addr = 0;
  2410. uint32_t adrp_inst = 0;
  2411. std::unique_ptr<SymbolAddressMap> bindtable;
  2412. uint32_t depth = 0;
  2413. };
  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 = 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. // These are structs in the Objective-C meta data and read to produce the
  3196. // comments for disassembly. While these are part of the ABI they are no
  3197. // public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
  3198. // .
  3199. // The cfstring object in a 64-bit Mach-O file.
  3200. struct cfstring64_t {
  3201. uint64_t isa; // class64_t * (64-bit pointer)
  3202. uint64_t flags; // flag bits
  3203. uint64_t characters; // char * (64-bit pointer)
  3204. uint64_t length; // number of non-NULL characters in above
  3205. };
  3206. // The class object in a 64-bit Mach-O file.
  3207. struct class64_t {
  3208. uint64_t isa; // class64_t * (64-bit pointer)
  3209. uint64_t superclass; // class64_t * (64-bit pointer)
  3210. uint64_t cache; // Cache (64-bit pointer)
  3211. uint64_t vtable; // IMP * (64-bit pointer)
  3212. uint64_t data; // class_ro64_t * (64-bit pointer)
  3213. };
  3214. struct class32_t {
  3215. uint32_t isa; /* class32_t * (32-bit pointer) */
  3216. uint32_t superclass; /* class32_t * (32-bit pointer) */
  3217. uint32_t cache; /* Cache (32-bit pointer) */
  3218. uint32_t vtable; /* IMP * (32-bit pointer) */
  3219. uint32_t data; /* class_ro32_t * (32-bit pointer) */
  3220. };
  3221. struct class_ro64_t {
  3222. uint32_t flags;
  3223. uint32_t instanceStart;
  3224. uint32_t instanceSize;
  3225. uint32_t reserved;
  3226. uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
  3227. uint64_t name; // const char * (64-bit pointer)
  3228. uint64_t baseMethods; // const method_list_t * (64-bit pointer)
  3229. uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
  3230. uint64_t ivars; // const ivar_list_t * (64-bit pointer)
  3231. uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
  3232. uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
  3233. };
  3234. struct class_ro32_t {
  3235. uint32_t flags;
  3236. uint32_t instanceStart;
  3237. uint32_t instanceSize;
  3238. uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
  3239. uint32_t name; /* const char * (32-bit pointer) */
  3240. uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
  3241. uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
  3242. uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
  3243. uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
  3244. uint32_t baseProperties; /* const struct objc_property_list *
  3245. (32-bit pointer) */
  3246. };
  3247. /* Values for class_ro{64,32}_t->flags */
  3248. #define RO_META (1 << 0)
  3249. #define RO_ROOT (1 << 1)
  3250. #define RO_HAS_CXX_STRUCTORS (1 << 2)
  3251. struct method_list64_t {
  3252. uint32_t entsize;
  3253. uint32_t count;
  3254. /* struct method64_t first; These structures follow inline */
  3255. };
  3256. struct method_list32_t {
  3257. uint32_t entsize;
  3258. uint32_t count;
  3259. /* struct method32_t first; These structures follow inline */
  3260. };
  3261. struct method64_t {
  3262. uint64_t name; /* SEL (64-bit pointer) */
  3263. uint64_t types; /* const char * (64-bit pointer) */
  3264. uint64_t imp; /* IMP (64-bit pointer) */
  3265. };
  3266. struct method32_t {
  3267. uint32_t name; /* SEL (32-bit pointer) */
  3268. uint32_t types; /* const char * (32-bit pointer) */
  3269. uint32_t imp; /* IMP (32-bit pointer) */
  3270. };
  3271. struct protocol_list64_t {
  3272. uint64_t count; /* uintptr_t (a 64-bit value) */
  3273. /* struct protocol64_t * list[0]; These pointers follow inline */
  3274. };
  3275. struct protocol_list32_t {
  3276. uint32_t count; /* uintptr_t (a 32-bit value) */
  3277. /* struct protocol32_t * list[0]; These pointers follow inline */
  3278. };
  3279. struct protocol64_t {
  3280. uint64_t isa; /* id * (64-bit pointer) */
  3281. uint64_t name; /* const char * (64-bit pointer) */
  3282. uint64_t protocols; /* struct protocol_list64_t *
  3283. (64-bit pointer) */
  3284. uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
  3285. uint64_t classMethods; /* method_list_t * (64-bit pointer) */
  3286. uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
  3287. uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
  3288. uint64_t instanceProperties; /* struct objc_property_list *
  3289. (64-bit pointer) */
  3290. };
  3291. struct protocol32_t {
  3292. uint32_t isa; /* id * (32-bit pointer) */
  3293. uint32_t name; /* const char * (32-bit pointer) */
  3294. uint32_t protocols; /* struct protocol_list_t *
  3295. (32-bit pointer) */
  3296. uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
  3297. uint32_t classMethods; /* method_list_t * (32-bit pointer) */
  3298. uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
  3299. uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
  3300. uint32_t instanceProperties; /* struct objc_property_list *
  3301. (32-bit pointer) */
  3302. };
  3303. struct ivar_list64_t {
  3304. uint32_t entsize;
  3305. uint32_t count;
  3306. /* struct ivar64_t first; These structures follow inline */
  3307. };
  3308. struct ivar_list32_t {
  3309. uint32_t entsize;
  3310. uint32_t count;
  3311. /* struct ivar32_t first; These structures follow inline */
  3312. };
  3313. struct ivar64_t {
  3314. uint64_t offset; /* uintptr_t * (64-bit pointer) */
  3315. uint64_t name; /* const char * (64-bit pointer) */
  3316. uint64_t type; /* const char * (64-bit pointer) */
  3317. uint32_t alignment;
  3318. uint32_t size;
  3319. };
  3320. struct ivar32_t {
  3321. uint32_t offset; /* uintptr_t * (32-bit pointer) */
  3322. uint32_t name; /* const char * (32-bit pointer) */
  3323. uint32_t type; /* const char * (32-bit pointer) */
  3324. uint32_t alignment;
  3325. uint32_t size;
  3326. };
  3327. struct objc_property_list64 {
  3328. uint32_t entsize;
  3329. uint32_t count;
  3330. /* struct objc_property64 first; These structures follow inline */
  3331. };
  3332. struct objc_property_list32 {
  3333. uint32_t entsize;
  3334. uint32_t count;
  3335. /* struct objc_property32 first; These structures follow inline */
  3336. };
  3337. struct objc_property64 {
  3338. uint64_t name; /* const char * (64-bit pointer) */
  3339. uint64_t attributes; /* const char * (64-bit pointer) */
  3340. };
  3341. struct objc_property32 {
  3342. uint32_t name; /* const char * (32-bit pointer) */
  3343. uint32_t attributes; /* const char * (32-bit pointer) */
  3344. };
  3345. struct category64_t {
  3346. uint64_t name; /* const char * (64-bit pointer) */
  3347. uint64_t cls; /* struct class_t * (64-bit pointer) */
  3348. uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
  3349. uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
  3350. uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
  3351. uint64_t instanceProperties; /* struct objc_property_list *
  3352. (64-bit pointer) */
  3353. };
  3354. struct category32_t {
  3355. uint32_t name; /* const char * (32-bit pointer) */
  3356. uint32_t cls; /* struct class_t * (32-bit pointer) */
  3357. uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
  3358. uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
  3359. uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
  3360. uint32_t instanceProperties; /* struct objc_property_list *
  3361. (32-bit pointer) */
  3362. };
  3363. struct objc_image_info64 {
  3364. uint32_t version;
  3365. uint32_t flags;
  3366. };
  3367. struct objc_image_info32 {
  3368. uint32_t version;
  3369. uint32_t flags;
  3370. };
  3371. struct imageInfo_t {
  3372. uint32_t version;
  3373. uint32_t flags;
  3374. };
  3375. /* masks for objc_image_info.flags */
  3376. #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
  3377. #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
  3378. #define OBJC_IMAGE_IS_SIMULATED (1 << 5)
  3379. #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
  3380. struct message_ref64 {
  3381. uint64_t imp; /* IMP (64-bit pointer) */
  3382. uint64_t sel; /* SEL (64-bit pointer) */
  3383. };
  3384. struct message_ref32 {
  3385. uint32_t imp; /* IMP (32-bit pointer) */
  3386. uint32_t sel; /* SEL (32-bit pointer) */
  3387. };
  3388. // Objective-C 1 (32-bit only) meta data structs.
  3389. struct objc_module_t {
  3390. uint32_t version;
  3391. uint32_t size;
  3392. uint32_t name; /* char * (32-bit pointer) */
  3393. uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
  3394. };
  3395. struct objc_symtab_t {
  3396. uint32_t sel_ref_cnt;
  3397. uint32_t refs; /* SEL * (32-bit pointer) */
  3398. uint16_t cls_def_cnt;
  3399. uint16_t cat_def_cnt;
  3400. // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
  3401. };
  3402. struct objc_class_t {
  3403. uint32_t isa; /* struct objc_class * (32-bit pointer) */
  3404. uint32_t super_class; /* struct objc_class * (32-bit pointer) */
  3405. uint32_t name; /* const char * (32-bit pointer) */
  3406. int32_t version;
  3407. int32_t info;
  3408. int32_t instance_size;
  3409. uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
  3410. uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
  3411. uint32_t cache; /* struct objc_cache * (32-bit pointer) */
  3412. uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
  3413. };
  3414. #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
  3415. // class is not a metaclass
  3416. #define CLS_CLASS 0x1
  3417. // class is a metaclass
  3418. #define CLS_META 0x2
  3419. struct objc_category_t {
  3420. uint32_t category_name; /* char * (32-bit pointer) */
  3421. uint32_t class_name; /* char * (32-bit pointer) */
  3422. uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
  3423. uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
  3424. uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
  3425. };
  3426. struct objc_ivar_t {
  3427. uint32_t ivar_name; /* char * (32-bit pointer) */
  3428. uint32_t ivar_type; /* char * (32-bit pointer) */
  3429. int32_t ivar_offset;
  3430. };
  3431. struct objc_ivar_list_t {
  3432. int32_t ivar_count;
  3433. // struct objc_ivar_t ivar_list[1]; /* variable length structure */
  3434. };
  3435. struct objc_method_list_t {
  3436. uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
  3437. int32_t method_count;
  3438. // struct objc_method_t method_list[1]; /* variable length structure */
  3439. };
  3440. struct objc_method_t {
  3441. uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
  3442. uint32_t method_types; /* char * (32-bit pointer) */
  3443. uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
  3444. (32-bit pointer) */
  3445. };
  3446. struct objc_protocol_list_t {
  3447. uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
  3448. int32_t count;
  3449. // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
  3450. // (32-bit pointer) */
  3451. };
  3452. struct objc_protocol_t {
  3453. uint32_t isa; /* struct objc_class * (32-bit pointer) */
  3454. uint32_t protocol_name; /* char * (32-bit pointer) */
  3455. uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
  3456. uint32_t instance_methods; /* struct objc_method_description_list *
  3457. (32-bit pointer) */
  3458. uint32_t class_methods; /* struct objc_method_description_list *
  3459. (32-bit pointer) */
  3460. };
  3461. struct objc_method_description_list_t {
  3462. int32_t count;
  3463. // struct objc_method_description_t list[1];
  3464. };
  3465. struct objc_method_description_t {
  3466. uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
  3467. uint32_t types; /* char * (32-bit pointer) */
  3468. };
  3469. inline void swapStruct(struct cfstring64_t &cfs) {
  3470. sys::swapByteOrder(cfs.isa);
  3471. sys::swapByteOrder(cfs.flags);
  3472. sys::swapByteOrder(cfs.characters);
  3473. sys::swapByteOrder(cfs.length);
  3474. }
  3475. inline void swapStruct(struct class64_t &c) {
  3476. sys::swapByteOrder(c.isa);
  3477. sys::swapByteOrder(c.superclass);
  3478. sys::swapByteOrder(c.cache);
  3479. sys::swapByteOrder(c.vtable);
  3480. sys::swapByteOrder(c.data);
  3481. }
  3482. inline void swapStruct(struct class32_t &c) {
  3483. sys::swapByteOrder(c.isa);
  3484. sys::swapByteOrder(c.superclass);
  3485. sys::swapByteOrder(c.cache);
  3486. sys::swapByteOrder(c.vtable);
  3487. sys::swapByteOrder(c.data);
  3488. }
  3489. inline void swapStruct(struct class_ro64_t &cro) {
  3490. sys::swapByteOrder(cro.flags);
  3491. sys::swapByteOrder(cro.instanceStart);
  3492. sys::swapByteOrder(cro.instanceSize);
  3493. sys::swapByteOrder(cro.reserved);
  3494. sys::swapByteOrder(cro.ivarLayout);
  3495. sys::swapByteOrder(cro.name);
  3496. sys::swapByteOrder(cro.baseMethods);
  3497. sys::swapByteOrder(cro.baseProtocols);
  3498. sys::swapByteOrder(cro.ivars);
  3499. sys::swapByteOrder(cro.weakIvarLayout);
  3500. sys::swapByteOrder(cro.baseProperties);
  3501. }
  3502. inline void swapStruct(struct class_ro32_t &cro) {
  3503. sys::swapByteOrder(cro.flags);
  3504. sys::swapByteOrder(cro.instanceStart);
  3505. sys::swapByteOrder(cro.instanceSize);
  3506. sys::swapByteOrder(cro.ivarLayout);
  3507. sys::swapByteOrder(cro.name);
  3508. sys::swapByteOrder(cro.baseMethods);
  3509. sys::swapByteOrder(cro.baseProtocols);
  3510. sys::swapByteOrder(cro.ivars);
  3511. sys::swapByteOrder(cro.weakIvarLayout);
  3512. sys::swapByteOrder(cro.baseProperties);
  3513. }
  3514. inline void swapStruct(struct method_list64_t &ml) {
  3515. sys::swapByteOrder(ml.entsize);
  3516. sys::swapByteOrder(ml.count);
  3517. }
  3518. inline void swapStruct(struct method_list32_t &ml) {
  3519. sys::swapByteOrder(ml.entsize);
  3520. sys::swapByteOrder(ml.count);
  3521. }
  3522. inline void swapStruct(struct method64_t &m) {
  3523. sys::swapByteOrder(m.name);
  3524. sys::swapByteOrder(m.types);
  3525. sys::swapByteOrder(m.imp);
  3526. }
  3527. inline void swapStruct(struct method32_t &m) {
  3528. sys::swapByteOrder(m.name);
  3529. sys::swapByteOrder(m.types);
  3530. sys::swapByteOrder(m.imp);
  3531. }
  3532. inline void swapStruct(struct protocol_list64_t &pl) {
  3533. sys::swapByteOrder(pl.count);
  3534. }
  3535. inline void swapStruct(struct protocol_list32_t &pl) {
  3536. sys::swapByteOrder(pl.count);
  3537. }
  3538. inline void swapStruct(struct protocol64_t &p) {
  3539. sys::swapByteOrder(p.isa);
  3540. sys::swapByteOrder(p.name);
  3541. sys::swapByteOrder(p.protocols);
  3542. sys::swapByteOrder(p.instanceMethods);
  3543. sys::swapByteOrder(p.classMethods);
  3544. sys::swapByteOrder(p.optionalInstanceMethods);
  3545. sys::swapByteOrder(p.optionalClassMethods);
  3546. sys::swapByteOrder(p.instanceProperties);
  3547. }
  3548. inline void swapStruct(struct protocol32_t &p) {
  3549. sys::swapByteOrder(p.isa);
  3550. sys::swapByteOrder(p.name);
  3551. sys::swapByteOrder(p.protocols);
  3552. sys::swapByteOrder(p.instanceMethods);
  3553. sys::swapByteOrder(p.classMethods);
  3554. sys::swapByteOrder(p.optionalInstanceMethods);
  3555. sys::swapByteOrder(p.optionalClassMethods);
  3556. sys::swapByteOrder(p.instanceProperties);
  3557. }
  3558. inline void swapStruct(struct ivar_list64_t &il) {
  3559. sys::swapByteOrder(il.entsize);
  3560. sys::swapByteOrder(il.count);
  3561. }
  3562. inline void swapStruct(struct ivar_list32_t &il) {
  3563. sys::swapByteOrder(il.entsize);
  3564. sys::swapByteOrder(il.count);
  3565. }
  3566. inline void swapStruct(struct ivar64_t &i) {
  3567. sys::swapByteOrder(i.offset);
  3568. sys::swapByteOrder(i.name);
  3569. sys::swapByteOrder(i.type);
  3570. sys::swapByteOrder(i.alignment);
  3571. sys::swapByteOrder(i.size);
  3572. }
  3573. inline void swapStruct(struct ivar32_t &i) {
  3574. sys::swapByteOrder(i.offset);
  3575. sys::swapByteOrder(i.name);
  3576. sys::swapByteOrder(i.type);
  3577. sys::swapByteOrder(i.alignment);
  3578. sys::swapByteOrder(i.size);
  3579. }
  3580. inline void swapStruct(struct objc_property_list64 &pl) {
  3581. sys::swapByteOrder(pl.entsize);
  3582. sys::swapByteOrder(pl.count);
  3583. }
  3584. inline void swapStruct(struct objc_property_list32 &pl) {
  3585. sys::swapByteOrder(pl.entsize);
  3586. sys::swapByteOrder(pl.count);
  3587. }
  3588. inline void swapStruct(struct objc_property64 &op) {
  3589. sys::swapByteOrder(op.name);
  3590. sys::swapByteOrder(op.attributes);
  3591. }
  3592. inline void swapStruct(struct objc_property32 &op) {
  3593. sys::swapByteOrder(op.name);
  3594. sys::swapByteOrder(op.attributes);
  3595. }
  3596. inline void swapStruct(struct category64_t &c) {
  3597. sys::swapByteOrder(c.name);
  3598. sys::swapByteOrder(c.cls);
  3599. sys::swapByteOrder(c.instanceMethods);
  3600. sys::swapByteOrder(c.classMethods);
  3601. sys::swapByteOrder(c.protocols);
  3602. sys::swapByteOrder(c.instanceProperties);
  3603. }
  3604. inline void swapStruct(struct category32_t &c) {
  3605. sys::swapByteOrder(c.name);
  3606. sys::swapByteOrder(c.cls);
  3607. sys::swapByteOrder(c.instanceMethods);
  3608. sys::swapByteOrder(c.classMethods);
  3609. sys::swapByteOrder(c.protocols);
  3610. sys::swapByteOrder(c.instanceProperties);
  3611. }
  3612. inline void swapStruct(struct objc_image_info64 &o) {
  3613. sys::swapByteOrder(o.version);
  3614. sys::swapByteOrder(o.flags);
  3615. }
  3616. inline void swapStruct(struct objc_image_info32 &o) {
  3617. sys::swapByteOrder(o.version);
  3618. sys::swapByteOrder(o.flags);
  3619. }
  3620. inline void swapStruct(struct imageInfo_t &o) {
  3621. sys::swapByteOrder(o.version);
  3622. sys::swapByteOrder(o.flags);
  3623. }
  3624. inline void swapStruct(struct message_ref64 &mr) {
  3625. sys::swapByteOrder(mr.imp);
  3626. sys::swapByteOrder(mr.sel);
  3627. }
  3628. inline void swapStruct(struct message_ref32 &mr) {
  3629. sys::swapByteOrder(mr.imp);
  3630. sys::swapByteOrder(mr.sel);
  3631. }
  3632. inline void swapStruct(struct objc_module_t &module) {
  3633. sys::swapByteOrder(module.version);
  3634. sys::swapByteOrder(module.size);
  3635. sys::swapByteOrder(module.name);
  3636. sys::swapByteOrder(module.symtab);
  3637. }
  3638. inline void swapStruct(struct objc_symtab_t &symtab) {
  3639. sys::swapByteOrder(symtab.sel_ref_cnt);
  3640. sys::swapByteOrder(symtab.refs);
  3641. sys::swapByteOrder(symtab.cls_def_cnt);
  3642. sys::swapByteOrder(symtab.cat_def_cnt);
  3643. }
  3644. inline void swapStruct(struct objc_class_t &objc_class) {
  3645. sys::swapByteOrder(objc_class.isa);
  3646. sys::swapByteOrder(objc_class.super_class);
  3647. sys::swapByteOrder(objc_class.name);
  3648. sys::swapByteOrder(objc_class.version);
  3649. sys::swapByteOrder(objc_class.info);
  3650. sys::swapByteOrder(objc_class.instance_size);
  3651. sys::swapByteOrder(objc_class.ivars);
  3652. sys::swapByteOrder(objc_class.methodLists);
  3653. sys::swapByteOrder(objc_class.cache);
  3654. sys::swapByteOrder(objc_class.protocols);
  3655. }
  3656. inline void swapStruct(struct objc_category_t &objc_category) {
  3657. sys::swapByteOrder(objc_category.category_name);
  3658. sys::swapByteOrder(objc_category.class_name);
  3659. sys::swapByteOrder(objc_category.instance_methods);
  3660. sys::swapByteOrder(objc_category.class_methods);
  3661. sys::swapByteOrder(objc_category.protocols);
  3662. }
  3663. inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
  3664. sys::swapByteOrder(objc_ivar_list.ivar_count);
  3665. }
  3666. inline void swapStruct(struct objc_ivar_t &objc_ivar) {
  3667. sys::swapByteOrder(objc_ivar.ivar_name);
  3668. sys::swapByteOrder(objc_ivar.ivar_type);
  3669. sys::swapByteOrder(objc_ivar.ivar_offset);
  3670. }
  3671. inline void swapStruct(struct objc_method_list_t &method_list) {
  3672. sys::swapByteOrder(method_list.obsolete);
  3673. sys::swapByteOrder(method_list.method_count);
  3674. }
  3675. inline void swapStruct(struct objc_method_t &method) {
  3676. sys::swapByteOrder(method.method_name);
  3677. sys::swapByteOrder(method.method_types);
  3678. sys::swapByteOrder(method.method_imp);
  3679. }
  3680. inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
  3681. sys::swapByteOrder(protocol_list.next);
  3682. sys::swapByteOrder(protocol_list.count);
  3683. }
  3684. inline void swapStruct(struct objc_protocol_t &protocol) {
  3685. sys::swapByteOrder(protocol.isa);
  3686. sys::swapByteOrder(protocol.protocol_name);
  3687. sys::swapByteOrder(protocol.protocol_list);
  3688. sys::swapByteOrder(protocol.instance_methods);
  3689. sys::swapByteOrder(protocol.class_methods);
  3690. }
  3691. inline void swapStruct(struct objc_method_description_list_t &mdl) {
  3692. sys::swapByteOrder(mdl.count);
  3693. }
  3694. inline void swapStruct(struct objc_method_description_t &md) {
  3695. sys::swapByteOrder(md.name);
  3696. sys::swapByteOrder(md.types);
  3697. }
  3698. static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
  3699. struct DisassembleInfo *info);
  3700. // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
  3701. // to an Objective-C class and returns the class name. It is also passed the
  3702. // address of the pointer, so when the pointer is zero as it can be in an .o
  3703. // file, that is used to look for an external relocation entry with a symbol
  3704. // name.
  3705. static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
  3706. uint64_t ReferenceValue,
  3707. struct DisassembleInfo *info) {
  3708. const char *r;
  3709. uint32_t offset, left;
  3710. SectionRef S;
  3711. // The pointer_value can be 0 in an object file and have a relocation
  3712. // entry for the class symbol at the ReferenceValue (the address of the
  3713. // pointer).
  3714. if (pointer_value == 0) {
  3715. r = get_pointer_64(ReferenceValue, offset, left, S, info);
  3716. if (r == nullptr || left < sizeof(uint64_t))
  3717. return nullptr;
  3718. uint64_t n_value;
  3719. const char *symbol_name = get_symbol_64(offset, S, info, n_value);
  3720. if (symbol_name == nullptr)
  3721. return nullptr;
  3722. const char *class_name = strrchr(symbol_name, '$');
  3723. if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
  3724. return class_name + 2;
  3725. else
  3726. return nullptr;
  3727. }
  3728. // The case were the pointer_value is non-zero and points to a class defined
  3729. // in this Mach-O file.
  3730. r = get_pointer_64(pointer_value, offset, left, S, info);
  3731. if (r == nullptr || left < sizeof(struct class64_t))
  3732. return nullptr;
  3733. struct class64_t c;
  3734. memcpy(&c, r, sizeof(struct class64_t));
  3735. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3736. swapStruct(c);
  3737. if (c.data == 0)
  3738. return nullptr;
  3739. r = get_pointer_64(c.data, offset, left, S, info);
  3740. if (r == nullptr || left < sizeof(struct class_ro64_t))
  3741. return nullptr;
  3742. struct class_ro64_t cro;
  3743. memcpy(&cro, r, sizeof(struct class_ro64_t));
  3744. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3745. swapStruct(cro);
  3746. if (cro.name == 0)
  3747. return nullptr;
  3748. const char *name = get_pointer_64(cro.name, offset, left, S, info);
  3749. return name;
  3750. }
  3751. // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
  3752. // pointer to a cfstring and returns its name or nullptr.
  3753. static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
  3754. struct DisassembleInfo *info) {
  3755. const char *r, *name;
  3756. uint32_t offset, left;
  3757. SectionRef S;
  3758. struct cfstring64_t cfs;
  3759. uint64_t cfs_characters;
  3760. r = get_pointer_64(ReferenceValue, offset, left, S, info);
  3761. if (r == nullptr || left < sizeof(struct cfstring64_t))
  3762. return nullptr;
  3763. memcpy(&cfs, r, sizeof(struct cfstring64_t));
  3764. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3765. swapStruct(cfs);
  3766. if (cfs.characters == 0) {
  3767. uint64_t n_value;
  3768. const char *symbol_name = get_symbol_64(
  3769. offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
  3770. if (symbol_name == nullptr)
  3771. return nullptr;
  3772. cfs_characters = n_value;
  3773. } else
  3774. cfs_characters = cfs.characters;
  3775. name = get_pointer_64(cfs_characters, offset, left, S, info);
  3776. return name;
  3777. }
  3778. // get_objc2_64bit_selref() is used for disassembly and is passed a the address
  3779. // of a pointer to an Objective-C selector reference when the pointer value is
  3780. // zero as in a .o file and is likely to have a external relocation entry with
  3781. // who's symbol's n_value is the real pointer to the selector name. If that is
  3782. // the case the real pointer to the selector name is returned else 0 is
  3783. // returned
  3784. static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
  3785. struct DisassembleInfo *info) {
  3786. uint32_t offset, left;
  3787. SectionRef S;
  3788. const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
  3789. if (r == nullptr || left < sizeof(uint64_t))
  3790. return 0;
  3791. uint64_t n_value;
  3792. const char *symbol_name = get_symbol_64(offset, S, info, n_value);
  3793. if (symbol_name == nullptr)
  3794. return 0;
  3795. return n_value;
  3796. }
  3797. static const SectionRef get_section(MachOObjectFile *O, const char *segname,
  3798. const char *sectname) {
  3799. for (const SectionRef &Section : O->sections()) {
  3800. StringRef SectName;
  3801. Expected<StringRef> SecNameOrErr = Section.getName();
  3802. if (SecNameOrErr)
  3803. SectName = *SecNameOrErr;
  3804. else
  3805. consumeError(SecNameOrErr.takeError());
  3806. DataRefImpl Ref = Section.getRawDataRefImpl();
  3807. StringRef SegName = O->getSectionFinalSegmentName(Ref);
  3808. if (SegName == segname && SectName == sectname)
  3809. return Section;
  3810. }
  3811. return SectionRef();
  3812. }
  3813. static void
  3814. walk_pointer_list_64(const char *listname, const SectionRef S,
  3815. MachOObjectFile *O, struct DisassembleInfo *info,
  3816. void (*func)(uint64_t, struct DisassembleInfo *info)) {
  3817. if (S == SectionRef())
  3818. return;
  3819. StringRef SectName;
  3820. Expected<StringRef> SecNameOrErr = S.getName();
  3821. if (SecNameOrErr)
  3822. SectName = *SecNameOrErr;
  3823. else
  3824. consumeError(SecNameOrErr.takeError());
  3825. DataRefImpl Ref = S.getRawDataRefImpl();
  3826. StringRef SegName = O->getSectionFinalSegmentName(Ref);
  3827. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  3828. StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
  3829. const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
  3830. for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
  3831. uint32_t left = S.getSize() - i;
  3832. uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
  3833. uint64_t p = 0;
  3834. memcpy(&p, Contents + i, size);
  3835. if (i + sizeof(uint64_t) > S.getSize())
  3836. outs() << listname << " list pointer extends past end of (" << SegName
  3837. << "," << SectName << ") section\n";
  3838. outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
  3839. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  3840. sys::swapByteOrder(p);
  3841. uint64_t n_value = 0;
  3842. const char *name = get_symbol_64(i, S, info, n_value, p);
  3843. if (name == nullptr)
  3844. name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
  3845. if (n_value != 0) {
  3846. outs() << format("0x%" PRIx64, n_value);
  3847. if (p != 0)
  3848. outs() << " + " << format("0x%" PRIx64, p);
  3849. } else
  3850. outs() << format("0x%" PRIx64, p);
  3851. if (name != nullptr)
  3852. outs() << " " << name;
  3853. outs() << "\n";
  3854. p += n_value;
  3855. if (func)
  3856. func(p, info);
  3857. }
  3858. }
  3859. static void
  3860. walk_pointer_list_32(const char *listname, const SectionRef S,
  3861. MachOObjectFile *O, struct DisassembleInfo *info,
  3862. void (*func)(uint32_t, struct DisassembleInfo *info)) {
  3863. if (S == SectionRef())
  3864. return;
  3865. StringRef SectName = unwrapOrError(S.getName(), O->getFileName());
  3866. DataRefImpl Ref = S.getRawDataRefImpl();
  3867. StringRef SegName = O->getSectionFinalSegmentName(Ref);
  3868. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  3869. StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
  3870. const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
  3871. for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
  3872. uint32_t left = S.getSize() - i;
  3873. uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
  3874. uint32_t p = 0;
  3875. memcpy(&p, Contents + i, size);
  3876. if (i + sizeof(uint32_t) > S.getSize())
  3877. outs() << listname << " list pointer extends past end of (" << SegName
  3878. << "," << SectName << ") section\n";
  3879. uint32_t Address = S.getAddress() + i;
  3880. outs() << format("%08" PRIx32, Address) << " ";
  3881. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  3882. sys::swapByteOrder(p);
  3883. outs() << format("0x%" PRIx32, p);
  3884. const char *name = get_symbol_32(i, S, info, p);
  3885. if (name != nullptr)
  3886. outs() << " " << name;
  3887. outs() << "\n";
  3888. if (func)
  3889. func(p, info);
  3890. }
  3891. }
  3892. static void print_layout_map(const char *layout_map, uint32_t left) {
  3893. if (layout_map == nullptr)
  3894. return;
  3895. outs() << " layout map: ";
  3896. do {
  3897. outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
  3898. left--;
  3899. layout_map++;
  3900. } while (*layout_map != '\0' && left != 0);
  3901. outs() << "\n";
  3902. }
  3903. static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
  3904. uint32_t offset, left;
  3905. SectionRef S;
  3906. const char *layout_map;
  3907. if (p == 0)
  3908. return;
  3909. layout_map = get_pointer_64(p, offset, left, S, info);
  3910. print_layout_map(layout_map, left);
  3911. }
  3912. static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
  3913. uint32_t offset, left;
  3914. SectionRef S;
  3915. const char *layout_map;
  3916. if (p == 0)
  3917. return;
  3918. layout_map = get_pointer_32(p, offset, left, S, info);
  3919. print_layout_map(layout_map, left);
  3920. }
  3921. static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
  3922. const char *indent) {
  3923. struct method_list64_t ml;
  3924. struct method64_t m;
  3925. const char *r;
  3926. uint32_t offset, xoffset, left, i;
  3927. SectionRef S, xS;
  3928. const char *name, *sym_name;
  3929. uint64_t n_value;
  3930. r = get_pointer_64(p, offset, left, S, info);
  3931. if (r == nullptr)
  3932. return;
  3933. memset(&ml, '\0', sizeof(struct method_list64_t));
  3934. if (left < sizeof(struct method_list64_t)) {
  3935. memcpy(&ml, r, left);
  3936. outs() << " (method_list_t entends past the end of the section)\n";
  3937. } else
  3938. memcpy(&ml, r, sizeof(struct method_list64_t));
  3939. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3940. swapStruct(ml);
  3941. outs() << indent << "\t\t entsize " << ml.entsize << "\n";
  3942. outs() << indent << "\t\t count " << ml.count << "\n";
  3943. p += sizeof(struct method_list64_t);
  3944. offset += sizeof(struct method_list64_t);
  3945. for (i = 0; i < ml.count; i++) {
  3946. r = get_pointer_64(p, offset, left, S, info);
  3947. if (r == nullptr)
  3948. return;
  3949. memset(&m, '\0', sizeof(struct method64_t));
  3950. if (left < sizeof(struct method64_t)) {
  3951. memcpy(&m, r, left);
  3952. outs() << indent << " (method_t extends past the end of the section)\n";
  3953. } else
  3954. memcpy(&m, r, sizeof(struct method64_t));
  3955. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  3956. swapStruct(m);
  3957. outs() << indent << "\t\t name ";
  3958. sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
  3959. info, n_value, m.name);
  3960. if (n_value != 0) {
  3961. if (info->verbose && sym_name != nullptr)
  3962. outs() << sym_name;
  3963. else
  3964. outs() << format("0x%" PRIx64, n_value);
  3965. if (m.name != 0)
  3966. outs() << " + " << format("0x%" PRIx64, m.name);
  3967. } else
  3968. outs() << format("0x%" PRIx64, m.name);
  3969. name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
  3970. if (name != nullptr)
  3971. outs() << format(" %.*s", left, name);
  3972. outs() << "\n";
  3973. outs() << indent << "\t\t types ";
  3974. sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
  3975. info, n_value, m.types);
  3976. if (n_value != 0) {
  3977. if (info->verbose && sym_name != nullptr)
  3978. outs() << sym_name;
  3979. else
  3980. outs() << format("0x%" PRIx64, n_value);
  3981. if (m.types != 0)
  3982. outs() << " + " << format("0x%" PRIx64, m.types);
  3983. } else
  3984. outs() << format("0x%" PRIx64, m.types);
  3985. name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
  3986. if (name != nullptr)
  3987. outs() << format(" %.*s", left, name);
  3988. outs() << "\n";
  3989. outs() << indent << "\t\t imp ";
  3990. name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
  3991. n_value, m.imp);
  3992. if (info->verbose && name == nullptr) {
  3993. if (n_value != 0) {
  3994. outs() << format("0x%" PRIx64, n_value) << " ";
  3995. if (m.imp != 0)
  3996. outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
  3997. } else
  3998. outs() << format("0x%" PRIx64, m.imp) << " ";
  3999. }
  4000. if (name != nullptr)
  4001. outs() << name;
  4002. outs() << "\n";
  4003. p += sizeof(struct method64_t);
  4004. offset += sizeof(struct method64_t);
  4005. }
  4006. }
  4007. static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
  4008. const char *indent) {
  4009. struct method_list32_t ml;
  4010. struct method32_t m;
  4011. const char *r, *name;
  4012. uint32_t offset, xoffset, left, i;
  4013. SectionRef S, xS;
  4014. r = get_pointer_32(p, offset, left, S, info);
  4015. if (r == nullptr)
  4016. return;
  4017. memset(&ml, '\0', sizeof(struct method_list32_t));
  4018. if (left < sizeof(struct method_list32_t)) {
  4019. memcpy(&ml, r, left);
  4020. outs() << " (method_list_t entends past the end of the section)\n";
  4021. } else
  4022. memcpy(&ml, r, sizeof(struct method_list32_t));
  4023. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4024. swapStruct(ml);
  4025. outs() << indent << "\t\t entsize " << ml.entsize << "\n";
  4026. outs() << indent << "\t\t count " << ml.count << "\n";
  4027. p += sizeof(struct method_list32_t);
  4028. offset += sizeof(struct method_list32_t);
  4029. for (i = 0; i < ml.count; i++) {
  4030. r = get_pointer_32(p, offset, left, S, info);
  4031. if (r == nullptr)
  4032. return;
  4033. memset(&m, '\0', sizeof(struct method32_t));
  4034. if (left < sizeof(struct method32_t)) {
  4035. memcpy(&ml, r, left);
  4036. outs() << indent << " (method_t entends past the end of the section)\n";
  4037. } else
  4038. memcpy(&m, r, sizeof(struct method32_t));
  4039. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4040. swapStruct(m);
  4041. outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
  4042. name = get_pointer_32(m.name, xoffset, left, xS, info);
  4043. if (name != nullptr)
  4044. outs() << format(" %.*s", left, name);
  4045. outs() << "\n";
  4046. outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
  4047. name = get_pointer_32(m.types, xoffset, left, xS, info);
  4048. if (name != nullptr)
  4049. outs() << format(" %.*s", left, name);
  4050. outs() << "\n";
  4051. outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
  4052. name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
  4053. m.imp);
  4054. if (name != nullptr)
  4055. outs() << " " << name;
  4056. outs() << "\n";
  4057. p += sizeof(struct method32_t);
  4058. offset += sizeof(struct method32_t);
  4059. }
  4060. }
  4061. static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
  4062. uint32_t offset, left, xleft;
  4063. SectionRef S;
  4064. struct objc_method_list_t method_list;
  4065. struct objc_method_t method;
  4066. const char *r, *methods, *name, *SymbolName;
  4067. int32_t i;
  4068. r = get_pointer_32(p, offset, left, S, info, true);
  4069. if (r == nullptr)
  4070. return true;
  4071. outs() << "\n";
  4072. if (left > sizeof(struct objc_method_list_t)) {
  4073. memcpy(&method_list, r, sizeof(struct objc_method_list_t));
  4074. } else {
  4075. outs() << "\t\t objc_method_list extends past end of the section\n";
  4076. memset(&method_list, '\0', sizeof(struct objc_method_list_t));
  4077. memcpy(&method_list, r, left);
  4078. }
  4079. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4080. swapStruct(method_list);
  4081. outs() << "\t\t obsolete "
  4082. << format("0x%08" PRIx32, method_list.obsolete) << "\n";
  4083. outs() << "\t\t method_count " << method_list.method_count << "\n";
  4084. methods = r + sizeof(struct objc_method_list_t);
  4085. for (i = 0; i < method_list.method_count; i++) {
  4086. if ((i + 1) * sizeof(struct objc_method_t) > left) {
  4087. outs() << "\t\t remaining method's extend past the of the section\n";
  4088. break;
  4089. }
  4090. memcpy(&method, methods + i * sizeof(struct objc_method_t),
  4091. sizeof(struct objc_method_t));
  4092. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4093. swapStruct(method);
  4094. outs() << "\t\t method_name "
  4095. << format("0x%08" PRIx32, method.method_name);
  4096. if (info->verbose) {
  4097. name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
  4098. if (name != nullptr)
  4099. outs() << format(" %.*s", xleft, name);
  4100. else
  4101. outs() << " (not in an __OBJC section)";
  4102. }
  4103. outs() << "\n";
  4104. outs() << "\t\t method_types "
  4105. << format("0x%08" PRIx32, method.method_types);
  4106. if (info->verbose) {
  4107. name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
  4108. if (name != nullptr)
  4109. outs() << format(" %.*s", xleft, name);
  4110. else
  4111. outs() << " (not in an __OBJC section)";
  4112. }
  4113. outs() << "\n";
  4114. outs() << "\t\t method_imp "
  4115. << format("0x%08" PRIx32, method.method_imp) << " ";
  4116. if (info->verbose) {
  4117. SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
  4118. if (SymbolName != nullptr)
  4119. outs() << SymbolName;
  4120. }
  4121. outs() << "\n";
  4122. }
  4123. return false;
  4124. }
  4125. static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
  4126. struct protocol_list64_t pl;
  4127. uint64_t q, n_value;
  4128. struct protocol64_t pc;
  4129. const char *r;
  4130. uint32_t offset, xoffset, left, i;
  4131. SectionRef S, xS;
  4132. const char *name, *sym_name;
  4133. r = get_pointer_64(p, offset, left, S, info);
  4134. if (r == nullptr)
  4135. return;
  4136. memset(&pl, '\0', sizeof(struct protocol_list64_t));
  4137. if (left < sizeof(struct protocol_list64_t)) {
  4138. memcpy(&pl, r, left);
  4139. outs() << " (protocol_list_t entends past the end of the section)\n";
  4140. } else
  4141. memcpy(&pl, r, sizeof(struct protocol_list64_t));
  4142. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4143. swapStruct(pl);
  4144. outs() << " count " << pl.count << "\n";
  4145. p += sizeof(struct protocol_list64_t);
  4146. offset += sizeof(struct protocol_list64_t);
  4147. for (i = 0; i < pl.count; i++) {
  4148. r = get_pointer_64(p, offset, left, S, info);
  4149. if (r == nullptr)
  4150. return;
  4151. q = 0;
  4152. if (left < sizeof(uint64_t)) {
  4153. memcpy(&q, r, left);
  4154. outs() << " (protocol_t * entends past the end of the section)\n";
  4155. } else
  4156. memcpy(&q, r, sizeof(uint64_t));
  4157. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4158. sys::swapByteOrder(q);
  4159. outs() << "\t\t list[" << i << "] ";
  4160. sym_name = get_symbol_64(offset, S, info, n_value, q);
  4161. if (n_value != 0) {
  4162. if (info->verbose && sym_name != nullptr)
  4163. outs() << sym_name;
  4164. else
  4165. outs() << format("0x%" PRIx64, n_value);
  4166. if (q != 0)
  4167. outs() << " + " << format("0x%" PRIx64, q);
  4168. } else
  4169. outs() << format("0x%" PRIx64, q);
  4170. outs() << " (struct protocol_t *)\n";
  4171. r = get_pointer_64(q + n_value, offset, left, S, info);
  4172. if (r == nullptr)
  4173. return;
  4174. memset(&pc, '\0', sizeof(struct protocol64_t));
  4175. if (left < sizeof(struct protocol64_t)) {
  4176. memcpy(&pc, r, left);
  4177. outs() << " (protocol_t entends past the end of the section)\n";
  4178. } else
  4179. memcpy(&pc, r, sizeof(struct protocol64_t));
  4180. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4181. swapStruct(pc);
  4182. outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
  4183. outs() << "\t\t\t name ";
  4184. sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
  4185. info, n_value, pc.name);
  4186. if (n_value != 0) {
  4187. if (info->verbose && sym_name != nullptr)
  4188. outs() << sym_name;
  4189. else
  4190. outs() << format("0x%" PRIx64, n_value);
  4191. if (pc.name != 0)
  4192. outs() << " + " << format("0x%" PRIx64, pc.name);
  4193. } else
  4194. outs() << format("0x%" PRIx64, pc.name);
  4195. name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
  4196. if (name != nullptr)
  4197. outs() << format(" %.*s", left, name);
  4198. outs() << "\n";
  4199. outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
  4200. outs() << "\t\t instanceMethods ";
  4201. sym_name =
  4202. get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
  4203. S, info, n_value, pc.instanceMethods);
  4204. if (n_value != 0) {
  4205. if (info->verbose && sym_name != nullptr)
  4206. outs() << sym_name;
  4207. else
  4208. outs() << format("0x%" PRIx64, n_value);
  4209. if (pc.instanceMethods != 0)
  4210. outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
  4211. } else
  4212. outs() << format("0x%" PRIx64, pc.instanceMethods);
  4213. outs() << " (struct method_list_t *)\n";
  4214. if (pc.instanceMethods + n_value != 0)
  4215. print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
  4216. outs() << "\t\t classMethods ";
  4217. sym_name =
  4218. get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
  4219. info, n_value, pc.classMethods);
  4220. if (n_value != 0) {
  4221. if (info->verbose && sym_name != nullptr)
  4222. outs() << sym_name;
  4223. else
  4224. outs() << format("0x%" PRIx64, n_value);
  4225. if (pc.classMethods != 0)
  4226. outs() << " + " << format("0x%" PRIx64, pc.classMethods);
  4227. } else
  4228. outs() << format("0x%" PRIx64, pc.classMethods);
  4229. outs() << " (struct method_list_t *)\n";
  4230. if (pc.classMethods + n_value != 0)
  4231. print_method_list64_t(pc.classMethods + n_value, info, "\t");
  4232. outs() << "\t optionalInstanceMethods "
  4233. << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
  4234. outs() << "\t optionalClassMethods "
  4235. << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
  4236. outs() << "\t instanceProperties "
  4237. << format("0x%" PRIx64, pc.instanceProperties) << "\n";
  4238. p += sizeof(uint64_t);
  4239. offset += sizeof(uint64_t);
  4240. }
  4241. }
  4242. static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
  4243. struct protocol_list32_t pl;
  4244. uint32_t q;
  4245. struct protocol32_t pc;
  4246. const char *r;
  4247. uint32_t offset, xoffset, left, i;
  4248. SectionRef S, xS;
  4249. const char *name;
  4250. r = get_pointer_32(p, offset, left, S, info);
  4251. if (r == nullptr)
  4252. return;
  4253. memset(&pl, '\0', sizeof(struct protocol_list32_t));
  4254. if (left < sizeof(struct protocol_list32_t)) {
  4255. memcpy(&pl, r, left);
  4256. outs() << " (protocol_list_t entends past the end of the section)\n";
  4257. } else
  4258. memcpy(&pl, r, sizeof(struct protocol_list32_t));
  4259. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4260. swapStruct(pl);
  4261. outs() << " count " << pl.count << "\n";
  4262. p += sizeof(struct protocol_list32_t);
  4263. offset += sizeof(struct protocol_list32_t);
  4264. for (i = 0; i < pl.count; i++) {
  4265. r = get_pointer_32(p, offset, left, S, info);
  4266. if (r == nullptr)
  4267. return;
  4268. q = 0;
  4269. if (left < sizeof(uint32_t)) {
  4270. memcpy(&q, r, left);
  4271. outs() << " (protocol_t * entends past the end of the section)\n";
  4272. } else
  4273. memcpy(&q, r, sizeof(uint32_t));
  4274. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4275. sys::swapByteOrder(q);
  4276. outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
  4277. << " (struct protocol_t *)\n";
  4278. r = get_pointer_32(q, offset, left, S, info);
  4279. if (r == nullptr)
  4280. return;
  4281. memset(&pc, '\0', sizeof(struct protocol32_t));
  4282. if (left < sizeof(struct protocol32_t)) {
  4283. memcpy(&pc, r, left);
  4284. outs() << " (protocol_t entends past the end of the section)\n";
  4285. } else
  4286. memcpy(&pc, r, sizeof(struct protocol32_t));
  4287. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4288. swapStruct(pc);
  4289. outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
  4290. outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
  4291. name = get_pointer_32(pc.name, xoffset, left, xS, info);
  4292. if (name != nullptr)
  4293. outs() << format(" %.*s", left, name);
  4294. outs() << "\n";
  4295. outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
  4296. outs() << "\t\t instanceMethods "
  4297. << format("0x%" PRIx32, pc.instanceMethods)
  4298. << " (struct method_list_t *)\n";
  4299. if (pc.instanceMethods != 0)
  4300. print_method_list32_t(pc.instanceMethods, info, "\t");
  4301. outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
  4302. << " (struct method_list_t *)\n";
  4303. if (pc.classMethods != 0)
  4304. print_method_list32_t(pc.classMethods, info, "\t");
  4305. outs() << "\t optionalInstanceMethods "
  4306. << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
  4307. outs() << "\t optionalClassMethods "
  4308. << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
  4309. outs() << "\t instanceProperties "
  4310. << format("0x%" PRIx32, pc.instanceProperties) << "\n";
  4311. p += sizeof(uint32_t);
  4312. offset += sizeof(uint32_t);
  4313. }
  4314. }
  4315. static void print_indent(uint32_t indent) {
  4316. for (uint32_t i = 0; i < indent;) {
  4317. if (indent - i >= 8) {
  4318. outs() << "\t";
  4319. i += 8;
  4320. } else {
  4321. for (uint32_t j = i; j < indent; j++)
  4322. outs() << " ";
  4323. return;
  4324. }
  4325. }
  4326. }
  4327. static bool print_method_description_list(uint32_t p, uint32_t indent,
  4328. struct DisassembleInfo *info) {
  4329. uint32_t offset, left, xleft;
  4330. SectionRef S;
  4331. struct objc_method_description_list_t mdl;
  4332. struct objc_method_description_t md;
  4333. const char *r, *list, *name;
  4334. int32_t i;
  4335. r = get_pointer_32(p, offset, left, S, info, true);
  4336. if (r == nullptr)
  4337. return true;
  4338. outs() << "\n";
  4339. if (left > sizeof(struct objc_method_description_list_t)) {
  4340. memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
  4341. } else {
  4342. print_indent(indent);
  4343. outs() << " objc_method_description_list extends past end of the section\n";
  4344. memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
  4345. memcpy(&mdl, r, left);
  4346. }
  4347. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4348. swapStruct(mdl);
  4349. print_indent(indent);
  4350. outs() << " count " << mdl.count << "\n";
  4351. list = r + sizeof(struct objc_method_description_list_t);
  4352. for (i = 0; i < mdl.count; i++) {
  4353. if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
  4354. print_indent(indent);
  4355. outs() << " remaining list entries extend past the of the section\n";
  4356. break;
  4357. }
  4358. print_indent(indent);
  4359. outs() << " list[" << i << "]\n";
  4360. memcpy(&md, list + i * sizeof(struct objc_method_description_t),
  4361. sizeof(struct objc_method_description_t));
  4362. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4363. swapStruct(md);
  4364. print_indent(indent);
  4365. outs() << " name " << format("0x%08" PRIx32, md.name);
  4366. if (info->verbose) {
  4367. name = get_pointer_32(md.name, offset, xleft, S, info, true);
  4368. if (name != nullptr)
  4369. outs() << format(" %.*s", xleft, name);
  4370. else
  4371. outs() << " (not in an __OBJC section)";
  4372. }
  4373. outs() << "\n";
  4374. print_indent(indent);
  4375. outs() << " types " << format("0x%08" PRIx32, md.types);
  4376. if (info->verbose) {
  4377. name = get_pointer_32(md.types, offset, xleft, S, info, true);
  4378. if (name != nullptr)
  4379. outs() << format(" %.*s", xleft, name);
  4380. else
  4381. outs() << " (not in an __OBJC section)";
  4382. }
  4383. outs() << "\n";
  4384. }
  4385. return false;
  4386. }
  4387. static bool print_protocol_list(uint32_t p, uint32_t indent,
  4388. struct DisassembleInfo *info);
  4389. static bool print_protocol(uint32_t p, uint32_t indent,
  4390. struct DisassembleInfo *info) {
  4391. uint32_t offset, left;
  4392. SectionRef S;
  4393. struct objc_protocol_t protocol;
  4394. const char *r, *name;
  4395. r = get_pointer_32(p, offset, left, S, info, true);
  4396. if (r == nullptr)
  4397. return true;
  4398. outs() << "\n";
  4399. if (left >= sizeof(struct objc_protocol_t)) {
  4400. memcpy(&protocol, r, sizeof(struct objc_protocol_t));
  4401. } else {
  4402. print_indent(indent);
  4403. outs() << " Protocol extends past end of the section\n";
  4404. memset(&protocol, '\0', sizeof(struct objc_protocol_t));
  4405. memcpy(&protocol, r, left);
  4406. }
  4407. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4408. swapStruct(protocol);
  4409. print_indent(indent);
  4410. outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
  4411. << "\n";
  4412. print_indent(indent);
  4413. outs() << " protocol_name "
  4414. << format("0x%08" PRIx32, protocol.protocol_name);
  4415. if (info->verbose) {
  4416. name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
  4417. if (name != nullptr)
  4418. outs() << format(" %.*s", left, name);
  4419. else
  4420. outs() << " (not in an __OBJC section)";
  4421. }
  4422. outs() << "\n";
  4423. print_indent(indent);
  4424. outs() << " protocol_list "
  4425. << format("0x%08" PRIx32, protocol.protocol_list);
  4426. if (print_protocol_list(protocol.protocol_list, indent + 4, info))
  4427. outs() << " (not in an __OBJC section)\n";
  4428. print_indent(indent);
  4429. outs() << " instance_methods "
  4430. << format("0x%08" PRIx32, protocol.instance_methods);
  4431. if (print_method_description_list(protocol.instance_methods, indent, info))
  4432. outs() << " (not in an __OBJC section)\n";
  4433. print_indent(indent);
  4434. outs() << " class_methods "
  4435. << format("0x%08" PRIx32, protocol.class_methods);
  4436. if (print_method_description_list(protocol.class_methods, indent, info))
  4437. outs() << " (not in an __OBJC section)\n";
  4438. return false;
  4439. }
  4440. static bool print_protocol_list(uint32_t p, uint32_t indent,
  4441. struct DisassembleInfo *info) {
  4442. uint32_t offset, left, l;
  4443. SectionRef S;
  4444. struct objc_protocol_list_t protocol_list;
  4445. const char *r, *list;
  4446. int32_t i;
  4447. r = get_pointer_32(p, offset, left, S, info, true);
  4448. if (r == nullptr)
  4449. return true;
  4450. outs() << "\n";
  4451. if (left > sizeof(struct objc_protocol_list_t)) {
  4452. memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
  4453. } else {
  4454. outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
  4455. memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
  4456. memcpy(&protocol_list, r, left);
  4457. }
  4458. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4459. swapStruct(protocol_list);
  4460. print_indent(indent);
  4461. outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
  4462. << "\n";
  4463. print_indent(indent);
  4464. outs() << " count " << protocol_list.count << "\n";
  4465. list = r + sizeof(struct objc_protocol_list_t);
  4466. for (i = 0; i < protocol_list.count; i++) {
  4467. if ((i + 1) * sizeof(uint32_t) > left) {
  4468. outs() << "\t\t remaining list entries extend past the of the section\n";
  4469. break;
  4470. }
  4471. memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
  4472. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4473. sys::swapByteOrder(l);
  4474. print_indent(indent);
  4475. outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
  4476. if (print_protocol(l, indent, info))
  4477. outs() << "(not in an __OBJC section)\n";
  4478. }
  4479. return false;
  4480. }
  4481. static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
  4482. struct ivar_list64_t il;
  4483. struct ivar64_t i;
  4484. const char *r;
  4485. uint32_t offset, xoffset, left, j;
  4486. SectionRef S, xS;
  4487. const char *name, *sym_name, *ivar_offset_p;
  4488. uint64_t ivar_offset, n_value;
  4489. r = get_pointer_64(p, offset, left, S, info);
  4490. if (r == nullptr)
  4491. return;
  4492. memset(&il, '\0', sizeof(struct ivar_list64_t));
  4493. if (left < sizeof(struct ivar_list64_t)) {
  4494. memcpy(&il, r, left);
  4495. outs() << " (ivar_list_t entends past the end of the section)\n";
  4496. } else
  4497. memcpy(&il, r, sizeof(struct ivar_list64_t));
  4498. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4499. swapStruct(il);
  4500. outs() << " entsize " << il.entsize << "\n";
  4501. outs() << " count " << il.count << "\n";
  4502. p += sizeof(struct ivar_list64_t);
  4503. offset += sizeof(struct ivar_list64_t);
  4504. for (j = 0; j < il.count; j++) {
  4505. r = get_pointer_64(p, offset, left, S, info);
  4506. if (r == nullptr)
  4507. return;
  4508. memset(&i, '\0', sizeof(struct ivar64_t));
  4509. if (left < sizeof(struct ivar64_t)) {
  4510. memcpy(&i, r, left);
  4511. outs() << " (ivar_t entends past the end of the section)\n";
  4512. } else
  4513. memcpy(&i, r, sizeof(struct ivar64_t));
  4514. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4515. swapStruct(i);
  4516. outs() << "\t\t\t offset ";
  4517. sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
  4518. info, n_value, i.offset);
  4519. if (n_value != 0) {
  4520. if (info->verbose && sym_name != nullptr)
  4521. outs() << sym_name;
  4522. else
  4523. outs() << format("0x%" PRIx64, n_value);
  4524. if (i.offset != 0)
  4525. outs() << " + " << format("0x%" PRIx64, i.offset);
  4526. } else
  4527. outs() << format("0x%" PRIx64, i.offset);
  4528. ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
  4529. if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
  4530. memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
  4531. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4532. sys::swapByteOrder(ivar_offset);
  4533. outs() << " " << ivar_offset << "\n";
  4534. } else
  4535. outs() << "\n";
  4536. outs() << "\t\t\t name ";
  4537. sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
  4538. n_value, i.name);
  4539. if (n_value != 0) {
  4540. if (info->verbose && sym_name != nullptr)
  4541. outs() << sym_name;
  4542. else
  4543. outs() << format("0x%" PRIx64, n_value);
  4544. if (i.name != 0)
  4545. outs() << " + " << format("0x%" PRIx64, i.name);
  4546. } else
  4547. outs() << format("0x%" PRIx64, i.name);
  4548. name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
  4549. if (name != nullptr)
  4550. outs() << format(" %.*s", left, name);
  4551. outs() << "\n";
  4552. outs() << "\t\t\t type ";
  4553. sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
  4554. n_value, i.name);
  4555. name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
  4556. if (n_value != 0) {
  4557. if (info->verbose && sym_name != nullptr)
  4558. outs() << sym_name;
  4559. else
  4560. outs() << format("0x%" PRIx64, n_value);
  4561. if (i.type != 0)
  4562. outs() << " + " << format("0x%" PRIx64, i.type);
  4563. } else
  4564. outs() << format("0x%" PRIx64, i.type);
  4565. if (name != nullptr)
  4566. outs() << format(" %.*s", left, name);
  4567. outs() << "\n";
  4568. outs() << "\t\t\talignment " << i.alignment << "\n";
  4569. outs() << "\t\t\t size " << i.size << "\n";
  4570. p += sizeof(struct ivar64_t);
  4571. offset += sizeof(struct ivar64_t);
  4572. }
  4573. }
  4574. static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
  4575. struct ivar_list32_t il;
  4576. struct ivar32_t i;
  4577. const char *r;
  4578. uint32_t offset, xoffset, left, j;
  4579. SectionRef S, xS;
  4580. const char *name, *ivar_offset_p;
  4581. uint32_t ivar_offset;
  4582. r = get_pointer_32(p, offset, left, S, info);
  4583. if (r == nullptr)
  4584. return;
  4585. memset(&il, '\0', sizeof(struct ivar_list32_t));
  4586. if (left < sizeof(struct ivar_list32_t)) {
  4587. memcpy(&il, r, left);
  4588. outs() << " (ivar_list_t entends past the end of the section)\n";
  4589. } else
  4590. memcpy(&il, r, sizeof(struct ivar_list32_t));
  4591. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4592. swapStruct(il);
  4593. outs() << " entsize " << il.entsize << "\n";
  4594. outs() << " count " << il.count << "\n";
  4595. p += sizeof(struct ivar_list32_t);
  4596. offset += sizeof(struct ivar_list32_t);
  4597. for (j = 0; j < il.count; j++) {
  4598. r = get_pointer_32(p, offset, left, S, info);
  4599. if (r == nullptr)
  4600. return;
  4601. memset(&i, '\0', sizeof(struct ivar32_t));
  4602. if (left < sizeof(struct ivar32_t)) {
  4603. memcpy(&i, r, left);
  4604. outs() << " (ivar_t entends past the end of the section)\n";
  4605. } else
  4606. memcpy(&i, r, sizeof(struct ivar32_t));
  4607. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4608. swapStruct(i);
  4609. outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
  4610. ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
  4611. if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
  4612. memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
  4613. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4614. sys::swapByteOrder(ivar_offset);
  4615. outs() << " " << ivar_offset << "\n";
  4616. } else
  4617. outs() << "\n";
  4618. outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
  4619. name = get_pointer_32(i.name, xoffset, left, xS, info);
  4620. if (name != nullptr)
  4621. outs() << format(" %.*s", left, name);
  4622. outs() << "\n";
  4623. outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
  4624. name = get_pointer_32(i.type, xoffset, left, xS, info);
  4625. if (name != nullptr)
  4626. outs() << format(" %.*s", left, name);
  4627. outs() << "\n";
  4628. outs() << "\t\t\talignment " << i.alignment << "\n";
  4629. outs() << "\t\t\t size " << i.size << "\n";
  4630. p += sizeof(struct ivar32_t);
  4631. offset += sizeof(struct ivar32_t);
  4632. }
  4633. }
  4634. static void print_objc_property_list64(uint64_t p,
  4635. struct DisassembleInfo *info) {
  4636. struct objc_property_list64 opl;
  4637. struct objc_property64 op;
  4638. const char *r;
  4639. uint32_t offset, xoffset, left, j;
  4640. SectionRef S, xS;
  4641. const char *name, *sym_name;
  4642. uint64_t n_value;
  4643. r = get_pointer_64(p, offset, left, S, info);
  4644. if (r == nullptr)
  4645. return;
  4646. memset(&opl, '\0', sizeof(struct objc_property_list64));
  4647. if (left < sizeof(struct objc_property_list64)) {
  4648. memcpy(&opl, r, left);
  4649. outs() << " (objc_property_list entends past the end of the section)\n";
  4650. } else
  4651. memcpy(&opl, r, sizeof(struct objc_property_list64));
  4652. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4653. swapStruct(opl);
  4654. outs() << " entsize " << opl.entsize << "\n";
  4655. outs() << " count " << opl.count << "\n";
  4656. p += sizeof(struct objc_property_list64);
  4657. offset += sizeof(struct objc_property_list64);
  4658. for (j = 0; j < opl.count; j++) {
  4659. r = get_pointer_64(p, offset, left, S, info);
  4660. if (r == nullptr)
  4661. return;
  4662. memset(&op, '\0', sizeof(struct objc_property64));
  4663. if (left < sizeof(struct objc_property64)) {
  4664. memcpy(&op, r, left);
  4665. outs() << " (objc_property entends past the end of the section)\n";
  4666. } else
  4667. memcpy(&op, r, sizeof(struct objc_property64));
  4668. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4669. swapStruct(op);
  4670. outs() << "\t\t\t name ";
  4671. sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
  4672. info, n_value, op.name);
  4673. if (n_value != 0) {
  4674. if (info->verbose && sym_name != nullptr)
  4675. outs() << sym_name;
  4676. else
  4677. outs() << format("0x%" PRIx64, n_value);
  4678. if (op.name != 0)
  4679. outs() << " + " << format("0x%" PRIx64, op.name);
  4680. } else
  4681. outs() << format("0x%" PRIx64, op.name);
  4682. name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
  4683. if (name != nullptr)
  4684. outs() << format(" %.*s", left, name);
  4685. outs() << "\n";
  4686. outs() << "\t\t\tattributes ";
  4687. sym_name =
  4688. get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
  4689. info, n_value, op.attributes);
  4690. if (n_value != 0) {
  4691. if (info->verbose && sym_name != nullptr)
  4692. outs() << sym_name;
  4693. else
  4694. outs() << format("0x%" PRIx64, n_value);
  4695. if (op.attributes != 0)
  4696. outs() << " + " << format("0x%" PRIx64, op.attributes);
  4697. } else
  4698. outs() << format("0x%" PRIx64, op.attributes);
  4699. name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
  4700. if (name != nullptr)
  4701. outs() << format(" %.*s", left, name);
  4702. outs() << "\n";
  4703. p += sizeof(struct objc_property64);
  4704. offset += sizeof(struct objc_property64);
  4705. }
  4706. }
  4707. static void print_objc_property_list32(uint32_t p,
  4708. struct DisassembleInfo *info) {
  4709. struct objc_property_list32 opl;
  4710. struct objc_property32 op;
  4711. const char *r;
  4712. uint32_t offset, xoffset, left, j;
  4713. SectionRef S, xS;
  4714. const char *name;
  4715. r = get_pointer_32(p, offset, left, S, info);
  4716. if (r == nullptr)
  4717. return;
  4718. memset(&opl, '\0', sizeof(struct objc_property_list32));
  4719. if (left < sizeof(struct objc_property_list32)) {
  4720. memcpy(&opl, r, left);
  4721. outs() << " (objc_property_list entends past the end of the section)\n";
  4722. } else
  4723. memcpy(&opl, r, sizeof(struct objc_property_list32));
  4724. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4725. swapStruct(opl);
  4726. outs() << " entsize " << opl.entsize << "\n";
  4727. outs() << " count " << opl.count << "\n";
  4728. p += sizeof(struct objc_property_list32);
  4729. offset += sizeof(struct objc_property_list32);
  4730. for (j = 0; j < opl.count; j++) {
  4731. r = get_pointer_32(p, offset, left, S, info);
  4732. if (r == nullptr)
  4733. return;
  4734. memset(&op, '\0', sizeof(struct objc_property32));
  4735. if (left < sizeof(struct objc_property32)) {
  4736. memcpy(&op, r, left);
  4737. outs() << " (objc_property entends past the end of the section)\n";
  4738. } else
  4739. memcpy(&op, r, sizeof(struct objc_property32));
  4740. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4741. swapStruct(op);
  4742. outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
  4743. name = get_pointer_32(op.name, xoffset, left, xS, info);
  4744. if (name != nullptr)
  4745. outs() << format(" %.*s", left, name);
  4746. outs() << "\n";
  4747. outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
  4748. name = get_pointer_32(op.attributes, xoffset, left, xS, info);
  4749. if (name != nullptr)
  4750. outs() << format(" %.*s", left, name);
  4751. outs() << "\n";
  4752. p += sizeof(struct objc_property32);
  4753. offset += sizeof(struct objc_property32);
  4754. }
  4755. }
  4756. static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
  4757. bool &is_meta_class) {
  4758. struct class_ro64_t cro;
  4759. const char *r;
  4760. uint32_t offset, xoffset, left;
  4761. SectionRef S, xS;
  4762. const char *name, *sym_name;
  4763. uint64_t n_value;
  4764. r = get_pointer_64(p, offset, left, S, info);
  4765. if (r == nullptr || left < sizeof(struct class_ro64_t))
  4766. return false;
  4767. memcpy(&cro, r, sizeof(struct class_ro64_t));
  4768. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4769. swapStruct(cro);
  4770. outs() << " flags " << format("0x%" PRIx32, cro.flags);
  4771. if (cro.flags & RO_META)
  4772. outs() << " RO_META";
  4773. if (cro.flags & RO_ROOT)
  4774. outs() << " RO_ROOT";
  4775. if (cro.flags & RO_HAS_CXX_STRUCTORS)
  4776. outs() << " RO_HAS_CXX_STRUCTORS";
  4777. outs() << "\n";
  4778. outs() << " instanceStart " << cro.instanceStart << "\n";
  4779. outs() << " instanceSize " << cro.instanceSize << "\n";
  4780. outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
  4781. << "\n";
  4782. outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
  4783. << "\n";
  4784. print_layout_map64(cro.ivarLayout, info);
  4785. outs() << " name ";
  4786. sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
  4787. info, n_value, cro.name);
  4788. if (n_value != 0) {
  4789. if (info->verbose && sym_name != nullptr)
  4790. outs() << sym_name;
  4791. else
  4792. outs() << format("0x%" PRIx64, n_value);
  4793. if (cro.name != 0)
  4794. outs() << " + " << format("0x%" PRIx64, cro.name);
  4795. } else
  4796. outs() << format("0x%" PRIx64, cro.name);
  4797. name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
  4798. if (name != nullptr)
  4799. outs() << format(" %.*s", left, name);
  4800. outs() << "\n";
  4801. outs() << " baseMethods ";
  4802. sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
  4803. S, info, n_value, cro.baseMethods);
  4804. if (n_value != 0) {
  4805. if (info->verbose && sym_name != nullptr)
  4806. outs() << sym_name;
  4807. else
  4808. outs() << format("0x%" PRIx64, n_value);
  4809. if (cro.baseMethods != 0)
  4810. outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
  4811. } else
  4812. outs() << format("0x%" PRIx64, cro.baseMethods);
  4813. outs() << " (struct method_list_t *)\n";
  4814. if (cro.baseMethods + n_value != 0)
  4815. print_method_list64_t(cro.baseMethods + n_value, info, "");
  4816. outs() << " baseProtocols ";
  4817. sym_name =
  4818. get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
  4819. info, n_value, cro.baseProtocols);
  4820. if (n_value != 0) {
  4821. if (info->verbose && sym_name != nullptr)
  4822. outs() << sym_name;
  4823. else
  4824. outs() << format("0x%" PRIx64, n_value);
  4825. if (cro.baseProtocols != 0)
  4826. outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
  4827. } else
  4828. outs() << format("0x%" PRIx64, cro.baseProtocols);
  4829. outs() << "\n";
  4830. if (cro.baseProtocols + n_value != 0)
  4831. print_protocol_list64_t(cro.baseProtocols + n_value, info);
  4832. outs() << " ivars ";
  4833. sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
  4834. info, n_value, cro.ivars);
  4835. if (n_value != 0) {
  4836. if (info->verbose && sym_name != nullptr)
  4837. outs() << sym_name;
  4838. else
  4839. outs() << format("0x%" PRIx64, n_value);
  4840. if (cro.ivars != 0)
  4841. outs() << " + " << format("0x%" PRIx64, cro.ivars);
  4842. } else
  4843. outs() << format("0x%" PRIx64, cro.ivars);
  4844. outs() << "\n";
  4845. if (cro.ivars + n_value != 0)
  4846. print_ivar_list64_t(cro.ivars + n_value, info);
  4847. outs() << " weakIvarLayout ";
  4848. sym_name =
  4849. get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
  4850. info, n_value, cro.weakIvarLayout);
  4851. if (n_value != 0) {
  4852. if (info->verbose && sym_name != nullptr)
  4853. outs() << sym_name;
  4854. else
  4855. outs() << format("0x%" PRIx64, n_value);
  4856. if (cro.weakIvarLayout != 0)
  4857. outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
  4858. } else
  4859. outs() << format("0x%" PRIx64, cro.weakIvarLayout);
  4860. outs() << "\n";
  4861. print_layout_map64(cro.weakIvarLayout + n_value, info);
  4862. outs() << " baseProperties ";
  4863. sym_name =
  4864. get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
  4865. info, n_value, cro.baseProperties);
  4866. if (n_value != 0) {
  4867. if (info->verbose && sym_name != nullptr)
  4868. outs() << sym_name;
  4869. else
  4870. outs() << format("0x%" PRIx64, n_value);
  4871. if (cro.baseProperties != 0)
  4872. outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
  4873. } else
  4874. outs() << format("0x%" PRIx64, cro.baseProperties);
  4875. outs() << "\n";
  4876. if (cro.baseProperties + n_value != 0)
  4877. print_objc_property_list64(cro.baseProperties + n_value, info);
  4878. is_meta_class = (cro.flags & RO_META) != 0;
  4879. return true;
  4880. }
  4881. static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
  4882. bool &is_meta_class) {
  4883. struct class_ro32_t cro;
  4884. const char *r;
  4885. uint32_t offset, xoffset, left;
  4886. SectionRef S, xS;
  4887. const char *name;
  4888. r = get_pointer_32(p, offset, left, S, info);
  4889. if (r == nullptr)
  4890. return false;
  4891. memset(&cro, '\0', sizeof(struct class_ro32_t));
  4892. if (left < sizeof(struct class_ro32_t)) {
  4893. memcpy(&cro, r, left);
  4894. outs() << " (class_ro_t entends past the end of the section)\n";
  4895. } else
  4896. memcpy(&cro, r, sizeof(struct class_ro32_t));
  4897. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4898. swapStruct(cro);
  4899. outs() << " flags " << format("0x%" PRIx32, cro.flags);
  4900. if (cro.flags & RO_META)
  4901. outs() << " RO_META";
  4902. if (cro.flags & RO_ROOT)
  4903. outs() << " RO_ROOT";
  4904. if (cro.flags & RO_HAS_CXX_STRUCTORS)
  4905. outs() << " RO_HAS_CXX_STRUCTORS";
  4906. outs() << "\n";
  4907. outs() << " instanceStart " << cro.instanceStart << "\n";
  4908. outs() << " instanceSize " << cro.instanceSize << "\n";
  4909. outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
  4910. << "\n";
  4911. print_layout_map32(cro.ivarLayout, info);
  4912. outs() << " name " << format("0x%" PRIx32, cro.name);
  4913. name = get_pointer_32(cro.name, xoffset, left, xS, info);
  4914. if (name != nullptr)
  4915. outs() << format(" %.*s", left, name);
  4916. outs() << "\n";
  4917. outs() << " baseMethods "
  4918. << format("0x%" PRIx32, cro.baseMethods)
  4919. << " (struct method_list_t *)\n";
  4920. if (cro.baseMethods != 0)
  4921. print_method_list32_t(cro.baseMethods, info, "");
  4922. outs() << " baseProtocols "
  4923. << format("0x%" PRIx32, cro.baseProtocols) << "\n";
  4924. if (cro.baseProtocols != 0)
  4925. print_protocol_list32_t(cro.baseProtocols, info);
  4926. outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
  4927. << "\n";
  4928. if (cro.ivars != 0)
  4929. print_ivar_list32_t(cro.ivars, info);
  4930. outs() << " weakIvarLayout "
  4931. << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
  4932. print_layout_map32(cro.weakIvarLayout, info);
  4933. outs() << " baseProperties "
  4934. << format("0x%" PRIx32, cro.baseProperties) << "\n";
  4935. if (cro.baseProperties != 0)
  4936. print_objc_property_list32(cro.baseProperties, info);
  4937. is_meta_class = (cro.flags & RO_META) != 0;
  4938. return true;
  4939. }
  4940. static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
  4941. struct class64_t c;
  4942. const char *r;
  4943. uint32_t offset, left;
  4944. SectionRef S;
  4945. const char *name;
  4946. uint64_t isa_n_value, n_value;
  4947. r = get_pointer_64(p, offset, left, S, info);
  4948. if (r == nullptr || left < sizeof(struct class64_t))
  4949. return;
  4950. memcpy(&c, r, sizeof(struct class64_t));
  4951. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  4952. swapStruct(c);
  4953. outs() << " isa " << format("0x%" PRIx64, c.isa);
  4954. name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
  4955. isa_n_value, c.isa);
  4956. if (name != nullptr)
  4957. outs() << " " << name;
  4958. outs() << "\n";
  4959. outs() << " superclass " << format("0x%" PRIx64, c.superclass);
  4960. name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
  4961. n_value, c.superclass);
  4962. if (name != nullptr)
  4963. outs() << " " << name;
  4964. else {
  4965. name = get_dyld_bind_info_symbolname(S.getAddress() +
  4966. offset + offsetof(struct class64_t, superclass), info);
  4967. if (name != nullptr)
  4968. outs() << " " << name;
  4969. }
  4970. outs() << "\n";
  4971. outs() << " cache " << format("0x%" PRIx64, c.cache);
  4972. name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
  4973. n_value, c.cache);
  4974. if (name != nullptr)
  4975. outs() << " " << name;
  4976. outs() << "\n";
  4977. outs() << " vtable " << format("0x%" PRIx64, c.vtable);
  4978. name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
  4979. n_value, c.vtable);
  4980. if (name != nullptr)
  4981. outs() << " " << name;
  4982. outs() << "\n";
  4983. name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
  4984. n_value, c.data);
  4985. outs() << " data ";
  4986. if (n_value != 0) {
  4987. if (info->verbose && name != nullptr)
  4988. outs() << name;
  4989. else
  4990. outs() << format("0x%" PRIx64, n_value);
  4991. if (c.data != 0)
  4992. outs() << " + " << format("0x%" PRIx64, c.data);
  4993. } else
  4994. outs() << format("0x%" PRIx64, c.data);
  4995. outs() << " (struct class_ro_t *)";
  4996. // This is a Swift class if some of the low bits of the pointer are set.
  4997. if ((c.data + n_value) & 0x7)
  4998. outs() << " Swift class";
  4999. outs() << "\n";
  5000. bool is_meta_class;
  5001. if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
  5002. return;
  5003. if (!is_meta_class &&
  5004. c.isa + isa_n_value != p &&
  5005. c.isa + isa_n_value != 0 &&
  5006. info->depth < 100) {
  5007. info->depth++;
  5008. outs() << "Meta Class\n";
  5009. print_class64_t(c.isa + isa_n_value, info);
  5010. }
  5011. }
  5012. static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
  5013. struct class32_t c;
  5014. const char *r;
  5015. uint32_t offset, left;
  5016. SectionRef S;
  5017. const char *name;
  5018. r = get_pointer_32(p, offset, left, S, info);
  5019. if (r == nullptr)
  5020. return;
  5021. memset(&c, '\0', sizeof(struct class32_t));
  5022. if (left < sizeof(struct class32_t)) {
  5023. memcpy(&c, r, left);
  5024. outs() << " (class_t entends past the end of the section)\n";
  5025. } else
  5026. memcpy(&c, r, sizeof(struct class32_t));
  5027. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5028. swapStruct(c);
  5029. outs() << " isa " << format("0x%" PRIx32, c.isa);
  5030. name =
  5031. get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
  5032. if (name != nullptr)
  5033. outs() << " " << name;
  5034. outs() << "\n";
  5035. outs() << " superclass " << format("0x%" PRIx32, c.superclass);
  5036. name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
  5037. c.superclass);
  5038. if (name != nullptr)
  5039. outs() << " " << name;
  5040. outs() << "\n";
  5041. outs() << " cache " << format("0x%" PRIx32, c.cache);
  5042. name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
  5043. c.cache);
  5044. if (name != nullptr)
  5045. outs() << " " << name;
  5046. outs() << "\n";
  5047. outs() << " vtable " << format("0x%" PRIx32, c.vtable);
  5048. name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
  5049. c.vtable);
  5050. if (name != nullptr)
  5051. outs() << " " << name;
  5052. outs() << "\n";
  5053. name =
  5054. get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
  5055. outs() << " data " << format("0x%" PRIx32, c.data)
  5056. << " (struct class_ro_t *)";
  5057. // This is a Swift class if some of the low bits of the pointer are set.
  5058. if (c.data & 0x3)
  5059. outs() << " Swift class";
  5060. outs() << "\n";
  5061. bool is_meta_class;
  5062. if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
  5063. return;
  5064. if (!is_meta_class) {
  5065. outs() << "Meta Class\n";
  5066. print_class32_t(c.isa, info);
  5067. }
  5068. }
  5069. static void print_objc_class_t(struct objc_class_t *objc_class,
  5070. struct DisassembleInfo *info) {
  5071. uint32_t offset, left, xleft;
  5072. const char *name, *p, *ivar_list;
  5073. SectionRef S;
  5074. int32_t i;
  5075. struct objc_ivar_list_t objc_ivar_list;
  5076. struct objc_ivar_t ivar;
  5077. outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
  5078. if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
  5079. name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
  5080. if (name != nullptr)
  5081. outs() << format(" %.*s", left, name);
  5082. else
  5083. outs() << " (not in an __OBJC section)";
  5084. }
  5085. outs() << "\n";
  5086. outs() << "\t super_class "
  5087. << format("0x%08" PRIx32, objc_class->super_class);
  5088. if (info->verbose) {
  5089. name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
  5090. if (name != nullptr)
  5091. outs() << format(" %.*s", left, name);
  5092. else
  5093. outs() << " (not in an __OBJC section)";
  5094. }
  5095. outs() << "\n";
  5096. outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
  5097. if (info->verbose) {
  5098. name = get_pointer_32(objc_class->name, offset, left, S, info, true);
  5099. if (name != nullptr)
  5100. outs() << format(" %.*s", left, name);
  5101. else
  5102. outs() << " (not in an __OBJC section)";
  5103. }
  5104. outs() << "\n";
  5105. outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
  5106. << "\n";
  5107. outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
  5108. if (info->verbose) {
  5109. if (CLS_GETINFO(objc_class, CLS_CLASS))
  5110. outs() << " CLS_CLASS";
  5111. else if (CLS_GETINFO(objc_class, CLS_META))
  5112. outs() << " CLS_META";
  5113. }
  5114. outs() << "\n";
  5115. outs() << "\t instance_size "
  5116. << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
  5117. p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
  5118. outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
  5119. if (p != nullptr) {
  5120. if (left > sizeof(struct objc_ivar_list_t)) {
  5121. outs() << "\n";
  5122. memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
  5123. } else {
  5124. outs() << " (entends past the end of the section)\n";
  5125. memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
  5126. memcpy(&objc_ivar_list, p, left);
  5127. }
  5128. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5129. swapStruct(objc_ivar_list);
  5130. outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
  5131. ivar_list = p + sizeof(struct objc_ivar_list_t);
  5132. for (i = 0; i < objc_ivar_list.ivar_count; i++) {
  5133. if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
  5134. outs() << "\t\t remaining ivar's extend past the of the section\n";
  5135. break;
  5136. }
  5137. memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
  5138. sizeof(struct objc_ivar_t));
  5139. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5140. swapStruct(ivar);
  5141. outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
  5142. if (info->verbose) {
  5143. name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
  5144. if (name != nullptr)
  5145. outs() << format(" %.*s", xleft, name);
  5146. else
  5147. outs() << " (not in an __OBJC section)";
  5148. }
  5149. outs() << "\n";
  5150. outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
  5151. if (info->verbose) {
  5152. name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
  5153. if (name != nullptr)
  5154. outs() << format(" %.*s", xleft, name);
  5155. else
  5156. outs() << " (not in an __OBJC section)";
  5157. }
  5158. outs() << "\n";
  5159. outs() << "\t\t ivar_offset "
  5160. << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
  5161. }
  5162. } else {
  5163. outs() << " (not in an __OBJC section)\n";
  5164. }
  5165. outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
  5166. if (print_method_list(objc_class->methodLists, info))
  5167. outs() << " (not in an __OBJC section)\n";
  5168. outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
  5169. << "\n";
  5170. outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
  5171. if (print_protocol_list(objc_class->protocols, 16, info))
  5172. outs() << " (not in an __OBJC section)\n";
  5173. }
  5174. static void print_objc_objc_category_t(struct objc_category_t *objc_category,
  5175. struct DisassembleInfo *info) {
  5176. uint32_t offset, left;
  5177. const char *name;
  5178. SectionRef S;
  5179. outs() << "\t category name "
  5180. << format("0x%08" PRIx32, objc_category->category_name);
  5181. if (info->verbose) {
  5182. name = get_pointer_32(objc_category->category_name, offset, left, S, info,
  5183. true);
  5184. if (name != nullptr)
  5185. outs() << format(" %.*s", left, name);
  5186. else
  5187. outs() << " (not in an __OBJC section)";
  5188. }
  5189. outs() << "\n";
  5190. outs() << "\t\t class name "
  5191. << format("0x%08" PRIx32, objc_category->class_name);
  5192. if (info->verbose) {
  5193. name =
  5194. get_pointer_32(objc_category->class_name, offset, left, S, info, true);
  5195. if (name != nullptr)
  5196. outs() << format(" %.*s", left, name);
  5197. else
  5198. outs() << " (not in an __OBJC section)";
  5199. }
  5200. outs() << "\n";
  5201. outs() << "\t instance methods "
  5202. << format("0x%08" PRIx32, objc_category->instance_methods);
  5203. if (print_method_list(objc_category->instance_methods, info))
  5204. outs() << " (not in an __OBJC section)\n";
  5205. outs() << "\t class methods "
  5206. << format("0x%08" PRIx32, objc_category->class_methods);
  5207. if (print_method_list(objc_category->class_methods, info))
  5208. outs() << " (not in an __OBJC section)\n";
  5209. }
  5210. static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
  5211. struct category64_t c;
  5212. const char *r;
  5213. uint32_t offset, xoffset, left;
  5214. SectionRef S, xS;
  5215. const char *name, *sym_name;
  5216. uint64_t n_value;
  5217. r = get_pointer_64(p, offset, left, S, info);
  5218. if (r == nullptr)
  5219. return;
  5220. memset(&c, '\0', sizeof(struct category64_t));
  5221. if (left < sizeof(struct category64_t)) {
  5222. memcpy(&c, r, left);
  5223. outs() << " (category_t entends past the end of the section)\n";
  5224. } else
  5225. memcpy(&c, r, sizeof(struct category64_t));
  5226. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5227. swapStruct(c);
  5228. outs() << " name ";
  5229. sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
  5230. info, n_value, c.name);
  5231. if (n_value != 0) {
  5232. if (info->verbose && sym_name != nullptr)
  5233. outs() << sym_name;
  5234. else
  5235. outs() << format("0x%" PRIx64, n_value);
  5236. if (c.name != 0)
  5237. outs() << " + " << format("0x%" PRIx64, c.name);
  5238. } else
  5239. outs() << format("0x%" PRIx64, c.name);
  5240. name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
  5241. if (name != nullptr)
  5242. outs() << format(" %.*s", left, name);
  5243. outs() << "\n";
  5244. outs() << " cls ";
  5245. sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
  5246. n_value, c.cls);
  5247. if (n_value != 0) {
  5248. if (info->verbose && sym_name != nullptr)
  5249. outs() << sym_name;
  5250. else
  5251. outs() << format("0x%" PRIx64, n_value);
  5252. if (c.cls != 0)
  5253. outs() << " + " << format("0x%" PRIx64, c.cls);
  5254. } else
  5255. outs() << format("0x%" PRIx64, c.cls);
  5256. outs() << "\n";
  5257. if (c.cls + n_value != 0)
  5258. print_class64_t(c.cls + n_value, info);
  5259. outs() << " instanceMethods ";
  5260. sym_name =
  5261. get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
  5262. info, n_value, c.instanceMethods);
  5263. if (n_value != 0) {
  5264. if (info->verbose && sym_name != nullptr)
  5265. outs() << sym_name;
  5266. else
  5267. outs() << format("0x%" PRIx64, n_value);
  5268. if (c.instanceMethods != 0)
  5269. outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
  5270. } else
  5271. outs() << format("0x%" PRIx64, c.instanceMethods);
  5272. outs() << "\n";
  5273. if (c.instanceMethods + n_value != 0)
  5274. print_method_list64_t(c.instanceMethods + n_value, info, "");
  5275. outs() << " classMethods ";
  5276. sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
  5277. S, info, n_value, c.classMethods);
  5278. if (n_value != 0) {
  5279. if (info->verbose && sym_name != nullptr)
  5280. outs() << sym_name;
  5281. else
  5282. outs() << format("0x%" PRIx64, n_value);
  5283. if (c.classMethods != 0)
  5284. outs() << " + " << format("0x%" PRIx64, c.classMethods);
  5285. } else
  5286. outs() << format("0x%" PRIx64, c.classMethods);
  5287. outs() << "\n";
  5288. if (c.classMethods + n_value != 0)
  5289. print_method_list64_t(c.classMethods + n_value, info, "");
  5290. outs() << " protocols ";
  5291. sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
  5292. info, n_value, c.protocols);
  5293. if (n_value != 0) {
  5294. if (info->verbose && sym_name != nullptr)
  5295. outs() << sym_name;
  5296. else
  5297. outs() << format("0x%" PRIx64, n_value);
  5298. if (c.protocols != 0)
  5299. outs() << " + " << format("0x%" PRIx64, c.protocols);
  5300. } else
  5301. outs() << format("0x%" PRIx64, c.protocols);
  5302. outs() << "\n";
  5303. if (c.protocols + n_value != 0)
  5304. print_protocol_list64_t(c.protocols + n_value, info);
  5305. outs() << "instanceProperties ";
  5306. sym_name =
  5307. get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
  5308. S, info, n_value, c.instanceProperties);
  5309. if (n_value != 0) {
  5310. if (info->verbose && sym_name != nullptr)
  5311. outs() << sym_name;
  5312. else
  5313. outs() << format("0x%" PRIx64, n_value);
  5314. if (c.instanceProperties != 0)
  5315. outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
  5316. } else
  5317. outs() << format("0x%" PRIx64, c.instanceProperties);
  5318. outs() << "\n";
  5319. if (c.instanceProperties + n_value != 0)
  5320. print_objc_property_list64(c.instanceProperties + n_value, info);
  5321. }
  5322. static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
  5323. struct category32_t c;
  5324. const char *r;
  5325. uint32_t offset, left;
  5326. SectionRef S, xS;
  5327. const char *name;
  5328. r = get_pointer_32(p, offset, left, S, info);
  5329. if (r == nullptr)
  5330. return;
  5331. memset(&c, '\0', sizeof(struct category32_t));
  5332. if (left < sizeof(struct category32_t)) {
  5333. memcpy(&c, r, left);
  5334. outs() << " (category_t entends past the end of the section)\n";
  5335. } else
  5336. memcpy(&c, r, sizeof(struct category32_t));
  5337. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5338. swapStruct(c);
  5339. outs() << " name " << format("0x%" PRIx32, c.name);
  5340. name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
  5341. c.name);
  5342. if (name)
  5343. outs() << " " << name;
  5344. outs() << "\n";
  5345. outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
  5346. if (c.cls != 0)
  5347. print_class32_t(c.cls, info);
  5348. outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
  5349. << "\n";
  5350. if (c.instanceMethods != 0)
  5351. print_method_list32_t(c.instanceMethods, info, "");
  5352. outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
  5353. << "\n";
  5354. if (c.classMethods != 0)
  5355. print_method_list32_t(c.classMethods, info, "");
  5356. outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
  5357. if (c.protocols != 0)
  5358. print_protocol_list32_t(c.protocols, info);
  5359. outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
  5360. << "\n";
  5361. if (c.instanceProperties != 0)
  5362. print_objc_property_list32(c.instanceProperties, info);
  5363. }
  5364. static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
  5365. uint32_t i, left, offset, xoffset;
  5366. uint64_t p, n_value;
  5367. struct message_ref64 mr;
  5368. const char *name, *sym_name;
  5369. const char *r;
  5370. SectionRef xS;
  5371. if (S == SectionRef())
  5372. return;
  5373. StringRef SectName;
  5374. Expected<StringRef> SecNameOrErr = S.getName();
  5375. if (SecNameOrErr)
  5376. SectName = *SecNameOrErr;
  5377. else
  5378. consumeError(SecNameOrErr.takeError());
  5379. DataRefImpl Ref = S.getRawDataRefImpl();
  5380. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  5381. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  5382. offset = 0;
  5383. for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
  5384. p = S.getAddress() + i;
  5385. r = get_pointer_64(p, offset, left, S, info);
  5386. if (r == nullptr)
  5387. return;
  5388. memset(&mr, '\0', sizeof(struct message_ref64));
  5389. if (left < sizeof(struct message_ref64)) {
  5390. memcpy(&mr, r, left);
  5391. outs() << " (message_ref entends past the end of the section)\n";
  5392. } else
  5393. memcpy(&mr, r, sizeof(struct message_ref64));
  5394. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5395. swapStruct(mr);
  5396. outs() << " imp ";
  5397. name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
  5398. n_value, mr.imp);
  5399. if (n_value != 0) {
  5400. outs() << format("0x%" PRIx64, n_value) << " ";
  5401. if (mr.imp != 0)
  5402. outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
  5403. } else
  5404. outs() << format("0x%" PRIx64, mr.imp) << " ";
  5405. if (name != nullptr)
  5406. outs() << " " << name;
  5407. outs() << "\n";
  5408. outs() << " sel ";
  5409. sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
  5410. info, n_value, mr.sel);
  5411. if (n_value != 0) {
  5412. if (info->verbose && sym_name != nullptr)
  5413. outs() << sym_name;
  5414. else
  5415. outs() << format("0x%" PRIx64, n_value);
  5416. if (mr.sel != 0)
  5417. outs() << " + " << format("0x%" PRIx64, mr.sel);
  5418. } else
  5419. outs() << format("0x%" PRIx64, mr.sel);
  5420. name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
  5421. if (name != nullptr)
  5422. outs() << format(" %.*s", left, name);
  5423. outs() << "\n";
  5424. offset += sizeof(struct message_ref64);
  5425. }
  5426. }
  5427. static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
  5428. uint32_t i, left, offset, xoffset, p;
  5429. struct message_ref32 mr;
  5430. const char *name, *r;
  5431. SectionRef xS;
  5432. if (S == SectionRef())
  5433. return;
  5434. StringRef SectName;
  5435. Expected<StringRef> SecNameOrErr = S.getName();
  5436. if (SecNameOrErr)
  5437. SectName = *SecNameOrErr;
  5438. else
  5439. consumeError(SecNameOrErr.takeError());
  5440. DataRefImpl Ref = S.getRawDataRefImpl();
  5441. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  5442. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  5443. offset = 0;
  5444. for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
  5445. p = S.getAddress() + i;
  5446. r = get_pointer_32(p, offset, left, S, info);
  5447. if (r == nullptr)
  5448. return;
  5449. memset(&mr, '\0', sizeof(struct message_ref32));
  5450. if (left < sizeof(struct message_ref32)) {
  5451. memcpy(&mr, r, left);
  5452. outs() << " (message_ref entends past the end of the section)\n";
  5453. } else
  5454. memcpy(&mr, r, sizeof(struct message_ref32));
  5455. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5456. swapStruct(mr);
  5457. outs() << " imp " << format("0x%" PRIx32, mr.imp);
  5458. name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
  5459. mr.imp);
  5460. if (name != nullptr)
  5461. outs() << " " << name;
  5462. outs() << "\n";
  5463. outs() << " sel " << format("0x%" PRIx32, mr.sel);
  5464. name = get_pointer_32(mr.sel, xoffset, left, xS, info);
  5465. if (name != nullptr)
  5466. outs() << " " << name;
  5467. outs() << "\n";
  5468. offset += sizeof(struct message_ref32);
  5469. }
  5470. }
  5471. static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
  5472. uint32_t left, offset, swift_version;
  5473. uint64_t p;
  5474. struct objc_image_info64 o;
  5475. const char *r;
  5476. if (S == SectionRef())
  5477. return;
  5478. StringRef SectName;
  5479. Expected<StringRef> SecNameOrErr = S.getName();
  5480. if (SecNameOrErr)
  5481. SectName = *SecNameOrErr;
  5482. else
  5483. consumeError(SecNameOrErr.takeError());
  5484. DataRefImpl Ref = S.getRawDataRefImpl();
  5485. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  5486. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  5487. p = S.getAddress();
  5488. r = get_pointer_64(p, offset, left, S, info);
  5489. if (r == nullptr)
  5490. return;
  5491. memset(&o, '\0', sizeof(struct objc_image_info64));
  5492. if (left < sizeof(struct objc_image_info64)) {
  5493. memcpy(&o, r, left);
  5494. outs() << " (objc_image_info entends past the end of the section)\n";
  5495. } else
  5496. memcpy(&o, r, sizeof(struct objc_image_info64));
  5497. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5498. swapStruct(o);
  5499. outs() << " version " << o.version << "\n";
  5500. outs() << " flags " << format("0x%" PRIx32, o.flags);
  5501. if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
  5502. outs() << " OBJC_IMAGE_IS_REPLACEMENT";
  5503. if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
  5504. outs() << " OBJC_IMAGE_SUPPORTS_GC";
  5505. if (o.flags & OBJC_IMAGE_IS_SIMULATED)
  5506. outs() << " OBJC_IMAGE_IS_SIMULATED";
  5507. if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
  5508. outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
  5509. swift_version = (o.flags >> 8) & 0xff;
  5510. if (swift_version != 0) {
  5511. if (swift_version == 1)
  5512. outs() << " Swift 1.0";
  5513. else if (swift_version == 2)
  5514. outs() << " Swift 1.1";
  5515. else if(swift_version == 3)
  5516. outs() << " Swift 2.0";
  5517. else if(swift_version == 4)
  5518. outs() << " Swift 3.0";
  5519. else if(swift_version == 5)
  5520. outs() << " Swift 4.0";
  5521. else if(swift_version == 6)
  5522. outs() << " Swift 4.1/Swift 4.2";
  5523. else if(swift_version == 7)
  5524. outs() << " Swift 5 or later";
  5525. else
  5526. outs() << " unknown future Swift version (" << swift_version << ")";
  5527. }
  5528. outs() << "\n";
  5529. }
  5530. static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
  5531. uint32_t left, offset, swift_version, p;
  5532. struct objc_image_info32 o;
  5533. const char *r;
  5534. if (S == SectionRef())
  5535. return;
  5536. StringRef SectName;
  5537. Expected<StringRef> SecNameOrErr = S.getName();
  5538. if (SecNameOrErr)
  5539. SectName = *SecNameOrErr;
  5540. else
  5541. consumeError(SecNameOrErr.takeError());
  5542. DataRefImpl Ref = S.getRawDataRefImpl();
  5543. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  5544. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  5545. p = S.getAddress();
  5546. r = get_pointer_32(p, offset, left, S, info);
  5547. if (r == nullptr)
  5548. return;
  5549. memset(&o, '\0', sizeof(struct objc_image_info32));
  5550. if (left < sizeof(struct objc_image_info32)) {
  5551. memcpy(&o, r, left);
  5552. outs() << " (objc_image_info entends past the end of the section)\n";
  5553. } else
  5554. memcpy(&o, r, sizeof(struct objc_image_info32));
  5555. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5556. swapStruct(o);
  5557. outs() << " version " << o.version << "\n";
  5558. outs() << " flags " << format("0x%" PRIx32, o.flags);
  5559. if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
  5560. outs() << " OBJC_IMAGE_IS_REPLACEMENT";
  5561. if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
  5562. outs() << " OBJC_IMAGE_SUPPORTS_GC";
  5563. swift_version = (o.flags >> 8) & 0xff;
  5564. if (swift_version != 0) {
  5565. if (swift_version == 1)
  5566. outs() << " Swift 1.0";
  5567. else if (swift_version == 2)
  5568. outs() << " Swift 1.1";
  5569. else if(swift_version == 3)
  5570. outs() << " Swift 2.0";
  5571. else if(swift_version == 4)
  5572. outs() << " Swift 3.0";
  5573. else if(swift_version == 5)
  5574. outs() << " Swift 4.0";
  5575. else if(swift_version == 6)
  5576. outs() << " Swift 4.1/Swift 4.2";
  5577. else if(swift_version == 7)
  5578. outs() << " Swift 5 or later";
  5579. else
  5580. outs() << " unknown future Swift version (" << swift_version << ")";
  5581. }
  5582. outs() << "\n";
  5583. }
  5584. static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
  5585. uint32_t left, offset, p;
  5586. struct imageInfo_t o;
  5587. const char *r;
  5588. StringRef SectName;
  5589. Expected<StringRef> SecNameOrErr = S.getName();
  5590. if (SecNameOrErr)
  5591. SectName = *SecNameOrErr;
  5592. else
  5593. consumeError(SecNameOrErr.takeError());
  5594. DataRefImpl Ref = S.getRawDataRefImpl();
  5595. StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
  5596. outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
  5597. p = S.getAddress();
  5598. r = get_pointer_32(p, offset, left, S, info);
  5599. if (r == nullptr)
  5600. return;
  5601. memset(&o, '\0', sizeof(struct imageInfo_t));
  5602. if (left < sizeof(struct imageInfo_t)) {
  5603. memcpy(&o, r, left);
  5604. outs() << " (imageInfo entends past the end of the section)\n";
  5605. } else
  5606. memcpy(&o, r, sizeof(struct imageInfo_t));
  5607. if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
  5608. swapStruct(o);
  5609. outs() << " version " << o.version << "\n";
  5610. outs() << " flags " << format("0x%" PRIx32, o.flags);
  5611. if (o.flags & 0x1)
  5612. outs() << " F&C";
  5613. if (o.flags & 0x2)
  5614. outs() << " GC";
  5615. if (o.flags & 0x4)
  5616. outs() << " GC-only";
  5617. else
  5618. outs() << " RR";
  5619. outs() << "\n";
  5620. }
  5621. static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
  5622. SymbolAddressMap AddrMap;
  5623. if (verbose)
  5624. CreateSymbolAddressMap(O, &AddrMap);
  5625. std::vector<SectionRef> Sections;
  5626. for (const SectionRef &Section : O->sections())
  5627. Sections.push_back(Section);
  5628. struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
  5629. SectionRef CL = get_section(O, "__OBJC2", "__class_list");
  5630. if (CL == SectionRef())
  5631. CL = get_section(O, "__DATA", "__objc_classlist");
  5632. if (CL == SectionRef())
  5633. CL = get_section(O, "__DATA_CONST", "__objc_classlist");
  5634. if (CL == SectionRef())
  5635. CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
  5636. info.S = CL;
  5637. walk_pointer_list_64("class", CL, O, &info, print_class64_t);
  5638. SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
  5639. if (CR == SectionRef())
  5640. CR = get_section(O, "__DATA", "__objc_classrefs");
  5641. if (CR == SectionRef())
  5642. CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
  5643. if (CR == SectionRef())
  5644. CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
  5645. info.S = CR;
  5646. walk_pointer_list_64("class refs", CR, O, &info, nullptr);
  5647. SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
  5648. if (SR == SectionRef())
  5649. SR = get_section(O, "__DATA", "__objc_superrefs");
  5650. if (SR == SectionRef())
  5651. SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
  5652. if (SR == SectionRef())
  5653. SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
  5654. info.S = SR;
  5655. walk_pointer_list_64("super refs", SR, O, &info, nullptr);
  5656. SectionRef CA = get_section(O, "__OBJC2", "__category_list");
  5657. if (CA == SectionRef())
  5658. CA = get_section(O, "__DATA", "__objc_catlist");
  5659. if (CA == SectionRef())
  5660. CA = get_section(O, "__DATA_CONST", "__objc_catlist");
  5661. if (CA == SectionRef())
  5662. CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
  5663. info.S = CA;
  5664. walk_pointer_list_64("category", CA, O, &info, print_category64_t);
  5665. SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
  5666. if (PL == SectionRef())
  5667. PL = get_section(O, "__DATA", "__objc_protolist");
  5668. if (PL == SectionRef())
  5669. PL = get_section(O, "__DATA_CONST", "__objc_protolist");
  5670. if (PL == SectionRef())
  5671. PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
  5672. info.S = PL;
  5673. walk_pointer_list_64("protocol", PL, O, &info, nullptr);
  5674. SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
  5675. if (MR == SectionRef())
  5676. MR = get_section(O, "__DATA", "__objc_msgrefs");
  5677. if (MR == SectionRef())
  5678. MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
  5679. if (MR == SectionRef())
  5680. MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
  5681. info.S = MR;
  5682. print_message_refs64(MR, &info);
  5683. SectionRef II = get_section(O, "__OBJC2", "__image_info");
  5684. if (II == SectionRef())
  5685. II = get_section(O, "__DATA", "__objc_imageinfo");
  5686. if (II == SectionRef())
  5687. II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
  5688. if (II == SectionRef())
  5689. II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
  5690. info.S = II;
  5691. print_image_info64(II, &info);
  5692. }
  5693. static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
  5694. SymbolAddressMap AddrMap;
  5695. if (verbose)
  5696. CreateSymbolAddressMap(O, &AddrMap);
  5697. std::vector<SectionRef> Sections;
  5698. for (const SectionRef &Section : O->sections())
  5699. Sections.push_back(Section);
  5700. struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
  5701. SectionRef CL = get_section(O, "__OBJC2", "__class_list");
  5702. if (CL == SectionRef())
  5703. CL = get_section(O, "__DATA", "__objc_classlist");
  5704. if (CL == SectionRef())
  5705. CL = get_section(O, "__DATA_CONST", "__objc_classlist");
  5706. if (CL == SectionRef())
  5707. CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
  5708. info.S = CL;
  5709. walk_pointer_list_32("class", CL, O, &info, print_class32_t);
  5710. SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
  5711. if (CR == SectionRef())
  5712. CR = get_section(O, "__DATA", "__objc_classrefs");
  5713. if (CR == SectionRef())
  5714. CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
  5715. if (CR == SectionRef())
  5716. CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
  5717. info.S = CR;
  5718. walk_pointer_list_32("class refs", CR, O, &info, nullptr);
  5719. SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
  5720. if (SR == SectionRef())
  5721. SR = get_section(O, "__DATA", "__objc_superrefs");
  5722. if (SR == SectionRef())
  5723. SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
  5724. if (SR == SectionRef())
  5725. SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
  5726. info.S = SR;
  5727. walk_pointer_list_32("super refs", SR, O, &info, nullptr);
  5728. SectionRef CA = get_section(O, "__OBJC2", "__category_list");
  5729. if (CA == SectionRef())
  5730. CA = get_section(O, "__DATA", "__objc_catlist");
  5731. if (CA == SectionRef())
  5732. CA = get_section(O, "__DATA_CONST", "__objc_catlist");
  5733. if (CA == SectionRef())
  5734. CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
  5735. info.S = CA;
  5736. walk_pointer_list_32("category", CA, O, &info, print_category32_t);
  5737. SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
  5738. if (PL == SectionRef())
  5739. PL = get_section(O, "__DATA", "__objc_protolist");
  5740. if (PL == SectionRef())
  5741. PL = get_section(O, "__DATA_CONST", "__objc_protolist");
  5742. if (PL == SectionRef())
  5743. PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
  5744. info.S = PL;
  5745. walk_pointer_list_32("protocol", PL, O, &info, nullptr);
  5746. SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
  5747. if (MR == SectionRef())
  5748. MR = get_section(O, "__DATA", "__objc_msgrefs");
  5749. if (MR == SectionRef())
  5750. MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
  5751. if (MR == SectionRef())
  5752. MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
  5753. info.S = MR;
  5754. print_message_refs32(MR, &info);
  5755. SectionRef II = get_section(O, "__OBJC2", "__image_info");
  5756. if (II == SectionRef())
  5757. II = get_section(O, "__DATA", "__objc_imageinfo");
  5758. if (II == SectionRef())
  5759. II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
  5760. if (II == SectionRef())
  5761. II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
  5762. info.S = II;
  5763. print_image_info32(II, &info);
  5764. }
  5765. static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
  5766. uint32_t i, j, p, offset, xoffset, left, defs_left, def;
  5767. const char *r, *name, *defs;
  5768. struct objc_module_t module;
  5769. SectionRef S, xS;
  5770. struct objc_symtab_t symtab;
  5771. struct objc_class_t objc_class;
  5772. struct objc_category_t objc_category;
  5773. outs() << "Objective-C segment\n";
  5774. S = get_section(O, "__OBJC", "__module_info");
  5775. if (S == SectionRef())
  5776. return false;
  5777. SymbolAddressMap AddrMap;
  5778. if (verbose)
  5779. CreateSymbolAddressMap(O, &AddrMap);
  5780. std::vector<SectionRef> Sections;
  5781. for (const SectionRef &Section : O->sections())
  5782. Sections.push_back(Section);
  5783. struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
  5784. for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
  5785. p = S.getAddress() + i;
  5786. r = get_pointer_32(p, offset, left, S, &info, true);
  5787. if (r == nullptr)
  5788. return true;
  5789. memset(&module, '\0', sizeof(struct objc_module_t));
  5790. if (left < sizeof(struct objc_module_t)) {
  5791. memcpy(&module, r, left);
  5792. outs() << " (module extends past end of __module_info section)\n";
  5793. } else
  5794. memcpy(&module, r, sizeof(struct objc_module_t));
  5795. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5796. swapStruct(module);
  5797. outs() << "Module " << format("0x%" PRIx32, p) << "\n";
  5798. outs() << " version " << module.version << "\n";
  5799. outs() << " size " << module.size << "\n";
  5800. outs() << " name ";
  5801. name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
  5802. if (name != nullptr)
  5803. outs() << format("%.*s", left, name);
  5804. else
  5805. outs() << format("0x%08" PRIx32, module.name)
  5806. << "(not in an __OBJC section)";
  5807. outs() << "\n";
  5808. r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
  5809. if (module.symtab == 0 || r == nullptr) {
  5810. outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
  5811. << " (not in an __OBJC section)\n";
  5812. continue;
  5813. }
  5814. outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
  5815. memset(&symtab, '\0', sizeof(struct objc_symtab_t));
  5816. defs_left = 0;
  5817. defs = nullptr;
  5818. if (left < sizeof(struct objc_symtab_t)) {
  5819. memcpy(&symtab, r, left);
  5820. outs() << "\tsymtab extends past end of an __OBJC section)\n";
  5821. } else {
  5822. memcpy(&symtab, r, sizeof(struct objc_symtab_t));
  5823. if (left > sizeof(struct objc_symtab_t)) {
  5824. defs_left = left - sizeof(struct objc_symtab_t);
  5825. defs = r + sizeof(struct objc_symtab_t);
  5826. }
  5827. }
  5828. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5829. swapStruct(symtab);
  5830. outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
  5831. r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
  5832. outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
  5833. if (r == nullptr)
  5834. outs() << " (not in an __OBJC section)";
  5835. outs() << "\n";
  5836. outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
  5837. outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
  5838. if (symtab.cls_def_cnt > 0)
  5839. outs() << "\tClass Definitions\n";
  5840. for (j = 0; j < symtab.cls_def_cnt; j++) {
  5841. if ((j + 1) * sizeof(uint32_t) > defs_left) {
  5842. outs() << "\t(remaining class defs entries entends past the end of the "
  5843. << "section)\n";
  5844. break;
  5845. }
  5846. memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
  5847. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5848. sys::swapByteOrder(def);
  5849. r = get_pointer_32(def, xoffset, left, xS, &info, true);
  5850. outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
  5851. if (r != nullptr) {
  5852. if (left > sizeof(struct objc_class_t)) {
  5853. outs() << "\n";
  5854. memcpy(&objc_class, r, sizeof(struct objc_class_t));
  5855. } else {
  5856. outs() << " (entends past the end of the section)\n";
  5857. memset(&objc_class, '\0', sizeof(struct objc_class_t));
  5858. memcpy(&objc_class, r, left);
  5859. }
  5860. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5861. swapStruct(objc_class);
  5862. print_objc_class_t(&objc_class, &info);
  5863. } else {
  5864. outs() << "(not in an __OBJC section)\n";
  5865. }
  5866. if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
  5867. outs() << "\tMeta Class";
  5868. r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
  5869. if (r != nullptr) {
  5870. if (left > sizeof(struct objc_class_t)) {
  5871. outs() << "\n";
  5872. memcpy(&objc_class, r, sizeof(struct objc_class_t));
  5873. } else {
  5874. outs() << " (entends past the end of the section)\n";
  5875. memset(&objc_class, '\0', sizeof(struct objc_class_t));
  5876. memcpy(&objc_class, r, left);
  5877. }
  5878. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5879. swapStruct(objc_class);
  5880. print_objc_class_t(&objc_class, &info);
  5881. } else {
  5882. outs() << "(not in an __OBJC section)\n";
  5883. }
  5884. }
  5885. }
  5886. if (symtab.cat_def_cnt > 0)
  5887. outs() << "\tCategory Definitions\n";
  5888. for (j = 0; j < symtab.cat_def_cnt; j++) {
  5889. if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
  5890. outs() << "\t(remaining category defs entries entends past the end of "
  5891. << "the section)\n";
  5892. break;
  5893. }
  5894. memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
  5895. sizeof(uint32_t));
  5896. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5897. sys::swapByteOrder(def);
  5898. r = get_pointer_32(def, xoffset, left, xS, &info, true);
  5899. outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
  5900. << format("0x%08" PRIx32, def);
  5901. if (r != nullptr) {
  5902. if (left > sizeof(struct objc_category_t)) {
  5903. outs() << "\n";
  5904. memcpy(&objc_category, r, sizeof(struct objc_category_t));
  5905. } else {
  5906. outs() << " (entends past the end of the section)\n";
  5907. memset(&objc_category, '\0', sizeof(struct objc_category_t));
  5908. memcpy(&objc_category, r, left);
  5909. }
  5910. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5911. swapStruct(objc_category);
  5912. print_objc_objc_category_t(&objc_category, &info);
  5913. } else {
  5914. outs() << "(not in an __OBJC section)\n";
  5915. }
  5916. }
  5917. }
  5918. const SectionRef II = get_section(O, "__OBJC", "__image_info");
  5919. if (II != SectionRef())
  5920. print_image_info(II, &info);
  5921. return true;
  5922. }
  5923. static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
  5924. uint32_t size, uint32_t addr) {
  5925. SymbolAddressMap AddrMap;
  5926. CreateSymbolAddressMap(O, &AddrMap);
  5927. std::vector<SectionRef> Sections;
  5928. for (const SectionRef &Section : O->sections())
  5929. Sections.push_back(Section);
  5930. struct DisassembleInfo info(O, &AddrMap, &Sections, true);
  5931. const char *p;
  5932. struct objc_protocol_t protocol;
  5933. uint32_t left, paddr;
  5934. for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
  5935. memset(&protocol, '\0', sizeof(struct objc_protocol_t));
  5936. left = size - (p - sect);
  5937. if (left < sizeof(struct objc_protocol_t)) {
  5938. outs() << "Protocol extends past end of __protocol section\n";
  5939. memcpy(&protocol, p, left);
  5940. } else
  5941. memcpy(&protocol, p, sizeof(struct objc_protocol_t));
  5942. if (O->isLittleEndian() != sys::IsLittleEndianHost)
  5943. swapStruct(protocol);
  5944. paddr = addr + (p - sect);
  5945. outs() << "Protocol " << format("0x%" PRIx32, paddr);
  5946. if (print_protocol(paddr, 0, &info))
  5947. outs() << "(not in an __OBJC section)\n";
  5948. }
  5949. }
  5950. #ifdef HAVE_LIBXAR
  5951. inline void swapStruct(struct xar_header &xar) {
  5952. sys::swapByteOrder(xar.magic);
  5953. sys::swapByteOrder(xar.size);
  5954. sys::swapByteOrder(xar.version);
  5955. sys::swapByteOrder(xar.toc_length_compressed);
  5956. sys::swapByteOrder(xar.toc_length_uncompressed);
  5957. sys::swapByteOrder(xar.cksum_alg);
  5958. }
  5959. static void PrintModeVerbose(uint32_t mode) {
  5960. switch(mode & S_IFMT){
  5961. case S_IFDIR:
  5962. outs() << "d";
  5963. break;
  5964. case S_IFCHR:
  5965. outs() << "c";
  5966. break;
  5967. case S_IFBLK:
  5968. outs() << "b";
  5969. break;
  5970. case S_IFREG:
  5971. outs() << "-";
  5972. break;
  5973. case S_IFLNK:
  5974. outs() << "l";
  5975. break;
  5976. case S_IFSOCK:
  5977. outs() << "s";
  5978. break;
  5979. default:
  5980. outs() << "?";
  5981. break;
  5982. }
  5983. /* owner permissions */
  5984. if(mode & S_IREAD)
  5985. outs() << "r";
  5986. else
  5987. outs() << "-";
  5988. if(mode & S_IWRITE)
  5989. outs() << "w";
  5990. else
  5991. outs() << "-";
  5992. if(mode & S_ISUID)
  5993. outs() << "s";
  5994. else if(mode & S_IEXEC)
  5995. outs() << "x";
  5996. else
  5997. outs() << "-";
  5998. /* group permissions */
  5999. if(mode & (S_IREAD >> 3))
  6000. outs() << "r";
  6001. else
  6002. outs() << "-";
  6003. if(mode & (S_IWRITE >> 3))
  6004. outs() << "w";
  6005. else
  6006. outs() << "-";
  6007. if(mode & S_ISGID)
  6008. outs() << "s";
  6009. else if(mode & (S_IEXEC >> 3))
  6010. outs() << "x";
  6011. else
  6012. outs() << "-";
  6013. /* other permissions */
  6014. if(mode & (S_IREAD >> 6))
  6015. outs() << "r";
  6016. else
  6017. outs() << "-";
  6018. if(mode & (S_IWRITE >> 6))
  6019. outs() << "w";
  6020. else
  6021. outs() << "-";
  6022. if(mode & S_ISVTX)
  6023. outs() << "t";
  6024. else if(mode & (S_IEXEC >> 6))
  6025. outs() << "x";
  6026. else
  6027. outs() << "-";
  6028. }
  6029. static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
  6030. xar_file_t xf;
  6031. const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
  6032. char *endp;
  6033. uint32_t mode_value;
  6034. ScopedXarIter xi;
  6035. if (!xi) {
  6036. WithColor::error(errs(), "llvm-objdump")
  6037. << "can't obtain an xar iterator for xar archive " << XarFilename
  6038. << "\n";
  6039. return;
  6040. }
  6041. // Go through the xar's files.
  6042. for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
  6043. ScopedXarIter xp;
  6044. if(!xp){
  6045. WithColor::error(errs(), "llvm-objdump")
  6046. << "can't obtain an xar iterator for xar archive " << XarFilename
  6047. << "\n";
  6048. return;
  6049. }
  6050. type = nullptr;
  6051. mode = nullptr;
  6052. user = nullptr;
  6053. group = nullptr;
  6054. size = nullptr;
  6055. mtime = nullptr;
  6056. name = nullptr;
  6057. for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
  6058. const char *val = nullptr;
  6059. xar_prop_get(xf, key, &val);
  6060. #if 0 // Useful for debugging.
  6061. outs() << "key: " << key << " value: " << val << "\n";
  6062. #endif
  6063. if(strcmp(key, "type") == 0)
  6064. type = val;
  6065. if(strcmp(key, "mode") == 0)
  6066. mode = val;
  6067. if(strcmp(key, "user") == 0)
  6068. user = val;
  6069. if(strcmp(key, "group") == 0)
  6070. group = val;
  6071. if(strcmp(key, "data/size") == 0)
  6072. size = val;
  6073. if(strcmp(key, "mtime") == 0)
  6074. mtime = val;
  6075. if(strcmp(key, "name") == 0)
  6076. name = val;
  6077. }
  6078. if(mode != nullptr){
  6079. mode_value = strtoul(mode, &endp, 8);
  6080. if(*endp != '\0')
  6081. outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
  6082. if(strcmp(type, "file") == 0)
  6083. mode_value |= S_IFREG;
  6084. PrintModeVerbose(mode_value);
  6085. outs() << " ";
  6086. }
  6087. if(user != nullptr)
  6088. outs() << format("%10s/", user);
  6089. if(group != nullptr)
  6090. outs() << format("%-10s ", group);
  6091. if(size != nullptr)
  6092. outs() << format("%7s ", size);
  6093. if(mtime != nullptr){
  6094. for(m = mtime; *m != 'T' && *m != '\0'; m++)
  6095. outs() << *m;
  6096. if(*m == 'T')
  6097. m++;
  6098. outs() << " ";
  6099. for( ; *m != 'Z' && *m != '\0'; m++)
  6100. outs() << *m;
  6101. outs() << " ";
  6102. }
  6103. if(name != nullptr)
  6104. outs() << name;
  6105. outs() << "\n";
  6106. }
  6107. }
  6108. static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
  6109. uint32_t size, bool verbose,
  6110. bool PrintXarHeader, bool PrintXarFileHeaders,
  6111. std::string XarMemberName) {
  6112. if(size < sizeof(struct xar_header)) {
  6113. outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
  6114. "of struct xar_header)\n";
  6115. return;
  6116. }
  6117. struct xar_header XarHeader;
  6118. memcpy(&XarHeader, sect, sizeof(struct xar_header));
  6119. if (sys::IsLittleEndianHost)
  6120. swapStruct(XarHeader);
  6121. if (PrintXarHeader) {
  6122. if (!XarMemberName.empty())
  6123. outs() << "In xar member " << XarMemberName << ": ";
  6124. else
  6125. outs() << "For (__LLVM,__bundle) section: ";
  6126. outs() << "xar header\n";
  6127. if (XarHeader.magic == XAR_HEADER_MAGIC)
  6128. outs() << " magic XAR_HEADER_MAGIC\n";
  6129. else
  6130. outs() << " magic "
  6131. << format_hex(XarHeader.magic, 10, true)
  6132. << " (not XAR_HEADER_MAGIC)\n";
  6133. outs() << " size " << XarHeader.size << "\n";
  6134. outs() << " version " << XarHeader.version << "\n";
  6135. outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
  6136. << "\n";
  6137. outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
  6138. << "\n";
  6139. outs() << " cksum_alg ";
  6140. switch (XarHeader.cksum_alg) {
  6141. case XAR_CKSUM_NONE:
  6142. outs() << "XAR_CKSUM_NONE\n";
  6143. break;
  6144. case XAR_CKSUM_SHA1:
  6145. outs() << "XAR_CKSUM_SHA1\n";
  6146. break;
  6147. case XAR_CKSUM_MD5:
  6148. outs() << "XAR_CKSUM_MD5\n";
  6149. break;
  6150. #ifdef XAR_CKSUM_SHA256
  6151. case XAR_CKSUM_SHA256:
  6152. outs() << "XAR_CKSUM_SHA256\n";
  6153. break;
  6154. #endif
  6155. #ifdef XAR_CKSUM_SHA512
  6156. case XAR_CKSUM_SHA512:
  6157. outs() << "XAR_CKSUM_SHA512\n";
  6158. break;
  6159. #endif
  6160. default:
  6161. outs() << XarHeader.cksum_alg << "\n";
  6162. }
  6163. }
  6164. SmallString<128> XarFilename;
  6165. int FD;
  6166. std::error_code XarEC =
  6167. sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
  6168. if (XarEC) {
  6169. WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
  6170. return;
  6171. }
  6172. ToolOutputFile XarFile(XarFilename, FD);
  6173. raw_fd_ostream &XarOut = XarFile.os();
  6174. StringRef XarContents(sect, size);
  6175. XarOut << XarContents;
  6176. XarOut.close();
  6177. if (XarOut.has_error())
  6178. return;
  6179. ScopedXarFile xar(XarFilename.c_str(), READ);
  6180. if (!xar) {
  6181. WithColor::error(errs(), "llvm-objdump")
  6182. << "can't create temporary xar archive " << XarFilename << "\n";
  6183. return;
  6184. }
  6185. SmallString<128> TocFilename;
  6186. std::error_code TocEC =
  6187. sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
  6188. if (TocEC) {
  6189. WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
  6190. return;
  6191. }
  6192. xar_serialize(xar, TocFilename.c_str());
  6193. if (PrintXarFileHeaders) {
  6194. if (!XarMemberName.empty())
  6195. outs() << "In xar member " << XarMemberName << ": ";
  6196. else
  6197. outs() << "For (__LLVM,__bundle) section: ";
  6198. outs() << "xar archive files:\n";
  6199. PrintXarFilesSummary(XarFilename.c_str(), xar);
  6200. }
  6201. ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
  6202. MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
  6203. if (std::error_code EC = FileOrErr.getError()) {
  6204. WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
  6205. return;
  6206. }
  6207. std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
  6208. if (!XarMemberName.empty())
  6209. outs() << "In xar member " << XarMemberName << ": ";
  6210. else
  6211. outs() << "For (__LLVM,__bundle) section: ";
  6212. outs() << "xar table of contents:\n";
  6213. outs() << Buffer->getBuffer() << "\n";
  6214. // TODO: Go through the xar's files.
  6215. ScopedXarIter xi;
  6216. if(!xi){
  6217. WithColor::error(errs(), "llvm-objdump")
  6218. << "can't obtain an xar iterator for xar archive "
  6219. << XarFilename.c_str() << "\n";
  6220. return;
  6221. }
  6222. for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
  6223. const char *key;
  6224. const char *member_name, *member_type, *member_size_string;
  6225. size_t member_size;
  6226. ScopedXarIter xp;
  6227. if(!xp){
  6228. WithColor::error(errs(), "llvm-objdump")
  6229. << "can't obtain an xar iterator for xar archive "
  6230. << XarFilename.c_str() << "\n";
  6231. return;
  6232. }
  6233. member_name = NULL;
  6234. member_type = NULL;
  6235. member_size_string = NULL;
  6236. for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
  6237. const char *val = nullptr;
  6238. xar_prop_get(xf, key, &val);
  6239. #if 0 // Useful for debugging.
  6240. outs() << "key: " << key << " value: " << val << "\n";
  6241. #endif
  6242. if (strcmp(key, "name") == 0)
  6243. member_name = val;
  6244. if (strcmp(key, "type") == 0)
  6245. member_type = val;
  6246. if (strcmp(key, "data/size") == 0)
  6247. member_size_string = val;
  6248. }
  6249. /*
  6250. * If we find a file with a name, date/size and type properties
  6251. * and with the type being "file" see if that is a xar file.
  6252. */
  6253. if (member_name != NULL && member_type != NULL &&
  6254. strcmp(member_type, "file") == 0 &&
  6255. member_size_string != NULL){
  6256. // Extract the file into a buffer.
  6257. char *endptr;
  6258. member_size = strtoul(member_size_string, &endptr, 10);
  6259. if (*endptr == '\0' && member_size != 0) {
  6260. char *buffer;
  6261. if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
  6262. #if 0 // Useful for debugging.
  6263. outs() << "xar member: " << member_name << " extracted\n";
  6264. #endif
  6265. // Set the XarMemberName we want to see printed in the header.
  6266. std::string OldXarMemberName;
  6267. // If XarMemberName is already set this is nested. So
  6268. // save the old name and create the nested name.
  6269. if (!XarMemberName.empty()) {
  6270. OldXarMemberName = XarMemberName;
  6271. XarMemberName =
  6272. (Twine("[") + XarMemberName + "]" + member_name).str();
  6273. } else {
  6274. OldXarMemberName = "";
  6275. XarMemberName = member_name;
  6276. }
  6277. // See if this is could be a xar file (nested).
  6278. if (member_size >= sizeof(struct xar_header)) {
  6279. #if 0 // Useful for debugging.
  6280. outs() << "could be a xar file: " << member_name << "\n";
  6281. #endif
  6282. memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
  6283. if (sys::IsLittleEndianHost)
  6284. swapStruct(XarHeader);
  6285. if (XarHeader.magic == XAR_HEADER_MAGIC)
  6286. DumpBitcodeSection(O, buffer, member_size, verbose,
  6287. PrintXarHeader, PrintXarFileHeaders,
  6288. XarMemberName);
  6289. }
  6290. XarMemberName = OldXarMemberName;
  6291. delete buffer;
  6292. }
  6293. }
  6294. }
  6295. }
  6296. }
  6297. #endif // defined(HAVE_LIBXAR)
  6298. static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
  6299. if (O->is64Bit())
  6300. printObjc2_64bit_MetaData(O, verbose);
  6301. else {
  6302. MachO::mach_header H;
  6303. H = O->getHeader();
  6304. if (H.cputype == MachO::CPU_TYPE_ARM)
  6305. printObjc2_32bit_MetaData(O, verbose);
  6306. else {
  6307. // This is the 32-bit non-arm cputype case. Which is normally
  6308. // the first Objective-C ABI. But it may be the case of a
  6309. // binary for the iOS simulator which is the second Objective-C
  6310. // ABI. In that case printObjc1_32bit_MetaData() will determine that
  6311. // and return false.
  6312. if (!printObjc1_32bit_MetaData(O, verbose))
  6313. printObjc2_32bit_MetaData(O, verbose);
  6314. }
  6315. }
  6316. }
  6317. // GuessLiteralPointer returns a string which for the item in the Mach-O file
  6318. // for the address passed in as ReferenceValue for printing as a comment with
  6319. // the instruction and also returns the corresponding type of that item
  6320. // indirectly through ReferenceType.
  6321. //
  6322. // If ReferenceValue is an address of literal cstring then a pointer to the
  6323. // cstring is returned and ReferenceType is set to
  6324. // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
  6325. //
  6326. // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
  6327. // Class ref that name is returned and the ReferenceType is set accordingly.
  6328. //
  6329. // Lastly, literals which are Symbol address in a literal pool are looked for
  6330. // and if found the symbol name is returned and ReferenceType is set to
  6331. // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
  6332. //
  6333. // If there is no item in the Mach-O file for the address passed in as
  6334. // ReferenceValue nullptr is returned and ReferenceType is unchanged.
  6335. static const char *GuessLiteralPointer(uint64_t ReferenceValue,
  6336. uint64_t ReferencePC,
  6337. uint64_t *ReferenceType,
  6338. struct DisassembleInfo *info) {
  6339. // First see if there is an external relocation entry at the ReferencePC.
  6340. if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
  6341. uint64_t sect_addr = info->S.getAddress();
  6342. uint64_t sect_offset = ReferencePC - sect_addr;
  6343. bool reloc_found = false;
  6344. DataRefImpl Rel;
  6345. MachO::any_relocation_info RE;
  6346. bool isExtern = false;
  6347. SymbolRef Symbol;
  6348. for (const RelocationRef &Reloc : info->S.relocations()) {
  6349. uint64_t RelocOffset = Reloc.getOffset();
  6350. if (RelocOffset == sect_offset) {
  6351. Rel = Reloc.getRawDataRefImpl();
  6352. RE = info->O->getRelocation(Rel);
  6353. if (info->O->isRelocationScattered(RE))
  6354. continue;
  6355. isExtern = info->O->getPlainRelocationExternal(RE);
  6356. if (isExtern) {
  6357. symbol_iterator RelocSym = Reloc.getSymbol();
  6358. Symbol = *RelocSym;
  6359. }
  6360. reloc_found = true;
  6361. break;
  6362. }
  6363. }
  6364. // If there is an external relocation entry for a symbol in a section
  6365. // then used that symbol's value for the value of the reference.
  6366. if (reloc_found && isExtern) {
  6367. if (info->O->getAnyRelocationPCRel(RE)) {
  6368. unsigned Type = info->O->getAnyRelocationType(RE);
  6369. if (Type == MachO::X86_64_RELOC_SIGNED) {
  6370. ReferenceValue = Symbol.getValue();
  6371. }
  6372. }
  6373. }
  6374. }
  6375. // Look for literals such as Objective-C CFStrings refs, Selector refs,
  6376. // Message refs and Class refs.
  6377. bool classref, selref, msgref, cfstring;
  6378. uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
  6379. selref, msgref, cfstring);
  6380. if (classref && pointer_value == 0) {
  6381. // Note the ReferenceValue is a pointer into the __objc_classrefs section.
  6382. // And the pointer_value in that section is typically zero as it will be
  6383. // set by dyld as part of the "bind information".
  6384. const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
  6385. if (name != nullptr) {
  6386. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
  6387. const char *class_name = strrchr(name, '$');
  6388. if (class_name != nullptr && class_name[1] == '_' &&
  6389. class_name[2] != '\0') {
  6390. info->class_name = class_name + 2;
  6391. return name;
  6392. }
  6393. }
  6394. }
  6395. if (classref) {
  6396. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
  6397. const char *name =
  6398. get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
  6399. if (name != nullptr)
  6400. info->class_name = name;
  6401. else
  6402. name = "bad class ref";
  6403. return name;
  6404. }
  6405. if (cfstring) {
  6406. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
  6407. const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
  6408. return name;
  6409. }
  6410. if (selref && pointer_value == 0)
  6411. pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
  6412. if (pointer_value != 0)
  6413. ReferenceValue = pointer_value;
  6414. const char *name = GuessCstringPointer(ReferenceValue, info);
  6415. if (name) {
  6416. if (pointer_value != 0 && selref) {
  6417. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
  6418. info->selector_name = name;
  6419. } else if (pointer_value != 0 && msgref) {
  6420. info->class_name = nullptr;
  6421. *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
  6422. info->selector_name = name;
  6423. } else
  6424. *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
  6425. return name;
  6426. }
  6427. // Lastly look for an indirect symbol with this ReferenceValue which is in
  6428. // a literal pool. If found return that symbol name.
  6429. name = GuessIndirectSymbol(ReferenceValue, info);
  6430. if (name) {
  6431. *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
  6432. return name;
  6433. }
  6434. return nullptr;
  6435. }
  6436. // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
  6437. // the Symbolizer. It looks up the ReferenceValue using the info passed via the
  6438. // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
  6439. // is created and returns the symbol name that matches the ReferenceValue or
  6440. // nullptr if none. The ReferenceType is passed in for the IN type of
  6441. // reference the instruction is making from the values in defined in the header
  6442. // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
  6443. // Out type and the ReferenceName will also be set which is added as a comment
  6444. // to the disassembled instruction.
  6445. //
  6446. // If the symbol name is a C++ mangled name then the demangled name is
  6447. // returned through ReferenceName and ReferenceType is set to
  6448. // LLVMDisassembler_ReferenceType_DeMangled_Name .
  6449. //
  6450. // When this is called to get a symbol name for a branch target then the
  6451. // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
  6452. // SymbolValue will be looked for in the indirect symbol table to determine if
  6453. // it is an address for a symbol stub. If so then the symbol name for that
  6454. // stub is returned indirectly through ReferenceName and then ReferenceType is
  6455. // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
  6456. //
  6457. // When this is called with an value loaded via a PC relative load then
  6458. // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
  6459. // SymbolValue is checked to be an address of literal pointer, symbol pointer,
  6460. // or an Objective-C meta data reference. If so the output ReferenceType is
  6461. // set to correspond to that as well as setting the ReferenceName.
  6462. static const char *SymbolizerSymbolLookUp(void *DisInfo,
  6463. uint64_t ReferenceValue,
  6464. uint64_t *ReferenceType,
  6465. uint64_t ReferencePC,
  6466. const char **ReferenceName) {
  6467. struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
  6468. // If no verbose symbolic information is wanted then just return nullptr.
  6469. if (!info->verbose) {
  6470. *ReferenceName = nullptr;
  6471. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6472. return nullptr;
  6473. }
  6474. const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
  6475. if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
  6476. *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
  6477. if (*ReferenceName != nullptr) {
  6478. method_reference(info, ReferenceType, ReferenceName);
  6479. if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
  6480. *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
  6481. } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
  6482. if (info->demangled_name != nullptr)
  6483. free(info->demangled_name);
  6484. int status;
  6485. info->demangled_name =
  6486. itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
  6487. if (info->demangled_name != nullptr) {
  6488. *ReferenceName = info->demangled_name;
  6489. *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
  6490. } else
  6491. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6492. } else
  6493. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6494. } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
  6495. *ReferenceName =
  6496. GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
  6497. if (*ReferenceName)
  6498. method_reference(info, ReferenceType, ReferenceName);
  6499. else
  6500. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6501. // If this is arm64 and the reference is an adrp instruction save the
  6502. // instruction, passed in ReferenceValue and the address of the instruction
  6503. // for use later if we see and add immediate instruction.
  6504. } else if (info->O->getArch() == Triple::aarch64 &&
  6505. *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
  6506. info->adrp_inst = ReferenceValue;
  6507. info->adrp_addr = ReferencePC;
  6508. SymbolName = nullptr;
  6509. *ReferenceName = nullptr;
  6510. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6511. // If this is arm64 and reference is an add immediate instruction and we
  6512. // have
  6513. // seen an adrp instruction just before it and the adrp's Xd register
  6514. // matches
  6515. // this add's Xn register reconstruct the value being referenced and look to
  6516. // see if it is a literal pointer. Note the add immediate instruction is
  6517. // passed in ReferenceValue.
  6518. } else if (info->O->getArch() == Triple::aarch64 &&
  6519. *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
  6520. ReferencePC - 4 == info->adrp_addr &&
  6521. (info->adrp_inst & 0x9f000000) == 0x90000000 &&
  6522. (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
  6523. uint32_t addxri_inst;
  6524. uint64_t adrp_imm, addxri_imm;
  6525. adrp_imm =
  6526. ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
  6527. if (info->adrp_inst & 0x0200000)
  6528. adrp_imm |= 0xfffffffffc000000LL;
  6529. addxri_inst = ReferenceValue;
  6530. addxri_imm = (addxri_inst >> 10) & 0xfff;
  6531. if (((addxri_inst >> 22) & 0x3) == 1)
  6532. addxri_imm <<= 12;
  6533. ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
  6534. (adrp_imm << 12) + addxri_imm;
  6535. *ReferenceName =
  6536. GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
  6537. if (*ReferenceName == nullptr)
  6538. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6539. // If this is arm64 and the reference is a load register instruction and we
  6540. // have seen an adrp instruction just before it and the adrp's Xd register
  6541. // matches this add's Xn register reconstruct the value being referenced and
  6542. // look to see if it is a literal pointer. Note the load register
  6543. // instruction is passed in ReferenceValue.
  6544. } else if (info->O->getArch() == Triple::aarch64 &&
  6545. *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
  6546. ReferencePC - 4 == info->adrp_addr &&
  6547. (info->adrp_inst & 0x9f000000) == 0x90000000 &&
  6548. (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
  6549. uint32_t ldrxui_inst;
  6550. uint64_t adrp_imm, ldrxui_imm;
  6551. adrp_imm =
  6552. ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
  6553. if (info->adrp_inst & 0x0200000)
  6554. adrp_imm |= 0xfffffffffc000000LL;
  6555. ldrxui_inst = ReferenceValue;
  6556. ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
  6557. ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
  6558. (adrp_imm << 12) + (ldrxui_imm << 3);
  6559. *ReferenceName =
  6560. GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
  6561. if (*ReferenceName == nullptr)
  6562. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6563. }
  6564. // If this arm64 and is an load register (PC-relative) instruction the
  6565. // ReferenceValue is the PC plus the immediate value.
  6566. else if (info->O->getArch() == Triple::aarch64 &&
  6567. (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
  6568. *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
  6569. *ReferenceName =
  6570. GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
  6571. if (*ReferenceName == nullptr)
  6572. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6573. } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
  6574. if (info->demangled_name != nullptr)
  6575. free(info->demangled_name);
  6576. int status;
  6577. info->demangled_name =
  6578. itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
  6579. if (info->demangled_name != nullptr) {
  6580. *ReferenceName = info->demangled_name;
  6581. *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
  6582. }
  6583. }
  6584. else {
  6585. *ReferenceName = nullptr;
  6586. *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
  6587. }
  6588. return SymbolName;
  6589. }
  6590. /// Emits the comments that are stored in the CommentStream.
  6591. /// Each comment in the CommentStream must end with a newline.
  6592. static void emitComments(raw_svector_ostream &CommentStream,
  6593. SmallString<128> &CommentsToEmit,
  6594. formatted_raw_ostream &FormattedOS,
  6595. const MCAsmInfo &MAI) {
  6596. // Flush the stream before taking its content.
  6597. StringRef Comments = CommentsToEmit.str();
  6598. // Get the default information for printing a comment.
  6599. StringRef CommentBegin = MAI.getCommentString();
  6600. unsigned CommentColumn = MAI.getCommentColumn();
  6601. bool IsFirst = true;
  6602. while (!Comments.empty()) {
  6603. if (!IsFirst)
  6604. FormattedOS << '\n';
  6605. // Emit a line of comments.
  6606. FormattedOS.PadToColumn(CommentColumn);
  6607. size_t Position = Comments.find('\n');
  6608. FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
  6609. // Move after the newline character.
  6610. Comments = Comments.substr(Position + 1);
  6611. IsFirst = false;
  6612. }
  6613. FormattedOS.flush();
  6614. // Tell the comment stream that the vector changed underneath it.
  6615. CommentsToEmit.clear();
  6616. }
  6617. static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
  6618. StringRef DisSegName, StringRef DisSectName) {
  6619. const char *McpuDefault = nullptr;
  6620. const Target *ThumbTarget = nullptr;
  6621. const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
  6622. if (!TheTarget) {
  6623. // GetTarget prints out stuff.
  6624. return;
  6625. }
  6626. std::string MachOMCPU;
  6627. if (MCPU.empty() && McpuDefault)
  6628. MachOMCPU = McpuDefault;
  6629. else
  6630. MachOMCPU = MCPU;
  6631. std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
  6632. std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
  6633. if (ThumbTarget)
  6634. ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
  6635. // Package up features to be passed to target/subtarget
  6636. std::string FeaturesStr;
  6637. if (!MAttrs.empty()) {
  6638. SubtargetFeatures Features;
  6639. for (unsigned i = 0; i != MAttrs.size(); ++i)
  6640. Features.AddFeature(MAttrs[i]);
  6641. FeaturesStr = Features.getString();
  6642. }
  6643. // Set up disassembler.
  6644. std::unique_ptr<const MCRegisterInfo> MRI(
  6645. TheTarget->createMCRegInfo(TripleName));
  6646. std::unique_ptr<const MCAsmInfo> AsmInfo(
  6647. TheTarget->createMCAsmInfo(*MRI, TripleName));
  6648. std::unique_ptr<const MCSubtargetInfo> STI(
  6649. TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
  6650. MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
  6651. std::unique_ptr<MCDisassembler> DisAsm(
  6652. TheTarget->createMCDisassembler(*STI, Ctx));
  6653. std::unique_ptr<MCSymbolizer> Symbolizer;
  6654. struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
  6655. std::unique_ptr<MCRelocationInfo> RelInfo(
  6656. TheTarget->createMCRelocationInfo(TripleName, Ctx));
  6657. if (RelInfo) {
  6658. Symbolizer.reset(TheTarget->createMCSymbolizer(
  6659. TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
  6660. &SymbolizerInfo, &Ctx, std::move(RelInfo)));
  6661. DisAsm->setSymbolizer(std::move(Symbolizer));
  6662. }
  6663. int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
  6664. std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
  6665. Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
  6666. // Set the display preference for hex vs. decimal immediates.
  6667. IP->setPrintImmHex(PrintImmHex);
  6668. // Comment stream and backing vector.
  6669. SmallString<128> CommentsToEmit;
  6670. raw_svector_ostream CommentStream(CommentsToEmit);
  6671. // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
  6672. // if it is done then arm64 comments for string literals don't get printed
  6673. // and some constant get printed instead and not setting it causes intel
  6674. // (32-bit and 64-bit) comments printed with different spacing before the
  6675. // comment causing different diffs with the 'C' disassembler library API.
  6676. // IP->setCommentStream(CommentStream);
  6677. if (!AsmInfo || !STI || !DisAsm || !IP) {
  6678. WithColor::error(errs(), "llvm-objdump")
  6679. << "couldn't initialize disassembler for target " << TripleName << '\n';
  6680. return;
  6681. }
  6682. // Set up separate thumb disassembler if needed.
  6683. std::unique_ptr<const MCRegisterInfo> ThumbMRI;
  6684. std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
  6685. std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
  6686. std::unique_ptr<MCDisassembler> ThumbDisAsm;
  6687. std::unique_ptr<MCInstPrinter> ThumbIP;
  6688. std::unique_ptr<MCContext> ThumbCtx;
  6689. std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
  6690. struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
  6691. std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
  6692. if (ThumbTarget) {
  6693. ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
  6694. ThumbAsmInfo.reset(
  6695. ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
  6696. ThumbSTI.reset(
  6697. ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
  6698. FeaturesStr));
  6699. ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
  6700. ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
  6701. MCContext *PtrThumbCtx = ThumbCtx.get();
  6702. ThumbRelInfo.reset(
  6703. ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
  6704. if (ThumbRelInfo) {
  6705. ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
  6706. ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
  6707. &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
  6708. ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
  6709. }
  6710. int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
  6711. ThumbIP.reset(ThumbTarget->createMCInstPrinter(
  6712. Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
  6713. *ThumbInstrInfo, *ThumbMRI));
  6714. // Set the display preference for hex vs. decimal immediates.
  6715. ThumbIP->setPrintImmHex(PrintImmHex);
  6716. }
  6717. if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
  6718. WithColor::error(errs(), "llvm-objdump")
  6719. << "couldn't initialize disassembler for target " << ThumbTripleName
  6720. << '\n';
  6721. return;
  6722. }
  6723. MachO::mach_header Header = MachOOF->getHeader();
  6724. // FIXME: Using the -cfg command line option, this code used to be able to
  6725. // annotate relocations with the referenced symbol's name, and if this was
  6726. // inside a __[cf]string section, the data it points to. This is now replaced
  6727. // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
  6728. std::vector<SectionRef> Sections;
  6729. std::vector<SymbolRef> Symbols;
  6730. SmallVector<uint64_t, 8> FoundFns;
  6731. uint64_t BaseSegmentAddress = 0;
  6732. getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
  6733. BaseSegmentAddress);
  6734. // Sort the symbols by address, just in case they didn't come in that way.
  6735. llvm::sort(Symbols, SymbolSorter());
  6736. // Build a data in code table that is sorted on by the address of each entry.
  6737. uint64_t BaseAddress = 0;
  6738. if (Header.filetype == MachO::MH_OBJECT)
  6739. BaseAddress = Sections[0].getAddress();
  6740. else
  6741. BaseAddress = BaseSegmentAddress;
  6742. DiceTable Dices;
  6743. for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
  6744. DI != DE; ++DI) {
  6745. uint32_t Offset;
  6746. DI->getOffset(Offset);
  6747. Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
  6748. }
  6749. array_pod_sort(Dices.begin(), Dices.end());
  6750. #ifndef NDEBUG
  6751. raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
  6752. #else
  6753. raw_ostream &DebugOut = nulls();
  6754. #endif
  6755. // Try to find debug info and set up the DIContext for it.
  6756. std::unique_ptr<DIContext> diContext;
  6757. std::unique_ptr<Binary> DSYMBinary;
  6758. std::unique_ptr<MemoryBuffer> DSYMBuf;
  6759. if (UseDbg) {
  6760. ObjectFile *DbgObj = MachOOF;
  6761. // A separate DSym file path was specified, parse it as a macho file,
  6762. // get the sections and supply it to the section name parsing machinery.
  6763. if (!DSYMFile.empty()) {
  6764. std::string DSYMPath(DSYMFile);
  6765. // If DSYMPath is a .dSYM directory, append the Mach-O file.
  6766. if (llvm::sys::fs::is_directory(DSYMPath) &&
  6767. llvm::sys::path::extension(DSYMPath) == ".dSYM") {
  6768. SmallString<128> ShortName(llvm::sys::path::filename(DSYMPath));
  6769. llvm::sys::path::replace_extension(ShortName, "");
  6770. SmallString<1024> FullPath(DSYMPath);
  6771. llvm::sys::path::append(FullPath, "Contents", "Resources", "DWARF",
  6772. ShortName);
  6773. DSYMPath = FullPath.str();
  6774. }
  6775. // Load the file.
  6776. ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
  6777. MemoryBuffer::getFileOrSTDIN(DSYMPath);
  6778. if (std::error_code EC = BufOrErr.getError()) {
  6779. reportError(errorCodeToError(EC), DSYMPath);
  6780. return;
  6781. }
  6782. // We need to keep the file alive, because we're replacing DbgObj with it.
  6783. DSYMBuf = std::move(BufOrErr.get());
  6784. Expected<std::unique_ptr<Binary>> BinaryOrErr =
  6785. createBinary(DSYMBuf.get()->getMemBufferRef());
  6786. if (!BinaryOrErr) {
  6787. reportError(BinaryOrErr.takeError(), DSYMPath);
  6788. return;
  6789. }
  6790. // We need to keep the Binary alive with the buffer
  6791. DSYMBinary = std::move(BinaryOrErr.get());
  6792. if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) {
  6793. // this is a Mach-O object file, use it
  6794. if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) {
  6795. DbgObj = MachDSYM;
  6796. }
  6797. else {
  6798. WithColor::error(errs(), "llvm-objdump")
  6799. << DSYMPath << " is not a Mach-O file type.\n";
  6800. return;
  6801. }
  6802. }
  6803. else if (auto UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())){
  6804. // this is a Universal Binary, find a Mach-O for this architecture
  6805. uint32_t CPUType, CPUSubType;
  6806. const char *ArchFlag;
  6807. if (MachOOF->is64Bit()) {
  6808. const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
  6809. CPUType = H_64.cputype;
  6810. CPUSubType = H_64.cpusubtype;
  6811. } else {
  6812. const MachO::mach_header H = MachOOF->getHeader();
  6813. CPUType = H.cputype;
  6814. CPUSubType = H.cpusubtype;
  6815. }
  6816. Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr,
  6817. &ArchFlag);
  6818. Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
  6819. UB->getMachOObjectForArch(ArchFlag);
  6820. if (!MachDSYM) {
  6821. reportError(MachDSYM.takeError(), DSYMPath);
  6822. return;
  6823. }
  6824. // We need to keep the Binary alive with the buffer
  6825. DbgObj = &*MachDSYM.get();
  6826. DSYMBinary = std::move(*MachDSYM);
  6827. }
  6828. else {
  6829. WithColor::error(errs(), "llvm-objdump")
  6830. << DSYMPath << " is not a Mach-O or Universal file type.\n";
  6831. return;
  6832. }
  6833. }
  6834. // Setup the DIContext
  6835. diContext = DWARFContext::create(*DbgObj);
  6836. }
  6837. if (FilterSections.empty())
  6838. outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
  6839. for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
  6840. Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName();
  6841. if (!SecNameOrErr) {
  6842. consumeError(SecNameOrErr.takeError());
  6843. continue;
  6844. }
  6845. if (*SecNameOrErr != DisSectName)
  6846. continue;
  6847. DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
  6848. StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
  6849. if (SegmentName != DisSegName)
  6850. continue;
  6851. StringRef BytesStr =
  6852. unwrapOrError(Sections[SectIdx].getContents(), Filename);
  6853. ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
  6854. uint64_t SectAddress = Sections[SectIdx].getAddress();
  6855. bool symbolTableWorked = false;
  6856. // Create a map of symbol addresses to symbol names for use by
  6857. // the SymbolizerSymbolLookUp() routine.
  6858. SymbolAddressMap AddrMap;
  6859. bool DisSymNameFound = false;
  6860. for (const SymbolRef &Symbol : MachOOF->symbols()) {
  6861. SymbolRef::Type ST =
  6862. unwrapOrError(Symbol.getType(), MachOOF->getFileName());
  6863. if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
  6864. ST == SymbolRef::ST_Other) {
  6865. uint64_t Address = Symbol.getValue();
  6866. StringRef SymName =
  6867. unwrapOrError(Symbol.getName(), MachOOF->getFileName());
  6868. AddrMap[Address] = SymName;
  6869. if (!DisSymName.empty() && DisSymName == SymName)
  6870. DisSymNameFound = true;
  6871. }
  6872. }
  6873. if (!DisSymName.empty() && !DisSymNameFound) {
  6874. outs() << "Can't find -dis-symname: " << DisSymName << "\n";
  6875. return;
  6876. }
  6877. // Set up the block of info used by the Symbolizer call backs.
  6878. SymbolizerInfo.verbose = !NoSymbolicOperands;
  6879. SymbolizerInfo.O = MachOOF;
  6880. SymbolizerInfo.S = Sections[SectIdx];
  6881. SymbolizerInfo.AddrMap = &AddrMap;
  6882. SymbolizerInfo.Sections = &Sections;
  6883. // Same for the ThumbSymbolizer
  6884. ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
  6885. ThumbSymbolizerInfo.O = MachOOF;
  6886. ThumbSymbolizerInfo.S = Sections[SectIdx];
  6887. ThumbSymbolizerInfo.AddrMap = &AddrMap;
  6888. ThumbSymbolizerInfo.Sections = &Sections;
  6889. unsigned int Arch = MachOOF->getArch();
  6890. // Skip all symbols if this is a stubs file.
  6891. if (Bytes.empty())
  6892. return;
  6893. // If the section has symbols but no symbol at the start of the section
  6894. // these are used to make sure the bytes before the first symbol are
  6895. // disassembled.
  6896. bool FirstSymbol = true;
  6897. bool FirstSymbolAtSectionStart = true;
  6898. // Disassemble symbol by symbol.
  6899. for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
  6900. StringRef SymName =
  6901. unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
  6902. SymbolRef::Type ST =
  6903. unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
  6904. if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
  6905. continue;
  6906. // Make sure the symbol is defined in this section.
  6907. bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
  6908. if (!containsSym) {
  6909. if (!DisSymName.empty() && DisSymName == SymName) {
  6910. outs() << "-dis-symname: " << DisSymName << " not in the section\n";
  6911. return;
  6912. }
  6913. continue;
  6914. }
  6915. // The __mh_execute_header is special and we need to deal with that fact
  6916. // this symbol is before the start of the (__TEXT,__text) section and at the
  6917. // address of the start of the __TEXT segment. This is because this symbol
  6918. // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
  6919. // start of the section in a standard MH_EXECUTE filetype.
  6920. if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
  6921. outs() << "-dis-symname: __mh_execute_header not in any section\n";
  6922. return;
  6923. }
  6924. // When this code is trying to disassemble a symbol at a time and in the
  6925. // case there is only the __mh_execute_header symbol left as in a stripped
  6926. // executable, we need to deal with this by ignoring this symbol so the
  6927. // whole section is disassembled and this symbol is then not displayed.
  6928. if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
  6929. SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
  6930. SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
  6931. continue;
  6932. // If we are only disassembling one symbol see if this is that symbol.
  6933. if (!DisSymName.empty() && DisSymName != SymName)
  6934. continue;
  6935. // Start at the address of the symbol relative to the section's address.
  6936. uint64_t SectSize = Sections[SectIdx].getSize();
  6937. uint64_t Start = Symbols[SymIdx].getValue();
  6938. uint64_t SectionAddress = Sections[SectIdx].getAddress();
  6939. Start -= SectionAddress;
  6940. if (Start > SectSize) {
  6941. outs() << "section data ends, " << SymName
  6942. << " lies outside valid range\n";
  6943. return;
  6944. }
  6945. // Stop disassembling either at the beginning of the next symbol or at
  6946. // the end of the section.
  6947. bool containsNextSym = false;
  6948. uint64_t NextSym = 0;
  6949. uint64_t NextSymIdx = SymIdx + 1;
  6950. while (Symbols.size() > NextSymIdx) {
  6951. SymbolRef::Type NextSymType = unwrapOrError(
  6952. Symbols[NextSymIdx].getType(), MachOOF->getFileName());
  6953. if (NextSymType == SymbolRef::ST_Function) {
  6954. containsNextSym =
  6955. Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
  6956. NextSym = Symbols[NextSymIdx].getValue();
  6957. NextSym -= SectionAddress;
  6958. break;
  6959. }
  6960. ++NextSymIdx;
  6961. }
  6962. uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
  6963. uint64_t Size;
  6964. symbolTableWorked = true;
  6965. DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
  6966. bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
  6967. // We only need the dedicated Thumb target if there's a real choice
  6968. // (i.e. we're not targeting M-class) and the function is Thumb.
  6969. bool UseThumbTarget = IsThumb && ThumbTarget;
  6970. // If we are not specifying a symbol to start disassembly with and this
  6971. // is the first symbol in the section but not at the start of the section
  6972. // then move the disassembly index to the start of the section and
  6973. // don't print the symbol name just yet. This is so the bytes before the
  6974. // first symbol are disassembled.
  6975. uint64_t SymbolStart = Start;
  6976. if (DisSymName.empty() && FirstSymbol && Start != 0) {
  6977. FirstSymbolAtSectionStart = false;
  6978. Start = 0;
  6979. }
  6980. else
  6981. outs() << SymName << ":\n";
  6982. DILineInfo lastLine;
  6983. for (uint64_t Index = Start; Index < End; Index += Size) {
  6984. MCInst Inst;
  6985. // If this is the first symbol in the section and it was not at the
  6986. // start of the section, see if we are at its Index now and if so print
  6987. // the symbol name.
  6988. if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
  6989. outs() << SymName << ":\n";
  6990. uint64_t PC = SectAddress + Index;
  6991. if (!NoLeadingAddr) {
  6992. if (FullLeadingAddr) {
  6993. if (MachOOF->is64Bit())
  6994. outs() << format("%016" PRIx64, PC);
  6995. else
  6996. outs() << format("%08" PRIx64, PC);
  6997. } else {
  6998. outs() << format("%8" PRIx64 ":", PC);
  6999. }
  7000. }
  7001. if (!NoShowRawInsn || Arch == Triple::arm)
  7002. outs() << "\t";
  7003. if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, Size))
  7004. continue;
  7005. SmallVector<char, 64> AnnotationsBytes;
  7006. raw_svector_ostream Annotations(AnnotationsBytes);
  7007. bool gotInst;
  7008. if (UseThumbTarget)
  7009. gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
  7010. PC, DebugOut, Annotations);
  7011. else
  7012. gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
  7013. DebugOut, Annotations);
  7014. if (gotInst) {
  7015. if (!NoShowRawInsn || Arch == Triple::arm) {
  7016. dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
  7017. }
  7018. formatted_raw_ostream FormattedOS(outs());
  7019. StringRef AnnotationsStr = Annotations.str();
  7020. if (UseThumbTarget)
  7021. ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
  7022. else
  7023. IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
  7024. emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
  7025. // Print debug info.
  7026. if (diContext) {
  7027. DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
  7028. // Print valid line info if it changed.
  7029. if (dli != lastLine && dli.Line != 0)
  7030. outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
  7031. << dli.Column;
  7032. lastLine = dli;
  7033. }
  7034. outs() << "\n";
  7035. } else {
  7036. unsigned int Arch = MachOOF->getArch();
  7037. if (Arch == Triple::x86_64 || Arch == Triple::x86) {
  7038. outs() << format("\t.byte 0x%02x #bad opcode\n",
  7039. *(Bytes.data() + Index) & 0xff);
  7040. Size = 1; // skip exactly one illegible byte and move on.
  7041. } else if (Arch == Triple::aarch64 ||
  7042. (Arch == Triple::arm && !IsThumb)) {
  7043. uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
  7044. (*(Bytes.data() + Index + 1) & 0xff) << 8 |
  7045. (*(Bytes.data() + Index + 2) & 0xff) << 16 |
  7046. (*(Bytes.data() + Index + 3) & 0xff) << 24;
  7047. outs() << format("\t.long\t0x%08x\n", opcode);
  7048. Size = 4;
  7049. } else if (Arch == Triple::arm) {
  7050. assert(IsThumb && "ARM mode should have been dealt with above");
  7051. uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
  7052. (*(Bytes.data() + Index + 1) & 0xff) << 8;
  7053. outs() << format("\t.short\t0x%04x\n", opcode);
  7054. Size = 2;
  7055. } else{
  7056. WithColor::warning(errs(), "llvm-objdump")
  7057. << "invalid instruction encoding\n";
  7058. if (Size == 0)
  7059. Size = 1; // skip illegible bytes
  7060. }
  7061. }
  7062. }
  7063. // Now that we are done disassembled the first symbol set the bool that
  7064. // were doing this to false.
  7065. FirstSymbol = false;
  7066. }
  7067. if (!symbolTableWorked) {
  7068. // Reading the symbol table didn't work, disassemble the whole section.
  7069. uint64_t SectAddress = Sections[SectIdx].getAddress();
  7070. uint64_t SectSize = Sections[SectIdx].getSize();
  7071. uint64_t InstSize;
  7072. for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
  7073. MCInst Inst;
  7074. uint64_t PC = SectAddress + Index;
  7075. if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, InstSize))
  7076. continue;
  7077. SmallVector<char, 64> AnnotationsBytes;
  7078. raw_svector_ostream Annotations(AnnotationsBytes);
  7079. if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
  7080. DebugOut, Annotations)) {
  7081. if (!NoLeadingAddr) {
  7082. if (FullLeadingAddr) {
  7083. if (MachOOF->is64Bit())
  7084. outs() << format("%016" PRIx64, PC);
  7085. else
  7086. outs() << format("%08" PRIx64, PC);
  7087. } else {
  7088. outs() << format("%8" PRIx64 ":", PC);
  7089. }
  7090. }
  7091. if (!NoShowRawInsn || Arch == Triple::arm) {
  7092. outs() << "\t";
  7093. dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
  7094. }
  7095. StringRef AnnotationsStr = Annotations.str();
  7096. IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
  7097. outs() << "\n";
  7098. } else {
  7099. unsigned int Arch = MachOOF->getArch();
  7100. if (Arch == Triple::x86_64 || Arch == Triple::x86) {
  7101. outs() << format("\t.byte 0x%02x #bad opcode\n",
  7102. *(Bytes.data() + Index) & 0xff);
  7103. InstSize = 1; // skip exactly one illegible byte and move on.
  7104. } else {
  7105. WithColor::warning(errs(), "llvm-objdump")
  7106. << "invalid instruction encoding\n";
  7107. if (InstSize == 0)
  7108. InstSize = 1; // skip illegible bytes
  7109. }
  7110. }
  7111. }
  7112. }
  7113. // The TripleName's need to be reset if we are called again for a different
  7114. // archtecture.
  7115. TripleName = "";
  7116. ThumbTripleName = "";
  7117. if (SymbolizerInfo.demangled_name != nullptr)
  7118. free(SymbolizerInfo.demangled_name);
  7119. if (ThumbSymbolizerInfo.demangled_name != nullptr)
  7120. free(ThumbSymbolizerInfo.demangled_name);
  7121. }
  7122. }
  7123. //===----------------------------------------------------------------------===//
  7124. // __compact_unwind section dumping
  7125. //===----------------------------------------------------------------------===//
  7126. namespace {
  7127. template <typename T>
  7128. static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
  7129. using llvm::support::little;
  7130. using llvm::support::unaligned;
  7131. if (Offset + sizeof(T) > Contents.size()) {
  7132. outs() << "warning: attempt to read past end of buffer\n";
  7133. return T();
  7134. }
  7135. uint64_t Val =
  7136. support::endian::read<T, little, unaligned>(Contents.data() + Offset);
  7137. return Val;
  7138. }
  7139. template <typename T>
  7140. static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
  7141. T Val = read<T>(Contents, Offset);
  7142. Offset += sizeof(T);
  7143. return Val;
  7144. }
  7145. struct CompactUnwindEntry {
  7146. uint32_t OffsetInSection;
  7147. uint64_t FunctionAddr;
  7148. uint32_t Length;
  7149. uint32_t CompactEncoding;
  7150. uint64_t PersonalityAddr;
  7151. uint64_t LSDAAddr;
  7152. RelocationRef FunctionReloc;
  7153. RelocationRef PersonalityReloc;
  7154. RelocationRef LSDAReloc;
  7155. CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
  7156. : OffsetInSection(Offset) {
  7157. if (Is64)
  7158. read<uint64_t>(Contents, Offset);
  7159. else
  7160. read<uint32_t>(Contents, Offset);
  7161. }
  7162. private:
  7163. template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
  7164. FunctionAddr = readNext<UIntPtr>(Contents, Offset);
  7165. Length = readNext<uint32_t>(Contents, Offset);
  7166. CompactEncoding = readNext<uint32_t>(Contents, Offset);
  7167. PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
  7168. LSDAAddr = readNext<UIntPtr>(Contents, Offset);
  7169. }
  7170. };
  7171. }
  7172. /// Given a relocation from __compact_unwind, consisting of the RelocationRef
  7173. /// and data being relocated, determine the best base Name and Addend to use for
  7174. /// display purposes.
  7175. ///
  7176. /// 1. An Extern relocation will directly reference a symbol (and the data is
  7177. /// then already an addend), so use that.
  7178. /// 2. Otherwise the data is an offset in the object file's layout; try to find
  7179. // a symbol before it in the same section, and use the offset from there.
  7180. /// 3. Finally, if all that fails, fall back to an offset from the start of the
  7181. /// referenced section.
  7182. static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
  7183. std::map<uint64_t, SymbolRef> &Symbols,
  7184. const RelocationRef &Reloc, uint64_t Addr,
  7185. StringRef &Name, uint64_t &Addend) {
  7186. if (Reloc.getSymbol() != Obj->symbol_end()) {
  7187. Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
  7188. Addend = Addr;
  7189. return;
  7190. }
  7191. auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
  7192. SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
  7193. uint64_t SectionAddr = RelocSection.getAddress();
  7194. auto Sym = Symbols.upper_bound(Addr);
  7195. if (Sym == Symbols.begin()) {
  7196. // The first symbol in the object is after this reference, the best we can
  7197. // do is section-relative notation.
  7198. if (Expected<StringRef> NameOrErr = RelocSection.getName())
  7199. Name = *NameOrErr;
  7200. else
  7201. consumeError(NameOrErr.takeError());
  7202. Addend = Addr - SectionAddr;
  7203. return;
  7204. }
  7205. // Go back one so that SymbolAddress <= Addr.
  7206. --Sym;
  7207. section_iterator SymSection =
  7208. unwrapOrError(Sym->second.getSection(), Obj->getFileName());
  7209. if (RelocSection == *SymSection) {
  7210. // There's a valid symbol in the same section before this reference.
  7211. Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
  7212. Addend = Addr - Sym->first;
  7213. return;
  7214. }
  7215. // There is a symbol before this reference, but it's in a different
  7216. // section. Probably not helpful to mention it, so use the section name.
  7217. if (Expected<StringRef> NameOrErr = RelocSection.getName())
  7218. Name = *NameOrErr;
  7219. else
  7220. consumeError(NameOrErr.takeError());
  7221. Addend = Addr - SectionAddr;
  7222. }
  7223. static void printUnwindRelocDest(const MachOObjectFile *Obj,
  7224. std::map<uint64_t, SymbolRef> &Symbols,
  7225. const RelocationRef &Reloc, uint64_t Addr) {
  7226. StringRef Name;
  7227. uint64_t Addend;
  7228. if (!Reloc.getObject())
  7229. return;
  7230. findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
  7231. outs() << Name;
  7232. if (Addend)
  7233. outs() << " + " << format("0x%" PRIx64, Addend);
  7234. }
  7235. static void
  7236. printMachOCompactUnwindSection(const MachOObjectFile *Obj,
  7237. std::map<uint64_t, SymbolRef> &Symbols,
  7238. const SectionRef &CompactUnwind) {
  7239. if (!Obj->isLittleEndian()) {
  7240. outs() << "Skipping big-endian __compact_unwind section\n";
  7241. return;
  7242. }
  7243. bool Is64 = Obj->is64Bit();
  7244. uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
  7245. uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
  7246. StringRef Contents =
  7247. unwrapOrError(CompactUnwind.getContents(), Obj->getFileName());
  7248. SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
  7249. // First populate the initial raw offsets, encodings and so on from the entry.
  7250. for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
  7251. CompactUnwindEntry Entry(Contents, Offset, Is64);
  7252. CompactUnwinds.push_back(Entry);
  7253. }
  7254. // Next we need to look at the relocations to find out what objects are
  7255. // actually being referred to.
  7256. for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
  7257. uint64_t RelocAddress = Reloc.getOffset();
  7258. uint32_t EntryIdx = RelocAddress / EntrySize;
  7259. uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
  7260. CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
  7261. if (OffsetInEntry == 0)
  7262. Entry.FunctionReloc = Reloc;
  7263. else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
  7264. Entry.PersonalityReloc = Reloc;
  7265. else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
  7266. Entry.LSDAReloc = Reloc;
  7267. else {
  7268. outs() << "Invalid relocation in __compact_unwind section\n";
  7269. return;
  7270. }
  7271. }
  7272. // Finally, we're ready to print the data we've gathered.
  7273. outs() << "Contents of __compact_unwind section:\n";
  7274. for (auto &Entry : CompactUnwinds) {
  7275. outs() << " Entry at offset "
  7276. << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
  7277. // 1. Start of the region this entry applies to.
  7278. outs() << " start: " << format("0x%" PRIx64,
  7279. Entry.FunctionAddr) << ' ';
  7280. printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
  7281. outs() << '\n';
  7282. // 2. Length of the region this entry applies to.
  7283. outs() << " length: " << format("0x%" PRIx32, Entry.Length)
  7284. << '\n';
  7285. // 3. The 32-bit compact encoding.
  7286. outs() << " compact encoding: "
  7287. << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
  7288. // 4. The personality function, if present.
  7289. if (Entry.PersonalityReloc.getObject()) {
  7290. outs() << " personality function: "
  7291. << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
  7292. printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
  7293. Entry.PersonalityAddr);
  7294. outs() << '\n';
  7295. }
  7296. // 5. This entry's language-specific data area.
  7297. if (Entry.LSDAReloc.getObject()) {
  7298. outs() << " LSDA: " << format("0x%" PRIx64,
  7299. Entry.LSDAAddr) << ' ';
  7300. printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
  7301. outs() << '\n';
  7302. }
  7303. }
  7304. }
  7305. //===----------------------------------------------------------------------===//
  7306. // __unwind_info section dumping
  7307. //===----------------------------------------------------------------------===//
  7308. static void printRegularSecondLevelUnwindPage(StringRef PageData) {
  7309. ptrdiff_t Pos = 0;
  7310. uint32_t Kind = readNext<uint32_t>(PageData, Pos);
  7311. (void)Kind;
  7312. assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
  7313. uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
  7314. uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
  7315. Pos = EntriesStart;
  7316. for (unsigned i = 0; i < NumEntries; ++i) {
  7317. uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
  7318. uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
  7319. outs() << " [" << i << "]: "
  7320. << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
  7321. << ", "
  7322. << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
  7323. }
  7324. }
  7325. static void printCompressedSecondLevelUnwindPage(
  7326. StringRef PageData, uint32_t FunctionBase,
  7327. const SmallVectorImpl<uint32_t> &CommonEncodings) {
  7328. ptrdiff_t Pos = 0;
  7329. uint32_t Kind = readNext<uint32_t>(PageData, Pos);
  7330. (void)Kind;
  7331. assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
  7332. uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
  7333. uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
  7334. uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
  7335. readNext<uint16_t>(PageData, Pos);
  7336. StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
  7337. Pos = EntriesStart;
  7338. for (unsigned i = 0; i < NumEntries; ++i) {
  7339. uint32_t Entry = readNext<uint32_t>(PageData, Pos);
  7340. uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
  7341. uint32_t EncodingIdx = Entry >> 24;
  7342. uint32_t Encoding;
  7343. if (EncodingIdx < CommonEncodings.size())
  7344. Encoding = CommonEncodings[EncodingIdx];
  7345. else
  7346. Encoding = read<uint32_t>(PageEncodings,
  7347. sizeof(uint32_t) *
  7348. (EncodingIdx - CommonEncodings.size()));
  7349. outs() << " [" << i << "]: "
  7350. << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
  7351. << ", "
  7352. << "encoding[" << EncodingIdx
  7353. << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
  7354. }
  7355. }
  7356. static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
  7357. std::map<uint64_t, SymbolRef> &Symbols,
  7358. const SectionRef &UnwindInfo) {
  7359. if (!Obj->isLittleEndian()) {
  7360. outs() << "Skipping big-endian __unwind_info section\n";
  7361. return;
  7362. }
  7363. outs() << "Contents of __unwind_info section:\n";
  7364. StringRef Contents =
  7365. unwrapOrError(UnwindInfo.getContents(), Obj->getFileName());
  7366. ptrdiff_t Pos = 0;
  7367. //===----------------------------------
  7368. // Section header
  7369. //===----------------------------------
  7370. uint32_t Version = readNext<uint32_t>(Contents, Pos);
  7371. outs() << " Version: "
  7372. << format("0x%" PRIx32, Version) << '\n';
  7373. if (Version != 1) {
  7374. outs() << " Skipping section with unknown version\n";
  7375. return;
  7376. }
  7377. uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
  7378. outs() << " Common encodings array section offset: "
  7379. << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
  7380. uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
  7381. outs() << " Number of common encodings in array: "
  7382. << format("0x%" PRIx32, NumCommonEncodings) << '\n';
  7383. uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
  7384. outs() << " Personality function array section offset: "
  7385. << format("0x%" PRIx32, PersonalitiesStart) << '\n';
  7386. uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
  7387. outs() << " Number of personality functions in array: "
  7388. << format("0x%" PRIx32, NumPersonalities) << '\n';
  7389. uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
  7390. outs() << " Index array section offset: "
  7391. << format("0x%" PRIx32, IndicesStart) << '\n';
  7392. uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
  7393. outs() << " Number of indices in array: "
  7394. << format("0x%" PRIx32, NumIndices) << '\n';
  7395. //===----------------------------------
  7396. // A shared list of common encodings
  7397. //===----------------------------------
  7398. // These occupy indices in the range [0, N] whenever an encoding is referenced
  7399. // from a compressed 2nd level index table. In practice the linker only
  7400. // creates ~128 of these, so that indices are available to embed encodings in
  7401. // the 2nd level index.
  7402. SmallVector<uint32_t, 64> CommonEncodings;
  7403. outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
  7404. Pos = CommonEncodingsStart;
  7405. for (unsigned i = 0; i < NumCommonEncodings; ++i) {
  7406. uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
  7407. CommonEncodings.push_back(Encoding);
  7408. outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
  7409. << '\n';
  7410. }
  7411. //===----------------------------------
  7412. // Personality functions used in this executable
  7413. //===----------------------------------
  7414. // There should be only a handful of these (one per source language,
  7415. // roughly). Particularly since they only get 2 bits in the compact encoding.
  7416. outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
  7417. Pos = PersonalitiesStart;
  7418. for (unsigned i = 0; i < NumPersonalities; ++i) {
  7419. uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
  7420. outs() << " personality[" << i + 1
  7421. << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
  7422. }
  7423. //===----------------------------------
  7424. // The level 1 index entries
  7425. //===----------------------------------
  7426. // These specify an approximate place to start searching for the more detailed
  7427. // information, sorted by PC.
  7428. struct IndexEntry {
  7429. uint32_t FunctionOffset;
  7430. uint32_t SecondLevelPageStart;
  7431. uint32_t LSDAStart;
  7432. };
  7433. SmallVector<IndexEntry, 4> IndexEntries;
  7434. outs() << " Top level indices: (count = " << NumIndices << ")\n";
  7435. Pos = IndicesStart;
  7436. for (unsigned i = 0; i < NumIndices; ++i) {
  7437. IndexEntry Entry;
  7438. Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
  7439. Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
  7440. Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
  7441. IndexEntries.push_back(Entry);
  7442. outs() << " [" << i << "]: "
  7443. << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
  7444. << ", "
  7445. << "2nd level page offset="
  7446. << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
  7447. << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
  7448. }
  7449. //===----------------------------------
  7450. // Next come the LSDA tables
  7451. //===----------------------------------
  7452. // The LSDA layout is rather implicit: it's a contiguous array of entries from
  7453. // the first top-level index's LSDAOffset to the last (sentinel).
  7454. outs() << " LSDA descriptors:\n";
  7455. Pos = IndexEntries[0].LSDAStart;
  7456. const uint32_t LSDASize = 2 * sizeof(uint32_t);
  7457. int NumLSDAs =
  7458. (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
  7459. for (int i = 0; i < NumLSDAs; ++i) {
  7460. uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
  7461. uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
  7462. outs() << " [" << i << "]: "
  7463. << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
  7464. << ", "
  7465. << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
  7466. }
  7467. //===----------------------------------
  7468. // Finally, the 2nd level indices
  7469. //===----------------------------------
  7470. // Generally these are 4K in size, and have 2 possible forms:
  7471. // + Regular stores up to 511 entries with disparate encodings
  7472. // + Compressed stores up to 1021 entries if few enough compact encoding
  7473. // values are used.
  7474. outs() << " Second level indices:\n";
  7475. for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
  7476. // The final sentinel top-level index has no associated 2nd level page
  7477. if (IndexEntries[i].SecondLevelPageStart == 0)
  7478. break;
  7479. outs() << " Second level index[" << i << "]: "
  7480. << "offset in section="
  7481. << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
  7482. << ", "
  7483. << "base function offset="
  7484. << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
  7485. Pos = IndexEntries[i].SecondLevelPageStart;
  7486. if (Pos + sizeof(uint32_t) > Contents.size()) {
  7487. outs() << "warning: invalid offset for second level page: " << Pos << '\n';
  7488. continue;
  7489. }
  7490. uint32_t Kind =
  7491. *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
  7492. if (Kind == 2)
  7493. printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
  7494. else if (Kind == 3)
  7495. printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
  7496. IndexEntries[i].FunctionOffset,
  7497. CommonEncodings);
  7498. else
  7499. outs() << " Skipping 2nd level page with unknown kind " << Kind
  7500. << '\n';
  7501. }
  7502. }
  7503. void printMachOUnwindInfo(const MachOObjectFile *Obj) {
  7504. std::map<uint64_t, SymbolRef> Symbols;
  7505. for (const SymbolRef &SymRef : Obj->symbols()) {
  7506. // Discard any undefined or absolute symbols. They're not going to take part
  7507. // in the convenience lookup for unwind info and just take up resources.
  7508. auto SectOrErr = SymRef.getSection();
  7509. if (!SectOrErr) {
  7510. // TODO: Actually report errors helpfully.
  7511. consumeError(SectOrErr.takeError());
  7512. continue;
  7513. }
  7514. section_iterator Section = *SectOrErr;
  7515. if (Section == Obj->section_end())
  7516. continue;
  7517. uint64_t Addr = SymRef.getValue();
  7518. Symbols.insert(std::make_pair(Addr, SymRef));
  7519. }
  7520. for (const SectionRef &Section : Obj->sections()) {
  7521. StringRef SectName;
  7522. if (Expected<StringRef> NameOrErr = Section.getName())
  7523. SectName = *NameOrErr;
  7524. else
  7525. consumeError(NameOrErr.takeError());
  7526. if (SectName == "__compact_unwind")
  7527. printMachOCompactUnwindSection(Obj, Symbols, Section);
  7528. else if (SectName == "__unwind_info")
  7529. printMachOUnwindInfoSection(Obj, Symbols, Section);
  7530. }
  7531. }
  7532. static void PrintMachHeader(uint32_t magic, uint32_t cputype,
  7533. uint32_t cpusubtype, uint32_t filetype,
  7534. uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
  7535. bool verbose) {
  7536. outs() << "Mach header\n";
  7537. outs() << " magic cputype cpusubtype caps filetype ncmds "
  7538. "sizeofcmds flags\n";
  7539. if (verbose) {
  7540. if (magic == MachO::MH_MAGIC)
  7541. outs() << " MH_MAGIC";
  7542. else if (magic == MachO::MH_MAGIC_64)
  7543. outs() << "MH_MAGIC_64";
  7544. else
  7545. outs() << format(" 0x%08" PRIx32, magic);
  7546. switch (cputype) {
  7547. case MachO::CPU_TYPE_I386:
  7548. outs() << " I386";
  7549. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7550. case MachO::CPU_SUBTYPE_I386_ALL:
  7551. outs() << " ALL";
  7552. break;
  7553. default:
  7554. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7555. break;
  7556. }
  7557. break;
  7558. case MachO::CPU_TYPE_X86_64:
  7559. outs() << " X86_64";
  7560. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7561. case MachO::CPU_SUBTYPE_X86_64_ALL:
  7562. outs() << " ALL";
  7563. break;
  7564. case MachO::CPU_SUBTYPE_X86_64_H:
  7565. outs() << " Haswell";
  7566. break;
  7567. default:
  7568. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7569. break;
  7570. }
  7571. break;
  7572. case MachO::CPU_TYPE_ARM:
  7573. outs() << " ARM";
  7574. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7575. case MachO::CPU_SUBTYPE_ARM_ALL:
  7576. outs() << " ALL";
  7577. break;
  7578. case MachO::CPU_SUBTYPE_ARM_V4T:
  7579. outs() << " V4T";
  7580. break;
  7581. case MachO::CPU_SUBTYPE_ARM_V5TEJ:
  7582. outs() << " V5TEJ";
  7583. break;
  7584. case MachO::CPU_SUBTYPE_ARM_XSCALE:
  7585. outs() << " XSCALE";
  7586. break;
  7587. case MachO::CPU_SUBTYPE_ARM_V6:
  7588. outs() << " V6";
  7589. break;
  7590. case MachO::CPU_SUBTYPE_ARM_V6M:
  7591. outs() << " V6M";
  7592. break;
  7593. case MachO::CPU_SUBTYPE_ARM_V7:
  7594. outs() << " V7";
  7595. break;
  7596. case MachO::CPU_SUBTYPE_ARM_V7EM:
  7597. outs() << " V7EM";
  7598. break;
  7599. case MachO::CPU_SUBTYPE_ARM_V7K:
  7600. outs() << " V7K";
  7601. break;
  7602. case MachO::CPU_SUBTYPE_ARM_V7M:
  7603. outs() << " V7M";
  7604. break;
  7605. case MachO::CPU_SUBTYPE_ARM_V7S:
  7606. outs() << " V7S";
  7607. break;
  7608. default:
  7609. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7610. break;
  7611. }
  7612. break;
  7613. case MachO::CPU_TYPE_ARM64:
  7614. outs() << " ARM64";
  7615. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7616. case MachO::CPU_SUBTYPE_ARM64_ALL:
  7617. outs() << " ALL";
  7618. break;
  7619. case MachO::CPU_SUBTYPE_ARM64E:
  7620. outs() << " E";
  7621. break;
  7622. default:
  7623. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7624. break;
  7625. }
  7626. break;
  7627. case MachO::CPU_TYPE_ARM64_32:
  7628. outs() << " ARM64_32";
  7629. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7630. case MachO::CPU_SUBTYPE_ARM64_32_V8:
  7631. outs() << " V8";
  7632. break;
  7633. default:
  7634. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7635. break;
  7636. }
  7637. break;
  7638. case MachO::CPU_TYPE_POWERPC:
  7639. outs() << " PPC";
  7640. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7641. case MachO::CPU_SUBTYPE_POWERPC_ALL:
  7642. outs() << " ALL";
  7643. break;
  7644. default:
  7645. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7646. break;
  7647. }
  7648. break;
  7649. case MachO::CPU_TYPE_POWERPC64:
  7650. outs() << " PPC64";
  7651. switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
  7652. case MachO::CPU_SUBTYPE_POWERPC_ALL:
  7653. outs() << " ALL";
  7654. break;
  7655. default:
  7656. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7657. break;
  7658. }
  7659. break;
  7660. default:
  7661. outs() << format(" %7d", cputype);
  7662. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7663. break;
  7664. }
  7665. if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
  7666. outs() << " LIB64";
  7667. } else {
  7668. outs() << format(" 0x%02" PRIx32,
  7669. (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
  7670. }
  7671. switch (filetype) {
  7672. case MachO::MH_OBJECT:
  7673. outs() << " OBJECT";
  7674. break;
  7675. case MachO::MH_EXECUTE:
  7676. outs() << " EXECUTE";
  7677. break;
  7678. case MachO::MH_FVMLIB:
  7679. outs() << " FVMLIB";
  7680. break;
  7681. case MachO::MH_CORE:
  7682. outs() << " CORE";
  7683. break;
  7684. case MachO::MH_PRELOAD:
  7685. outs() << " PRELOAD";
  7686. break;
  7687. case MachO::MH_DYLIB:
  7688. outs() << " DYLIB";
  7689. break;
  7690. case MachO::MH_DYLIB_STUB:
  7691. outs() << " DYLIB_STUB";
  7692. break;
  7693. case MachO::MH_DYLINKER:
  7694. outs() << " DYLINKER";
  7695. break;
  7696. case MachO::MH_BUNDLE:
  7697. outs() << " BUNDLE";
  7698. break;
  7699. case MachO::MH_DSYM:
  7700. outs() << " DSYM";
  7701. break;
  7702. case MachO::MH_KEXT_BUNDLE:
  7703. outs() << " KEXTBUNDLE";
  7704. break;
  7705. default:
  7706. outs() << format(" %10u", filetype);
  7707. break;
  7708. }
  7709. outs() << format(" %5u", ncmds);
  7710. outs() << format(" %10u", sizeofcmds);
  7711. uint32_t f = flags;
  7712. if (f & MachO::MH_NOUNDEFS) {
  7713. outs() << " NOUNDEFS";
  7714. f &= ~MachO::MH_NOUNDEFS;
  7715. }
  7716. if (f & MachO::MH_INCRLINK) {
  7717. outs() << " INCRLINK";
  7718. f &= ~MachO::MH_INCRLINK;
  7719. }
  7720. if (f & MachO::MH_DYLDLINK) {
  7721. outs() << " DYLDLINK";
  7722. f &= ~MachO::MH_DYLDLINK;
  7723. }
  7724. if (f & MachO::MH_BINDATLOAD) {
  7725. outs() << " BINDATLOAD";
  7726. f &= ~MachO::MH_BINDATLOAD;
  7727. }
  7728. if (f & MachO::MH_PREBOUND) {
  7729. outs() << " PREBOUND";
  7730. f &= ~MachO::MH_PREBOUND;
  7731. }
  7732. if (f & MachO::MH_SPLIT_SEGS) {
  7733. outs() << " SPLIT_SEGS";
  7734. f &= ~MachO::MH_SPLIT_SEGS;
  7735. }
  7736. if (f & MachO::MH_LAZY_INIT) {
  7737. outs() << " LAZY_INIT";
  7738. f &= ~MachO::MH_LAZY_INIT;
  7739. }
  7740. if (f & MachO::MH_TWOLEVEL) {
  7741. outs() << " TWOLEVEL";
  7742. f &= ~MachO::MH_TWOLEVEL;
  7743. }
  7744. if (f & MachO::MH_FORCE_FLAT) {
  7745. outs() << " FORCE_FLAT";
  7746. f &= ~MachO::MH_FORCE_FLAT;
  7747. }
  7748. if (f & MachO::MH_NOMULTIDEFS) {
  7749. outs() << " NOMULTIDEFS";
  7750. f &= ~MachO::MH_NOMULTIDEFS;
  7751. }
  7752. if (f & MachO::MH_NOFIXPREBINDING) {
  7753. outs() << " NOFIXPREBINDING";
  7754. f &= ~MachO::MH_NOFIXPREBINDING;
  7755. }
  7756. if (f & MachO::MH_PREBINDABLE) {
  7757. outs() << " PREBINDABLE";
  7758. f &= ~MachO::MH_PREBINDABLE;
  7759. }
  7760. if (f & MachO::MH_ALLMODSBOUND) {
  7761. outs() << " ALLMODSBOUND";
  7762. f &= ~MachO::MH_ALLMODSBOUND;
  7763. }
  7764. if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
  7765. outs() << " SUBSECTIONS_VIA_SYMBOLS";
  7766. f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
  7767. }
  7768. if (f & MachO::MH_CANONICAL) {
  7769. outs() << " CANONICAL";
  7770. f &= ~MachO::MH_CANONICAL;
  7771. }
  7772. if (f & MachO::MH_WEAK_DEFINES) {
  7773. outs() << " WEAK_DEFINES";
  7774. f &= ~MachO::MH_WEAK_DEFINES;
  7775. }
  7776. if (f & MachO::MH_BINDS_TO_WEAK) {
  7777. outs() << " BINDS_TO_WEAK";
  7778. f &= ~MachO::MH_BINDS_TO_WEAK;
  7779. }
  7780. if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
  7781. outs() << " ALLOW_STACK_EXECUTION";
  7782. f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
  7783. }
  7784. if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
  7785. outs() << " DEAD_STRIPPABLE_DYLIB";
  7786. f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
  7787. }
  7788. if (f & MachO::MH_PIE) {
  7789. outs() << " PIE";
  7790. f &= ~MachO::MH_PIE;
  7791. }
  7792. if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
  7793. outs() << " NO_REEXPORTED_DYLIBS";
  7794. f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
  7795. }
  7796. if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
  7797. outs() << " MH_HAS_TLV_DESCRIPTORS";
  7798. f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
  7799. }
  7800. if (f & MachO::MH_NO_HEAP_EXECUTION) {
  7801. outs() << " MH_NO_HEAP_EXECUTION";
  7802. f &= ~MachO::MH_NO_HEAP_EXECUTION;
  7803. }
  7804. if (f & MachO::MH_APP_EXTENSION_SAFE) {
  7805. outs() << " APP_EXTENSION_SAFE";
  7806. f &= ~MachO::MH_APP_EXTENSION_SAFE;
  7807. }
  7808. if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
  7809. outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
  7810. f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
  7811. }
  7812. if (f != 0 || flags == 0)
  7813. outs() << format(" 0x%08" PRIx32, f);
  7814. } else {
  7815. outs() << format(" 0x%08" PRIx32, magic);
  7816. outs() << format(" %7d", cputype);
  7817. outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
  7818. outs() << format(" 0x%02" PRIx32,
  7819. (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
  7820. outs() << format(" %10u", filetype);
  7821. outs() << format(" %5u", ncmds);
  7822. outs() << format(" %10u", sizeofcmds);
  7823. outs() << format(" 0x%08" PRIx32, flags);
  7824. }
  7825. outs() << "\n";
  7826. }
  7827. static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
  7828. StringRef SegName, uint64_t vmaddr,
  7829. uint64_t vmsize, uint64_t fileoff,
  7830. uint64_t filesize, uint32_t maxprot,
  7831. uint32_t initprot, uint32_t nsects,
  7832. uint32_t flags, uint32_t object_size,
  7833. bool verbose) {
  7834. uint64_t expected_cmdsize;
  7835. if (cmd == MachO::LC_SEGMENT) {
  7836. outs() << " cmd LC_SEGMENT\n";
  7837. expected_cmdsize = nsects;
  7838. expected_cmdsize *= sizeof(struct MachO::section);
  7839. expected_cmdsize += sizeof(struct MachO::segment_command);
  7840. } else {
  7841. outs() << " cmd LC_SEGMENT_64\n";
  7842. expected_cmdsize = nsects;
  7843. expected_cmdsize *= sizeof(struct MachO::section_64);
  7844. expected_cmdsize += sizeof(struct MachO::segment_command_64);
  7845. }
  7846. outs() << " cmdsize " << cmdsize;
  7847. if (cmdsize != expected_cmdsize)
  7848. outs() << " Inconsistent size\n";
  7849. else
  7850. outs() << "\n";
  7851. outs() << " segname " << SegName << "\n";
  7852. if (cmd == MachO::LC_SEGMENT_64) {
  7853. outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
  7854. outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
  7855. } else {
  7856. outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
  7857. outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
  7858. }
  7859. outs() << " fileoff " << fileoff;
  7860. if (fileoff > object_size)
  7861. outs() << " (past end of file)\n";
  7862. else
  7863. outs() << "\n";
  7864. outs() << " filesize " << filesize;
  7865. if (fileoff + filesize > object_size)
  7866. outs() << " (past end of file)\n";
  7867. else
  7868. outs() << "\n";
  7869. if (verbose) {
  7870. if ((maxprot &
  7871. ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
  7872. MachO::VM_PROT_EXECUTE)) != 0)
  7873. outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
  7874. else {
  7875. outs() << " maxprot ";
  7876. outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
  7877. outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
  7878. outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
  7879. }
  7880. if ((initprot &
  7881. ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
  7882. MachO::VM_PROT_EXECUTE)) != 0)
  7883. outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
  7884. else {
  7885. outs() << " initprot ";
  7886. outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
  7887. outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
  7888. outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
  7889. }
  7890. } else {
  7891. outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
  7892. outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
  7893. }
  7894. outs() << " nsects " << nsects << "\n";
  7895. if (verbose) {
  7896. outs() << " flags";
  7897. if (flags == 0)
  7898. outs() << " (none)\n";
  7899. else {
  7900. if (flags & MachO::SG_HIGHVM) {
  7901. outs() << " HIGHVM";
  7902. flags &= ~MachO::SG_HIGHVM;
  7903. }
  7904. if (flags & MachO::SG_FVMLIB) {
  7905. outs() << " FVMLIB";
  7906. flags &= ~MachO::SG_FVMLIB;
  7907. }
  7908. if (flags & MachO::SG_NORELOC) {
  7909. outs() << " NORELOC";
  7910. flags &= ~MachO::SG_NORELOC;
  7911. }
  7912. if (flags & MachO::SG_PROTECTED_VERSION_1) {
  7913. outs() << " PROTECTED_VERSION_1";
  7914. flags &= ~MachO::SG_PROTECTED_VERSION_1;
  7915. }
  7916. if (flags)
  7917. outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
  7918. else
  7919. outs() << "\n";
  7920. }
  7921. } else {
  7922. outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
  7923. }
  7924. }
  7925. static void PrintSection(const char *sectname, const char *segname,
  7926. uint64_t addr, uint64_t size, uint32_t offset,
  7927. uint32_t align, uint32_t reloff, uint32_t nreloc,
  7928. uint32_t flags, uint32_t reserved1, uint32_t reserved2,
  7929. uint32_t cmd, const char *sg_segname,
  7930. uint32_t filetype, uint32_t object_size,
  7931. bool verbose) {
  7932. outs() << "Section\n";
  7933. outs() << " sectname " << format("%.16s\n", sectname);
  7934. outs() << " segname " << format("%.16s", segname);
  7935. if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
  7936. outs() << " (does not match segment)\n";
  7937. else
  7938. outs() << "\n";
  7939. if (cmd == MachO::LC_SEGMENT_64) {
  7940. outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
  7941. outs() << " size " << format("0x%016" PRIx64, size);
  7942. } else {
  7943. outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
  7944. outs() << " size " << format("0x%08" PRIx64, size);
  7945. }
  7946. if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
  7947. outs() << " (past end of file)\n";
  7948. else
  7949. outs() << "\n";
  7950. outs() << " offset " << offset;
  7951. if (offset > object_size)
  7952. outs() << " (past end of file)\n";
  7953. else
  7954. outs() << "\n";
  7955. uint32_t align_shifted = 1 << align;
  7956. outs() << " align 2^" << align << " (" << align_shifted << ")\n";
  7957. outs() << " reloff " << reloff;
  7958. if (reloff > object_size)
  7959. outs() << " (past end of file)\n";
  7960. else
  7961. outs() << "\n";
  7962. outs() << " nreloc " << nreloc;
  7963. if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
  7964. outs() << " (past end of file)\n";
  7965. else
  7966. outs() << "\n";
  7967. uint32_t section_type = flags & MachO::SECTION_TYPE;
  7968. if (verbose) {
  7969. outs() << " type";
  7970. if (section_type == MachO::S_REGULAR)
  7971. outs() << " S_REGULAR\n";
  7972. else if (section_type == MachO::S_ZEROFILL)
  7973. outs() << " S_ZEROFILL\n";
  7974. else if (section_type == MachO::S_CSTRING_LITERALS)
  7975. outs() << " S_CSTRING_LITERALS\n";
  7976. else if (section_type == MachO::S_4BYTE_LITERALS)
  7977. outs() << " S_4BYTE_LITERALS\n";
  7978. else if (section_type == MachO::S_8BYTE_LITERALS)
  7979. outs() << " S_8BYTE_LITERALS\n";
  7980. else if (section_type == MachO::S_16BYTE_LITERALS)
  7981. outs() << " S_16BYTE_LITERALS\n";
  7982. else if (section_type == MachO::S_LITERAL_POINTERS)
  7983. outs() << " S_LITERAL_POINTERS\n";
  7984. else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
  7985. outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
  7986. else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
  7987. outs() << " S_LAZY_SYMBOL_POINTERS\n";
  7988. else if (section_type == MachO::S_SYMBOL_STUBS)
  7989. outs() << " S_SYMBOL_STUBS\n";
  7990. else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
  7991. outs() << " S_MOD_INIT_FUNC_POINTERS\n";
  7992. else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
  7993. outs() << " S_MOD_TERM_FUNC_POINTERS\n";
  7994. else if (section_type == MachO::S_COALESCED)
  7995. outs() << " S_COALESCED\n";
  7996. else if (section_type == MachO::S_INTERPOSING)
  7997. outs() << " S_INTERPOSING\n";
  7998. else if (section_type == MachO::S_DTRACE_DOF)
  7999. outs() << " S_DTRACE_DOF\n";
  8000. else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
  8001. outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
  8002. else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
  8003. outs() << " S_THREAD_LOCAL_REGULAR\n";
  8004. else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
  8005. outs() << " S_THREAD_LOCAL_ZEROFILL\n";
  8006. else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
  8007. outs() << " S_THREAD_LOCAL_VARIABLES\n";
  8008. else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
  8009. outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
  8010. else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
  8011. outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
  8012. else
  8013. outs() << format("0x%08" PRIx32, section_type) << "\n";
  8014. outs() << "attributes";
  8015. uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
  8016. if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
  8017. outs() << " PURE_INSTRUCTIONS";
  8018. if (section_attributes & MachO::S_ATTR_NO_TOC)
  8019. outs() << " NO_TOC";
  8020. if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
  8021. outs() << " STRIP_STATIC_SYMS";
  8022. if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
  8023. outs() << " NO_DEAD_STRIP";
  8024. if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
  8025. outs() << " LIVE_SUPPORT";
  8026. if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
  8027. outs() << " SELF_MODIFYING_CODE";
  8028. if (section_attributes & MachO::S_ATTR_DEBUG)
  8029. outs() << " DEBUG";
  8030. if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
  8031. outs() << " SOME_INSTRUCTIONS";
  8032. if (section_attributes & MachO::S_ATTR_EXT_RELOC)
  8033. outs() << " EXT_RELOC";
  8034. if (section_attributes & MachO::S_ATTR_LOC_RELOC)
  8035. outs() << " LOC_RELOC";
  8036. if (section_attributes == 0)
  8037. outs() << " (none)";
  8038. outs() << "\n";
  8039. } else
  8040. outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
  8041. outs() << " reserved1 " << reserved1;
  8042. if (section_type == MachO::S_SYMBOL_STUBS ||
  8043. section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
  8044. section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
  8045. section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
  8046. section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
  8047. outs() << " (index into indirect symbol table)\n";
  8048. else
  8049. outs() << "\n";
  8050. outs() << " reserved2 " << reserved2;
  8051. if (section_type == MachO::S_SYMBOL_STUBS)
  8052. outs() << " (size of stubs)\n";
  8053. else
  8054. outs() << "\n";
  8055. }
  8056. static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
  8057. uint32_t object_size) {
  8058. outs() << " cmd LC_SYMTAB\n";
  8059. outs() << " cmdsize " << st.cmdsize;
  8060. if (st.cmdsize != sizeof(struct MachO::symtab_command))
  8061. outs() << " Incorrect size\n";
  8062. else
  8063. outs() << "\n";
  8064. outs() << " symoff " << st.symoff;
  8065. if (st.symoff > object_size)
  8066. outs() << " (past end of file)\n";
  8067. else
  8068. outs() << "\n";
  8069. outs() << " nsyms " << st.nsyms;
  8070. uint64_t big_size;
  8071. if (Is64Bit) {
  8072. big_size = st.nsyms;
  8073. big_size *= sizeof(struct MachO::nlist_64);
  8074. big_size += st.symoff;
  8075. if (big_size > object_size)
  8076. outs() << " (past end of file)\n";
  8077. else
  8078. outs() << "\n";
  8079. } else {
  8080. big_size = st.nsyms;
  8081. big_size *= sizeof(struct MachO::nlist);
  8082. big_size += st.symoff;
  8083. if (big_size > object_size)
  8084. outs() << " (past end of file)\n";
  8085. else
  8086. outs() << "\n";
  8087. }
  8088. outs() << " stroff " << st.stroff;
  8089. if (st.stroff > object_size)
  8090. outs() << " (past end of file)\n";
  8091. else
  8092. outs() << "\n";
  8093. outs() << " strsize " << st.strsize;
  8094. big_size = st.stroff;
  8095. big_size += st.strsize;
  8096. if (big_size > object_size)
  8097. outs() << " (past end of file)\n";
  8098. else
  8099. outs() << "\n";
  8100. }
  8101. static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
  8102. uint32_t nsyms, uint32_t object_size,
  8103. bool Is64Bit) {
  8104. outs() << " cmd LC_DYSYMTAB\n";
  8105. outs() << " cmdsize " << dyst.cmdsize;
  8106. if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
  8107. outs() << " Incorrect size\n";
  8108. else
  8109. outs() << "\n";
  8110. outs() << " ilocalsym " << dyst.ilocalsym;
  8111. if (dyst.ilocalsym > nsyms)
  8112. outs() << " (greater than the number of symbols)\n";
  8113. else
  8114. outs() << "\n";
  8115. outs() << " nlocalsym " << dyst.nlocalsym;
  8116. uint64_t big_size;
  8117. big_size = dyst.ilocalsym;
  8118. big_size += dyst.nlocalsym;
  8119. if (big_size > nsyms)
  8120. outs() << " (past the end of the symbol table)\n";
  8121. else
  8122. outs() << "\n";
  8123. outs() << " iextdefsym " << dyst.iextdefsym;
  8124. if (dyst.iextdefsym > nsyms)
  8125. outs() << " (greater than the number of symbols)\n";
  8126. else
  8127. outs() << "\n";
  8128. outs() << " nextdefsym " << dyst.nextdefsym;
  8129. big_size = dyst.iextdefsym;
  8130. big_size += dyst.nextdefsym;
  8131. if (big_size > nsyms)
  8132. outs() << " (past the end of the symbol table)\n";
  8133. else
  8134. outs() << "\n";
  8135. outs() << " iundefsym " << dyst.iundefsym;
  8136. if (dyst.iundefsym > nsyms)
  8137. outs() << " (greater than the number of symbols)\n";
  8138. else
  8139. outs() << "\n";
  8140. outs() << " nundefsym " << dyst.nundefsym;
  8141. big_size = dyst.iundefsym;
  8142. big_size += dyst.nundefsym;
  8143. if (big_size > nsyms)
  8144. outs() << " (past the end of the symbol table)\n";
  8145. else
  8146. outs() << "\n";
  8147. outs() << " tocoff " << dyst.tocoff;
  8148. if (dyst.tocoff > object_size)
  8149. outs() << " (past end of file)\n";
  8150. else
  8151. outs() << "\n";
  8152. outs() << " ntoc " << dyst.ntoc;
  8153. big_size = dyst.ntoc;
  8154. big_size *= sizeof(struct MachO::dylib_table_of_contents);
  8155. big_size += dyst.tocoff;
  8156. if (big_size > object_size)
  8157. outs() << " (past end of file)\n";
  8158. else
  8159. outs() << "\n";
  8160. outs() << " modtaboff " << dyst.modtaboff;
  8161. if (dyst.modtaboff > object_size)
  8162. outs() << " (past end of file)\n";
  8163. else
  8164. outs() << "\n";
  8165. outs() << " nmodtab " << dyst.nmodtab;
  8166. uint64_t modtabend;
  8167. if (Is64Bit) {
  8168. modtabend = dyst.nmodtab;
  8169. modtabend *= sizeof(struct MachO::dylib_module_64);
  8170. modtabend += dyst.modtaboff;
  8171. } else {
  8172. modtabend = dyst.nmodtab;
  8173. modtabend *= sizeof(struct MachO::dylib_module);
  8174. modtabend += dyst.modtaboff;
  8175. }
  8176. if (modtabend > object_size)
  8177. outs() << " (past end of file)\n";
  8178. else
  8179. outs() << "\n";
  8180. outs() << " extrefsymoff " << dyst.extrefsymoff;
  8181. if (dyst.extrefsymoff > object_size)
  8182. outs() << " (past end of file)\n";
  8183. else
  8184. outs() << "\n";
  8185. outs() << " nextrefsyms " << dyst.nextrefsyms;
  8186. big_size = dyst.nextrefsyms;
  8187. big_size *= sizeof(struct MachO::dylib_reference);
  8188. big_size += dyst.extrefsymoff;
  8189. if (big_size > object_size)
  8190. outs() << " (past end of file)\n";
  8191. else
  8192. outs() << "\n";
  8193. outs() << " indirectsymoff " << dyst.indirectsymoff;
  8194. if (dyst.indirectsymoff > object_size)
  8195. outs() << " (past end of file)\n";
  8196. else
  8197. outs() << "\n";
  8198. outs() << " nindirectsyms " << dyst.nindirectsyms;
  8199. big_size = dyst.nindirectsyms;
  8200. big_size *= sizeof(uint32_t);
  8201. big_size += dyst.indirectsymoff;
  8202. if (big_size > object_size)
  8203. outs() << " (past end of file)\n";
  8204. else
  8205. outs() << "\n";
  8206. outs() << " extreloff " << dyst.extreloff;
  8207. if (dyst.extreloff > object_size)
  8208. outs() << " (past end of file)\n";
  8209. else
  8210. outs() << "\n";
  8211. outs() << " nextrel " << dyst.nextrel;
  8212. big_size = dyst.nextrel;
  8213. big_size *= sizeof(struct MachO::relocation_info);
  8214. big_size += dyst.extreloff;
  8215. if (big_size > object_size)
  8216. outs() << " (past end of file)\n";
  8217. else
  8218. outs() << "\n";
  8219. outs() << " locreloff " << dyst.locreloff;
  8220. if (dyst.locreloff > object_size)
  8221. outs() << " (past end of file)\n";
  8222. else
  8223. outs() << "\n";
  8224. outs() << " nlocrel " << dyst.nlocrel;
  8225. big_size = dyst.nlocrel;
  8226. big_size *= sizeof(struct MachO::relocation_info);
  8227. big_size += dyst.locreloff;
  8228. if (big_size > object_size)
  8229. outs() << " (past end of file)\n";
  8230. else
  8231. outs() << "\n";
  8232. }
  8233. static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
  8234. uint32_t object_size) {
  8235. if (dc.cmd == MachO::LC_DYLD_INFO)
  8236. outs() << " cmd LC_DYLD_INFO\n";
  8237. else
  8238. outs() << " cmd LC_DYLD_INFO_ONLY\n";
  8239. outs() << " cmdsize " << dc.cmdsize;
  8240. if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
  8241. outs() << " Incorrect size\n";
  8242. else
  8243. outs() << "\n";
  8244. outs() << " rebase_off " << dc.rebase_off;
  8245. if (dc.rebase_off > object_size)
  8246. outs() << " (past end of file)\n";
  8247. else
  8248. outs() << "\n";
  8249. outs() << " rebase_size " << dc.rebase_size;
  8250. uint64_t big_size;
  8251. big_size = dc.rebase_off;
  8252. big_size += dc.rebase_size;
  8253. if (big_size > object_size)
  8254. outs() << " (past end of file)\n";
  8255. else
  8256. outs() << "\n";
  8257. outs() << " bind_off " << dc.bind_off;
  8258. if (dc.bind_off > object_size)
  8259. outs() << " (past end of file)\n";
  8260. else
  8261. outs() << "\n";
  8262. outs() << " bind_size " << dc.bind_size;
  8263. big_size = dc.bind_off;
  8264. big_size += dc.bind_size;
  8265. if (big_size > object_size)
  8266. outs() << " (past end of file)\n";
  8267. else
  8268. outs() << "\n";
  8269. outs() << " weak_bind_off " << dc.weak_bind_off;
  8270. if (dc.weak_bind_off > object_size)
  8271. outs() << " (past end of file)\n";
  8272. else
  8273. outs() << "\n";
  8274. outs() << " weak_bind_size " << dc.weak_bind_size;
  8275. big_size = dc.weak_bind_off;
  8276. big_size += dc.weak_bind_size;
  8277. if (big_size > object_size)
  8278. outs() << " (past end of file)\n";
  8279. else
  8280. outs() << "\n";
  8281. outs() << " lazy_bind_off " << dc.lazy_bind_off;
  8282. if (dc.lazy_bind_off > object_size)
  8283. outs() << " (past end of file)\n";
  8284. else
  8285. outs() << "\n";
  8286. outs() << " lazy_bind_size " << dc.lazy_bind_size;
  8287. big_size = dc.lazy_bind_off;
  8288. big_size += dc.lazy_bind_size;
  8289. if (big_size > object_size)
  8290. outs() << " (past end of file)\n";
  8291. else
  8292. outs() << "\n";
  8293. outs() << " export_off " << dc.export_off;
  8294. if (dc.export_off > object_size)
  8295. outs() << " (past end of file)\n";
  8296. else
  8297. outs() << "\n";
  8298. outs() << " export_size " << dc.export_size;
  8299. big_size = dc.export_off;
  8300. big_size += dc.export_size;
  8301. if (big_size > object_size)
  8302. outs() << " (past end of file)\n";
  8303. else
  8304. outs() << "\n";
  8305. }
  8306. static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
  8307. const char *Ptr) {
  8308. if (dyld.cmd == MachO::LC_ID_DYLINKER)
  8309. outs() << " cmd LC_ID_DYLINKER\n";
  8310. else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
  8311. outs() << " cmd LC_LOAD_DYLINKER\n";
  8312. else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
  8313. outs() << " cmd LC_DYLD_ENVIRONMENT\n";
  8314. else
  8315. outs() << " cmd ?(" << dyld.cmd << ")\n";
  8316. outs() << " cmdsize " << dyld.cmdsize;
  8317. if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
  8318. outs() << " Incorrect size\n";
  8319. else
  8320. outs() << "\n";
  8321. if (dyld.name >= dyld.cmdsize)
  8322. outs() << " name ?(bad offset " << dyld.name << ")\n";
  8323. else {
  8324. const char *P = (const char *)(Ptr) + dyld.name;
  8325. outs() << " name " << P << " (offset " << dyld.name << ")\n";
  8326. }
  8327. }
  8328. static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
  8329. outs() << " cmd LC_UUID\n";
  8330. outs() << " cmdsize " << uuid.cmdsize;
  8331. if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
  8332. outs() << " Incorrect size\n";
  8333. else
  8334. outs() << "\n";
  8335. outs() << " uuid ";
  8336. for (int i = 0; i < 16; ++i) {
  8337. outs() << format("%02" PRIX32, uuid.uuid[i]);
  8338. if (i == 3 || i == 5 || i == 7 || i == 9)
  8339. outs() << "-";
  8340. }
  8341. outs() << "\n";
  8342. }
  8343. static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
  8344. outs() << " cmd LC_RPATH\n";
  8345. outs() << " cmdsize " << rpath.cmdsize;
  8346. if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
  8347. outs() << " Incorrect size\n";
  8348. else
  8349. outs() << "\n";
  8350. if (rpath.path >= rpath.cmdsize)
  8351. outs() << " path ?(bad offset " << rpath.path << ")\n";
  8352. else {
  8353. const char *P = (const char *)(Ptr) + rpath.path;
  8354. outs() << " path " << P << " (offset " << rpath.path << ")\n";
  8355. }
  8356. }
  8357. static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
  8358. StringRef LoadCmdName;
  8359. switch (vd.cmd) {
  8360. case MachO::LC_VERSION_MIN_MACOSX:
  8361. LoadCmdName = "LC_VERSION_MIN_MACOSX";
  8362. break;
  8363. case MachO::LC_VERSION_MIN_IPHONEOS:
  8364. LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
  8365. break;
  8366. case MachO::LC_VERSION_MIN_TVOS:
  8367. LoadCmdName = "LC_VERSION_MIN_TVOS";
  8368. break;
  8369. case MachO::LC_VERSION_MIN_WATCHOS:
  8370. LoadCmdName = "LC_VERSION_MIN_WATCHOS";
  8371. break;
  8372. default:
  8373. llvm_unreachable("Unknown version min load command");
  8374. }
  8375. outs() << " cmd " << LoadCmdName << '\n';
  8376. outs() << " cmdsize " << vd.cmdsize;
  8377. if (vd.cmdsize != sizeof(struct MachO::version_min_command))
  8378. outs() << " Incorrect size\n";
  8379. else
  8380. outs() << "\n";
  8381. outs() << " version "
  8382. << MachOObjectFile::getVersionMinMajor(vd, false) << "."
  8383. << MachOObjectFile::getVersionMinMinor(vd, false);
  8384. uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
  8385. if (Update != 0)
  8386. outs() << "." << Update;
  8387. outs() << "\n";
  8388. if (vd.sdk == 0)
  8389. outs() << " sdk n/a";
  8390. else {
  8391. outs() << " sdk "
  8392. << MachOObjectFile::getVersionMinMajor(vd, true) << "."
  8393. << MachOObjectFile::getVersionMinMinor(vd, true);
  8394. }
  8395. Update = MachOObjectFile::getVersionMinUpdate(vd, true);
  8396. if (Update != 0)
  8397. outs() << "." << Update;
  8398. outs() << "\n";
  8399. }
  8400. static void PrintNoteLoadCommand(MachO::note_command Nt) {
  8401. outs() << " cmd LC_NOTE\n";
  8402. outs() << " cmdsize " << Nt.cmdsize;
  8403. if (Nt.cmdsize != sizeof(struct MachO::note_command))
  8404. outs() << " Incorrect size\n";
  8405. else
  8406. outs() << "\n";
  8407. const char *d = Nt.data_owner;
  8408. outs() << "data_owner " << format("%.16s\n", d);
  8409. outs() << " offset " << Nt.offset << "\n";
  8410. outs() << " size " << Nt.size << "\n";
  8411. }
  8412. static void PrintBuildToolVersion(MachO::build_tool_version bv) {
  8413. outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
  8414. outs() << " version " << MachOObjectFile::getVersionString(bv.version)
  8415. << "\n";
  8416. }
  8417. static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
  8418. MachO::build_version_command bd) {
  8419. outs() << " cmd LC_BUILD_VERSION\n";
  8420. outs() << " cmdsize " << bd.cmdsize;
  8421. if (bd.cmdsize !=
  8422. sizeof(struct MachO::build_version_command) +
  8423. bd.ntools * sizeof(struct MachO::build_tool_version))
  8424. outs() << " Incorrect size\n";
  8425. else
  8426. outs() << "\n";
  8427. outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
  8428. << "\n";
  8429. if (bd.sdk)
  8430. outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
  8431. << "\n";
  8432. else
  8433. outs() << " sdk n/a\n";
  8434. outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
  8435. << "\n";
  8436. outs() << " ntools " << bd.ntools << "\n";
  8437. for (unsigned i = 0; i < bd.ntools; ++i) {
  8438. MachO::build_tool_version bv = obj->getBuildToolVersion(i);
  8439. PrintBuildToolVersion(bv);
  8440. }
  8441. }
  8442. static void PrintSourceVersionCommand(MachO::source_version_command sd) {
  8443. outs() << " cmd LC_SOURCE_VERSION\n";
  8444. outs() << " cmdsize " << sd.cmdsize;
  8445. if (sd.cmdsize != sizeof(struct MachO::source_version_command))
  8446. outs() << " Incorrect size\n";
  8447. else
  8448. outs() << "\n";
  8449. uint64_t a = (sd.version >> 40) & 0xffffff;
  8450. uint64_t b = (sd.version >> 30) & 0x3ff;
  8451. uint64_t c = (sd.version >> 20) & 0x3ff;
  8452. uint64_t d = (sd.version >> 10) & 0x3ff;
  8453. uint64_t e = sd.version & 0x3ff;
  8454. outs() << " version " << a << "." << b;
  8455. if (e != 0)
  8456. outs() << "." << c << "." << d << "." << e;
  8457. else if (d != 0)
  8458. outs() << "." << c << "." << d;
  8459. else if (c != 0)
  8460. outs() << "." << c;
  8461. outs() << "\n";
  8462. }
  8463. static void PrintEntryPointCommand(MachO::entry_point_command ep) {
  8464. outs() << " cmd LC_MAIN\n";
  8465. outs() << " cmdsize " << ep.cmdsize;
  8466. if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
  8467. outs() << " Incorrect size\n";
  8468. else
  8469. outs() << "\n";
  8470. outs() << " entryoff " << ep.entryoff << "\n";
  8471. outs() << " stacksize " << ep.stacksize << "\n";
  8472. }
  8473. static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
  8474. uint32_t object_size) {
  8475. outs() << " cmd LC_ENCRYPTION_INFO\n";
  8476. outs() << " cmdsize " << ec.cmdsize;
  8477. if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
  8478. outs() << " Incorrect size\n";
  8479. else
  8480. outs() << "\n";
  8481. outs() << " cryptoff " << ec.cryptoff;
  8482. if (ec.cryptoff > object_size)
  8483. outs() << " (past end of file)\n";
  8484. else
  8485. outs() << "\n";
  8486. outs() << " cryptsize " << ec.cryptsize;
  8487. if (ec.cryptsize > object_size)
  8488. outs() << " (past end of file)\n";
  8489. else
  8490. outs() << "\n";
  8491. outs() << " cryptid " << ec.cryptid << "\n";
  8492. }
  8493. static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
  8494. uint32_t object_size) {
  8495. outs() << " cmd LC_ENCRYPTION_INFO_64\n";
  8496. outs() << " cmdsize " << ec.cmdsize;
  8497. if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
  8498. outs() << " Incorrect size\n";
  8499. else
  8500. outs() << "\n";
  8501. outs() << " cryptoff " << ec.cryptoff;
  8502. if (ec.cryptoff > object_size)
  8503. outs() << " (past end of file)\n";
  8504. else
  8505. outs() << "\n";
  8506. outs() << " cryptsize " << ec.cryptsize;
  8507. if (ec.cryptsize > object_size)
  8508. outs() << " (past end of file)\n";
  8509. else
  8510. outs() << "\n";
  8511. outs() << " cryptid " << ec.cryptid << "\n";
  8512. outs() << " pad " << ec.pad << "\n";
  8513. }
  8514. static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
  8515. const char *Ptr) {
  8516. outs() << " cmd LC_LINKER_OPTION\n";
  8517. outs() << " cmdsize " << lo.cmdsize;
  8518. if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
  8519. outs() << " Incorrect size\n";
  8520. else
  8521. outs() << "\n";
  8522. outs() << " count " << lo.count << "\n";
  8523. const char *string = Ptr + sizeof(struct MachO::linker_option_command);
  8524. uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
  8525. uint32_t i = 0;
  8526. while (left > 0) {
  8527. while (*string == '\0' && left > 0) {
  8528. string++;
  8529. left--;
  8530. }
  8531. if (left > 0) {
  8532. i++;
  8533. outs() << " string #" << i << " " << format("%.*s\n", left, string);
  8534. uint32_t NullPos = StringRef(string, left).find('\0');
  8535. uint32_t len = std::min(NullPos, left) + 1;
  8536. string += len;
  8537. left -= len;
  8538. }
  8539. }
  8540. if (lo.count != i)
  8541. outs() << " count " << lo.count << " does not match number of strings "
  8542. << i << "\n";
  8543. }
  8544. static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
  8545. const char *Ptr) {
  8546. outs() << " cmd LC_SUB_FRAMEWORK\n";
  8547. outs() << " cmdsize " << sub.cmdsize;
  8548. if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
  8549. outs() << " Incorrect size\n";
  8550. else
  8551. outs() << "\n";
  8552. if (sub.umbrella < sub.cmdsize) {
  8553. const char *P = Ptr + sub.umbrella;
  8554. outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
  8555. } else {
  8556. outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
  8557. }
  8558. }
  8559. static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
  8560. const char *Ptr) {
  8561. outs() << " cmd LC_SUB_UMBRELLA\n";
  8562. outs() << " cmdsize " << sub.cmdsize;
  8563. if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
  8564. outs() << " Incorrect size\n";
  8565. else
  8566. outs() << "\n";
  8567. if (sub.sub_umbrella < sub.cmdsize) {
  8568. const char *P = Ptr + sub.sub_umbrella;
  8569. outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
  8570. } else {
  8571. outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
  8572. }
  8573. }
  8574. static void PrintSubLibraryCommand(MachO::sub_library_command sub,
  8575. const char *Ptr) {
  8576. outs() << " cmd LC_SUB_LIBRARY\n";
  8577. outs() << " cmdsize " << sub.cmdsize;
  8578. if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
  8579. outs() << " Incorrect size\n";
  8580. else
  8581. outs() << "\n";
  8582. if (sub.sub_library < sub.cmdsize) {
  8583. const char *P = Ptr + sub.sub_library;
  8584. outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
  8585. } else {
  8586. outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
  8587. }
  8588. }
  8589. static void PrintSubClientCommand(MachO::sub_client_command sub,
  8590. const char *Ptr) {
  8591. outs() << " cmd LC_SUB_CLIENT\n";
  8592. outs() << " cmdsize " << sub.cmdsize;
  8593. if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
  8594. outs() << " Incorrect size\n";
  8595. else
  8596. outs() << "\n";
  8597. if (sub.client < sub.cmdsize) {
  8598. const char *P = Ptr + sub.client;
  8599. outs() << " client " << P << " (offset " << sub.client << ")\n";
  8600. } else {
  8601. outs() << " client ?(bad offset " << sub.client << ")\n";
  8602. }
  8603. }
  8604. static void PrintRoutinesCommand(MachO::routines_command r) {
  8605. outs() << " cmd LC_ROUTINES\n";
  8606. outs() << " cmdsize " << r.cmdsize;
  8607. if (r.cmdsize != sizeof(struct MachO::routines_command))
  8608. outs() << " Incorrect size\n";
  8609. else
  8610. outs() << "\n";
  8611. outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
  8612. outs() << " init_module " << r.init_module << "\n";
  8613. outs() << " reserved1 " << r.reserved1 << "\n";
  8614. outs() << " reserved2 " << r.reserved2 << "\n";
  8615. outs() << " reserved3 " << r.reserved3 << "\n";
  8616. outs() << " reserved4 " << r.reserved4 << "\n";
  8617. outs() << " reserved5 " << r.reserved5 << "\n";
  8618. outs() << " reserved6 " << r.reserved6 << "\n";
  8619. }
  8620. static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
  8621. outs() << " cmd LC_ROUTINES_64\n";
  8622. outs() << " cmdsize " << r.cmdsize;
  8623. if (r.cmdsize != sizeof(struct MachO::routines_command_64))
  8624. outs() << " Incorrect size\n";
  8625. else
  8626. outs() << "\n";
  8627. outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
  8628. outs() << " init_module " << r.init_module << "\n";
  8629. outs() << " reserved1 " << r.reserved1 << "\n";
  8630. outs() << " reserved2 " << r.reserved2 << "\n";
  8631. outs() << " reserved3 " << r.reserved3 << "\n";
  8632. outs() << " reserved4 " << r.reserved4 << "\n";
  8633. outs() << " reserved5 " << r.reserved5 << "\n";
  8634. outs() << " reserved6 " << r.reserved6 << "\n";
  8635. }
  8636. static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
  8637. outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
  8638. outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
  8639. outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
  8640. outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
  8641. outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
  8642. outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
  8643. outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
  8644. outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
  8645. outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
  8646. outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
  8647. outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
  8648. outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
  8649. outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
  8650. outs() << " es " << format("0x%08" PRIx32, cpu32.es);
  8651. outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
  8652. outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
  8653. }
  8654. static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
  8655. outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
  8656. outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
  8657. outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
  8658. outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
  8659. outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
  8660. outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
  8661. outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
  8662. outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
  8663. outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
  8664. outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
  8665. outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
  8666. outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
  8667. outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
  8668. outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
  8669. outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
  8670. outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
  8671. outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
  8672. outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
  8673. outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
  8674. outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
  8675. outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
  8676. }
  8677. static void Print_mmst_reg(MachO::mmst_reg_t &r) {
  8678. uint32_t f;
  8679. outs() << "\t mmst_reg ";
  8680. for (f = 0; f < 10; f++)
  8681. outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
  8682. outs() << "\n";
  8683. outs() << "\t mmst_rsrv ";
  8684. for (f = 0; f < 6; f++)
  8685. outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
  8686. outs() << "\n";
  8687. }
  8688. static void Print_xmm_reg(MachO::xmm_reg_t &r) {
  8689. uint32_t f;
  8690. outs() << "\t xmm_reg ";
  8691. for (f = 0; f < 16; f++)
  8692. outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
  8693. outs() << "\n";
  8694. }
  8695. static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
  8696. outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
  8697. outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
  8698. outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
  8699. outs() << " denorm " << fpu.fpu_fcw.denorm;
  8700. outs() << " zdiv " << fpu.fpu_fcw.zdiv;
  8701. outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
  8702. outs() << " undfl " << fpu.fpu_fcw.undfl;
  8703. outs() << " precis " << fpu.fpu_fcw.precis << "\n";
  8704. outs() << "\t\t pc ";
  8705. if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
  8706. outs() << "FP_PREC_24B ";
  8707. else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
  8708. outs() << "FP_PREC_53B ";
  8709. else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
  8710. outs() << "FP_PREC_64B ";
  8711. else
  8712. outs() << fpu.fpu_fcw.pc << " ";
  8713. outs() << "rc ";
  8714. if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
  8715. outs() << "FP_RND_NEAR ";
  8716. else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
  8717. outs() << "FP_RND_DOWN ";
  8718. else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
  8719. outs() << "FP_RND_UP ";
  8720. else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
  8721. outs() << "FP_CHOP ";
  8722. outs() << "\n";
  8723. outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
  8724. outs() << " denorm " << fpu.fpu_fsw.denorm;
  8725. outs() << " zdiv " << fpu.fpu_fsw.zdiv;
  8726. outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
  8727. outs() << " undfl " << fpu.fpu_fsw.undfl;
  8728. outs() << " precis " << fpu.fpu_fsw.precis;
  8729. outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
  8730. outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
  8731. outs() << " c0 " << fpu.fpu_fsw.c0;
  8732. outs() << " c1 " << fpu.fpu_fsw.c1;
  8733. outs() << " c2 " << fpu.fpu_fsw.c2;
  8734. outs() << " tos " << fpu.fpu_fsw.tos;
  8735. outs() << " c3 " << fpu.fpu_fsw.c3;
  8736. outs() << " busy " << fpu.fpu_fsw.busy << "\n";
  8737. outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
  8738. outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
  8739. outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
  8740. outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
  8741. outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
  8742. outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
  8743. outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
  8744. outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
  8745. outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
  8746. outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
  8747. outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
  8748. outs() << "\n";
  8749. outs() << "\t fpu_stmm0:\n";
  8750. Print_mmst_reg(fpu.fpu_stmm0);
  8751. outs() << "\t fpu_stmm1:\n";
  8752. Print_mmst_reg(fpu.fpu_stmm1);
  8753. outs() << "\t fpu_stmm2:\n";
  8754. Print_mmst_reg(fpu.fpu_stmm2);
  8755. outs() << "\t fpu_stmm3:\n";
  8756. Print_mmst_reg(fpu.fpu_stmm3);
  8757. outs() << "\t fpu_stmm4:\n";
  8758. Print_mmst_reg(fpu.fpu_stmm4);
  8759. outs() << "\t fpu_stmm5:\n";
  8760. Print_mmst_reg(fpu.fpu_stmm5);
  8761. outs() << "\t fpu_stmm6:\n";
  8762. Print_mmst_reg(fpu.fpu_stmm6);
  8763. outs() << "\t fpu_stmm7:\n";
  8764. Print_mmst_reg(fpu.fpu_stmm7);
  8765. outs() << "\t fpu_xmm0:\n";
  8766. Print_xmm_reg(fpu.fpu_xmm0);
  8767. outs() << "\t fpu_xmm1:\n";
  8768. Print_xmm_reg(fpu.fpu_xmm1);
  8769. outs() << "\t fpu_xmm2:\n";
  8770. Print_xmm_reg(fpu.fpu_xmm2);
  8771. outs() << "\t fpu_xmm3:\n";
  8772. Print_xmm_reg(fpu.fpu_xmm3);
  8773. outs() << "\t fpu_xmm4:\n";
  8774. Print_xmm_reg(fpu.fpu_xmm4);
  8775. outs() << "\t fpu_xmm5:\n";
  8776. Print_xmm_reg(fpu.fpu_xmm5);
  8777. outs() << "\t fpu_xmm6:\n";
  8778. Print_xmm_reg(fpu.fpu_xmm6);
  8779. outs() << "\t fpu_xmm7:\n";
  8780. Print_xmm_reg(fpu.fpu_xmm7);
  8781. outs() << "\t fpu_xmm8:\n";
  8782. Print_xmm_reg(fpu.fpu_xmm8);
  8783. outs() << "\t fpu_xmm9:\n";
  8784. Print_xmm_reg(fpu.fpu_xmm9);
  8785. outs() << "\t fpu_xmm10:\n";
  8786. Print_xmm_reg(fpu.fpu_xmm10);
  8787. outs() << "\t fpu_xmm11:\n";
  8788. Print_xmm_reg(fpu.fpu_xmm11);
  8789. outs() << "\t fpu_xmm12:\n";
  8790. Print_xmm_reg(fpu.fpu_xmm12);
  8791. outs() << "\t fpu_xmm13:\n";
  8792. Print_xmm_reg(fpu.fpu_xmm13);
  8793. outs() << "\t fpu_xmm14:\n";
  8794. Print_xmm_reg(fpu.fpu_xmm14);
  8795. outs() << "\t fpu_xmm15:\n";
  8796. Print_xmm_reg(fpu.fpu_xmm15);
  8797. outs() << "\t fpu_rsrv4:\n";
  8798. for (uint32_t f = 0; f < 6; f++) {
  8799. outs() << "\t ";
  8800. for (uint32_t g = 0; g < 16; g++)
  8801. outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
  8802. outs() << "\n";
  8803. }
  8804. outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
  8805. outs() << "\n";
  8806. }
  8807. static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
  8808. outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
  8809. outs() << " err " << format("0x%08" PRIx32, exc64.err);
  8810. outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
  8811. }
  8812. static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
  8813. outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
  8814. outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
  8815. outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
  8816. outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
  8817. outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
  8818. outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
  8819. outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
  8820. outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
  8821. outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
  8822. outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
  8823. outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
  8824. outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
  8825. outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
  8826. outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
  8827. outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
  8828. outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
  8829. outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
  8830. }
  8831. static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
  8832. outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
  8833. outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
  8834. outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
  8835. outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
  8836. outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
  8837. outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
  8838. outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
  8839. outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
  8840. outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
  8841. outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
  8842. outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
  8843. outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
  8844. outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
  8845. outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
  8846. outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
  8847. outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
  8848. outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
  8849. outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
  8850. outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
  8851. outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
  8852. outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
  8853. outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
  8854. outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
  8855. outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
  8856. outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
  8857. outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
  8858. outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
  8859. outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
  8860. outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
  8861. outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
  8862. outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
  8863. outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
  8864. outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
  8865. outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
  8866. }
  8867. static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
  8868. bool isLittleEndian, uint32_t cputype) {
  8869. if (t.cmd == MachO::LC_THREAD)
  8870. outs() << " cmd LC_THREAD\n";
  8871. else if (t.cmd == MachO::LC_UNIXTHREAD)
  8872. outs() << " cmd LC_UNIXTHREAD\n";
  8873. else
  8874. outs() << " cmd " << t.cmd << " (unknown)\n";
  8875. outs() << " cmdsize " << t.cmdsize;
  8876. if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
  8877. outs() << " Incorrect size\n";
  8878. else
  8879. outs() << "\n";
  8880. const char *begin = Ptr + sizeof(struct MachO::thread_command);
  8881. const char *end = Ptr + t.cmdsize;
  8882. uint32_t flavor, count, left;
  8883. if (cputype == MachO::CPU_TYPE_I386) {
  8884. while (begin < end) {
  8885. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  8886. memcpy((char *)&flavor, begin, sizeof(uint32_t));
  8887. begin += sizeof(uint32_t);
  8888. } else {
  8889. flavor = 0;
  8890. begin = end;
  8891. }
  8892. if (isLittleEndian != sys::IsLittleEndianHost)
  8893. sys::swapByteOrder(flavor);
  8894. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  8895. memcpy((char *)&count, begin, sizeof(uint32_t));
  8896. begin += sizeof(uint32_t);
  8897. } else {
  8898. count = 0;
  8899. begin = end;
  8900. }
  8901. if (isLittleEndian != sys::IsLittleEndianHost)
  8902. sys::swapByteOrder(count);
  8903. if (flavor == MachO::x86_THREAD_STATE32) {
  8904. outs() << " flavor i386_THREAD_STATE\n";
  8905. if (count == MachO::x86_THREAD_STATE32_COUNT)
  8906. outs() << " count i386_THREAD_STATE_COUNT\n";
  8907. else
  8908. outs() << " count " << count
  8909. << " (not x86_THREAD_STATE32_COUNT)\n";
  8910. MachO::x86_thread_state32_t cpu32;
  8911. left = end - begin;
  8912. if (left >= sizeof(MachO::x86_thread_state32_t)) {
  8913. memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
  8914. begin += sizeof(MachO::x86_thread_state32_t);
  8915. } else {
  8916. memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
  8917. memcpy(&cpu32, begin, left);
  8918. begin += left;
  8919. }
  8920. if (isLittleEndian != sys::IsLittleEndianHost)
  8921. swapStruct(cpu32);
  8922. Print_x86_thread_state32_t(cpu32);
  8923. } else if (flavor == MachO::x86_THREAD_STATE) {
  8924. outs() << " flavor x86_THREAD_STATE\n";
  8925. if (count == MachO::x86_THREAD_STATE_COUNT)
  8926. outs() << " count x86_THREAD_STATE_COUNT\n";
  8927. else
  8928. outs() << " count " << count
  8929. << " (not x86_THREAD_STATE_COUNT)\n";
  8930. struct MachO::x86_thread_state_t ts;
  8931. left = end - begin;
  8932. if (left >= sizeof(MachO::x86_thread_state_t)) {
  8933. memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
  8934. begin += sizeof(MachO::x86_thread_state_t);
  8935. } else {
  8936. memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
  8937. memcpy(&ts, begin, left);
  8938. begin += left;
  8939. }
  8940. if (isLittleEndian != sys::IsLittleEndianHost)
  8941. swapStruct(ts);
  8942. if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
  8943. outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
  8944. if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
  8945. outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
  8946. else
  8947. outs() << "tsh.count " << ts.tsh.count
  8948. << " (not x86_THREAD_STATE32_COUNT\n";
  8949. Print_x86_thread_state32_t(ts.uts.ts32);
  8950. } else {
  8951. outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
  8952. << ts.tsh.count << "\n";
  8953. }
  8954. } else {
  8955. outs() << " flavor " << flavor << " (unknown)\n";
  8956. outs() << " count " << count << "\n";
  8957. outs() << " state (unknown)\n";
  8958. begin += count * sizeof(uint32_t);
  8959. }
  8960. }
  8961. } else if (cputype == MachO::CPU_TYPE_X86_64) {
  8962. while (begin < end) {
  8963. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  8964. memcpy((char *)&flavor, begin, sizeof(uint32_t));
  8965. begin += sizeof(uint32_t);
  8966. } else {
  8967. flavor = 0;
  8968. begin = end;
  8969. }
  8970. if (isLittleEndian != sys::IsLittleEndianHost)
  8971. sys::swapByteOrder(flavor);
  8972. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  8973. memcpy((char *)&count, begin, sizeof(uint32_t));
  8974. begin += sizeof(uint32_t);
  8975. } else {
  8976. count = 0;
  8977. begin = end;
  8978. }
  8979. if (isLittleEndian != sys::IsLittleEndianHost)
  8980. sys::swapByteOrder(count);
  8981. if (flavor == MachO::x86_THREAD_STATE64) {
  8982. outs() << " flavor x86_THREAD_STATE64\n";
  8983. if (count == MachO::x86_THREAD_STATE64_COUNT)
  8984. outs() << " count x86_THREAD_STATE64_COUNT\n";
  8985. else
  8986. outs() << " count " << count
  8987. << " (not x86_THREAD_STATE64_COUNT)\n";
  8988. MachO::x86_thread_state64_t cpu64;
  8989. left = end - begin;
  8990. if (left >= sizeof(MachO::x86_thread_state64_t)) {
  8991. memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
  8992. begin += sizeof(MachO::x86_thread_state64_t);
  8993. } else {
  8994. memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
  8995. memcpy(&cpu64, begin, left);
  8996. begin += left;
  8997. }
  8998. if (isLittleEndian != sys::IsLittleEndianHost)
  8999. swapStruct(cpu64);
  9000. Print_x86_thread_state64_t(cpu64);
  9001. } else if (flavor == MachO::x86_THREAD_STATE) {
  9002. outs() << " flavor x86_THREAD_STATE\n";
  9003. if (count == MachO::x86_THREAD_STATE_COUNT)
  9004. outs() << " count x86_THREAD_STATE_COUNT\n";
  9005. else
  9006. outs() << " count " << count
  9007. << " (not x86_THREAD_STATE_COUNT)\n";
  9008. struct MachO::x86_thread_state_t ts;
  9009. left = end - begin;
  9010. if (left >= sizeof(MachO::x86_thread_state_t)) {
  9011. memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
  9012. begin += sizeof(MachO::x86_thread_state_t);
  9013. } else {
  9014. memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
  9015. memcpy(&ts, begin, left);
  9016. begin += left;
  9017. }
  9018. if (isLittleEndian != sys::IsLittleEndianHost)
  9019. swapStruct(ts);
  9020. if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
  9021. outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
  9022. if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
  9023. outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
  9024. else
  9025. outs() << "tsh.count " << ts.tsh.count
  9026. << " (not x86_THREAD_STATE64_COUNT\n";
  9027. Print_x86_thread_state64_t(ts.uts.ts64);
  9028. } else {
  9029. outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
  9030. << ts.tsh.count << "\n";
  9031. }
  9032. } else if (flavor == MachO::x86_FLOAT_STATE) {
  9033. outs() << " flavor x86_FLOAT_STATE\n";
  9034. if (count == MachO::x86_FLOAT_STATE_COUNT)
  9035. outs() << " count x86_FLOAT_STATE_COUNT\n";
  9036. else
  9037. outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
  9038. struct MachO::x86_float_state_t fs;
  9039. left = end - begin;
  9040. if (left >= sizeof(MachO::x86_float_state_t)) {
  9041. memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
  9042. begin += sizeof(MachO::x86_float_state_t);
  9043. } else {
  9044. memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
  9045. memcpy(&fs, begin, left);
  9046. begin += left;
  9047. }
  9048. if (isLittleEndian != sys::IsLittleEndianHost)
  9049. swapStruct(fs);
  9050. if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
  9051. outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
  9052. if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
  9053. outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
  9054. else
  9055. outs() << "fsh.count " << fs.fsh.count
  9056. << " (not x86_FLOAT_STATE64_COUNT\n";
  9057. Print_x86_float_state_t(fs.ufs.fs64);
  9058. } else {
  9059. outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
  9060. << fs.fsh.count << "\n";
  9061. }
  9062. } else if (flavor == MachO::x86_EXCEPTION_STATE) {
  9063. outs() << " flavor x86_EXCEPTION_STATE\n";
  9064. if (count == MachO::x86_EXCEPTION_STATE_COUNT)
  9065. outs() << " count x86_EXCEPTION_STATE_COUNT\n";
  9066. else
  9067. outs() << " count " << count
  9068. << " (not x86_EXCEPTION_STATE_COUNT)\n";
  9069. struct MachO::x86_exception_state_t es;
  9070. left = end - begin;
  9071. if (left >= sizeof(MachO::x86_exception_state_t)) {
  9072. memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
  9073. begin += sizeof(MachO::x86_exception_state_t);
  9074. } else {
  9075. memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
  9076. memcpy(&es, begin, left);
  9077. begin += left;
  9078. }
  9079. if (isLittleEndian != sys::IsLittleEndianHost)
  9080. swapStruct(es);
  9081. if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
  9082. outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
  9083. if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
  9084. outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
  9085. else
  9086. outs() << "\t esh.count " << es.esh.count
  9087. << " (not x86_EXCEPTION_STATE64_COUNT\n";
  9088. Print_x86_exception_state_t(es.ues.es64);
  9089. } else {
  9090. outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
  9091. << es.esh.count << "\n";
  9092. }
  9093. } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
  9094. outs() << " flavor x86_EXCEPTION_STATE64\n";
  9095. if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
  9096. outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
  9097. else
  9098. outs() << " count " << count
  9099. << " (not x86_EXCEPTION_STATE64_COUNT)\n";
  9100. struct MachO::x86_exception_state64_t es64;
  9101. left = end - begin;
  9102. if (left >= sizeof(MachO::x86_exception_state64_t)) {
  9103. memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
  9104. begin += sizeof(MachO::x86_exception_state64_t);
  9105. } else {
  9106. memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
  9107. memcpy(&es64, begin, left);
  9108. begin += left;
  9109. }
  9110. if (isLittleEndian != sys::IsLittleEndianHost)
  9111. swapStruct(es64);
  9112. Print_x86_exception_state_t(es64);
  9113. } else {
  9114. outs() << " flavor " << flavor << " (unknown)\n";
  9115. outs() << " count " << count << "\n";
  9116. outs() << " state (unknown)\n";
  9117. begin += count * sizeof(uint32_t);
  9118. }
  9119. }
  9120. } else if (cputype == MachO::CPU_TYPE_ARM) {
  9121. while (begin < end) {
  9122. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9123. memcpy((char *)&flavor, begin, sizeof(uint32_t));
  9124. begin += sizeof(uint32_t);
  9125. } else {
  9126. flavor = 0;
  9127. begin = end;
  9128. }
  9129. if (isLittleEndian != sys::IsLittleEndianHost)
  9130. sys::swapByteOrder(flavor);
  9131. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9132. memcpy((char *)&count, begin, sizeof(uint32_t));
  9133. begin += sizeof(uint32_t);
  9134. } else {
  9135. count = 0;
  9136. begin = end;
  9137. }
  9138. if (isLittleEndian != sys::IsLittleEndianHost)
  9139. sys::swapByteOrder(count);
  9140. if (flavor == MachO::ARM_THREAD_STATE) {
  9141. outs() << " flavor ARM_THREAD_STATE\n";
  9142. if (count == MachO::ARM_THREAD_STATE_COUNT)
  9143. outs() << " count ARM_THREAD_STATE_COUNT\n";
  9144. else
  9145. outs() << " count " << count
  9146. << " (not ARM_THREAD_STATE_COUNT)\n";
  9147. MachO::arm_thread_state32_t cpu32;
  9148. left = end - begin;
  9149. if (left >= sizeof(MachO::arm_thread_state32_t)) {
  9150. memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
  9151. begin += sizeof(MachO::arm_thread_state32_t);
  9152. } else {
  9153. memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
  9154. memcpy(&cpu32, begin, left);
  9155. begin += left;
  9156. }
  9157. if (isLittleEndian != sys::IsLittleEndianHost)
  9158. swapStruct(cpu32);
  9159. Print_arm_thread_state32_t(cpu32);
  9160. } else {
  9161. outs() << " flavor " << flavor << " (unknown)\n";
  9162. outs() << " count " << count << "\n";
  9163. outs() << " state (unknown)\n";
  9164. begin += count * sizeof(uint32_t);
  9165. }
  9166. }
  9167. } else if (cputype == MachO::CPU_TYPE_ARM64 ||
  9168. cputype == MachO::CPU_TYPE_ARM64_32) {
  9169. while (begin < end) {
  9170. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9171. memcpy((char *)&flavor, begin, sizeof(uint32_t));
  9172. begin += sizeof(uint32_t);
  9173. } else {
  9174. flavor = 0;
  9175. begin = end;
  9176. }
  9177. if (isLittleEndian != sys::IsLittleEndianHost)
  9178. sys::swapByteOrder(flavor);
  9179. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9180. memcpy((char *)&count, begin, sizeof(uint32_t));
  9181. begin += sizeof(uint32_t);
  9182. } else {
  9183. count = 0;
  9184. begin = end;
  9185. }
  9186. if (isLittleEndian != sys::IsLittleEndianHost)
  9187. sys::swapByteOrder(count);
  9188. if (flavor == MachO::ARM_THREAD_STATE64) {
  9189. outs() << " flavor ARM_THREAD_STATE64\n";
  9190. if (count == MachO::ARM_THREAD_STATE64_COUNT)
  9191. outs() << " count ARM_THREAD_STATE64_COUNT\n";
  9192. else
  9193. outs() << " count " << count
  9194. << " (not ARM_THREAD_STATE64_COUNT)\n";
  9195. MachO::arm_thread_state64_t cpu64;
  9196. left = end - begin;
  9197. if (left >= sizeof(MachO::arm_thread_state64_t)) {
  9198. memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
  9199. begin += sizeof(MachO::arm_thread_state64_t);
  9200. } else {
  9201. memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
  9202. memcpy(&cpu64, begin, left);
  9203. begin += left;
  9204. }
  9205. if (isLittleEndian != sys::IsLittleEndianHost)
  9206. swapStruct(cpu64);
  9207. Print_arm_thread_state64_t(cpu64);
  9208. } else {
  9209. outs() << " flavor " << flavor << " (unknown)\n";
  9210. outs() << " count " << count << "\n";
  9211. outs() << " state (unknown)\n";
  9212. begin += count * sizeof(uint32_t);
  9213. }
  9214. }
  9215. } else {
  9216. while (begin < end) {
  9217. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9218. memcpy((char *)&flavor, begin, sizeof(uint32_t));
  9219. begin += sizeof(uint32_t);
  9220. } else {
  9221. flavor = 0;
  9222. begin = end;
  9223. }
  9224. if (isLittleEndian != sys::IsLittleEndianHost)
  9225. sys::swapByteOrder(flavor);
  9226. if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
  9227. memcpy((char *)&count, begin, sizeof(uint32_t));
  9228. begin += sizeof(uint32_t);
  9229. } else {
  9230. count = 0;
  9231. begin = end;
  9232. }
  9233. if (isLittleEndian != sys::IsLittleEndianHost)
  9234. sys::swapByteOrder(count);
  9235. outs() << " flavor " << flavor << "\n";
  9236. outs() << " count " << count << "\n";
  9237. outs() << " state (Unknown cputype/cpusubtype)\n";
  9238. begin += count * sizeof(uint32_t);
  9239. }
  9240. }
  9241. }
  9242. static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
  9243. if (dl.cmd == MachO::LC_ID_DYLIB)
  9244. outs() << " cmd LC_ID_DYLIB\n";
  9245. else if (dl.cmd == MachO::LC_LOAD_DYLIB)
  9246. outs() << " cmd LC_LOAD_DYLIB\n";
  9247. else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
  9248. outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
  9249. else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
  9250. outs() << " cmd LC_REEXPORT_DYLIB\n";
  9251. else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
  9252. outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
  9253. else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
  9254. outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
  9255. else
  9256. outs() << " cmd " << dl.cmd << " (unknown)\n";
  9257. outs() << " cmdsize " << dl.cmdsize;
  9258. if (dl.cmdsize < sizeof(struct MachO::dylib_command))
  9259. outs() << " Incorrect size\n";
  9260. else
  9261. outs() << "\n";
  9262. if (dl.dylib.name < dl.cmdsize) {
  9263. const char *P = (const char *)(Ptr) + dl.dylib.name;
  9264. outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
  9265. } else {
  9266. outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
  9267. }
  9268. outs() << " time stamp " << dl.dylib.timestamp << " ";
  9269. time_t t = dl.dylib.timestamp;
  9270. outs() << ctime(&t);
  9271. outs() << " current version ";
  9272. if (dl.dylib.current_version == 0xffffffff)
  9273. outs() << "n/a\n";
  9274. else
  9275. outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
  9276. << ((dl.dylib.current_version >> 8) & 0xff) << "."
  9277. << (dl.dylib.current_version & 0xff) << "\n";
  9278. outs() << "compatibility version ";
  9279. if (dl.dylib.compatibility_version == 0xffffffff)
  9280. outs() << "n/a\n";
  9281. else
  9282. outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
  9283. << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
  9284. << (dl.dylib.compatibility_version & 0xff) << "\n";
  9285. }
  9286. static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
  9287. uint32_t object_size) {
  9288. if (ld.cmd == MachO::LC_CODE_SIGNATURE)
  9289. outs() << " cmd LC_CODE_SIGNATURE\n";
  9290. else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
  9291. outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
  9292. else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
  9293. outs() << " cmd LC_FUNCTION_STARTS\n";
  9294. else if (ld.cmd == MachO::LC_DATA_IN_CODE)
  9295. outs() << " cmd LC_DATA_IN_CODE\n";
  9296. else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
  9297. outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
  9298. else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
  9299. outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
  9300. else
  9301. outs() << " cmd " << ld.cmd << " (?)\n";
  9302. outs() << " cmdsize " << ld.cmdsize;
  9303. if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
  9304. outs() << " Incorrect size\n";
  9305. else
  9306. outs() << "\n";
  9307. outs() << " dataoff " << ld.dataoff;
  9308. if (ld.dataoff > object_size)
  9309. outs() << " (past end of file)\n";
  9310. else
  9311. outs() << "\n";
  9312. outs() << " datasize " << ld.datasize;
  9313. uint64_t big_size = ld.dataoff;
  9314. big_size += ld.datasize;
  9315. if (big_size > object_size)
  9316. outs() << " (past end of file)\n";
  9317. else
  9318. outs() << "\n";
  9319. }
  9320. static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
  9321. uint32_t cputype, bool verbose) {
  9322. StringRef Buf = Obj->getData();
  9323. unsigned Index = 0;
  9324. for (const auto &Command : Obj->load_commands()) {
  9325. outs() << "Load command " << Index++ << "\n";
  9326. if (Command.C.cmd == MachO::LC_SEGMENT) {
  9327. MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
  9328. const char *sg_segname = SLC.segname;
  9329. PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
  9330. SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
  9331. SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
  9332. verbose);
  9333. for (unsigned j = 0; j < SLC.nsects; j++) {
  9334. MachO::section S = Obj->getSection(Command, j);
  9335. PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
  9336. S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
  9337. SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
  9338. }
  9339. } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
  9340. MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
  9341. const char *sg_segname = SLC_64.segname;
  9342. PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
  9343. SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
  9344. SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
  9345. SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
  9346. for (unsigned j = 0; j < SLC_64.nsects; j++) {
  9347. MachO::section_64 S_64 = Obj->getSection64(Command, j);
  9348. PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
  9349. S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
  9350. S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
  9351. sg_segname, filetype, Buf.size(), verbose);
  9352. }
  9353. } else if (Command.C.cmd == MachO::LC_SYMTAB) {
  9354. MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
  9355. PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
  9356. } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
  9357. MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
  9358. MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
  9359. PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
  9360. Obj->is64Bit());
  9361. } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
  9362. Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
  9363. MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
  9364. PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
  9365. } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
  9366. Command.C.cmd == MachO::LC_ID_DYLINKER ||
  9367. Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
  9368. MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
  9369. PrintDyldLoadCommand(Dyld, Command.Ptr);
  9370. } else if (Command.C.cmd == MachO::LC_UUID) {
  9371. MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
  9372. PrintUuidLoadCommand(Uuid);
  9373. } else if (Command.C.cmd == MachO::LC_RPATH) {
  9374. MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
  9375. PrintRpathLoadCommand(Rpath, Command.Ptr);
  9376. } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
  9377. Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
  9378. Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
  9379. Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
  9380. MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
  9381. PrintVersionMinLoadCommand(Vd);
  9382. } else if (Command.C.cmd == MachO::LC_NOTE) {
  9383. MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
  9384. PrintNoteLoadCommand(Nt);
  9385. } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
  9386. MachO::build_version_command Bv =
  9387. Obj->getBuildVersionLoadCommand(Command);
  9388. PrintBuildVersionLoadCommand(Obj, Bv);
  9389. } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
  9390. MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
  9391. PrintSourceVersionCommand(Sd);
  9392. } else if (Command.C.cmd == MachO::LC_MAIN) {
  9393. MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
  9394. PrintEntryPointCommand(Ep);
  9395. } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
  9396. MachO::encryption_info_command Ei =
  9397. Obj->getEncryptionInfoCommand(Command);
  9398. PrintEncryptionInfoCommand(Ei, Buf.size());
  9399. } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
  9400. MachO::encryption_info_command_64 Ei =
  9401. Obj->getEncryptionInfoCommand64(Command);
  9402. PrintEncryptionInfoCommand64(Ei, Buf.size());
  9403. } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
  9404. MachO::linker_option_command Lo =
  9405. Obj->getLinkerOptionLoadCommand(Command);
  9406. PrintLinkerOptionCommand(Lo, Command.Ptr);
  9407. } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
  9408. MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
  9409. PrintSubFrameworkCommand(Sf, Command.Ptr);
  9410. } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
  9411. MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
  9412. PrintSubUmbrellaCommand(Sf, Command.Ptr);
  9413. } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
  9414. MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
  9415. PrintSubLibraryCommand(Sl, Command.Ptr);
  9416. } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
  9417. MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
  9418. PrintSubClientCommand(Sc, Command.Ptr);
  9419. } else if (Command.C.cmd == MachO::LC_ROUTINES) {
  9420. MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
  9421. PrintRoutinesCommand(Rc);
  9422. } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
  9423. MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
  9424. PrintRoutinesCommand64(Rc);
  9425. } else if (Command.C.cmd == MachO::LC_THREAD ||
  9426. Command.C.cmd == MachO::LC_UNIXTHREAD) {
  9427. MachO::thread_command Tc = Obj->getThreadCommand(Command);
  9428. PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
  9429. } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
  9430. Command.C.cmd == MachO::LC_ID_DYLIB ||
  9431. Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
  9432. Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
  9433. Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
  9434. Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
  9435. MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
  9436. PrintDylibCommand(Dl, Command.Ptr);
  9437. } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
  9438. Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
  9439. Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
  9440. Command.C.cmd == MachO::LC_DATA_IN_CODE ||
  9441. Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
  9442. Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
  9443. MachO::linkedit_data_command Ld =
  9444. Obj->getLinkeditDataLoadCommand(Command);
  9445. PrintLinkEditDataCommand(Ld, Buf.size());
  9446. } else {
  9447. outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
  9448. << ")\n";
  9449. outs() << " cmdsize " << Command.C.cmdsize << "\n";
  9450. // TODO: get and print the raw bytes of the load command.
  9451. }
  9452. // TODO: print all the other kinds of load commands.
  9453. }
  9454. }
  9455. static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
  9456. if (Obj->is64Bit()) {
  9457. MachO::mach_header_64 H_64;
  9458. H_64 = Obj->getHeader64();
  9459. PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
  9460. H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
  9461. } else {
  9462. MachO::mach_header H;
  9463. H = Obj->getHeader();
  9464. PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
  9465. H.sizeofcmds, H.flags, verbose);
  9466. }
  9467. }
  9468. void printMachOFileHeader(const object::ObjectFile *Obj) {
  9469. const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
  9470. PrintMachHeader(file, !NonVerbose);
  9471. }
  9472. void printMachOLoadCommands(const object::ObjectFile *Obj) {
  9473. const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
  9474. uint32_t filetype = 0;
  9475. uint32_t cputype = 0;
  9476. if (file->is64Bit()) {
  9477. MachO::mach_header_64 H_64;
  9478. H_64 = file->getHeader64();
  9479. filetype = H_64.filetype;
  9480. cputype = H_64.cputype;
  9481. } else {
  9482. MachO::mach_header H;
  9483. H = file->getHeader();
  9484. filetype = H.filetype;
  9485. cputype = H.cputype;
  9486. }
  9487. PrintLoadCommands(file, filetype, cputype, !NonVerbose);
  9488. }
  9489. //===----------------------------------------------------------------------===//
  9490. // export trie dumping
  9491. //===----------------------------------------------------------------------===//
  9492. void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
  9493. uint64_t BaseSegmentAddress = 0;
  9494. for (const auto &Command : Obj->load_commands()) {
  9495. if (Command.C.cmd == MachO::LC_SEGMENT) {
  9496. MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
  9497. if (Seg.fileoff == 0 && Seg.filesize != 0) {
  9498. BaseSegmentAddress = Seg.vmaddr;
  9499. break;
  9500. }
  9501. } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
  9502. MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
  9503. if (Seg.fileoff == 0 && Seg.filesize != 0) {
  9504. BaseSegmentAddress = Seg.vmaddr;
  9505. break;
  9506. }
  9507. }
  9508. }
  9509. Error Err = Error::success();
  9510. for (const object::ExportEntry &Entry : Obj->exports(Err)) {
  9511. uint64_t Flags = Entry.flags();
  9512. bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
  9513. bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
  9514. bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
  9515. MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
  9516. bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
  9517. MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
  9518. bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
  9519. if (ReExport)
  9520. outs() << "[re-export] ";
  9521. else
  9522. outs() << format("0x%08llX ",
  9523. Entry.address() + BaseSegmentAddress);
  9524. outs() << Entry.name();
  9525. if (WeakDef || ThreadLocal || Resolver || Abs) {
  9526. bool NeedsComma = false;
  9527. outs() << " [";
  9528. if (WeakDef) {
  9529. outs() << "weak_def";
  9530. NeedsComma = true;
  9531. }
  9532. if (ThreadLocal) {
  9533. if (NeedsComma)
  9534. outs() << ", ";
  9535. outs() << "per-thread";
  9536. NeedsComma = true;
  9537. }
  9538. if (Abs) {
  9539. if (NeedsComma)
  9540. outs() << ", ";
  9541. outs() << "absolute";
  9542. NeedsComma = true;
  9543. }
  9544. if (Resolver) {
  9545. if (NeedsComma)
  9546. outs() << ", ";
  9547. outs() << format("resolver=0x%08llX", Entry.other());
  9548. NeedsComma = true;
  9549. }
  9550. outs() << "]";
  9551. }
  9552. if (ReExport) {
  9553. StringRef DylibName = "unknown";
  9554. int Ordinal = Entry.other() - 1;
  9555. Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
  9556. if (Entry.otherName().empty())
  9557. outs() << " (from " << DylibName << ")";
  9558. else
  9559. outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
  9560. }
  9561. outs() << "\n";
  9562. }
  9563. if (Err)
  9564. reportError(std::move(Err), Obj->getFileName());
  9565. }
  9566. //===----------------------------------------------------------------------===//
  9567. // rebase table dumping
  9568. //===----------------------------------------------------------------------===//
  9569. void printMachORebaseTable(object::MachOObjectFile *Obj) {
  9570. outs() << "segment section address type\n";
  9571. Error Err = Error::success();
  9572. for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
  9573. StringRef SegmentName = Entry.segmentName();
  9574. StringRef SectionName = Entry.sectionName();
  9575. uint64_t Address = Entry.address();
  9576. // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
  9577. outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
  9578. SegmentName.str().c_str(), SectionName.str().c_str(),
  9579. Address, Entry.typeName().str().c_str());
  9580. }
  9581. if (Err)
  9582. reportError(std::move(Err), Obj->getFileName());
  9583. }
  9584. static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
  9585. StringRef DylibName;
  9586. switch (Ordinal) {
  9587. case MachO::BIND_SPECIAL_DYLIB_SELF:
  9588. return "this-image";
  9589. case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
  9590. return "main-executable";
  9591. case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
  9592. return "flat-namespace";
  9593. default:
  9594. if (Ordinal > 0) {
  9595. std::error_code EC =
  9596. Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
  9597. if (EC)
  9598. return "<<bad library ordinal>>";
  9599. return DylibName;
  9600. }
  9601. }
  9602. return "<<unknown special ordinal>>";
  9603. }
  9604. //===----------------------------------------------------------------------===//
  9605. // bind table dumping
  9606. //===----------------------------------------------------------------------===//
  9607. void printMachOBindTable(object::MachOObjectFile *Obj) {
  9608. // Build table of sections so names can used in final output.
  9609. outs() << "segment section address type "
  9610. "addend dylib symbol\n";
  9611. Error Err = Error::success();
  9612. for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
  9613. StringRef SegmentName = Entry.segmentName();
  9614. StringRef SectionName = Entry.sectionName();
  9615. uint64_t Address = Entry.address();
  9616. // Table lines look like:
  9617. // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
  9618. StringRef Attr;
  9619. if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
  9620. Attr = " (weak_import)";
  9621. outs() << left_justify(SegmentName, 8) << " "
  9622. << left_justify(SectionName, 18) << " "
  9623. << format_hex(Address, 10, true) << " "
  9624. << left_justify(Entry.typeName(), 8) << " "
  9625. << format_decimal(Entry.addend(), 8) << " "
  9626. << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
  9627. << Entry.symbolName() << Attr << "\n";
  9628. }
  9629. if (Err)
  9630. reportError(std::move(Err), Obj->getFileName());
  9631. }
  9632. //===----------------------------------------------------------------------===//
  9633. // lazy bind table dumping
  9634. //===----------------------------------------------------------------------===//
  9635. void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
  9636. outs() << "segment section address "
  9637. "dylib symbol\n";
  9638. Error Err = Error::success();
  9639. for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
  9640. StringRef SegmentName = Entry.segmentName();
  9641. StringRef SectionName = Entry.sectionName();
  9642. uint64_t Address = Entry.address();
  9643. // Table lines look like:
  9644. // __DATA __got 0x00012010 libSystem ___stack_chk_guard
  9645. outs() << left_justify(SegmentName, 8) << " "
  9646. << left_justify(SectionName, 18) << " "
  9647. << format_hex(Address, 10, true) << " "
  9648. << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
  9649. << Entry.symbolName() << "\n";
  9650. }
  9651. if (Err)
  9652. reportError(std::move(Err), Obj->getFileName());
  9653. }
  9654. //===----------------------------------------------------------------------===//
  9655. // weak bind table dumping
  9656. //===----------------------------------------------------------------------===//
  9657. void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
  9658. outs() << "segment section address "
  9659. "type addend symbol\n";
  9660. Error Err = Error::success();
  9661. for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
  9662. // Strong symbols don't have a location to update.
  9663. if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
  9664. outs() << " strong "
  9665. << Entry.symbolName() << "\n";
  9666. continue;
  9667. }
  9668. StringRef SegmentName = Entry.segmentName();
  9669. StringRef SectionName = Entry.sectionName();
  9670. uint64_t Address = Entry.address();
  9671. // Table lines look like:
  9672. // __DATA __data 0x00001000 pointer 0 _foo
  9673. outs() << left_justify(SegmentName, 8) << " "
  9674. << left_justify(SectionName, 18) << " "
  9675. << format_hex(Address, 10, true) << " "
  9676. << left_justify(Entry.typeName(), 8) << " "
  9677. << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
  9678. << "\n";
  9679. }
  9680. if (Err)
  9681. reportError(std::move(Err), Obj->getFileName());
  9682. }
  9683. // get_dyld_bind_info_symbolname() is used for disassembly and passed an
  9684. // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
  9685. // information for that address. If the address is found its binding symbol
  9686. // name is returned. If not nullptr is returned.
  9687. static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
  9688. struct DisassembleInfo *info) {
  9689. if (info->bindtable == nullptr) {
  9690. info->bindtable = std::make_unique<SymbolAddressMap>();
  9691. Error Err = Error::success();
  9692. for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
  9693. uint64_t Address = Entry.address();
  9694. StringRef name = Entry.symbolName();
  9695. if (!name.empty())
  9696. (*info->bindtable)[Address] = name;
  9697. }
  9698. if (Err)
  9699. reportError(std::move(Err), info->O->getFileName());
  9700. }
  9701. auto name = info->bindtable->lookup(ReferenceValue);
  9702. return !name.empty() ? name.data() : nullptr;
  9703. }
  9704. void printLazyBindTable(ObjectFile *o) {
  9705. outs() << "Lazy bind table:\n";
  9706. if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  9707. printMachOLazyBindTable(MachO);
  9708. else
  9709. WithColor::error()
  9710. << "This operation is only currently supported "
  9711. "for Mach-O executable files.\n";
  9712. }
  9713. void printWeakBindTable(ObjectFile *o) {
  9714. outs() << "Weak bind table:\n";
  9715. if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  9716. printMachOWeakBindTable(MachO);
  9717. else
  9718. WithColor::error()
  9719. << "This operation is only currently supported "
  9720. "for Mach-O executable files.\n";
  9721. }
  9722. void printExportsTrie(const ObjectFile *o) {
  9723. outs() << "Exports trie:\n";
  9724. if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  9725. printMachOExportsTrie(MachO);
  9726. else
  9727. WithColor::error()
  9728. << "This operation is only currently supported "
  9729. "for Mach-O executable files.\n";
  9730. }
  9731. void printRebaseTable(ObjectFile *o) {
  9732. outs() << "Rebase table:\n";
  9733. if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  9734. printMachORebaseTable(MachO);
  9735. else
  9736. WithColor::error()
  9737. << "This operation is only currently supported "
  9738. "for Mach-O executable files.\n";
  9739. }
  9740. void printBindTable(ObjectFile *o) {
  9741. outs() << "Bind table:\n";
  9742. if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  9743. printMachOBindTable(MachO);
  9744. else
  9745. WithColor::error()
  9746. << "This operation is only currently supported "
  9747. "for Mach-O executable files.\n";
  9748. }
  9749. } // namespace llvm