ELFDumper.cpp 264 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362
  1. //===- ELFDumper.cpp - ELF-specific dumper --------------------------------===//
  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. /// \file
  10. /// This file implements the ELF-specific dumper for llvm-readobj.
  11. ///
  12. //===----------------------------------------------------------------------===//
  13. #include "ARMEHABIPrinter.h"
  14. #include "DwarfCFIEHPrinter.h"
  15. #include "ObjDumper.h"
  16. #include "StackMapPrinter.h"
  17. #include "llvm-readobj.h"
  18. #include "llvm/ADT/ArrayRef.h"
  19. #include "llvm/ADT/BitVector.h"
  20. #include "llvm/ADT/DenseMap.h"
  21. #include "llvm/ADT/DenseSet.h"
  22. #include "llvm/ADT/MapVector.h"
  23. #include "llvm/ADT/Optional.h"
  24. #include "llvm/ADT/PointerIntPair.h"
  25. #include "llvm/ADT/STLExtras.h"
  26. #include "llvm/ADT/SmallString.h"
  27. #include "llvm/ADT/SmallVector.h"
  28. #include "llvm/ADT/StringExtras.h"
  29. #include "llvm/ADT/StringRef.h"
  30. #include "llvm/ADT/Twine.h"
  31. #include "llvm/BinaryFormat/AMDGPUMetadataVerifier.h"
  32. #include "llvm/BinaryFormat/ELF.h"
  33. #include "llvm/BinaryFormat/MsgPackDocument.h"
  34. #include "llvm/Demangle/Demangle.h"
  35. #include "llvm/Object/Archive.h"
  36. #include "llvm/Object/ELF.h"
  37. #include "llvm/Object/ELFObjectFile.h"
  38. #include "llvm/Object/ELFTypes.h"
  39. #include "llvm/Object/Error.h"
  40. #include "llvm/Object/ObjectFile.h"
  41. #include "llvm/Object/RelocationResolver.h"
  42. #include "llvm/Object/StackMapParser.h"
  43. #include "llvm/Support/AMDGPUMetadata.h"
  44. #include "llvm/Support/ARMAttributeParser.h"
  45. #include "llvm/Support/ARMBuildAttributes.h"
  46. #include "llvm/Support/Casting.h"
  47. #include "llvm/Support/Compiler.h"
  48. #include "llvm/Support/Endian.h"
  49. #include "llvm/Support/ErrorHandling.h"
  50. #include "llvm/Support/Format.h"
  51. #include "llvm/Support/FormatVariadic.h"
  52. #include "llvm/Support/FormattedStream.h"
  53. #include "llvm/Support/LEB128.h"
  54. #include "llvm/Support/MSP430AttributeParser.h"
  55. #include "llvm/Support/MSP430Attributes.h"
  56. #include "llvm/Support/MathExtras.h"
  57. #include "llvm/Support/MipsABIFlags.h"
  58. #include "llvm/Support/RISCVAttributeParser.h"
  59. #include "llvm/Support/RISCVAttributes.h"
  60. #include "llvm/Support/ScopedPrinter.h"
  61. #include "llvm/Support/raw_ostream.h"
  62. #include <algorithm>
  63. #include <cinttypes>
  64. #include <cstddef>
  65. #include <cstdint>
  66. #include <cstdlib>
  67. #include <iterator>
  68. #include <memory>
  69. #include <string>
  70. #include <system_error>
  71. #include <vector>
  72. using namespace llvm;
  73. using namespace llvm::object;
  74. using namespace ELF;
  75. #define LLVM_READOBJ_ENUM_CASE(ns, enum) \
  76. case ns::enum: \
  77. return #enum;
  78. #define ENUM_ENT(enum, altName) \
  79. { #enum, altName, ELF::enum }
  80. #define ENUM_ENT_1(enum) \
  81. { #enum, #enum, ELF::enum }
  82. namespace {
  83. template <class ELFT> struct RelSymbol {
  84. RelSymbol(const typename ELFT::Sym *S, StringRef N)
  85. : Sym(S), Name(N.str()) {}
  86. const typename ELFT::Sym *Sym;
  87. std::string Name;
  88. };
  89. /// Represents a contiguous uniform range in the file. We cannot just create a
  90. /// range directly because when creating one of these from the .dynamic table
  91. /// the size, entity size and virtual address are different entries in arbitrary
  92. /// order (DT_REL, DT_RELSZ, DT_RELENT for example).
  93. struct DynRegionInfo {
  94. DynRegionInfo(const Binary &Owner, const ObjDumper &D)
  95. : Obj(&Owner), Dumper(&D) {}
  96. DynRegionInfo(const Binary &Owner, const ObjDumper &D, const uint8_t *A,
  97. uint64_t S, uint64_t ES)
  98. : Addr(A), Size(S), EntSize(ES), Obj(&Owner), Dumper(&D) {}
  99. /// Address in current address space.
  100. const uint8_t *Addr = nullptr;
  101. /// Size in bytes of the region.
  102. uint64_t Size = 0;
  103. /// Size of each entity in the region.
  104. uint64_t EntSize = 0;
  105. /// Owner object. Used for error reporting.
  106. const Binary *Obj;
  107. /// Dumper used for error reporting.
  108. const ObjDumper *Dumper;
  109. /// Error prefix. Used for error reporting to provide more information.
  110. std::string Context;
  111. /// Region size name. Used for error reporting.
  112. StringRef SizePrintName = "size";
  113. /// Entry size name. Used for error reporting. If this field is empty, errors
  114. /// will not mention the entry size.
  115. StringRef EntSizePrintName = "entry size";
  116. template <typename Type> ArrayRef<Type> getAsArrayRef() const {
  117. const Type *Start = reinterpret_cast<const Type *>(Addr);
  118. if (!Start)
  119. return {Start, Start};
  120. const uint64_t Offset =
  121. Addr - (const uint8_t *)Obj->getMemoryBufferRef().getBufferStart();
  122. const uint64_t ObjSize = Obj->getMemoryBufferRef().getBufferSize();
  123. if (Size > ObjSize - Offset) {
  124. Dumper->reportUniqueWarning(
  125. "unable to read data at 0x" + Twine::utohexstr(Offset) +
  126. " of size 0x" + Twine::utohexstr(Size) + " (" + SizePrintName +
  127. "): it goes past the end of the file of size 0x" +
  128. Twine::utohexstr(ObjSize));
  129. return {Start, Start};
  130. }
  131. if (EntSize == sizeof(Type) && (Size % EntSize == 0))
  132. return {Start, Start + (Size / EntSize)};
  133. std::string Msg;
  134. if (!Context.empty())
  135. Msg += Context + " has ";
  136. Msg += ("invalid " + SizePrintName + " (0x" + Twine::utohexstr(Size) + ")")
  137. .str();
  138. if (!EntSizePrintName.empty())
  139. Msg +=
  140. (" or " + EntSizePrintName + " (0x" + Twine::utohexstr(EntSize) + ")")
  141. .str();
  142. Dumper->reportUniqueWarning(Msg);
  143. return {Start, Start};
  144. }
  145. };
  146. struct GroupMember {
  147. StringRef Name;
  148. uint64_t Index;
  149. };
  150. struct GroupSection {
  151. StringRef Name;
  152. std::string Signature;
  153. uint64_t ShName;
  154. uint64_t Index;
  155. uint32_t Link;
  156. uint32_t Info;
  157. uint32_t Type;
  158. std::vector<GroupMember> Members;
  159. };
  160. namespace {
  161. struct NoteType {
  162. uint32_t ID;
  163. StringRef Name;
  164. };
  165. } // namespace
  166. template <class ELFT> class Relocation {
  167. public:
  168. Relocation(const typename ELFT::Rel &R, bool IsMips64EL)
  169. : Type(R.getType(IsMips64EL)), Symbol(R.getSymbol(IsMips64EL)),
  170. Offset(R.r_offset), Info(R.r_info) {}
  171. Relocation(const typename ELFT::Rela &R, bool IsMips64EL)
  172. : Relocation((const typename ELFT::Rel &)R, IsMips64EL) {
  173. Addend = R.r_addend;
  174. }
  175. uint32_t Type;
  176. uint32_t Symbol;
  177. typename ELFT::uint Offset;
  178. typename ELFT::uint Info;
  179. Optional<int64_t> Addend;
  180. };
  181. template <class ELFT> class MipsGOTParser;
  182. template <typename ELFT> class ELFDumper : public ObjDumper {
  183. LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
  184. public:
  185. ELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer);
  186. void printUnwindInfo() override;
  187. void printNeededLibraries() override;
  188. void printHashTable() override;
  189. void printGnuHashTable() override;
  190. void printLoadName() override;
  191. void printVersionInfo() override;
  192. void printArchSpecificInfo() override;
  193. void printStackMap() const override;
  194. const object::ELFObjectFile<ELFT> &getElfObject() const { return ObjF; };
  195. std::string describe(const Elf_Shdr &Sec) const;
  196. unsigned getHashTableEntSize() const {
  197. // EM_S390 and ELF::EM_ALPHA platforms use 8-bytes entries in SHT_HASH
  198. // sections. This violates the ELF specification.
  199. if (Obj.getHeader().e_machine == ELF::EM_S390 ||
  200. Obj.getHeader().e_machine == ELF::EM_ALPHA)
  201. return 8;
  202. return 4;
  203. }
  204. Elf_Dyn_Range dynamic_table() const {
  205. // A valid .dynamic section contains an array of entries terminated
  206. // with a DT_NULL entry. However, sometimes the section content may
  207. // continue past the DT_NULL entry, so to dump the section correctly,
  208. // we first find the end of the entries by iterating over them.
  209. Elf_Dyn_Range Table = DynamicTable.template getAsArrayRef<Elf_Dyn>();
  210. size_t Size = 0;
  211. while (Size < Table.size())
  212. if (Table[Size++].getTag() == DT_NULL)
  213. break;
  214. return Table.slice(0, Size);
  215. }
  216. Elf_Sym_Range dynamic_symbols() const {
  217. if (!DynSymRegion)
  218. return Elf_Sym_Range();
  219. return DynSymRegion->template getAsArrayRef<Elf_Sym>();
  220. }
  221. const Elf_Shdr *findSectionByName(StringRef Name) const;
  222. StringRef getDynamicStringTable() const { return DynamicStringTable; }
  223. protected:
  224. virtual void printVersionSymbolSection(const Elf_Shdr *Sec) = 0;
  225. virtual void printVersionDefinitionSection(const Elf_Shdr *Sec) = 0;
  226. virtual void printVersionDependencySection(const Elf_Shdr *Sec) = 0;
  227. void
  228. printDependentLibsHelper(function_ref<void(const Elf_Shdr &)> OnSectionStart,
  229. function_ref<void(StringRef, uint64_t)> OnLibEntry);
  230. virtual void printRelRelaReloc(const Relocation<ELFT> &R,
  231. const RelSymbol<ELFT> &RelSym) = 0;
  232. virtual void printRelrReloc(const Elf_Relr &R) = 0;
  233. virtual void printDynamicRelocHeader(unsigned Type, StringRef Name,
  234. const DynRegionInfo &Reg) {}
  235. void printReloc(const Relocation<ELFT> &R, unsigned RelIndex,
  236. const Elf_Shdr &Sec, const Elf_Shdr *SymTab);
  237. void printDynamicReloc(const Relocation<ELFT> &R);
  238. void printDynamicRelocationsHelper();
  239. void printRelocationsHelper(const Elf_Shdr &Sec);
  240. void forEachRelocationDo(
  241. const Elf_Shdr &Sec, bool RawRelr,
  242. llvm::function_ref<void(const Relocation<ELFT> &, unsigned,
  243. const Elf_Shdr &, const Elf_Shdr *)>
  244. RelRelaFn,
  245. llvm::function_ref<void(const Elf_Relr &)> RelrFn);
  246. virtual void printSymtabMessage(const Elf_Shdr *Symtab, size_t Offset,
  247. bool NonVisibilityBitsUsed) const {};
  248. virtual void printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
  249. DataRegion<Elf_Word> ShndxTable,
  250. Optional<StringRef> StrTable, bool IsDynamic,
  251. bool NonVisibilityBitsUsed) const = 0;
  252. virtual void printMipsABIFlags() = 0;
  253. virtual void printMipsGOT(const MipsGOTParser<ELFT> &Parser) = 0;
  254. virtual void printMipsPLT(const MipsGOTParser<ELFT> &Parser) = 0;
  255. Expected<ArrayRef<Elf_Versym>>
  256. getVersionTable(const Elf_Shdr &Sec, ArrayRef<Elf_Sym> *SymTab,
  257. StringRef *StrTab, const Elf_Shdr **SymTabSec) const;
  258. StringRef getPrintableSectionName(const Elf_Shdr &Sec) const;
  259. std::vector<GroupSection> getGroups();
  260. // Returns the function symbol index for the given address. Matches the
  261. // symbol's section with FunctionSec when specified.
  262. // Returns None if no function symbol can be found for the address or in case
  263. // it is not defined in the specified section.
  264. SmallVector<uint32_t>
  265. getSymbolIndexesForFunctionAddress(uint64_t SymValue,
  266. Optional<const Elf_Shdr *> FunctionSec);
  267. bool printFunctionStackSize(uint64_t SymValue,
  268. Optional<const Elf_Shdr *> FunctionSec,
  269. const Elf_Shdr &StackSizeSec, DataExtractor Data,
  270. uint64_t *Offset);
  271. void printStackSize(const Relocation<ELFT> &R, const Elf_Shdr &RelocSec,
  272. unsigned Ndx, const Elf_Shdr *SymTab,
  273. const Elf_Shdr *FunctionSec, const Elf_Shdr &StackSizeSec,
  274. const RelocationResolver &Resolver, DataExtractor Data);
  275. virtual void printStackSizeEntry(uint64_t Size,
  276. ArrayRef<std::string> FuncNames) = 0;
  277. void printRelocatableStackSizes(std::function<void()> PrintHeader);
  278. void printNonRelocatableStackSizes(std::function<void()> PrintHeader);
  279. /// Retrieves sections with corresponding relocation sections based on
  280. /// IsMatch.
  281. void getSectionAndRelocations(
  282. std::function<bool(const Elf_Shdr &)> IsMatch,
  283. llvm::MapVector<const Elf_Shdr *, const Elf_Shdr *> &SecToRelocMap);
  284. const object::ELFObjectFile<ELFT> &ObjF;
  285. const ELFFile<ELFT> &Obj;
  286. StringRef FileName;
  287. Expected<DynRegionInfo> createDRI(uint64_t Offset, uint64_t Size,
  288. uint64_t EntSize) {
  289. if (Offset + Size < Offset || Offset + Size > Obj.getBufSize())
  290. return createError("offset (0x" + Twine::utohexstr(Offset) +
  291. ") + size (0x" + Twine::utohexstr(Size) +
  292. ") is greater than the file size (0x" +
  293. Twine::utohexstr(Obj.getBufSize()) + ")");
  294. return DynRegionInfo(ObjF, *this, Obj.base() + Offset, Size, EntSize);
  295. }
  296. void printAttributes(unsigned, std::unique_ptr<ELFAttributeParser>,
  297. support::endianness);
  298. void printMipsReginfo();
  299. void printMipsOptions();
  300. std::pair<const Elf_Phdr *, const Elf_Shdr *> findDynamic();
  301. void loadDynamicTable();
  302. void parseDynamicTable();
  303. Expected<StringRef> getSymbolVersion(const Elf_Sym &Sym,
  304. bool &IsDefault) const;
  305. Expected<SmallVector<Optional<VersionEntry>, 0> *> getVersionMap() const;
  306. DynRegionInfo DynRelRegion;
  307. DynRegionInfo DynRelaRegion;
  308. DynRegionInfo DynRelrRegion;
  309. DynRegionInfo DynPLTRelRegion;
  310. Optional<DynRegionInfo> DynSymRegion;
  311. DynRegionInfo DynSymTabShndxRegion;
  312. DynRegionInfo DynamicTable;
  313. StringRef DynamicStringTable;
  314. const Elf_Hash *HashTable = nullptr;
  315. const Elf_GnuHash *GnuHashTable = nullptr;
  316. const Elf_Shdr *DotSymtabSec = nullptr;
  317. const Elf_Shdr *DotDynsymSec = nullptr;
  318. const Elf_Shdr *DotAddrsigSec = nullptr;
  319. DenseMap<const Elf_Shdr *, ArrayRef<Elf_Word>> ShndxTables;
  320. Optional<uint64_t> SONameOffset;
  321. Optional<DenseMap<uint64_t, std::vector<uint32_t>>> AddressToIndexMap;
  322. const Elf_Shdr *SymbolVersionSection = nullptr; // .gnu.version
  323. const Elf_Shdr *SymbolVersionNeedSection = nullptr; // .gnu.version_r
  324. const Elf_Shdr *SymbolVersionDefSection = nullptr; // .gnu.version_d
  325. std::string getFullSymbolName(const Elf_Sym &Symbol, unsigned SymIndex,
  326. DataRegion<Elf_Word> ShndxTable,
  327. Optional<StringRef> StrTable,
  328. bool IsDynamic) const;
  329. Expected<unsigned>
  330. getSymbolSectionIndex(const Elf_Sym &Symbol, unsigned SymIndex,
  331. DataRegion<Elf_Word> ShndxTable) const;
  332. Expected<StringRef> getSymbolSectionName(const Elf_Sym &Symbol,
  333. unsigned SectionIndex) const;
  334. std::string getStaticSymbolName(uint32_t Index) const;
  335. StringRef getDynamicString(uint64_t Value) const;
  336. void printSymbolsHelper(bool IsDynamic) const;
  337. std::string getDynamicEntry(uint64_t Type, uint64_t Value) const;
  338. Expected<RelSymbol<ELFT>> getRelocationTarget(const Relocation<ELFT> &R,
  339. const Elf_Shdr *SymTab) const;
  340. ArrayRef<Elf_Word> getShndxTable(const Elf_Shdr *Symtab) const;
  341. private:
  342. mutable SmallVector<Optional<VersionEntry>, 0> VersionMap;
  343. };
  344. template <class ELFT>
  345. std::string ELFDumper<ELFT>::describe(const Elf_Shdr &Sec) const {
  346. return ::describe(Obj, Sec);
  347. }
  348. namespace {
  349. template <class ELFT> struct SymtabLink {
  350. typename ELFT::SymRange Symbols;
  351. StringRef StringTable;
  352. const typename ELFT::Shdr *SymTab;
  353. };
  354. // Returns the linked symbol table, symbols and associated string table for a
  355. // given section.
  356. template <class ELFT>
  357. Expected<SymtabLink<ELFT>> getLinkAsSymtab(const ELFFile<ELFT> &Obj,
  358. const typename ELFT::Shdr &Sec,
  359. unsigned ExpectedType) {
  360. Expected<const typename ELFT::Shdr *> SymtabOrErr =
  361. Obj.getSection(Sec.sh_link);
  362. if (!SymtabOrErr)
  363. return createError("invalid section linked to " + describe(Obj, Sec) +
  364. ": " + toString(SymtabOrErr.takeError()));
  365. if ((*SymtabOrErr)->sh_type != ExpectedType)
  366. return createError(
  367. "invalid section linked to " + describe(Obj, Sec) + ": expected " +
  368. object::getELFSectionTypeName(Obj.getHeader().e_machine, ExpectedType) +
  369. ", but got " +
  370. object::getELFSectionTypeName(Obj.getHeader().e_machine,
  371. (*SymtabOrErr)->sh_type));
  372. Expected<StringRef> StrTabOrErr = Obj.getLinkAsStrtab(**SymtabOrErr);
  373. if (!StrTabOrErr)
  374. return createError(
  375. "can't get a string table for the symbol table linked to " +
  376. describe(Obj, Sec) + ": " + toString(StrTabOrErr.takeError()));
  377. Expected<typename ELFT::SymRange> SymsOrErr = Obj.symbols(*SymtabOrErr);
  378. if (!SymsOrErr)
  379. return createError("unable to read symbols from the " + describe(Obj, Sec) +
  380. ": " + toString(SymsOrErr.takeError()));
  381. return SymtabLink<ELFT>{*SymsOrErr, *StrTabOrErr, *SymtabOrErr};
  382. }
  383. } // namespace
  384. template <class ELFT>
  385. Expected<ArrayRef<typename ELFT::Versym>>
  386. ELFDumper<ELFT>::getVersionTable(const Elf_Shdr &Sec, ArrayRef<Elf_Sym> *SymTab,
  387. StringRef *StrTab,
  388. const Elf_Shdr **SymTabSec) const {
  389. assert((!SymTab && !StrTab && !SymTabSec) || (SymTab && StrTab && SymTabSec));
  390. if (reinterpret_cast<uintptr_t>(Obj.base() + Sec.sh_offset) %
  391. sizeof(uint16_t) !=
  392. 0)
  393. return createError("the " + describe(Sec) + " is misaligned");
  394. Expected<ArrayRef<Elf_Versym>> VersionsOrErr =
  395. Obj.template getSectionContentsAsArray<Elf_Versym>(Sec);
  396. if (!VersionsOrErr)
  397. return createError("cannot read content of " + describe(Sec) + ": " +
  398. toString(VersionsOrErr.takeError()));
  399. Expected<SymtabLink<ELFT>> SymTabOrErr =
  400. getLinkAsSymtab(Obj, Sec, SHT_DYNSYM);
  401. if (!SymTabOrErr) {
  402. reportUniqueWarning(SymTabOrErr.takeError());
  403. return *VersionsOrErr;
  404. }
  405. if (SymTabOrErr->Symbols.size() != VersionsOrErr->size())
  406. reportUniqueWarning(describe(Sec) + ": the number of entries (" +
  407. Twine(VersionsOrErr->size()) +
  408. ") does not match the number of symbols (" +
  409. Twine(SymTabOrErr->Symbols.size()) +
  410. ") in the symbol table with index " +
  411. Twine(Sec.sh_link));
  412. if (SymTab) {
  413. *SymTab = SymTabOrErr->Symbols;
  414. *StrTab = SymTabOrErr->StringTable;
  415. *SymTabSec = SymTabOrErr->SymTab;
  416. }
  417. return *VersionsOrErr;
  418. }
  419. template <class ELFT>
  420. void ELFDumper<ELFT>::printSymbolsHelper(bool IsDynamic) const {
  421. Optional<StringRef> StrTable;
  422. size_t Entries = 0;
  423. Elf_Sym_Range Syms(nullptr, nullptr);
  424. const Elf_Shdr *SymtabSec = IsDynamic ? DotDynsymSec : DotSymtabSec;
  425. if (IsDynamic) {
  426. StrTable = DynamicStringTable;
  427. Syms = dynamic_symbols();
  428. Entries = Syms.size();
  429. } else if (DotSymtabSec) {
  430. if (Expected<StringRef> StrTableOrErr =
  431. Obj.getStringTableForSymtab(*DotSymtabSec))
  432. StrTable = *StrTableOrErr;
  433. else
  434. reportUniqueWarning(
  435. "unable to get the string table for the SHT_SYMTAB section: " +
  436. toString(StrTableOrErr.takeError()));
  437. if (Expected<Elf_Sym_Range> SymsOrErr = Obj.symbols(DotSymtabSec))
  438. Syms = *SymsOrErr;
  439. else
  440. reportUniqueWarning(
  441. "unable to read symbols from the SHT_SYMTAB section: " +
  442. toString(SymsOrErr.takeError()));
  443. Entries = DotSymtabSec->getEntityCount();
  444. }
  445. if (Syms.empty())
  446. return;
  447. // The st_other field has 2 logical parts. The first two bits hold the symbol
  448. // visibility (STV_*) and the remainder hold other platform-specific values.
  449. bool NonVisibilityBitsUsed =
  450. llvm::any_of(Syms, [](const Elf_Sym &S) { return S.st_other & ~0x3; });
  451. DataRegion<Elf_Word> ShndxTable =
  452. IsDynamic ? DataRegion<Elf_Word>(
  453. (const Elf_Word *)this->DynSymTabShndxRegion.Addr,
  454. this->getElfObject().getELFFile().end())
  455. : DataRegion<Elf_Word>(this->getShndxTable(SymtabSec));
  456. printSymtabMessage(SymtabSec, Entries, NonVisibilityBitsUsed);
  457. for (const Elf_Sym &Sym : Syms)
  458. printSymbol(Sym, &Sym - Syms.begin(), ShndxTable, StrTable, IsDynamic,
  459. NonVisibilityBitsUsed);
  460. }
  461. template <typename ELFT> class GNUELFDumper : public ELFDumper<ELFT> {
  462. formatted_raw_ostream &OS;
  463. public:
  464. LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
  465. GNUELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer)
  466. : ELFDumper<ELFT>(ObjF, Writer),
  467. OS(static_cast<formatted_raw_ostream &>(Writer.getOStream())) {
  468. assert(&this->W.getOStream() == &llvm::fouts());
  469. }
  470. void printFileSummary(StringRef FileStr, ObjectFile &Obj,
  471. ArrayRef<std::string> InputFilenames,
  472. const Archive *A) override;
  473. void printFileHeaders() override;
  474. void printGroupSections() override;
  475. void printRelocations() override;
  476. void printSectionHeaders() override;
  477. void printSymbols(bool PrintSymbols, bool PrintDynamicSymbols) override;
  478. void printHashSymbols() override;
  479. void printSectionDetails() override;
  480. void printDependentLibs() override;
  481. void printDynamicTable() override;
  482. void printDynamicRelocations() override;
  483. void printSymtabMessage(const Elf_Shdr *Symtab, size_t Offset,
  484. bool NonVisibilityBitsUsed) const override;
  485. void printProgramHeaders(bool PrintProgramHeaders,
  486. cl::boolOrDefault PrintSectionMapping) override;
  487. void printVersionSymbolSection(const Elf_Shdr *Sec) override;
  488. void printVersionDefinitionSection(const Elf_Shdr *Sec) override;
  489. void printVersionDependencySection(const Elf_Shdr *Sec) override;
  490. void printHashHistograms() override;
  491. void printCGProfile() override;
  492. void printBBAddrMaps() override;
  493. void printAddrsig() override;
  494. void printNotes() override;
  495. void printELFLinkerOptions() override;
  496. void printStackSizes() override;
  497. private:
  498. void printHashHistogram(const Elf_Hash &HashTable);
  499. void printGnuHashHistogram(const Elf_GnuHash &GnuHashTable);
  500. void printHashTableSymbols(const Elf_Hash &HashTable);
  501. void printGnuHashTableSymbols(const Elf_GnuHash &GnuHashTable);
  502. struct Field {
  503. std::string Str;
  504. unsigned Column;
  505. Field(StringRef S, unsigned Col) : Str(std::string(S)), Column(Col) {}
  506. Field(unsigned Col) : Column(Col) {}
  507. };
  508. template <typename T, typename TEnum>
  509. std::string printFlags(T Value, ArrayRef<EnumEntry<TEnum>> EnumValues,
  510. TEnum EnumMask1 = {}, TEnum EnumMask2 = {},
  511. TEnum EnumMask3 = {}) const {
  512. std::string Str;
  513. for (const EnumEntry<TEnum> &Flag : EnumValues) {
  514. if (Flag.Value == 0)
  515. continue;
  516. TEnum EnumMask{};
  517. if (Flag.Value & EnumMask1)
  518. EnumMask = EnumMask1;
  519. else if (Flag.Value & EnumMask2)
  520. EnumMask = EnumMask2;
  521. else if (Flag.Value & EnumMask3)
  522. EnumMask = EnumMask3;
  523. bool IsEnum = (Flag.Value & EnumMask) != 0;
  524. if ((!IsEnum && (Value & Flag.Value) == Flag.Value) ||
  525. (IsEnum && (Value & EnumMask) == Flag.Value)) {
  526. if (!Str.empty())
  527. Str += ", ";
  528. Str += Flag.AltName;
  529. }
  530. }
  531. return Str;
  532. }
  533. formatted_raw_ostream &printField(struct Field F) const {
  534. if (F.Column != 0)
  535. OS.PadToColumn(F.Column);
  536. OS << F.Str;
  537. OS.flush();
  538. return OS;
  539. }
  540. void printHashedSymbol(const Elf_Sym *Sym, unsigned SymIndex,
  541. DataRegion<Elf_Word> ShndxTable, StringRef StrTable,
  542. uint32_t Bucket);
  543. void printRelrReloc(const Elf_Relr &R) override;
  544. void printRelRelaReloc(const Relocation<ELFT> &R,
  545. const RelSymbol<ELFT> &RelSym) override;
  546. void printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
  547. DataRegion<Elf_Word> ShndxTable,
  548. Optional<StringRef> StrTable, bool IsDynamic,
  549. bool NonVisibilityBitsUsed) const override;
  550. void printDynamicRelocHeader(unsigned Type, StringRef Name,
  551. const DynRegionInfo &Reg) override;
  552. std::string getSymbolSectionNdx(const Elf_Sym &Symbol, unsigned SymIndex,
  553. DataRegion<Elf_Word> ShndxTable) const;
  554. void printProgramHeaders() override;
  555. void printSectionMapping() override;
  556. void printGNUVersionSectionProlog(const typename ELFT::Shdr &Sec,
  557. const Twine &Label, unsigned EntriesNum);
  558. void printStackSizeEntry(uint64_t Size,
  559. ArrayRef<std::string> FuncNames) override;
  560. void printMipsGOT(const MipsGOTParser<ELFT> &Parser) override;
  561. void printMipsPLT(const MipsGOTParser<ELFT> &Parser) override;
  562. void printMipsABIFlags() override;
  563. };
  564. template <typename ELFT> class LLVMELFDumper : public ELFDumper<ELFT> {
  565. public:
  566. LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
  567. LLVMELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer)
  568. : ELFDumper<ELFT>(ObjF, Writer), W(Writer) {}
  569. void printFileHeaders() override;
  570. void printGroupSections() override;
  571. void printRelocations() override;
  572. void printSectionHeaders() override;
  573. void printSymbols(bool PrintSymbols, bool PrintDynamicSymbols) override;
  574. void printDependentLibs() override;
  575. void printDynamicTable() override;
  576. void printDynamicRelocations() override;
  577. void printProgramHeaders(bool PrintProgramHeaders,
  578. cl::boolOrDefault PrintSectionMapping) override;
  579. void printVersionSymbolSection(const Elf_Shdr *Sec) override;
  580. void printVersionDefinitionSection(const Elf_Shdr *Sec) override;
  581. void printVersionDependencySection(const Elf_Shdr *Sec) override;
  582. void printHashHistograms() override;
  583. void printCGProfile() override;
  584. void printBBAddrMaps() override;
  585. void printAddrsig() override;
  586. void printNotes() override;
  587. void printELFLinkerOptions() override;
  588. void printStackSizes() override;
  589. private:
  590. void printRelrReloc(const Elf_Relr &R) override;
  591. void printRelRelaReloc(const Relocation<ELFT> &R,
  592. const RelSymbol<ELFT> &RelSym) override;
  593. void printSymbolSection(const Elf_Sym &Symbol, unsigned SymIndex,
  594. DataRegion<Elf_Word> ShndxTable) const;
  595. void printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
  596. DataRegion<Elf_Word> ShndxTable,
  597. Optional<StringRef> StrTable, bool IsDynamic,
  598. bool /*NonVisibilityBitsUsed*/) const override;
  599. void printProgramHeaders() override;
  600. void printSectionMapping() override {}
  601. void printStackSizeEntry(uint64_t Size,
  602. ArrayRef<std::string> FuncNames) override;
  603. void printMipsGOT(const MipsGOTParser<ELFT> &Parser) override;
  604. void printMipsPLT(const MipsGOTParser<ELFT> &Parser) override;
  605. void printMipsABIFlags() override;
  606. protected:
  607. ScopedPrinter &W;
  608. };
  609. // JSONELFDumper shares most of the same implementation as LLVMELFDumper except
  610. // it uses a JSONScopedPrinter.
  611. template <typename ELFT> class JSONELFDumper : public LLVMELFDumper<ELFT> {
  612. public:
  613. LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
  614. JSONELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer)
  615. : LLVMELFDumper<ELFT>(ObjF, Writer) {}
  616. void printFileSummary(StringRef FileStr, ObjectFile &Obj,
  617. ArrayRef<std::string> InputFilenames,
  618. const Archive *A) override;
  619. private:
  620. std::unique_ptr<DictScope> FileScope;
  621. };
  622. } // end anonymous namespace
  623. namespace llvm {
  624. template <class ELFT>
  625. static std::unique_ptr<ObjDumper>
  626. createELFDumper(const ELFObjectFile<ELFT> &Obj, ScopedPrinter &Writer) {
  627. if (opts::Output == opts::GNU)
  628. return std::make_unique<GNUELFDumper<ELFT>>(Obj, Writer);
  629. else if (opts::Output == opts::JSON)
  630. return std::make_unique<JSONELFDumper<ELFT>>(Obj, Writer);
  631. return std::make_unique<LLVMELFDumper<ELFT>>(Obj, Writer);
  632. }
  633. std::unique_ptr<ObjDumper> createELFDumper(const object::ELFObjectFileBase &Obj,
  634. ScopedPrinter &Writer) {
  635. // Little-endian 32-bit
  636. if (const ELF32LEObjectFile *ELFObj = dyn_cast<ELF32LEObjectFile>(&Obj))
  637. return createELFDumper(*ELFObj, Writer);
  638. // Big-endian 32-bit
  639. if (const ELF32BEObjectFile *ELFObj = dyn_cast<ELF32BEObjectFile>(&Obj))
  640. return createELFDumper(*ELFObj, Writer);
  641. // Little-endian 64-bit
  642. if (const ELF64LEObjectFile *ELFObj = dyn_cast<ELF64LEObjectFile>(&Obj))
  643. return createELFDumper(*ELFObj, Writer);
  644. // Big-endian 64-bit
  645. return createELFDumper(*cast<ELF64BEObjectFile>(&Obj), Writer);
  646. }
  647. } // end namespace llvm
  648. template <class ELFT>
  649. Expected<SmallVector<Optional<VersionEntry>, 0> *>
  650. ELFDumper<ELFT>::getVersionMap() const {
  651. // If the VersionMap has already been loaded or if there is no dynamic symtab
  652. // or version table, there is nothing to do.
  653. if (!VersionMap.empty() || !DynSymRegion || !SymbolVersionSection)
  654. return &VersionMap;
  655. Expected<SmallVector<Optional<VersionEntry>, 0>> MapOrErr =
  656. Obj.loadVersionMap(SymbolVersionNeedSection, SymbolVersionDefSection);
  657. if (MapOrErr)
  658. VersionMap = *MapOrErr;
  659. else
  660. return MapOrErr.takeError();
  661. return &VersionMap;
  662. }
  663. template <typename ELFT>
  664. Expected<StringRef> ELFDumper<ELFT>::getSymbolVersion(const Elf_Sym &Sym,
  665. bool &IsDefault) const {
  666. // This is a dynamic symbol. Look in the GNU symbol version table.
  667. if (!SymbolVersionSection) {
  668. // No version table.
  669. IsDefault = false;
  670. return "";
  671. }
  672. assert(DynSymRegion && "DynSymRegion has not been initialised");
  673. // Determine the position in the symbol table of this entry.
  674. size_t EntryIndex = (reinterpret_cast<uintptr_t>(&Sym) -
  675. reinterpret_cast<uintptr_t>(DynSymRegion->Addr)) /
  676. sizeof(Elf_Sym);
  677. // Get the corresponding version index entry.
  678. Expected<const Elf_Versym *> EntryOrErr =
  679. Obj.template getEntry<Elf_Versym>(*SymbolVersionSection, EntryIndex);
  680. if (!EntryOrErr)
  681. return EntryOrErr.takeError();
  682. unsigned Version = (*EntryOrErr)->vs_index;
  683. if (Version == VER_NDX_LOCAL || Version == VER_NDX_GLOBAL) {
  684. IsDefault = false;
  685. return "";
  686. }
  687. Expected<SmallVector<Optional<VersionEntry>, 0> *> MapOrErr =
  688. getVersionMap();
  689. if (!MapOrErr)
  690. return MapOrErr.takeError();
  691. return Obj.getSymbolVersionByIndex(Version, IsDefault, **MapOrErr,
  692. Sym.st_shndx == ELF::SHN_UNDEF);
  693. }
  694. template <typename ELFT>
  695. Expected<RelSymbol<ELFT>>
  696. ELFDumper<ELFT>::getRelocationTarget(const Relocation<ELFT> &R,
  697. const Elf_Shdr *SymTab) const {
  698. if (R.Symbol == 0)
  699. return RelSymbol<ELFT>(nullptr, "");
  700. Expected<const Elf_Sym *> SymOrErr =
  701. Obj.template getEntry<Elf_Sym>(*SymTab, R.Symbol);
  702. if (!SymOrErr)
  703. return createError("unable to read an entry with index " + Twine(R.Symbol) +
  704. " from " + describe(*SymTab) + ": " +
  705. toString(SymOrErr.takeError()));
  706. const Elf_Sym *Sym = *SymOrErr;
  707. if (!Sym)
  708. return RelSymbol<ELFT>(nullptr, "");
  709. Expected<StringRef> StrTableOrErr = Obj.getStringTableForSymtab(*SymTab);
  710. if (!StrTableOrErr)
  711. return StrTableOrErr.takeError();
  712. const Elf_Sym *FirstSym =
  713. cantFail(Obj.template getEntry<Elf_Sym>(*SymTab, 0));
  714. std::string SymbolName =
  715. getFullSymbolName(*Sym, Sym - FirstSym, getShndxTable(SymTab),
  716. *StrTableOrErr, SymTab->sh_type == SHT_DYNSYM);
  717. return RelSymbol<ELFT>(Sym, SymbolName);
  718. }
  719. template <typename ELFT>
  720. ArrayRef<typename ELFT::Word>
  721. ELFDumper<ELFT>::getShndxTable(const Elf_Shdr *Symtab) const {
  722. if (Symtab) {
  723. auto It = ShndxTables.find(Symtab);
  724. if (It != ShndxTables.end())
  725. return It->second;
  726. }
  727. return {};
  728. }
  729. static std::string maybeDemangle(StringRef Name) {
  730. return opts::Demangle ? demangle(std::string(Name)) : Name.str();
  731. }
  732. template <typename ELFT>
  733. std::string ELFDumper<ELFT>::getStaticSymbolName(uint32_t Index) const {
  734. auto Warn = [&](Error E) -> std::string {
  735. reportUniqueWarning("unable to read the name of symbol with index " +
  736. Twine(Index) + ": " + toString(std::move(E)));
  737. return "<?>";
  738. };
  739. Expected<const typename ELFT::Sym *> SymOrErr =
  740. Obj.getSymbol(DotSymtabSec, Index);
  741. if (!SymOrErr)
  742. return Warn(SymOrErr.takeError());
  743. Expected<StringRef> StrTabOrErr = Obj.getStringTableForSymtab(*DotSymtabSec);
  744. if (!StrTabOrErr)
  745. return Warn(StrTabOrErr.takeError());
  746. Expected<StringRef> NameOrErr = (*SymOrErr)->getName(*StrTabOrErr);
  747. if (!NameOrErr)
  748. return Warn(NameOrErr.takeError());
  749. return maybeDemangle(*NameOrErr);
  750. }
  751. template <typename ELFT>
  752. std::string ELFDumper<ELFT>::getFullSymbolName(const Elf_Sym &Symbol,
  753. unsigned SymIndex,
  754. DataRegion<Elf_Word> ShndxTable,
  755. Optional<StringRef> StrTable,
  756. bool IsDynamic) const {
  757. if (!StrTable)
  758. return "<?>";
  759. std::string SymbolName;
  760. if (Expected<StringRef> NameOrErr = Symbol.getName(*StrTable)) {
  761. SymbolName = maybeDemangle(*NameOrErr);
  762. } else {
  763. reportUniqueWarning(NameOrErr.takeError());
  764. return "<?>";
  765. }
  766. if (SymbolName.empty() && Symbol.getType() == ELF::STT_SECTION) {
  767. Expected<unsigned> SectionIndex =
  768. getSymbolSectionIndex(Symbol, SymIndex, ShndxTable);
  769. if (!SectionIndex) {
  770. reportUniqueWarning(SectionIndex.takeError());
  771. return "<?>";
  772. }
  773. Expected<StringRef> NameOrErr = getSymbolSectionName(Symbol, *SectionIndex);
  774. if (!NameOrErr) {
  775. reportUniqueWarning(NameOrErr.takeError());
  776. return ("<section " + Twine(*SectionIndex) + ">").str();
  777. }
  778. return std::string(*NameOrErr);
  779. }
  780. if (!IsDynamic)
  781. return SymbolName;
  782. bool IsDefault;
  783. Expected<StringRef> VersionOrErr = getSymbolVersion(Symbol, IsDefault);
  784. if (!VersionOrErr) {
  785. reportUniqueWarning(VersionOrErr.takeError());
  786. return SymbolName + "@<corrupt>";
  787. }
  788. if (!VersionOrErr->empty()) {
  789. SymbolName += (IsDefault ? "@@" : "@");
  790. SymbolName += *VersionOrErr;
  791. }
  792. return SymbolName;
  793. }
  794. template <typename ELFT>
  795. Expected<unsigned>
  796. ELFDumper<ELFT>::getSymbolSectionIndex(const Elf_Sym &Symbol, unsigned SymIndex,
  797. DataRegion<Elf_Word> ShndxTable) const {
  798. unsigned Ndx = Symbol.st_shndx;
  799. if (Ndx == SHN_XINDEX)
  800. return object::getExtendedSymbolTableIndex<ELFT>(Symbol, SymIndex,
  801. ShndxTable);
  802. if (Ndx != SHN_UNDEF && Ndx < SHN_LORESERVE)
  803. return Ndx;
  804. auto CreateErr = [&](const Twine &Name, Optional<unsigned> Offset = None) {
  805. std::string Desc;
  806. if (Offset)
  807. Desc = (Name + "+0x" + Twine::utohexstr(*Offset)).str();
  808. else
  809. Desc = Name.str();
  810. return createError(
  811. "unable to get section index for symbol with st_shndx = 0x" +
  812. Twine::utohexstr(Ndx) + " (" + Desc + ")");
  813. };
  814. if (Ndx >= ELF::SHN_LOPROC && Ndx <= ELF::SHN_HIPROC)
  815. return CreateErr("SHN_LOPROC", Ndx - ELF::SHN_LOPROC);
  816. if (Ndx >= ELF::SHN_LOOS && Ndx <= ELF::SHN_HIOS)
  817. return CreateErr("SHN_LOOS", Ndx - ELF::SHN_LOOS);
  818. if (Ndx == ELF::SHN_UNDEF)
  819. return CreateErr("SHN_UNDEF");
  820. if (Ndx == ELF::SHN_ABS)
  821. return CreateErr("SHN_ABS");
  822. if (Ndx == ELF::SHN_COMMON)
  823. return CreateErr("SHN_COMMON");
  824. return CreateErr("SHN_LORESERVE", Ndx - SHN_LORESERVE);
  825. }
  826. template <typename ELFT>
  827. Expected<StringRef>
  828. ELFDumper<ELFT>::getSymbolSectionName(const Elf_Sym &Symbol,
  829. unsigned SectionIndex) const {
  830. Expected<const Elf_Shdr *> SecOrErr = Obj.getSection(SectionIndex);
  831. if (!SecOrErr)
  832. return SecOrErr.takeError();
  833. return Obj.getSectionName(**SecOrErr);
  834. }
  835. template <class ELFO>
  836. static const typename ELFO::Elf_Shdr *
  837. findNotEmptySectionByAddress(const ELFO &Obj, StringRef FileName,
  838. uint64_t Addr) {
  839. for (const typename ELFO::Elf_Shdr &Shdr : cantFail(Obj.sections()))
  840. if (Shdr.sh_addr == Addr && Shdr.sh_size > 0)
  841. return &Shdr;
  842. return nullptr;
  843. }
  844. const EnumEntry<unsigned> ElfClass[] = {
  845. {"None", "none", ELF::ELFCLASSNONE},
  846. {"32-bit", "ELF32", ELF::ELFCLASS32},
  847. {"64-bit", "ELF64", ELF::ELFCLASS64},
  848. };
  849. const EnumEntry<unsigned> ElfDataEncoding[] = {
  850. {"None", "none", ELF::ELFDATANONE},
  851. {"LittleEndian", "2's complement, little endian", ELF::ELFDATA2LSB},
  852. {"BigEndian", "2's complement, big endian", ELF::ELFDATA2MSB},
  853. };
  854. const EnumEntry<unsigned> ElfObjectFileType[] = {
  855. {"None", "NONE (none)", ELF::ET_NONE},
  856. {"Relocatable", "REL (Relocatable file)", ELF::ET_REL},
  857. {"Executable", "EXEC (Executable file)", ELF::ET_EXEC},
  858. {"SharedObject", "DYN (Shared object file)", ELF::ET_DYN},
  859. {"Core", "CORE (Core file)", ELF::ET_CORE},
  860. };
  861. const EnumEntry<unsigned> ElfOSABI[] = {
  862. {"SystemV", "UNIX - System V", ELF::ELFOSABI_NONE},
  863. {"HPUX", "UNIX - HP-UX", ELF::ELFOSABI_HPUX},
  864. {"NetBSD", "UNIX - NetBSD", ELF::ELFOSABI_NETBSD},
  865. {"GNU/Linux", "UNIX - GNU", ELF::ELFOSABI_LINUX},
  866. {"GNU/Hurd", "GNU/Hurd", ELF::ELFOSABI_HURD},
  867. {"Solaris", "UNIX - Solaris", ELF::ELFOSABI_SOLARIS},
  868. {"AIX", "UNIX - AIX", ELF::ELFOSABI_AIX},
  869. {"IRIX", "UNIX - IRIX", ELF::ELFOSABI_IRIX},
  870. {"FreeBSD", "UNIX - FreeBSD", ELF::ELFOSABI_FREEBSD},
  871. {"TRU64", "UNIX - TRU64", ELF::ELFOSABI_TRU64},
  872. {"Modesto", "Novell - Modesto", ELF::ELFOSABI_MODESTO},
  873. {"OpenBSD", "UNIX - OpenBSD", ELF::ELFOSABI_OPENBSD},
  874. {"OpenVMS", "VMS - OpenVMS", ELF::ELFOSABI_OPENVMS},
  875. {"NSK", "HP - Non-Stop Kernel", ELF::ELFOSABI_NSK},
  876. {"AROS", "AROS", ELF::ELFOSABI_AROS},
  877. {"FenixOS", "FenixOS", ELF::ELFOSABI_FENIXOS},
  878. {"CloudABI", "CloudABI", ELF::ELFOSABI_CLOUDABI},
  879. {"Standalone", "Standalone App", ELF::ELFOSABI_STANDALONE}
  880. };
  881. const EnumEntry<unsigned> AMDGPUElfOSABI[] = {
  882. {"AMDGPU_HSA", "AMDGPU - HSA", ELF::ELFOSABI_AMDGPU_HSA},
  883. {"AMDGPU_PAL", "AMDGPU - PAL", ELF::ELFOSABI_AMDGPU_PAL},
  884. {"AMDGPU_MESA3D", "AMDGPU - MESA3D", ELF::ELFOSABI_AMDGPU_MESA3D}
  885. };
  886. const EnumEntry<unsigned> ARMElfOSABI[] = {
  887. {"ARM", "ARM", ELF::ELFOSABI_ARM}
  888. };
  889. const EnumEntry<unsigned> C6000ElfOSABI[] = {
  890. {"C6000_ELFABI", "Bare-metal C6000", ELF::ELFOSABI_C6000_ELFABI},
  891. {"C6000_LINUX", "Linux C6000", ELF::ELFOSABI_C6000_LINUX}
  892. };
  893. const EnumEntry<unsigned> ElfMachineType[] = {
  894. ENUM_ENT(EM_NONE, "None"),
  895. ENUM_ENT(EM_M32, "WE32100"),
  896. ENUM_ENT(EM_SPARC, "Sparc"),
  897. ENUM_ENT(EM_386, "Intel 80386"),
  898. ENUM_ENT(EM_68K, "MC68000"),
  899. ENUM_ENT(EM_88K, "MC88000"),
  900. ENUM_ENT(EM_IAMCU, "EM_IAMCU"),
  901. ENUM_ENT(EM_860, "Intel 80860"),
  902. ENUM_ENT(EM_MIPS, "MIPS R3000"),
  903. ENUM_ENT(EM_S370, "IBM System/370"),
  904. ENUM_ENT(EM_MIPS_RS3_LE, "MIPS R3000 little-endian"),
  905. ENUM_ENT(EM_PARISC, "HPPA"),
  906. ENUM_ENT(EM_VPP500, "Fujitsu VPP500"),
  907. ENUM_ENT(EM_SPARC32PLUS, "Sparc v8+"),
  908. ENUM_ENT(EM_960, "Intel 80960"),
  909. ENUM_ENT(EM_PPC, "PowerPC"),
  910. ENUM_ENT(EM_PPC64, "PowerPC64"),
  911. ENUM_ENT(EM_S390, "IBM S/390"),
  912. ENUM_ENT(EM_SPU, "SPU"),
  913. ENUM_ENT(EM_V800, "NEC V800 series"),
  914. ENUM_ENT(EM_FR20, "Fujistsu FR20"),
  915. ENUM_ENT(EM_RH32, "TRW RH-32"),
  916. ENUM_ENT(EM_RCE, "Motorola RCE"),
  917. ENUM_ENT(EM_ARM, "ARM"),
  918. ENUM_ENT(EM_ALPHA, "EM_ALPHA"),
  919. ENUM_ENT(EM_SH, "Hitachi SH"),
  920. ENUM_ENT(EM_SPARCV9, "Sparc v9"),
  921. ENUM_ENT(EM_TRICORE, "Siemens Tricore"),
  922. ENUM_ENT(EM_ARC, "ARC"),
  923. ENUM_ENT(EM_H8_300, "Hitachi H8/300"),
  924. ENUM_ENT(EM_H8_300H, "Hitachi H8/300H"),
  925. ENUM_ENT(EM_H8S, "Hitachi H8S"),
  926. ENUM_ENT(EM_H8_500, "Hitachi H8/500"),
  927. ENUM_ENT(EM_IA_64, "Intel IA-64"),
  928. ENUM_ENT(EM_MIPS_X, "Stanford MIPS-X"),
  929. ENUM_ENT(EM_COLDFIRE, "Motorola Coldfire"),
  930. ENUM_ENT(EM_68HC12, "Motorola MC68HC12 Microcontroller"),
  931. ENUM_ENT(EM_MMA, "Fujitsu Multimedia Accelerator"),
  932. ENUM_ENT(EM_PCP, "Siemens PCP"),
  933. ENUM_ENT(EM_NCPU, "Sony nCPU embedded RISC processor"),
  934. ENUM_ENT(EM_NDR1, "Denso NDR1 microprocesspr"),
  935. ENUM_ENT(EM_STARCORE, "Motorola Star*Core processor"),
  936. ENUM_ENT(EM_ME16, "Toyota ME16 processor"),
  937. ENUM_ENT(EM_ST100, "STMicroelectronics ST100 processor"),
  938. ENUM_ENT(EM_TINYJ, "Advanced Logic Corp. TinyJ embedded processor"),
  939. ENUM_ENT(EM_X86_64, "Advanced Micro Devices X86-64"),
  940. ENUM_ENT(EM_PDSP, "Sony DSP processor"),
  941. ENUM_ENT(EM_PDP10, "Digital Equipment Corp. PDP-10"),
  942. ENUM_ENT(EM_PDP11, "Digital Equipment Corp. PDP-11"),
  943. ENUM_ENT(EM_FX66, "Siemens FX66 microcontroller"),
  944. ENUM_ENT(EM_ST9PLUS, "STMicroelectronics ST9+ 8/16 bit microcontroller"),
  945. ENUM_ENT(EM_ST7, "STMicroelectronics ST7 8-bit microcontroller"),
  946. ENUM_ENT(EM_68HC16, "Motorola MC68HC16 Microcontroller"),
  947. ENUM_ENT(EM_68HC11, "Motorola MC68HC11 Microcontroller"),
  948. ENUM_ENT(EM_68HC08, "Motorola MC68HC08 Microcontroller"),
  949. ENUM_ENT(EM_68HC05, "Motorola MC68HC05 Microcontroller"),
  950. ENUM_ENT(EM_SVX, "Silicon Graphics SVx"),
  951. ENUM_ENT(EM_ST19, "STMicroelectronics ST19 8-bit microcontroller"),
  952. ENUM_ENT(EM_VAX, "Digital VAX"),
  953. ENUM_ENT(EM_CRIS, "Axis Communications 32-bit embedded processor"),
  954. ENUM_ENT(EM_JAVELIN, "Infineon Technologies 32-bit embedded cpu"),
  955. ENUM_ENT(EM_FIREPATH, "Element 14 64-bit DSP processor"),
  956. ENUM_ENT(EM_ZSP, "LSI Logic's 16-bit DSP processor"),
  957. ENUM_ENT(EM_MMIX, "Donald Knuth's educational 64-bit processor"),
  958. ENUM_ENT(EM_HUANY, "Harvard Universitys's machine-independent object format"),
  959. ENUM_ENT(EM_PRISM, "Vitesse Prism"),
  960. ENUM_ENT(EM_AVR, "Atmel AVR 8-bit microcontroller"),
  961. ENUM_ENT(EM_FR30, "Fujitsu FR30"),
  962. ENUM_ENT(EM_D10V, "Mitsubishi D10V"),
  963. ENUM_ENT(EM_D30V, "Mitsubishi D30V"),
  964. ENUM_ENT(EM_V850, "NEC v850"),
  965. ENUM_ENT(EM_M32R, "Renesas M32R (formerly Mitsubishi M32r)"),
  966. ENUM_ENT(EM_MN10300, "Matsushita MN10300"),
  967. ENUM_ENT(EM_MN10200, "Matsushita MN10200"),
  968. ENUM_ENT(EM_PJ, "picoJava"),
  969. ENUM_ENT(EM_OPENRISC, "OpenRISC 32-bit embedded processor"),
  970. ENUM_ENT(EM_ARC_COMPACT, "EM_ARC_COMPACT"),
  971. ENUM_ENT(EM_XTENSA, "Tensilica Xtensa Processor"),
  972. ENUM_ENT(EM_VIDEOCORE, "Alphamosaic VideoCore processor"),
  973. ENUM_ENT(EM_TMM_GPP, "Thompson Multimedia General Purpose Processor"),
  974. ENUM_ENT(EM_NS32K, "National Semiconductor 32000 series"),
  975. ENUM_ENT(EM_TPC, "Tenor Network TPC processor"),
  976. ENUM_ENT(EM_SNP1K, "EM_SNP1K"),
  977. ENUM_ENT(EM_ST200, "STMicroelectronics ST200 microcontroller"),
  978. ENUM_ENT(EM_IP2K, "Ubicom IP2xxx 8-bit microcontrollers"),
  979. ENUM_ENT(EM_MAX, "MAX Processor"),
  980. ENUM_ENT(EM_CR, "National Semiconductor CompactRISC"),
  981. ENUM_ENT(EM_F2MC16, "Fujitsu F2MC16"),
  982. ENUM_ENT(EM_MSP430, "Texas Instruments msp430 microcontroller"),
  983. ENUM_ENT(EM_BLACKFIN, "Analog Devices Blackfin"),
  984. ENUM_ENT(EM_SE_C33, "S1C33 Family of Seiko Epson processors"),
  985. ENUM_ENT(EM_SEP, "Sharp embedded microprocessor"),
  986. ENUM_ENT(EM_ARCA, "Arca RISC microprocessor"),
  987. ENUM_ENT(EM_UNICORE, "Unicore"),
  988. ENUM_ENT(EM_EXCESS, "eXcess 16/32/64-bit configurable embedded CPU"),
  989. ENUM_ENT(EM_DXP, "Icera Semiconductor Inc. Deep Execution Processor"),
  990. ENUM_ENT(EM_ALTERA_NIOS2, "Altera Nios"),
  991. ENUM_ENT(EM_CRX, "National Semiconductor CRX microprocessor"),
  992. ENUM_ENT(EM_XGATE, "Motorola XGATE embedded processor"),
  993. ENUM_ENT(EM_C166, "Infineon Technologies xc16x"),
  994. ENUM_ENT(EM_M16C, "Renesas M16C"),
  995. ENUM_ENT(EM_DSPIC30F, "Microchip Technology dsPIC30F Digital Signal Controller"),
  996. ENUM_ENT(EM_CE, "Freescale Communication Engine RISC core"),
  997. ENUM_ENT(EM_M32C, "Renesas M32C"),
  998. ENUM_ENT(EM_TSK3000, "Altium TSK3000 core"),
  999. ENUM_ENT(EM_RS08, "Freescale RS08 embedded processor"),
  1000. ENUM_ENT(EM_SHARC, "EM_SHARC"),
  1001. ENUM_ENT(EM_ECOG2, "Cyan Technology eCOG2 microprocessor"),
  1002. ENUM_ENT(EM_SCORE7, "SUNPLUS S+Core"),
  1003. ENUM_ENT(EM_DSP24, "New Japan Radio (NJR) 24-bit DSP Processor"),
  1004. ENUM_ENT(EM_VIDEOCORE3, "Broadcom VideoCore III processor"),
  1005. ENUM_ENT(EM_LATTICEMICO32, "Lattice Mico32"),
  1006. ENUM_ENT(EM_SE_C17, "Seiko Epson C17 family"),
  1007. ENUM_ENT(EM_TI_C6000, "Texas Instruments TMS320C6000 DSP family"),
  1008. ENUM_ENT(EM_TI_C2000, "Texas Instruments TMS320C2000 DSP family"),
  1009. ENUM_ENT(EM_TI_C5500, "Texas Instruments TMS320C55x DSP family"),
  1010. ENUM_ENT(EM_MMDSP_PLUS, "STMicroelectronics 64bit VLIW Data Signal Processor"),
  1011. ENUM_ENT(EM_CYPRESS_M8C, "Cypress M8C microprocessor"),
  1012. ENUM_ENT(EM_R32C, "Renesas R32C series microprocessors"),
  1013. ENUM_ENT(EM_TRIMEDIA, "NXP Semiconductors TriMedia architecture family"),
  1014. ENUM_ENT(EM_HEXAGON, "Qualcomm Hexagon"),
  1015. ENUM_ENT(EM_8051, "Intel 8051 and variants"),
  1016. ENUM_ENT(EM_STXP7X, "STMicroelectronics STxP7x family"),
  1017. ENUM_ENT(EM_NDS32, "Andes Technology compact code size embedded RISC processor family"),
  1018. ENUM_ENT(EM_ECOG1, "Cyan Technology eCOG1 microprocessor"),
  1019. // FIXME: Following EM_ECOG1X definitions is dead code since EM_ECOG1X has
  1020. // an identical number to EM_ECOG1.
  1021. ENUM_ENT(EM_ECOG1X, "Cyan Technology eCOG1X family"),
  1022. ENUM_ENT(EM_MAXQ30, "Dallas Semiconductor MAXQ30 Core microcontrollers"),
  1023. ENUM_ENT(EM_XIMO16, "New Japan Radio (NJR) 16-bit DSP Processor"),
  1024. ENUM_ENT(EM_MANIK, "M2000 Reconfigurable RISC Microprocessor"),
  1025. ENUM_ENT(EM_CRAYNV2, "Cray Inc. NV2 vector architecture"),
  1026. ENUM_ENT(EM_RX, "Renesas RX"),
  1027. ENUM_ENT(EM_METAG, "Imagination Technologies Meta processor architecture"),
  1028. ENUM_ENT(EM_MCST_ELBRUS, "MCST Elbrus general purpose hardware architecture"),
  1029. ENUM_ENT(EM_ECOG16, "Cyan Technology eCOG16 family"),
  1030. ENUM_ENT(EM_CR16, "National Semiconductor CompactRISC 16-bit processor"),
  1031. ENUM_ENT(EM_ETPU, "Freescale Extended Time Processing Unit"),
  1032. ENUM_ENT(EM_SLE9X, "Infineon Technologies SLE9X core"),
  1033. ENUM_ENT(EM_L10M, "EM_L10M"),
  1034. ENUM_ENT(EM_K10M, "EM_K10M"),
  1035. ENUM_ENT(EM_AARCH64, "AArch64"),
  1036. ENUM_ENT(EM_AVR32, "Atmel Corporation 32-bit microprocessor family"),
  1037. ENUM_ENT(EM_STM8, "STMicroeletronics STM8 8-bit microcontroller"),
  1038. ENUM_ENT(EM_TILE64, "Tilera TILE64 multicore architecture family"),
  1039. ENUM_ENT(EM_TILEPRO, "Tilera TILEPro multicore architecture family"),
  1040. ENUM_ENT(EM_MICROBLAZE, "Xilinx MicroBlaze 32-bit RISC soft processor core"),
  1041. ENUM_ENT(EM_CUDA, "NVIDIA CUDA architecture"),
  1042. ENUM_ENT(EM_TILEGX, "Tilera TILE-Gx multicore architecture family"),
  1043. ENUM_ENT(EM_CLOUDSHIELD, "EM_CLOUDSHIELD"),
  1044. ENUM_ENT(EM_COREA_1ST, "EM_COREA_1ST"),
  1045. ENUM_ENT(EM_COREA_2ND, "EM_COREA_2ND"),
  1046. ENUM_ENT(EM_ARC_COMPACT2, "EM_ARC_COMPACT2"),
  1047. ENUM_ENT(EM_OPEN8, "EM_OPEN8"),
  1048. ENUM_ENT(EM_RL78, "Renesas RL78"),
  1049. ENUM_ENT(EM_VIDEOCORE5, "Broadcom VideoCore V processor"),
  1050. ENUM_ENT(EM_78KOR, "EM_78KOR"),
  1051. ENUM_ENT(EM_56800EX, "EM_56800EX"),
  1052. ENUM_ENT(EM_AMDGPU, "EM_AMDGPU"),
  1053. ENUM_ENT(EM_RISCV, "RISC-V"),
  1054. ENUM_ENT(EM_LANAI, "EM_LANAI"),
  1055. ENUM_ENT(EM_BPF, "EM_BPF"),
  1056. ENUM_ENT(EM_VE, "NEC SX-Aurora Vector Engine"),
  1057. };
  1058. const EnumEntry<unsigned> ElfSymbolBindings[] = {
  1059. {"Local", "LOCAL", ELF::STB_LOCAL},
  1060. {"Global", "GLOBAL", ELF::STB_GLOBAL},
  1061. {"Weak", "WEAK", ELF::STB_WEAK},
  1062. {"Unique", "UNIQUE", ELF::STB_GNU_UNIQUE}};
  1063. const EnumEntry<unsigned> ElfSymbolVisibilities[] = {
  1064. {"DEFAULT", "DEFAULT", ELF::STV_DEFAULT},
  1065. {"INTERNAL", "INTERNAL", ELF::STV_INTERNAL},
  1066. {"HIDDEN", "HIDDEN", ELF::STV_HIDDEN},
  1067. {"PROTECTED", "PROTECTED", ELF::STV_PROTECTED}};
  1068. const EnumEntry<unsigned> AMDGPUSymbolTypes[] = {
  1069. { "AMDGPU_HSA_KERNEL", ELF::STT_AMDGPU_HSA_KERNEL }
  1070. };
  1071. static const char *getGroupType(uint32_t Flag) {
  1072. if (Flag & ELF::GRP_COMDAT)
  1073. return "COMDAT";
  1074. else
  1075. return "(unknown)";
  1076. }
  1077. const EnumEntry<unsigned> ElfSectionFlags[] = {
  1078. ENUM_ENT(SHF_WRITE, "W"),
  1079. ENUM_ENT(SHF_ALLOC, "A"),
  1080. ENUM_ENT(SHF_EXECINSTR, "X"),
  1081. ENUM_ENT(SHF_MERGE, "M"),
  1082. ENUM_ENT(SHF_STRINGS, "S"),
  1083. ENUM_ENT(SHF_INFO_LINK, "I"),
  1084. ENUM_ENT(SHF_LINK_ORDER, "L"),
  1085. ENUM_ENT(SHF_OS_NONCONFORMING, "O"),
  1086. ENUM_ENT(SHF_GROUP, "G"),
  1087. ENUM_ENT(SHF_TLS, "T"),
  1088. ENUM_ENT(SHF_COMPRESSED, "C"),
  1089. ENUM_ENT(SHF_GNU_RETAIN, "R"),
  1090. ENUM_ENT(SHF_EXCLUDE, "E"),
  1091. };
  1092. const EnumEntry<unsigned> ElfXCoreSectionFlags[] = {
  1093. ENUM_ENT(XCORE_SHF_CP_SECTION, ""),
  1094. ENUM_ENT(XCORE_SHF_DP_SECTION, "")
  1095. };
  1096. const EnumEntry<unsigned> ElfARMSectionFlags[] = {
  1097. ENUM_ENT(SHF_ARM_PURECODE, "y")
  1098. };
  1099. const EnumEntry<unsigned> ElfHexagonSectionFlags[] = {
  1100. ENUM_ENT(SHF_HEX_GPREL, "")
  1101. };
  1102. const EnumEntry<unsigned> ElfMipsSectionFlags[] = {
  1103. ENUM_ENT(SHF_MIPS_NODUPES, ""),
  1104. ENUM_ENT(SHF_MIPS_NAMES, ""),
  1105. ENUM_ENT(SHF_MIPS_LOCAL, ""),
  1106. ENUM_ENT(SHF_MIPS_NOSTRIP, ""),
  1107. ENUM_ENT(SHF_MIPS_GPREL, ""),
  1108. ENUM_ENT(SHF_MIPS_MERGE, ""),
  1109. ENUM_ENT(SHF_MIPS_ADDR, ""),
  1110. ENUM_ENT(SHF_MIPS_STRING, "")
  1111. };
  1112. const EnumEntry<unsigned> ElfX86_64SectionFlags[] = {
  1113. ENUM_ENT(SHF_X86_64_LARGE, "l")
  1114. };
  1115. static std::vector<EnumEntry<unsigned>>
  1116. getSectionFlagsForTarget(unsigned EMachine) {
  1117. std::vector<EnumEntry<unsigned>> Ret(std::begin(ElfSectionFlags),
  1118. std::end(ElfSectionFlags));
  1119. switch (EMachine) {
  1120. case EM_ARM:
  1121. Ret.insert(Ret.end(), std::begin(ElfARMSectionFlags),
  1122. std::end(ElfARMSectionFlags));
  1123. break;
  1124. case EM_HEXAGON:
  1125. Ret.insert(Ret.end(), std::begin(ElfHexagonSectionFlags),
  1126. std::end(ElfHexagonSectionFlags));
  1127. break;
  1128. case EM_MIPS:
  1129. Ret.insert(Ret.end(), std::begin(ElfMipsSectionFlags),
  1130. std::end(ElfMipsSectionFlags));
  1131. break;
  1132. case EM_X86_64:
  1133. Ret.insert(Ret.end(), std::begin(ElfX86_64SectionFlags),
  1134. std::end(ElfX86_64SectionFlags));
  1135. break;
  1136. case EM_XCORE:
  1137. Ret.insert(Ret.end(), std::begin(ElfXCoreSectionFlags),
  1138. std::end(ElfXCoreSectionFlags));
  1139. break;
  1140. default:
  1141. break;
  1142. }
  1143. return Ret;
  1144. }
  1145. static std::string getGNUFlags(unsigned EMachine, uint64_t Flags) {
  1146. // Here we are trying to build the flags string in the same way as GNU does.
  1147. // It is not that straightforward. Imagine we have sh_flags == 0x90000000.
  1148. // SHF_EXCLUDE ("E") has a value of 0x80000000 and SHF_MASKPROC is 0xf0000000.
  1149. // GNU readelf will not print "E" or "Ep" in this case, but will print just
  1150. // "p". It only will print "E" when no other processor flag is set.
  1151. std::string Str;
  1152. bool HasUnknownFlag = false;
  1153. bool HasOSFlag = false;
  1154. bool HasProcFlag = false;
  1155. std::vector<EnumEntry<unsigned>> FlagsList =
  1156. getSectionFlagsForTarget(EMachine);
  1157. while (Flags) {
  1158. // Take the least significant bit as a flag.
  1159. uint64_t Flag = Flags & -Flags;
  1160. Flags -= Flag;
  1161. // Find the flag in the known flags list.
  1162. auto I = llvm::find_if(FlagsList, [=](const EnumEntry<unsigned> &E) {
  1163. // Flags with empty names are not printed in GNU style output.
  1164. return E.Value == Flag && !E.AltName.empty();
  1165. });
  1166. if (I != FlagsList.end()) {
  1167. Str += I->AltName;
  1168. continue;
  1169. }
  1170. // If we did not find a matching regular flag, then we deal with an OS
  1171. // specific flag, processor specific flag or an unknown flag.
  1172. if (Flag & ELF::SHF_MASKOS) {
  1173. HasOSFlag = true;
  1174. Flags &= ~ELF::SHF_MASKOS;
  1175. } else if (Flag & ELF::SHF_MASKPROC) {
  1176. HasProcFlag = true;
  1177. // Mask off all the processor-specific bits. This removes the SHF_EXCLUDE
  1178. // bit if set so that it doesn't also get printed.
  1179. Flags &= ~ELF::SHF_MASKPROC;
  1180. } else {
  1181. HasUnknownFlag = true;
  1182. }
  1183. }
  1184. // "o", "p" and "x" are printed last.
  1185. if (HasOSFlag)
  1186. Str += "o";
  1187. if (HasProcFlag)
  1188. Str += "p";
  1189. if (HasUnknownFlag)
  1190. Str += "x";
  1191. return Str;
  1192. }
  1193. static StringRef segmentTypeToString(unsigned Arch, unsigned Type) {
  1194. // Check potentially overlapped processor-specific program header type.
  1195. switch (Arch) {
  1196. case ELF::EM_ARM:
  1197. switch (Type) { LLVM_READOBJ_ENUM_CASE(ELF, PT_ARM_EXIDX); }
  1198. break;
  1199. case ELF::EM_MIPS:
  1200. case ELF::EM_MIPS_RS3_LE:
  1201. switch (Type) {
  1202. LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_REGINFO);
  1203. LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_RTPROC);
  1204. LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_OPTIONS);
  1205. LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_ABIFLAGS);
  1206. }
  1207. break;
  1208. }
  1209. switch (Type) {
  1210. LLVM_READOBJ_ENUM_CASE(ELF, PT_NULL);
  1211. LLVM_READOBJ_ENUM_CASE(ELF, PT_LOAD);
  1212. LLVM_READOBJ_ENUM_CASE(ELF, PT_DYNAMIC);
  1213. LLVM_READOBJ_ENUM_CASE(ELF, PT_INTERP);
  1214. LLVM_READOBJ_ENUM_CASE(ELF, PT_NOTE);
  1215. LLVM_READOBJ_ENUM_CASE(ELF, PT_SHLIB);
  1216. LLVM_READOBJ_ENUM_CASE(ELF, PT_PHDR);
  1217. LLVM_READOBJ_ENUM_CASE(ELF, PT_TLS);
  1218. LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_EH_FRAME);
  1219. LLVM_READOBJ_ENUM_CASE(ELF, PT_SUNW_UNWIND);
  1220. LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_STACK);
  1221. LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_RELRO);
  1222. LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_PROPERTY);
  1223. LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_RANDOMIZE);
  1224. LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_WXNEEDED);
  1225. LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_BOOTDATA);
  1226. default:
  1227. return "";
  1228. }
  1229. }
  1230. static std::string getGNUPtType(unsigned Arch, unsigned Type) {
  1231. StringRef Seg = segmentTypeToString(Arch, Type);
  1232. if (Seg.empty())
  1233. return std::string("<unknown>: ") + to_string(format_hex(Type, 1));
  1234. // E.g. "PT_ARM_EXIDX" -> "EXIDX".
  1235. if (Seg.startswith("PT_ARM_"))
  1236. return Seg.drop_front(7).str();
  1237. // E.g. "PT_MIPS_REGINFO" -> "REGINFO".
  1238. if (Seg.startswith("PT_MIPS_"))
  1239. return Seg.drop_front(8).str();
  1240. // E.g. "PT_LOAD" -> "LOAD".
  1241. assert(Seg.startswith("PT_"));
  1242. return Seg.drop_front(3).str();
  1243. }
  1244. const EnumEntry<unsigned> ElfSegmentFlags[] = {
  1245. LLVM_READOBJ_ENUM_ENT(ELF, PF_X),
  1246. LLVM_READOBJ_ENUM_ENT(ELF, PF_W),
  1247. LLVM_READOBJ_ENUM_ENT(ELF, PF_R)
  1248. };
  1249. const EnumEntry<unsigned> ElfHeaderMipsFlags[] = {
  1250. ENUM_ENT(EF_MIPS_NOREORDER, "noreorder"),
  1251. ENUM_ENT(EF_MIPS_PIC, "pic"),
  1252. ENUM_ENT(EF_MIPS_CPIC, "cpic"),
  1253. ENUM_ENT(EF_MIPS_ABI2, "abi2"),
  1254. ENUM_ENT(EF_MIPS_32BITMODE, "32bitmode"),
  1255. ENUM_ENT(EF_MIPS_FP64, "fp64"),
  1256. ENUM_ENT(EF_MIPS_NAN2008, "nan2008"),
  1257. ENUM_ENT(EF_MIPS_ABI_O32, "o32"),
  1258. ENUM_ENT(EF_MIPS_ABI_O64, "o64"),
  1259. ENUM_ENT(EF_MIPS_ABI_EABI32, "eabi32"),
  1260. ENUM_ENT(EF_MIPS_ABI_EABI64, "eabi64"),
  1261. ENUM_ENT(EF_MIPS_MACH_3900, "3900"),
  1262. ENUM_ENT(EF_MIPS_MACH_4010, "4010"),
  1263. ENUM_ENT(EF_MIPS_MACH_4100, "4100"),
  1264. ENUM_ENT(EF_MIPS_MACH_4650, "4650"),
  1265. ENUM_ENT(EF_MIPS_MACH_4120, "4120"),
  1266. ENUM_ENT(EF_MIPS_MACH_4111, "4111"),
  1267. ENUM_ENT(EF_MIPS_MACH_SB1, "sb1"),
  1268. ENUM_ENT(EF_MIPS_MACH_OCTEON, "octeon"),
  1269. ENUM_ENT(EF_MIPS_MACH_XLR, "xlr"),
  1270. ENUM_ENT(EF_MIPS_MACH_OCTEON2, "octeon2"),
  1271. ENUM_ENT(EF_MIPS_MACH_OCTEON3, "octeon3"),
  1272. ENUM_ENT(EF_MIPS_MACH_5400, "5400"),
  1273. ENUM_ENT(EF_MIPS_MACH_5900, "5900"),
  1274. ENUM_ENT(EF_MIPS_MACH_5500, "5500"),
  1275. ENUM_ENT(EF_MIPS_MACH_9000, "9000"),
  1276. ENUM_ENT(EF_MIPS_MACH_LS2E, "loongson-2e"),
  1277. ENUM_ENT(EF_MIPS_MACH_LS2F, "loongson-2f"),
  1278. ENUM_ENT(EF_MIPS_MACH_LS3A, "loongson-3a"),
  1279. ENUM_ENT(EF_MIPS_MICROMIPS, "micromips"),
  1280. ENUM_ENT(EF_MIPS_ARCH_ASE_M16, "mips16"),
  1281. ENUM_ENT(EF_MIPS_ARCH_ASE_MDMX, "mdmx"),
  1282. ENUM_ENT(EF_MIPS_ARCH_1, "mips1"),
  1283. ENUM_ENT(EF_MIPS_ARCH_2, "mips2"),
  1284. ENUM_ENT(EF_MIPS_ARCH_3, "mips3"),
  1285. ENUM_ENT(EF_MIPS_ARCH_4, "mips4"),
  1286. ENUM_ENT(EF_MIPS_ARCH_5, "mips5"),
  1287. ENUM_ENT(EF_MIPS_ARCH_32, "mips32"),
  1288. ENUM_ENT(EF_MIPS_ARCH_64, "mips64"),
  1289. ENUM_ENT(EF_MIPS_ARCH_32R2, "mips32r2"),
  1290. ENUM_ENT(EF_MIPS_ARCH_64R2, "mips64r2"),
  1291. ENUM_ENT(EF_MIPS_ARCH_32R6, "mips32r6"),
  1292. ENUM_ENT(EF_MIPS_ARCH_64R6, "mips64r6")
  1293. };
  1294. const EnumEntry<unsigned> ElfHeaderAMDGPUFlagsABIVersion3[] = {
  1295. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_NONE),
  1296. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_R600),
  1297. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_R630),
  1298. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RS880),
  1299. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV670),
  1300. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV710),
  1301. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV730),
  1302. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV770),
  1303. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CEDAR),
  1304. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CYPRESS),
  1305. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_JUNIPER),
  1306. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_REDWOOD),
  1307. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_SUMO),
  1308. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_BARTS),
  1309. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CAICOS),
  1310. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CAYMAN),
  1311. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_TURKS),
  1312. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX600),
  1313. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX601),
  1314. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX602),
  1315. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX700),
  1316. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX701),
  1317. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX702),
  1318. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX703),
  1319. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX704),
  1320. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX705),
  1321. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX801),
  1322. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX802),
  1323. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX803),
  1324. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX805),
  1325. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX810),
  1326. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX900),
  1327. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX902),
  1328. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX904),
  1329. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX906),
  1330. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX908),
  1331. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX909),
  1332. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX90A),
  1333. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX90C),
  1334. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1010),
  1335. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1011),
  1336. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1012),
  1337. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1013),
  1338. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1030),
  1339. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1031),
  1340. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1032),
  1341. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1033),
  1342. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1034),
  1343. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1035),
  1344. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_XNACK_V3),
  1345. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_SRAMECC_V3)
  1346. };
  1347. const EnumEntry<unsigned> ElfHeaderAMDGPUFlagsABIVersion4[] = {
  1348. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_NONE),
  1349. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_R600),
  1350. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_R630),
  1351. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RS880),
  1352. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV670),
  1353. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV710),
  1354. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV730),
  1355. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV770),
  1356. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CEDAR),
  1357. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CYPRESS),
  1358. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_JUNIPER),
  1359. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_REDWOOD),
  1360. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_SUMO),
  1361. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_BARTS),
  1362. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CAICOS),
  1363. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CAYMAN),
  1364. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_TURKS),
  1365. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX600),
  1366. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX601),
  1367. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX602),
  1368. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX700),
  1369. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX701),
  1370. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX702),
  1371. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX703),
  1372. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX704),
  1373. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX705),
  1374. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX801),
  1375. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX802),
  1376. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX803),
  1377. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX805),
  1378. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX810),
  1379. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX900),
  1380. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX902),
  1381. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX904),
  1382. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX906),
  1383. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX908),
  1384. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX909),
  1385. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX90A),
  1386. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX90C),
  1387. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1010),
  1388. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1011),
  1389. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1012),
  1390. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1013),
  1391. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1030),
  1392. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1031),
  1393. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1032),
  1394. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1033),
  1395. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1034),
  1396. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1035),
  1397. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_XNACK_ANY_V4),
  1398. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_XNACK_OFF_V4),
  1399. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_XNACK_ON_V4),
  1400. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_SRAMECC_ANY_V4),
  1401. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_SRAMECC_OFF_V4),
  1402. LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_SRAMECC_ON_V4)
  1403. };
  1404. const EnumEntry<unsigned> ElfHeaderRISCVFlags[] = {
  1405. ENUM_ENT(EF_RISCV_RVC, "RVC"),
  1406. ENUM_ENT(EF_RISCV_FLOAT_ABI_SINGLE, "single-float ABI"),
  1407. ENUM_ENT(EF_RISCV_FLOAT_ABI_DOUBLE, "double-float ABI"),
  1408. ENUM_ENT(EF_RISCV_FLOAT_ABI_QUAD, "quad-float ABI"),
  1409. ENUM_ENT(EF_RISCV_RVE, "RVE"),
  1410. ENUM_ENT(EF_RISCV_TSO, "TSO"),
  1411. };
  1412. const EnumEntry<unsigned> ElfHeaderAVRFlags[] = {
  1413. LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR1),
  1414. LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR2),
  1415. LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR25),
  1416. LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR3),
  1417. LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR31),
  1418. LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR35),
  1419. LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR4),
  1420. LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR5),
  1421. LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR51),
  1422. LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR6),
  1423. LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVRTINY),
  1424. LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA1),
  1425. LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA2),
  1426. LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA3),
  1427. LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA4),
  1428. LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA5),
  1429. LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA6),
  1430. LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA7),
  1431. ENUM_ENT(EF_AVR_LINKRELAX_PREPARED, "relaxable"),
  1432. };
  1433. const EnumEntry<unsigned> ElfSymOtherFlags[] = {
  1434. LLVM_READOBJ_ENUM_ENT(ELF, STV_INTERNAL),
  1435. LLVM_READOBJ_ENUM_ENT(ELF, STV_HIDDEN),
  1436. LLVM_READOBJ_ENUM_ENT(ELF, STV_PROTECTED)
  1437. };
  1438. const EnumEntry<unsigned> ElfMipsSymOtherFlags[] = {
  1439. LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_OPTIONAL),
  1440. LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PLT),
  1441. LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PIC),
  1442. LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_MICROMIPS)
  1443. };
  1444. const EnumEntry<unsigned> ElfAArch64SymOtherFlags[] = {
  1445. LLVM_READOBJ_ENUM_ENT(ELF, STO_AARCH64_VARIANT_PCS)
  1446. };
  1447. const EnumEntry<unsigned> ElfMips16SymOtherFlags[] = {
  1448. LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_OPTIONAL),
  1449. LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PLT),
  1450. LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_MIPS16)
  1451. };
  1452. const EnumEntry<unsigned> ElfRISCVSymOtherFlags[] = {
  1453. LLVM_READOBJ_ENUM_ENT(ELF, STO_RISCV_VARIANT_CC)};
  1454. static const char *getElfMipsOptionsOdkType(unsigned Odk) {
  1455. switch (Odk) {
  1456. LLVM_READOBJ_ENUM_CASE(ELF, ODK_NULL);
  1457. LLVM_READOBJ_ENUM_CASE(ELF, ODK_REGINFO);
  1458. LLVM_READOBJ_ENUM_CASE(ELF, ODK_EXCEPTIONS);
  1459. LLVM_READOBJ_ENUM_CASE(ELF, ODK_PAD);
  1460. LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWPATCH);
  1461. LLVM_READOBJ_ENUM_CASE(ELF, ODK_FILL);
  1462. LLVM_READOBJ_ENUM_CASE(ELF, ODK_TAGS);
  1463. LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWAND);
  1464. LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWOR);
  1465. LLVM_READOBJ_ENUM_CASE(ELF, ODK_GP_GROUP);
  1466. LLVM_READOBJ_ENUM_CASE(ELF, ODK_IDENT);
  1467. LLVM_READOBJ_ENUM_CASE(ELF, ODK_PAGESIZE);
  1468. default:
  1469. return "Unknown";
  1470. }
  1471. }
  1472. template <typename ELFT>
  1473. std::pair<const typename ELFT::Phdr *, const typename ELFT::Shdr *>
  1474. ELFDumper<ELFT>::findDynamic() {
  1475. // Try to locate the PT_DYNAMIC header.
  1476. const Elf_Phdr *DynamicPhdr = nullptr;
  1477. if (Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = Obj.program_headers()) {
  1478. for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
  1479. if (Phdr.p_type != ELF::PT_DYNAMIC)
  1480. continue;
  1481. DynamicPhdr = &Phdr;
  1482. break;
  1483. }
  1484. } else {
  1485. reportUniqueWarning(
  1486. "unable to read program headers to locate the PT_DYNAMIC segment: " +
  1487. toString(PhdrsOrErr.takeError()));
  1488. }
  1489. // Try to locate the .dynamic section in the sections header table.
  1490. const Elf_Shdr *DynamicSec = nullptr;
  1491. for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
  1492. if (Sec.sh_type != ELF::SHT_DYNAMIC)
  1493. continue;
  1494. DynamicSec = &Sec;
  1495. break;
  1496. }
  1497. if (DynamicPhdr && ((DynamicPhdr->p_offset + DynamicPhdr->p_filesz >
  1498. ObjF.getMemoryBufferRef().getBufferSize()) ||
  1499. (DynamicPhdr->p_offset + DynamicPhdr->p_filesz <
  1500. DynamicPhdr->p_offset))) {
  1501. reportUniqueWarning(
  1502. "PT_DYNAMIC segment offset (0x" +
  1503. Twine::utohexstr(DynamicPhdr->p_offset) + ") + file size (0x" +
  1504. Twine::utohexstr(DynamicPhdr->p_filesz) +
  1505. ") exceeds the size of the file (0x" +
  1506. Twine::utohexstr(ObjF.getMemoryBufferRef().getBufferSize()) + ")");
  1507. // Don't use the broken dynamic header.
  1508. DynamicPhdr = nullptr;
  1509. }
  1510. if (DynamicPhdr && DynamicSec) {
  1511. if (DynamicSec->sh_addr + DynamicSec->sh_size >
  1512. DynamicPhdr->p_vaddr + DynamicPhdr->p_memsz ||
  1513. DynamicSec->sh_addr < DynamicPhdr->p_vaddr)
  1514. reportUniqueWarning(describe(*DynamicSec) +
  1515. " is not contained within the "
  1516. "PT_DYNAMIC segment");
  1517. if (DynamicSec->sh_addr != DynamicPhdr->p_vaddr)
  1518. reportUniqueWarning(describe(*DynamicSec) + " is not at the start of "
  1519. "PT_DYNAMIC segment");
  1520. }
  1521. return std::make_pair(DynamicPhdr, DynamicSec);
  1522. }
  1523. template <typename ELFT>
  1524. void ELFDumper<ELFT>::loadDynamicTable() {
  1525. const Elf_Phdr *DynamicPhdr;
  1526. const Elf_Shdr *DynamicSec;
  1527. std::tie(DynamicPhdr, DynamicSec) = findDynamic();
  1528. if (!DynamicPhdr && !DynamicSec)
  1529. return;
  1530. DynRegionInfo FromPhdr(ObjF, *this);
  1531. bool IsPhdrTableValid = false;
  1532. if (DynamicPhdr) {
  1533. // Use cantFail(), because p_offset/p_filesz fields of a PT_DYNAMIC are
  1534. // validated in findDynamic() and so createDRI() is not expected to fail.
  1535. FromPhdr = cantFail(createDRI(DynamicPhdr->p_offset, DynamicPhdr->p_filesz,
  1536. sizeof(Elf_Dyn)));
  1537. FromPhdr.SizePrintName = "PT_DYNAMIC size";
  1538. FromPhdr.EntSizePrintName = "";
  1539. IsPhdrTableValid = !FromPhdr.template getAsArrayRef<Elf_Dyn>().empty();
  1540. }
  1541. // Locate the dynamic table described in a section header.
  1542. // Ignore sh_entsize and use the expected value for entry size explicitly.
  1543. // This allows us to dump dynamic sections with a broken sh_entsize
  1544. // field.
  1545. DynRegionInfo FromSec(ObjF, *this);
  1546. bool IsSecTableValid = false;
  1547. if (DynamicSec) {
  1548. Expected<DynRegionInfo> RegOrErr =
  1549. createDRI(DynamicSec->sh_offset, DynamicSec->sh_size, sizeof(Elf_Dyn));
  1550. if (RegOrErr) {
  1551. FromSec = *RegOrErr;
  1552. FromSec.Context = describe(*DynamicSec);
  1553. FromSec.EntSizePrintName = "";
  1554. IsSecTableValid = !FromSec.template getAsArrayRef<Elf_Dyn>().empty();
  1555. } else {
  1556. reportUniqueWarning("unable to read the dynamic table from " +
  1557. describe(*DynamicSec) + ": " +
  1558. toString(RegOrErr.takeError()));
  1559. }
  1560. }
  1561. // When we only have information from one of the SHT_DYNAMIC section header or
  1562. // PT_DYNAMIC program header, just use that.
  1563. if (!DynamicPhdr || !DynamicSec) {
  1564. if ((DynamicPhdr && IsPhdrTableValid) || (DynamicSec && IsSecTableValid)) {
  1565. DynamicTable = DynamicPhdr ? FromPhdr : FromSec;
  1566. parseDynamicTable();
  1567. } else {
  1568. reportUniqueWarning("no valid dynamic table was found");
  1569. }
  1570. return;
  1571. }
  1572. // At this point we have tables found from the section header and from the
  1573. // dynamic segment. Usually they match, but we have to do sanity checks to
  1574. // verify that.
  1575. if (FromPhdr.Addr != FromSec.Addr)
  1576. reportUniqueWarning("SHT_DYNAMIC section header and PT_DYNAMIC "
  1577. "program header disagree about "
  1578. "the location of the dynamic table");
  1579. if (!IsPhdrTableValid && !IsSecTableValid) {
  1580. reportUniqueWarning("no valid dynamic table was found");
  1581. return;
  1582. }
  1583. // Information in the PT_DYNAMIC program header has priority over the
  1584. // information in a section header.
  1585. if (IsPhdrTableValid) {
  1586. if (!IsSecTableValid)
  1587. reportUniqueWarning(
  1588. "SHT_DYNAMIC dynamic table is invalid: PT_DYNAMIC will be used");
  1589. DynamicTable = FromPhdr;
  1590. } else {
  1591. reportUniqueWarning(
  1592. "PT_DYNAMIC dynamic table is invalid: SHT_DYNAMIC will be used");
  1593. DynamicTable = FromSec;
  1594. }
  1595. parseDynamicTable();
  1596. }
  1597. template <typename ELFT>
  1598. ELFDumper<ELFT>::ELFDumper(const object::ELFObjectFile<ELFT> &O,
  1599. ScopedPrinter &Writer)
  1600. : ObjDumper(Writer, O.getFileName()), ObjF(O), Obj(O.getELFFile()),
  1601. FileName(O.getFileName()), DynRelRegion(O, *this),
  1602. DynRelaRegion(O, *this), DynRelrRegion(O, *this),
  1603. DynPLTRelRegion(O, *this), DynSymTabShndxRegion(O, *this),
  1604. DynamicTable(O, *this) {
  1605. if (!O.IsContentValid())
  1606. return;
  1607. typename ELFT::ShdrRange Sections = cantFail(Obj.sections());
  1608. for (const Elf_Shdr &Sec : Sections) {
  1609. switch (Sec.sh_type) {
  1610. case ELF::SHT_SYMTAB:
  1611. if (!DotSymtabSec)
  1612. DotSymtabSec = &Sec;
  1613. break;
  1614. case ELF::SHT_DYNSYM:
  1615. if (!DotDynsymSec)
  1616. DotDynsymSec = &Sec;
  1617. if (!DynSymRegion) {
  1618. Expected<DynRegionInfo> RegOrErr =
  1619. createDRI(Sec.sh_offset, Sec.sh_size, Sec.sh_entsize);
  1620. if (RegOrErr) {
  1621. DynSymRegion = *RegOrErr;
  1622. DynSymRegion->Context = describe(Sec);
  1623. if (Expected<StringRef> E = Obj.getStringTableForSymtab(Sec))
  1624. DynamicStringTable = *E;
  1625. else
  1626. reportUniqueWarning("unable to get the string table for the " +
  1627. describe(Sec) + ": " + toString(E.takeError()));
  1628. } else {
  1629. reportUniqueWarning("unable to read dynamic symbols from " +
  1630. describe(Sec) + ": " +
  1631. toString(RegOrErr.takeError()));
  1632. }
  1633. }
  1634. break;
  1635. case ELF::SHT_SYMTAB_SHNDX: {
  1636. uint32_t SymtabNdx = Sec.sh_link;
  1637. if (SymtabNdx >= Sections.size()) {
  1638. reportUniqueWarning(
  1639. "unable to get the associated symbol table for " + describe(Sec) +
  1640. ": sh_link (" + Twine(SymtabNdx) +
  1641. ") is greater than or equal to the total number of sections (" +
  1642. Twine(Sections.size()) + ")");
  1643. continue;
  1644. }
  1645. if (Expected<ArrayRef<Elf_Word>> ShndxTableOrErr =
  1646. Obj.getSHNDXTable(Sec)) {
  1647. if (!ShndxTables.insert({&Sections[SymtabNdx], *ShndxTableOrErr})
  1648. .second)
  1649. reportUniqueWarning(
  1650. "multiple SHT_SYMTAB_SHNDX sections are linked to " +
  1651. describe(Sec));
  1652. } else {
  1653. reportUniqueWarning(ShndxTableOrErr.takeError());
  1654. }
  1655. break;
  1656. }
  1657. case ELF::SHT_GNU_versym:
  1658. if (!SymbolVersionSection)
  1659. SymbolVersionSection = &Sec;
  1660. break;
  1661. case ELF::SHT_GNU_verdef:
  1662. if (!SymbolVersionDefSection)
  1663. SymbolVersionDefSection = &Sec;
  1664. break;
  1665. case ELF::SHT_GNU_verneed:
  1666. if (!SymbolVersionNeedSection)
  1667. SymbolVersionNeedSection = &Sec;
  1668. break;
  1669. case ELF::SHT_LLVM_ADDRSIG:
  1670. if (!DotAddrsigSec)
  1671. DotAddrsigSec = &Sec;
  1672. break;
  1673. }
  1674. }
  1675. loadDynamicTable();
  1676. }
  1677. template <typename ELFT> void ELFDumper<ELFT>::parseDynamicTable() {
  1678. auto toMappedAddr = [&](uint64_t Tag, uint64_t VAddr) -> const uint8_t * {
  1679. auto MappedAddrOrError = Obj.toMappedAddr(VAddr, [&](const Twine &Msg) {
  1680. this->reportUniqueWarning(Msg);
  1681. return Error::success();
  1682. });
  1683. if (!MappedAddrOrError) {
  1684. this->reportUniqueWarning("unable to parse DT_" +
  1685. Obj.getDynamicTagAsString(Tag) + ": " +
  1686. llvm::toString(MappedAddrOrError.takeError()));
  1687. return nullptr;
  1688. }
  1689. return MappedAddrOrError.get();
  1690. };
  1691. const char *StringTableBegin = nullptr;
  1692. uint64_t StringTableSize = 0;
  1693. Optional<DynRegionInfo> DynSymFromTable;
  1694. for (const Elf_Dyn &Dyn : dynamic_table()) {
  1695. switch (Dyn.d_tag) {
  1696. case ELF::DT_HASH:
  1697. HashTable = reinterpret_cast<const Elf_Hash *>(
  1698. toMappedAddr(Dyn.getTag(), Dyn.getPtr()));
  1699. break;
  1700. case ELF::DT_GNU_HASH:
  1701. GnuHashTable = reinterpret_cast<const Elf_GnuHash *>(
  1702. toMappedAddr(Dyn.getTag(), Dyn.getPtr()));
  1703. break;
  1704. case ELF::DT_STRTAB:
  1705. StringTableBegin = reinterpret_cast<const char *>(
  1706. toMappedAddr(Dyn.getTag(), Dyn.getPtr()));
  1707. break;
  1708. case ELF::DT_STRSZ:
  1709. StringTableSize = Dyn.getVal();
  1710. break;
  1711. case ELF::DT_SYMTAB: {
  1712. // If we can't map the DT_SYMTAB value to an address (e.g. when there are
  1713. // no program headers), we ignore its value.
  1714. if (const uint8_t *VA = toMappedAddr(Dyn.getTag(), Dyn.getPtr())) {
  1715. DynSymFromTable.emplace(ObjF, *this);
  1716. DynSymFromTable->Addr = VA;
  1717. DynSymFromTable->EntSize = sizeof(Elf_Sym);
  1718. DynSymFromTable->EntSizePrintName = "";
  1719. }
  1720. break;
  1721. }
  1722. case ELF::DT_SYMENT: {
  1723. uint64_t Val = Dyn.getVal();
  1724. if (Val != sizeof(Elf_Sym))
  1725. this->reportUniqueWarning("DT_SYMENT value of 0x" +
  1726. Twine::utohexstr(Val) +
  1727. " is not the size of a symbol (0x" +
  1728. Twine::utohexstr(sizeof(Elf_Sym)) + ")");
  1729. break;
  1730. }
  1731. case ELF::DT_RELA:
  1732. DynRelaRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
  1733. break;
  1734. case ELF::DT_RELASZ:
  1735. DynRelaRegion.Size = Dyn.getVal();
  1736. DynRelaRegion.SizePrintName = "DT_RELASZ value";
  1737. break;
  1738. case ELF::DT_RELAENT:
  1739. DynRelaRegion.EntSize = Dyn.getVal();
  1740. DynRelaRegion.EntSizePrintName = "DT_RELAENT value";
  1741. break;
  1742. case ELF::DT_SONAME:
  1743. SONameOffset = Dyn.getVal();
  1744. break;
  1745. case ELF::DT_REL:
  1746. DynRelRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
  1747. break;
  1748. case ELF::DT_RELSZ:
  1749. DynRelRegion.Size = Dyn.getVal();
  1750. DynRelRegion.SizePrintName = "DT_RELSZ value";
  1751. break;
  1752. case ELF::DT_RELENT:
  1753. DynRelRegion.EntSize = Dyn.getVal();
  1754. DynRelRegion.EntSizePrintName = "DT_RELENT value";
  1755. break;
  1756. case ELF::DT_RELR:
  1757. case ELF::DT_ANDROID_RELR:
  1758. DynRelrRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
  1759. break;
  1760. case ELF::DT_RELRSZ:
  1761. case ELF::DT_ANDROID_RELRSZ:
  1762. DynRelrRegion.Size = Dyn.getVal();
  1763. DynRelrRegion.SizePrintName = Dyn.d_tag == ELF::DT_RELRSZ
  1764. ? "DT_RELRSZ value"
  1765. : "DT_ANDROID_RELRSZ value";
  1766. break;
  1767. case ELF::DT_RELRENT:
  1768. case ELF::DT_ANDROID_RELRENT:
  1769. DynRelrRegion.EntSize = Dyn.getVal();
  1770. DynRelrRegion.EntSizePrintName = Dyn.d_tag == ELF::DT_RELRENT
  1771. ? "DT_RELRENT value"
  1772. : "DT_ANDROID_RELRENT value";
  1773. break;
  1774. case ELF::DT_PLTREL:
  1775. if (Dyn.getVal() == DT_REL)
  1776. DynPLTRelRegion.EntSize = sizeof(Elf_Rel);
  1777. else if (Dyn.getVal() == DT_RELA)
  1778. DynPLTRelRegion.EntSize = sizeof(Elf_Rela);
  1779. else
  1780. reportUniqueWarning(Twine("unknown DT_PLTREL value of ") +
  1781. Twine((uint64_t)Dyn.getVal()));
  1782. DynPLTRelRegion.EntSizePrintName = "PLTREL entry size";
  1783. break;
  1784. case ELF::DT_JMPREL:
  1785. DynPLTRelRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
  1786. break;
  1787. case ELF::DT_PLTRELSZ:
  1788. DynPLTRelRegion.Size = Dyn.getVal();
  1789. DynPLTRelRegion.SizePrintName = "DT_PLTRELSZ value";
  1790. break;
  1791. case ELF::DT_SYMTAB_SHNDX:
  1792. DynSymTabShndxRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
  1793. DynSymTabShndxRegion.EntSize = sizeof(Elf_Word);
  1794. break;
  1795. }
  1796. }
  1797. if (StringTableBegin) {
  1798. const uint64_t FileSize = Obj.getBufSize();
  1799. const uint64_t Offset = (const uint8_t *)StringTableBegin - Obj.base();
  1800. if (StringTableSize > FileSize - Offset)
  1801. reportUniqueWarning(
  1802. "the dynamic string table at 0x" + Twine::utohexstr(Offset) +
  1803. " goes past the end of the file (0x" + Twine::utohexstr(FileSize) +
  1804. ") with DT_STRSZ = 0x" + Twine::utohexstr(StringTableSize));
  1805. else
  1806. DynamicStringTable = StringRef(StringTableBegin, StringTableSize);
  1807. }
  1808. const bool IsHashTableSupported = getHashTableEntSize() == 4;
  1809. if (DynSymRegion) {
  1810. // Often we find the information about the dynamic symbol table
  1811. // location in the SHT_DYNSYM section header. However, the value in
  1812. // DT_SYMTAB has priority, because it is used by dynamic loaders to
  1813. // locate .dynsym at runtime. The location we find in the section header
  1814. // and the location we find here should match.
  1815. if (DynSymFromTable && DynSymFromTable->Addr != DynSymRegion->Addr)
  1816. reportUniqueWarning(
  1817. createError("SHT_DYNSYM section header and DT_SYMTAB disagree about "
  1818. "the location of the dynamic symbol table"));
  1819. // According to the ELF gABI: "The number of symbol table entries should
  1820. // equal nchain". Check to see if the DT_HASH hash table nchain value
  1821. // conflicts with the number of symbols in the dynamic symbol table
  1822. // according to the section header.
  1823. if (HashTable && IsHashTableSupported) {
  1824. if (DynSymRegion->EntSize == 0)
  1825. reportUniqueWarning("SHT_DYNSYM section has sh_entsize == 0");
  1826. else if (HashTable->nchain != DynSymRegion->Size / DynSymRegion->EntSize)
  1827. reportUniqueWarning(
  1828. "hash table nchain (" + Twine(HashTable->nchain) +
  1829. ") differs from symbol count derived from SHT_DYNSYM section "
  1830. "header (" +
  1831. Twine(DynSymRegion->Size / DynSymRegion->EntSize) + ")");
  1832. }
  1833. }
  1834. // Delay the creation of the actual dynamic symbol table until now, so that
  1835. // checks can always be made against the section header-based properties,
  1836. // without worrying about tag order.
  1837. if (DynSymFromTable) {
  1838. if (!DynSymRegion) {
  1839. DynSymRegion = DynSymFromTable;
  1840. } else {
  1841. DynSymRegion->Addr = DynSymFromTable->Addr;
  1842. DynSymRegion->EntSize = DynSymFromTable->EntSize;
  1843. DynSymRegion->EntSizePrintName = DynSymFromTable->EntSizePrintName;
  1844. }
  1845. }
  1846. // Derive the dynamic symbol table size from the DT_HASH hash table, if
  1847. // present.
  1848. if (HashTable && IsHashTableSupported && DynSymRegion) {
  1849. const uint64_t FileSize = Obj.getBufSize();
  1850. const uint64_t DerivedSize =
  1851. (uint64_t)HashTable->nchain * DynSymRegion->EntSize;
  1852. const uint64_t Offset = (const uint8_t *)DynSymRegion->Addr - Obj.base();
  1853. if (DerivedSize > FileSize - Offset)
  1854. reportUniqueWarning(
  1855. "the size (0x" + Twine::utohexstr(DerivedSize) +
  1856. ") of the dynamic symbol table at 0x" + Twine::utohexstr(Offset) +
  1857. ", derived from the hash table, goes past the end of the file (0x" +
  1858. Twine::utohexstr(FileSize) + ") and will be ignored");
  1859. else
  1860. DynSymRegion->Size = HashTable->nchain * DynSymRegion->EntSize;
  1861. }
  1862. }
  1863. template <typename ELFT> void ELFDumper<ELFT>::printVersionInfo() {
  1864. // Dump version symbol section.
  1865. printVersionSymbolSection(SymbolVersionSection);
  1866. // Dump version definition section.
  1867. printVersionDefinitionSection(SymbolVersionDefSection);
  1868. // Dump version dependency section.
  1869. printVersionDependencySection(SymbolVersionNeedSection);
  1870. }
  1871. #define LLVM_READOBJ_DT_FLAG_ENT(prefix, enum) \
  1872. { #enum, prefix##_##enum }
  1873. const EnumEntry<unsigned> ElfDynamicDTFlags[] = {
  1874. LLVM_READOBJ_DT_FLAG_ENT(DF, ORIGIN),
  1875. LLVM_READOBJ_DT_FLAG_ENT(DF, SYMBOLIC),
  1876. LLVM_READOBJ_DT_FLAG_ENT(DF, TEXTREL),
  1877. LLVM_READOBJ_DT_FLAG_ENT(DF, BIND_NOW),
  1878. LLVM_READOBJ_DT_FLAG_ENT(DF, STATIC_TLS)
  1879. };
  1880. const EnumEntry<unsigned> ElfDynamicDTFlags1[] = {
  1881. LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOW),
  1882. LLVM_READOBJ_DT_FLAG_ENT(DF_1, GLOBAL),
  1883. LLVM_READOBJ_DT_FLAG_ENT(DF_1, GROUP),
  1884. LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODELETE),
  1885. LLVM_READOBJ_DT_FLAG_ENT(DF_1, LOADFLTR),
  1886. LLVM_READOBJ_DT_FLAG_ENT(DF_1, INITFIRST),
  1887. LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOOPEN),
  1888. LLVM_READOBJ_DT_FLAG_ENT(DF_1, ORIGIN),
  1889. LLVM_READOBJ_DT_FLAG_ENT(DF_1, DIRECT),
  1890. LLVM_READOBJ_DT_FLAG_ENT(DF_1, TRANS),
  1891. LLVM_READOBJ_DT_FLAG_ENT(DF_1, INTERPOSE),
  1892. LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODEFLIB),
  1893. LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODUMP),
  1894. LLVM_READOBJ_DT_FLAG_ENT(DF_1, CONFALT),
  1895. LLVM_READOBJ_DT_FLAG_ENT(DF_1, ENDFILTEE),
  1896. LLVM_READOBJ_DT_FLAG_ENT(DF_1, DISPRELDNE),
  1897. LLVM_READOBJ_DT_FLAG_ENT(DF_1, DISPRELPND),
  1898. LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODIRECT),
  1899. LLVM_READOBJ_DT_FLAG_ENT(DF_1, IGNMULDEF),
  1900. LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOKSYMS),
  1901. LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOHDR),
  1902. LLVM_READOBJ_DT_FLAG_ENT(DF_1, EDITED),
  1903. LLVM_READOBJ_DT_FLAG_ENT(DF_1, NORELOC),
  1904. LLVM_READOBJ_DT_FLAG_ENT(DF_1, SYMINTPOSE),
  1905. LLVM_READOBJ_DT_FLAG_ENT(DF_1, GLOBAUDIT),
  1906. LLVM_READOBJ_DT_FLAG_ENT(DF_1, SINGLETON),
  1907. LLVM_READOBJ_DT_FLAG_ENT(DF_1, PIE),
  1908. };
  1909. const EnumEntry<unsigned> ElfDynamicDTMipsFlags[] = {
  1910. LLVM_READOBJ_DT_FLAG_ENT(RHF, NONE),
  1911. LLVM_READOBJ_DT_FLAG_ENT(RHF, QUICKSTART),
  1912. LLVM_READOBJ_DT_FLAG_ENT(RHF, NOTPOT),
  1913. LLVM_READOBJ_DT_FLAG_ENT(RHS, NO_LIBRARY_REPLACEMENT),
  1914. LLVM_READOBJ_DT_FLAG_ENT(RHF, NO_MOVE),
  1915. LLVM_READOBJ_DT_FLAG_ENT(RHF, SGI_ONLY),
  1916. LLVM_READOBJ_DT_FLAG_ENT(RHF, GUARANTEE_INIT),
  1917. LLVM_READOBJ_DT_FLAG_ENT(RHF, DELTA_C_PLUS_PLUS),
  1918. LLVM_READOBJ_DT_FLAG_ENT(RHF, GUARANTEE_START_INIT),
  1919. LLVM_READOBJ_DT_FLAG_ENT(RHF, PIXIE),
  1920. LLVM_READOBJ_DT_FLAG_ENT(RHF, DEFAULT_DELAY_LOAD),
  1921. LLVM_READOBJ_DT_FLAG_ENT(RHF, REQUICKSTART),
  1922. LLVM_READOBJ_DT_FLAG_ENT(RHF, REQUICKSTARTED),
  1923. LLVM_READOBJ_DT_FLAG_ENT(RHF, CORD),
  1924. LLVM_READOBJ_DT_FLAG_ENT(RHF, NO_UNRES_UNDEF),
  1925. LLVM_READOBJ_DT_FLAG_ENT(RHF, RLD_ORDER_SAFE)
  1926. };
  1927. #undef LLVM_READOBJ_DT_FLAG_ENT
  1928. template <typename T, typename TFlag>
  1929. void printFlags(T Value, ArrayRef<EnumEntry<TFlag>> Flags, raw_ostream &OS) {
  1930. SmallVector<EnumEntry<TFlag>, 10> SetFlags;
  1931. for (const EnumEntry<TFlag> &Flag : Flags)
  1932. if (Flag.Value != 0 && (Value & Flag.Value) == Flag.Value)
  1933. SetFlags.push_back(Flag);
  1934. for (const EnumEntry<TFlag> &Flag : SetFlags)
  1935. OS << Flag.Name << " ";
  1936. }
  1937. template <class ELFT>
  1938. const typename ELFT::Shdr *
  1939. ELFDumper<ELFT>::findSectionByName(StringRef Name) const {
  1940. for (const Elf_Shdr &Shdr : cantFail(Obj.sections())) {
  1941. if (Expected<StringRef> NameOrErr = Obj.getSectionName(Shdr)) {
  1942. if (*NameOrErr == Name)
  1943. return &Shdr;
  1944. } else {
  1945. reportUniqueWarning("unable to read the name of " + describe(Shdr) +
  1946. ": " + toString(NameOrErr.takeError()));
  1947. }
  1948. }
  1949. return nullptr;
  1950. }
  1951. template <class ELFT>
  1952. std::string ELFDumper<ELFT>::getDynamicEntry(uint64_t Type,
  1953. uint64_t Value) const {
  1954. auto FormatHexValue = [](uint64_t V) {
  1955. std::string Str;
  1956. raw_string_ostream OS(Str);
  1957. const char *ConvChar =
  1958. (opts::Output == opts::GNU) ? "0x%" PRIx64 : "0x%" PRIX64;
  1959. OS << format(ConvChar, V);
  1960. return OS.str();
  1961. };
  1962. auto FormatFlags = [](uint64_t V,
  1963. llvm::ArrayRef<llvm::EnumEntry<unsigned int>> Array) {
  1964. std::string Str;
  1965. raw_string_ostream OS(Str);
  1966. printFlags(V, Array, OS);
  1967. return OS.str();
  1968. };
  1969. // Handle custom printing of architecture specific tags
  1970. switch (Obj.getHeader().e_machine) {
  1971. case EM_AARCH64:
  1972. switch (Type) {
  1973. case DT_AARCH64_BTI_PLT:
  1974. case DT_AARCH64_PAC_PLT:
  1975. case DT_AARCH64_VARIANT_PCS:
  1976. return std::to_string(Value);
  1977. default:
  1978. break;
  1979. }
  1980. break;
  1981. case EM_HEXAGON:
  1982. switch (Type) {
  1983. case DT_HEXAGON_VER:
  1984. return std::to_string(Value);
  1985. case DT_HEXAGON_SYMSZ:
  1986. case DT_HEXAGON_PLT:
  1987. return FormatHexValue(Value);
  1988. default:
  1989. break;
  1990. }
  1991. break;
  1992. case EM_MIPS:
  1993. switch (Type) {
  1994. case DT_MIPS_RLD_VERSION:
  1995. case DT_MIPS_LOCAL_GOTNO:
  1996. case DT_MIPS_SYMTABNO:
  1997. case DT_MIPS_UNREFEXTNO:
  1998. return std::to_string(Value);
  1999. case DT_MIPS_TIME_STAMP:
  2000. case DT_MIPS_ICHECKSUM:
  2001. case DT_MIPS_IVERSION:
  2002. case DT_MIPS_BASE_ADDRESS:
  2003. case DT_MIPS_MSYM:
  2004. case DT_MIPS_CONFLICT:
  2005. case DT_MIPS_LIBLIST:
  2006. case DT_MIPS_CONFLICTNO:
  2007. case DT_MIPS_LIBLISTNO:
  2008. case DT_MIPS_GOTSYM:
  2009. case DT_MIPS_HIPAGENO:
  2010. case DT_MIPS_RLD_MAP:
  2011. case DT_MIPS_DELTA_CLASS:
  2012. case DT_MIPS_DELTA_CLASS_NO:
  2013. case DT_MIPS_DELTA_INSTANCE:
  2014. case DT_MIPS_DELTA_RELOC:
  2015. case DT_MIPS_DELTA_RELOC_NO:
  2016. case DT_MIPS_DELTA_SYM:
  2017. case DT_MIPS_DELTA_SYM_NO:
  2018. case DT_MIPS_DELTA_CLASSSYM:
  2019. case DT_MIPS_DELTA_CLASSSYM_NO:
  2020. case DT_MIPS_CXX_FLAGS:
  2021. case DT_MIPS_PIXIE_INIT:
  2022. case DT_MIPS_SYMBOL_LIB:
  2023. case DT_MIPS_LOCALPAGE_GOTIDX:
  2024. case DT_MIPS_LOCAL_GOTIDX:
  2025. case DT_MIPS_HIDDEN_GOTIDX:
  2026. case DT_MIPS_PROTECTED_GOTIDX:
  2027. case DT_MIPS_OPTIONS:
  2028. case DT_MIPS_INTERFACE:
  2029. case DT_MIPS_DYNSTR_ALIGN:
  2030. case DT_MIPS_INTERFACE_SIZE:
  2031. case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
  2032. case DT_MIPS_PERF_SUFFIX:
  2033. case DT_MIPS_COMPACT_SIZE:
  2034. case DT_MIPS_GP_VALUE:
  2035. case DT_MIPS_AUX_DYNAMIC:
  2036. case DT_MIPS_PLTGOT:
  2037. case DT_MIPS_RWPLT:
  2038. case DT_MIPS_RLD_MAP_REL:
  2039. case DT_MIPS_XHASH:
  2040. return FormatHexValue(Value);
  2041. case DT_MIPS_FLAGS:
  2042. return FormatFlags(Value, makeArrayRef(ElfDynamicDTMipsFlags));
  2043. default:
  2044. break;
  2045. }
  2046. break;
  2047. default:
  2048. break;
  2049. }
  2050. switch (Type) {
  2051. case DT_PLTREL:
  2052. if (Value == DT_REL)
  2053. return "REL";
  2054. if (Value == DT_RELA)
  2055. return "RELA";
  2056. LLVM_FALLTHROUGH;
  2057. case DT_PLTGOT:
  2058. case DT_HASH:
  2059. case DT_STRTAB:
  2060. case DT_SYMTAB:
  2061. case DT_RELA:
  2062. case DT_INIT:
  2063. case DT_FINI:
  2064. case DT_REL:
  2065. case DT_JMPREL:
  2066. case DT_INIT_ARRAY:
  2067. case DT_FINI_ARRAY:
  2068. case DT_PREINIT_ARRAY:
  2069. case DT_DEBUG:
  2070. case DT_VERDEF:
  2071. case DT_VERNEED:
  2072. case DT_VERSYM:
  2073. case DT_GNU_HASH:
  2074. case DT_NULL:
  2075. return FormatHexValue(Value);
  2076. case DT_RELACOUNT:
  2077. case DT_RELCOUNT:
  2078. case DT_VERDEFNUM:
  2079. case DT_VERNEEDNUM:
  2080. return std::to_string(Value);
  2081. case DT_PLTRELSZ:
  2082. case DT_RELASZ:
  2083. case DT_RELAENT:
  2084. case DT_STRSZ:
  2085. case DT_SYMENT:
  2086. case DT_RELSZ:
  2087. case DT_RELENT:
  2088. case DT_INIT_ARRAYSZ:
  2089. case DT_FINI_ARRAYSZ:
  2090. case DT_PREINIT_ARRAYSZ:
  2091. case DT_RELRSZ:
  2092. case DT_RELRENT:
  2093. case DT_ANDROID_RELSZ:
  2094. case DT_ANDROID_RELASZ:
  2095. return std::to_string(Value) + " (bytes)";
  2096. case DT_NEEDED:
  2097. case DT_SONAME:
  2098. case DT_AUXILIARY:
  2099. case DT_USED:
  2100. case DT_FILTER:
  2101. case DT_RPATH:
  2102. case DT_RUNPATH: {
  2103. const std::map<uint64_t, const char *> TagNames = {
  2104. {DT_NEEDED, "Shared library"}, {DT_SONAME, "Library soname"},
  2105. {DT_AUXILIARY, "Auxiliary library"}, {DT_USED, "Not needed object"},
  2106. {DT_FILTER, "Filter library"}, {DT_RPATH, "Library rpath"},
  2107. {DT_RUNPATH, "Library runpath"},
  2108. };
  2109. return (Twine(TagNames.at(Type)) + ": [" + getDynamicString(Value) + "]")
  2110. .str();
  2111. }
  2112. case DT_FLAGS:
  2113. return FormatFlags(Value, makeArrayRef(ElfDynamicDTFlags));
  2114. case DT_FLAGS_1:
  2115. return FormatFlags(Value, makeArrayRef(ElfDynamicDTFlags1));
  2116. default:
  2117. return FormatHexValue(Value);
  2118. }
  2119. }
  2120. template <class ELFT>
  2121. StringRef ELFDumper<ELFT>::getDynamicString(uint64_t Value) const {
  2122. if (DynamicStringTable.empty() && !DynamicStringTable.data()) {
  2123. reportUniqueWarning("string table was not found");
  2124. return "<?>";
  2125. }
  2126. auto WarnAndReturn = [this](const Twine &Msg, uint64_t Offset) {
  2127. reportUniqueWarning("string table at offset 0x" + Twine::utohexstr(Offset) +
  2128. Msg);
  2129. return "<?>";
  2130. };
  2131. const uint64_t FileSize = Obj.getBufSize();
  2132. const uint64_t Offset =
  2133. (const uint8_t *)DynamicStringTable.data() - Obj.base();
  2134. if (DynamicStringTable.size() > FileSize - Offset)
  2135. return WarnAndReturn(" with size 0x" +
  2136. Twine::utohexstr(DynamicStringTable.size()) +
  2137. " goes past the end of the file (0x" +
  2138. Twine::utohexstr(FileSize) + ")",
  2139. Offset);
  2140. if (Value >= DynamicStringTable.size())
  2141. return WarnAndReturn(
  2142. ": unable to read the string at 0x" + Twine::utohexstr(Offset + Value) +
  2143. ": it goes past the end of the table (0x" +
  2144. Twine::utohexstr(Offset + DynamicStringTable.size()) + ")",
  2145. Offset);
  2146. if (DynamicStringTable.back() != '\0')
  2147. return WarnAndReturn(": unable to read the string at 0x" +
  2148. Twine::utohexstr(Offset + Value) +
  2149. ": the string table is not null-terminated",
  2150. Offset);
  2151. return DynamicStringTable.data() + Value;
  2152. }
  2153. template <class ELFT> void ELFDumper<ELFT>::printUnwindInfo() {
  2154. DwarfCFIEH::PrinterContext<ELFT> Ctx(W, ObjF);
  2155. Ctx.printUnwindInformation();
  2156. }
  2157. // The namespace is needed to fix the compilation with GCC older than 7.0+.
  2158. namespace {
  2159. template <> void ELFDumper<ELF32LE>::printUnwindInfo() {
  2160. if (Obj.getHeader().e_machine == EM_ARM) {
  2161. ARM::EHABI::PrinterContext<ELF32LE> Ctx(W, Obj, ObjF.getFileName(),
  2162. DotSymtabSec);
  2163. Ctx.PrintUnwindInformation();
  2164. }
  2165. DwarfCFIEH::PrinterContext<ELF32LE> Ctx(W, ObjF);
  2166. Ctx.printUnwindInformation();
  2167. }
  2168. } // namespace
  2169. template <class ELFT> void ELFDumper<ELFT>::printNeededLibraries() {
  2170. ListScope D(W, "NeededLibraries");
  2171. std::vector<StringRef> Libs;
  2172. for (const auto &Entry : dynamic_table())
  2173. if (Entry.d_tag == ELF::DT_NEEDED)
  2174. Libs.push_back(getDynamicString(Entry.d_un.d_val));
  2175. llvm::sort(Libs);
  2176. for (StringRef L : Libs)
  2177. W.startLine() << L << "\n";
  2178. }
  2179. template <class ELFT>
  2180. static Error checkHashTable(const ELFDumper<ELFT> &Dumper,
  2181. const typename ELFT::Hash *H,
  2182. bool *IsHeaderValid = nullptr) {
  2183. const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
  2184. const uint64_t SecOffset = (const uint8_t *)H - Obj.base();
  2185. if (Dumper.getHashTableEntSize() == 8) {
  2186. auto It = llvm::find_if(ElfMachineType, [&](const EnumEntry<unsigned> &E) {
  2187. return E.Value == Obj.getHeader().e_machine;
  2188. });
  2189. if (IsHeaderValid)
  2190. *IsHeaderValid = false;
  2191. return createError("the hash table at 0x" + Twine::utohexstr(SecOffset) +
  2192. " is not supported: it contains non-standard 8 "
  2193. "byte entries on " +
  2194. It->AltName + " platform");
  2195. }
  2196. auto MakeError = [&](const Twine &Msg = "") {
  2197. return createError("the hash table at offset 0x" +
  2198. Twine::utohexstr(SecOffset) +
  2199. " goes past the end of the file (0x" +
  2200. Twine::utohexstr(Obj.getBufSize()) + ")" + Msg);
  2201. };
  2202. // Each SHT_HASH section starts from two 32-bit fields: nbucket and nchain.
  2203. const unsigned HeaderSize = 2 * sizeof(typename ELFT::Word);
  2204. if (IsHeaderValid)
  2205. *IsHeaderValid = Obj.getBufSize() - SecOffset >= HeaderSize;
  2206. if (Obj.getBufSize() - SecOffset < HeaderSize)
  2207. return MakeError();
  2208. if (Obj.getBufSize() - SecOffset - HeaderSize <
  2209. ((uint64_t)H->nbucket + H->nchain) * sizeof(typename ELFT::Word))
  2210. return MakeError(", nbucket = " + Twine(H->nbucket) +
  2211. ", nchain = " + Twine(H->nchain));
  2212. return Error::success();
  2213. }
  2214. template <class ELFT>
  2215. static Error checkGNUHashTable(const ELFFile<ELFT> &Obj,
  2216. const typename ELFT::GnuHash *GnuHashTable,
  2217. bool *IsHeaderValid = nullptr) {
  2218. const uint8_t *TableData = reinterpret_cast<const uint8_t *>(GnuHashTable);
  2219. assert(TableData >= Obj.base() && TableData < Obj.base() + Obj.getBufSize() &&
  2220. "GnuHashTable must always point to a location inside the file");
  2221. uint64_t TableOffset = TableData - Obj.base();
  2222. if (IsHeaderValid)
  2223. *IsHeaderValid = TableOffset + /*Header size:*/ 16 < Obj.getBufSize();
  2224. if (TableOffset + 16 + (uint64_t)GnuHashTable->nbuckets * 4 +
  2225. (uint64_t)GnuHashTable->maskwords * sizeof(typename ELFT::Off) >=
  2226. Obj.getBufSize())
  2227. return createError("unable to dump the SHT_GNU_HASH "
  2228. "section at 0x" +
  2229. Twine::utohexstr(TableOffset) +
  2230. ": it goes past the end of the file");
  2231. return Error::success();
  2232. }
  2233. template <typename ELFT> void ELFDumper<ELFT>::printHashTable() {
  2234. DictScope D(W, "HashTable");
  2235. if (!HashTable)
  2236. return;
  2237. bool IsHeaderValid;
  2238. Error Err = checkHashTable(*this, HashTable, &IsHeaderValid);
  2239. if (IsHeaderValid) {
  2240. W.printNumber("Num Buckets", HashTable->nbucket);
  2241. W.printNumber("Num Chains", HashTable->nchain);
  2242. }
  2243. if (Err) {
  2244. reportUniqueWarning(std::move(Err));
  2245. return;
  2246. }
  2247. W.printList("Buckets", HashTable->buckets());
  2248. W.printList("Chains", HashTable->chains());
  2249. }
  2250. template <class ELFT>
  2251. static Expected<ArrayRef<typename ELFT::Word>>
  2252. getGnuHashTableChains(Optional<DynRegionInfo> DynSymRegion,
  2253. const typename ELFT::GnuHash *GnuHashTable) {
  2254. if (!DynSymRegion)
  2255. return createError("no dynamic symbol table found");
  2256. ArrayRef<typename ELFT::Sym> DynSymTable =
  2257. DynSymRegion->template getAsArrayRef<typename ELFT::Sym>();
  2258. size_t NumSyms = DynSymTable.size();
  2259. if (!NumSyms)
  2260. return createError("the dynamic symbol table is empty");
  2261. if (GnuHashTable->symndx < NumSyms)
  2262. return GnuHashTable->values(NumSyms);
  2263. // A normal empty GNU hash table section produced by linker might have
  2264. // symndx set to the number of dynamic symbols + 1 (for the zero symbol)
  2265. // and have dummy null values in the Bloom filter and in the buckets
  2266. // vector (or no values at all). It happens because the value of symndx is not
  2267. // important for dynamic loaders when the GNU hash table is empty. They just
  2268. // skip the whole object during symbol lookup. In such cases, the symndx value
  2269. // is irrelevant and we should not report a warning.
  2270. ArrayRef<typename ELFT::Word> Buckets = GnuHashTable->buckets();
  2271. if (!llvm::all_of(Buckets, [](typename ELFT::Word V) { return V == 0; }))
  2272. return createError(
  2273. "the first hashed symbol index (" + Twine(GnuHashTable->symndx) +
  2274. ") is greater than or equal to the number of dynamic symbols (" +
  2275. Twine(NumSyms) + ")");
  2276. // There is no way to represent an array of (dynamic symbols count - symndx)
  2277. // length.
  2278. return ArrayRef<typename ELFT::Word>();
  2279. }
  2280. template <typename ELFT>
  2281. void ELFDumper<ELFT>::printGnuHashTable() {
  2282. DictScope D(W, "GnuHashTable");
  2283. if (!GnuHashTable)
  2284. return;
  2285. bool IsHeaderValid;
  2286. Error Err = checkGNUHashTable<ELFT>(Obj, GnuHashTable, &IsHeaderValid);
  2287. if (IsHeaderValid) {
  2288. W.printNumber("Num Buckets", GnuHashTable->nbuckets);
  2289. W.printNumber("First Hashed Symbol Index", GnuHashTable->symndx);
  2290. W.printNumber("Num Mask Words", GnuHashTable->maskwords);
  2291. W.printNumber("Shift Count", GnuHashTable->shift2);
  2292. }
  2293. if (Err) {
  2294. reportUniqueWarning(std::move(Err));
  2295. return;
  2296. }
  2297. ArrayRef<typename ELFT::Off> BloomFilter = GnuHashTable->filter();
  2298. W.printHexList("Bloom Filter", BloomFilter);
  2299. ArrayRef<Elf_Word> Buckets = GnuHashTable->buckets();
  2300. W.printList("Buckets", Buckets);
  2301. Expected<ArrayRef<Elf_Word>> Chains =
  2302. getGnuHashTableChains<ELFT>(DynSymRegion, GnuHashTable);
  2303. if (!Chains) {
  2304. reportUniqueWarning("unable to dump 'Values' for the SHT_GNU_HASH "
  2305. "section: " +
  2306. toString(Chains.takeError()));
  2307. return;
  2308. }
  2309. W.printHexList("Values", *Chains);
  2310. }
  2311. template <typename ELFT> void ELFDumper<ELFT>::printLoadName() {
  2312. StringRef SOName = "<Not found>";
  2313. if (SONameOffset)
  2314. SOName = getDynamicString(*SONameOffset);
  2315. W.printString("LoadName", SOName);
  2316. }
  2317. template <class ELFT> void ELFDumper<ELFT>::printArchSpecificInfo() {
  2318. switch (Obj.getHeader().e_machine) {
  2319. case EM_ARM:
  2320. if (Obj.isLE())
  2321. printAttributes(ELF::SHT_ARM_ATTRIBUTES,
  2322. std::make_unique<ARMAttributeParser>(&W),
  2323. support::little);
  2324. else
  2325. reportUniqueWarning("attribute printing not implemented for big-endian "
  2326. "ARM objects");
  2327. break;
  2328. case EM_RISCV:
  2329. if (Obj.isLE())
  2330. printAttributes(ELF::SHT_RISCV_ATTRIBUTES,
  2331. std::make_unique<RISCVAttributeParser>(&W),
  2332. support::little);
  2333. else
  2334. reportUniqueWarning("attribute printing not implemented for big-endian "
  2335. "RISC-V objects");
  2336. break;
  2337. case EM_MSP430:
  2338. printAttributes(ELF::SHT_MSP430_ATTRIBUTES,
  2339. std::make_unique<MSP430AttributeParser>(&W),
  2340. support::little);
  2341. break;
  2342. case EM_MIPS: {
  2343. printMipsABIFlags();
  2344. printMipsOptions();
  2345. printMipsReginfo();
  2346. MipsGOTParser<ELFT> Parser(*this);
  2347. if (Error E = Parser.findGOT(dynamic_table(), dynamic_symbols()))
  2348. reportUniqueWarning(std::move(E));
  2349. else if (!Parser.isGotEmpty())
  2350. printMipsGOT(Parser);
  2351. if (Error E = Parser.findPLT(dynamic_table()))
  2352. reportUniqueWarning(std::move(E));
  2353. else if (!Parser.isPltEmpty())
  2354. printMipsPLT(Parser);
  2355. break;
  2356. }
  2357. default:
  2358. break;
  2359. }
  2360. }
  2361. template <class ELFT>
  2362. void ELFDumper<ELFT>::printAttributes(
  2363. unsigned AttrShType, std::unique_ptr<ELFAttributeParser> AttrParser,
  2364. support::endianness Endianness) {
  2365. assert((AttrShType != ELF::SHT_NULL) && AttrParser &&
  2366. "Incomplete ELF attribute implementation");
  2367. DictScope BA(W, "BuildAttributes");
  2368. for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
  2369. if (Sec.sh_type != AttrShType)
  2370. continue;
  2371. ArrayRef<uint8_t> Contents;
  2372. if (Expected<ArrayRef<uint8_t>> ContentOrErr =
  2373. Obj.getSectionContents(Sec)) {
  2374. Contents = *ContentOrErr;
  2375. if (Contents.empty()) {
  2376. reportUniqueWarning("the " + describe(Sec) + " is empty");
  2377. continue;
  2378. }
  2379. } else {
  2380. reportUniqueWarning("unable to read the content of the " + describe(Sec) +
  2381. ": " + toString(ContentOrErr.takeError()));
  2382. continue;
  2383. }
  2384. W.printHex("FormatVersion", Contents[0]);
  2385. if (Error E = AttrParser->parse(Contents, Endianness))
  2386. reportUniqueWarning("unable to dump attributes from the " +
  2387. describe(Sec) + ": " + toString(std::move(E)));
  2388. }
  2389. }
  2390. namespace {
  2391. template <class ELFT> class MipsGOTParser {
  2392. public:
  2393. LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
  2394. using Entry = typename ELFT::Addr;
  2395. using Entries = ArrayRef<Entry>;
  2396. const bool IsStatic;
  2397. const ELFFile<ELFT> &Obj;
  2398. const ELFDumper<ELFT> &Dumper;
  2399. MipsGOTParser(const ELFDumper<ELFT> &D);
  2400. Error findGOT(Elf_Dyn_Range DynTable, Elf_Sym_Range DynSyms);
  2401. Error findPLT(Elf_Dyn_Range DynTable);
  2402. bool isGotEmpty() const { return GotEntries.empty(); }
  2403. bool isPltEmpty() const { return PltEntries.empty(); }
  2404. uint64_t getGp() const;
  2405. const Entry *getGotLazyResolver() const;
  2406. const Entry *getGotModulePointer() const;
  2407. const Entry *getPltLazyResolver() const;
  2408. const Entry *getPltModulePointer() const;
  2409. Entries getLocalEntries() const;
  2410. Entries getGlobalEntries() const;
  2411. Entries getOtherEntries() const;
  2412. Entries getPltEntries() const;
  2413. uint64_t getGotAddress(const Entry * E) const;
  2414. int64_t getGotOffset(const Entry * E) const;
  2415. const Elf_Sym *getGotSym(const Entry *E) const;
  2416. uint64_t getPltAddress(const Entry * E) const;
  2417. const Elf_Sym *getPltSym(const Entry *E) const;
  2418. StringRef getPltStrTable() const { return PltStrTable; }
  2419. const Elf_Shdr *getPltSymTable() const { return PltSymTable; }
  2420. private:
  2421. const Elf_Shdr *GotSec;
  2422. size_t LocalNum;
  2423. size_t GlobalNum;
  2424. const Elf_Shdr *PltSec;
  2425. const Elf_Shdr *PltRelSec;
  2426. const Elf_Shdr *PltSymTable;
  2427. StringRef FileName;
  2428. Elf_Sym_Range GotDynSyms;
  2429. StringRef PltStrTable;
  2430. Entries GotEntries;
  2431. Entries PltEntries;
  2432. };
  2433. } // end anonymous namespace
  2434. template <class ELFT>
  2435. MipsGOTParser<ELFT>::MipsGOTParser(const ELFDumper<ELFT> &D)
  2436. : IsStatic(D.dynamic_table().empty()), Obj(D.getElfObject().getELFFile()),
  2437. Dumper(D), GotSec(nullptr), LocalNum(0), GlobalNum(0), PltSec(nullptr),
  2438. PltRelSec(nullptr), PltSymTable(nullptr),
  2439. FileName(D.getElfObject().getFileName()) {}
  2440. template <class ELFT>
  2441. Error MipsGOTParser<ELFT>::findGOT(Elf_Dyn_Range DynTable,
  2442. Elf_Sym_Range DynSyms) {
  2443. // See "Global Offset Table" in Chapter 5 in the following document
  2444. // for detailed GOT description.
  2445. // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
  2446. // Find static GOT secton.
  2447. if (IsStatic) {
  2448. GotSec = Dumper.findSectionByName(".got");
  2449. if (!GotSec)
  2450. return Error::success();
  2451. ArrayRef<uint8_t> Content =
  2452. unwrapOrError(FileName, Obj.getSectionContents(*GotSec));
  2453. GotEntries = Entries(reinterpret_cast<const Entry *>(Content.data()),
  2454. Content.size() / sizeof(Entry));
  2455. LocalNum = GotEntries.size();
  2456. return Error::success();
  2457. }
  2458. // Lookup dynamic table tags which define the GOT layout.
  2459. Optional<uint64_t> DtPltGot;
  2460. Optional<uint64_t> DtLocalGotNum;
  2461. Optional<uint64_t> DtGotSym;
  2462. for (const auto &Entry : DynTable) {
  2463. switch (Entry.getTag()) {
  2464. case ELF::DT_PLTGOT:
  2465. DtPltGot = Entry.getVal();
  2466. break;
  2467. case ELF::DT_MIPS_LOCAL_GOTNO:
  2468. DtLocalGotNum = Entry.getVal();
  2469. break;
  2470. case ELF::DT_MIPS_GOTSYM:
  2471. DtGotSym = Entry.getVal();
  2472. break;
  2473. }
  2474. }
  2475. if (!DtPltGot && !DtLocalGotNum && !DtGotSym)
  2476. return Error::success();
  2477. if (!DtPltGot)
  2478. return createError("cannot find PLTGOT dynamic tag");
  2479. if (!DtLocalGotNum)
  2480. return createError("cannot find MIPS_LOCAL_GOTNO dynamic tag");
  2481. if (!DtGotSym)
  2482. return createError("cannot find MIPS_GOTSYM dynamic tag");
  2483. size_t DynSymTotal = DynSyms.size();
  2484. if (*DtGotSym > DynSymTotal)
  2485. return createError("DT_MIPS_GOTSYM value (" + Twine(*DtGotSym) +
  2486. ") exceeds the number of dynamic symbols (" +
  2487. Twine(DynSymTotal) + ")");
  2488. GotSec = findNotEmptySectionByAddress(Obj, FileName, *DtPltGot);
  2489. if (!GotSec)
  2490. return createError("there is no non-empty GOT section at 0x" +
  2491. Twine::utohexstr(*DtPltGot));
  2492. LocalNum = *DtLocalGotNum;
  2493. GlobalNum = DynSymTotal - *DtGotSym;
  2494. ArrayRef<uint8_t> Content =
  2495. unwrapOrError(FileName, Obj.getSectionContents(*GotSec));
  2496. GotEntries = Entries(reinterpret_cast<const Entry *>(Content.data()),
  2497. Content.size() / sizeof(Entry));
  2498. GotDynSyms = DynSyms.drop_front(*DtGotSym);
  2499. return Error::success();
  2500. }
  2501. template <class ELFT>
  2502. Error MipsGOTParser<ELFT>::findPLT(Elf_Dyn_Range DynTable) {
  2503. // Lookup dynamic table tags which define the PLT layout.
  2504. Optional<uint64_t> DtMipsPltGot;
  2505. Optional<uint64_t> DtJmpRel;
  2506. for (const auto &Entry : DynTable) {
  2507. switch (Entry.getTag()) {
  2508. case ELF::DT_MIPS_PLTGOT:
  2509. DtMipsPltGot = Entry.getVal();
  2510. break;
  2511. case ELF::DT_JMPREL:
  2512. DtJmpRel = Entry.getVal();
  2513. break;
  2514. }
  2515. }
  2516. if (!DtMipsPltGot && !DtJmpRel)
  2517. return Error::success();
  2518. // Find PLT section.
  2519. if (!DtMipsPltGot)
  2520. return createError("cannot find MIPS_PLTGOT dynamic tag");
  2521. if (!DtJmpRel)
  2522. return createError("cannot find JMPREL dynamic tag");
  2523. PltSec = findNotEmptySectionByAddress(Obj, FileName, *DtMipsPltGot);
  2524. if (!PltSec)
  2525. return createError("there is no non-empty PLTGOT section at 0x" +
  2526. Twine::utohexstr(*DtMipsPltGot));
  2527. PltRelSec = findNotEmptySectionByAddress(Obj, FileName, *DtJmpRel);
  2528. if (!PltRelSec)
  2529. return createError("there is no non-empty RELPLT section at 0x" +
  2530. Twine::utohexstr(*DtJmpRel));
  2531. if (Expected<ArrayRef<uint8_t>> PltContentOrErr =
  2532. Obj.getSectionContents(*PltSec))
  2533. PltEntries =
  2534. Entries(reinterpret_cast<const Entry *>(PltContentOrErr->data()),
  2535. PltContentOrErr->size() / sizeof(Entry));
  2536. else
  2537. return createError("unable to read PLTGOT section content: " +
  2538. toString(PltContentOrErr.takeError()));
  2539. if (Expected<const Elf_Shdr *> PltSymTableOrErr =
  2540. Obj.getSection(PltRelSec->sh_link))
  2541. PltSymTable = *PltSymTableOrErr;
  2542. else
  2543. return createError("unable to get a symbol table linked to the " +
  2544. describe(Obj, *PltRelSec) + ": " +
  2545. toString(PltSymTableOrErr.takeError()));
  2546. if (Expected<StringRef> StrTabOrErr =
  2547. Obj.getStringTableForSymtab(*PltSymTable))
  2548. PltStrTable = *StrTabOrErr;
  2549. else
  2550. return createError("unable to get a string table for the " +
  2551. describe(Obj, *PltSymTable) + ": " +
  2552. toString(StrTabOrErr.takeError()));
  2553. return Error::success();
  2554. }
  2555. template <class ELFT> uint64_t MipsGOTParser<ELFT>::getGp() const {
  2556. return GotSec->sh_addr + 0x7ff0;
  2557. }
  2558. template <class ELFT>
  2559. const typename MipsGOTParser<ELFT>::Entry *
  2560. MipsGOTParser<ELFT>::getGotLazyResolver() const {
  2561. return LocalNum > 0 ? &GotEntries[0] : nullptr;
  2562. }
  2563. template <class ELFT>
  2564. const typename MipsGOTParser<ELFT>::Entry *
  2565. MipsGOTParser<ELFT>::getGotModulePointer() const {
  2566. if (LocalNum < 2)
  2567. return nullptr;
  2568. const Entry &E = GotEntries[1];
  2569. if ((E >> (sizeof(Entry) * 8 - 1)) == 0)
  2570. return nullptr;
  2571. return &E;
  2572. }
  2573. template <class ELFT>
  2574. typename MipsGOTParser<ELFT>::Entries
  2575. MipsGOTParser<ELFT>::getLocalEntries() const {
  2576. size_t Skip = getGotModulePointer() ? 2 : 1;
  2577. if (LocalNum - Skip <= 0)
  2578. return Entries();
  2579. return GotEntries.slice(Skip, LocalNum - Skip);
  2580. }
  2581. template <class ELFT>
  2582. typename MipsGOTParser<ELFT>::Entries
  2583. MipsGOTParser<ELFT>::getGlobalEntries() const {
  2584. if (GlobalNum == 0)
  2585. return Entries();
  2586. return GotEntries.slice(LocalNum, GlobalNum);
  2587. }
  2588. template <class ELFT>
  2589. typename MipsGOTParser<ELFT>::Entries
  2590. MipsGOTParser<ELFT>::getOtherEntries() const {
  2591. size_t OtherNum = GotEntries.size() - LocalNum - GlobalNum;
  2592. if (OtherNum == 0)
  2593. return Entries();
  2594. return GotEntries.slice(LocalNum + GlobalNum, OtherNum);
  2595. }
  2596. template <class ELFT>
  2597. uint64_t MipsGOTParser<ELFT>::getGotAddress(const Entry *E) const {
  2598. int64_t Offset = std::distance(GotEntries.data(), E) * sizeof(Entry);
  2599. return GotSec->sh_addr + Offset;
  2600. }
  2601. template <class ELFT>
  2602. int64_t MipsGOTParser<ELFT>::getGotOffset(const Entry *E) const {
  2603. int64_t Offset = std::distance(GotEntries.data(), E) * sizeof(Entry);
  2604. return Offset - 0x7ff0;
  2605. }
  2606. template <class ELFT>
  2607. const typename MipsGOTParser<ELFT>::Elf_Sym *
  2608. MipsGOTParser<ELFT>::getGotSym(const Entry *E) const {
  2609. int64_t Offset = std::distance(GotEntries.data(), E);
  2610. return &GotDynSyms[Offset - LocalNum];
  2611. }
  2612. template <class ELFT>
  2613. const typename MipsGOTParser<ELFT>::Entry *
  2614. MipsGOTParser<ELFT>::getPltLazyResolver() const {
  2615. return PltEntries.empty() ? nullptr : &PltEntries[0];
  2616. }
  2617. template <class ELFT>
  2618. const typename MipsGOTParser<ELFT>::Entry *
  2619. MipsGOTParser<ELFT>::getPltModulePointer() const {
  2620. return PltEntries.size() < 2 ? nullptr : &PltEntries[1];
  2621. }
  2622. template <class ELFT>
  2623. typename MipsGOTParser<ELFT>::Entries
  2624. MipsGOTParser<ELFT>::getPltEntries() const {
  2625. if (PltEntries.size() <= 2)
  2626. return Entries();
  2627. return PltEntries.slice(2, PltEntries.size() - 2);
  2628. }
  2629. template <class ELFT>
  2630. uint64_t MipsGOTParser<ELFT>::getPltAddress(const Entry *E) const {
  2631. int64_t Offset = std::distance(PltEntries.data(), E) * sizeof(Entry);
  2632. return PltSec->sh_addr + Offset;
  2633. }
  2634. template <class ELFT>
  2635. const typename MipsGOTParser<ELFT>::Elf_Sym *
  2636. MipsGOTParser<ELFT>::getPltSym(const Entry *E) const {
  2637. int64_t Offset = std::distance(getPltEntries().data(), E);
  2638. if (PltRelSec->sh_type == ELF::SHT_REL) {
  2639. Elf_Rel_Range Rels = unwrapOrError(FileName, Obj.rels(*PltRelSec));
  2640. return unwrapOrError(FileName,
  2641. Obj.getRelocationSymbol(Rels[Offset], PltSymTable));
  2642. } else {
  2643. Elf_Rela_Range Rels = unwrapOrError(FileName, Obj.relas(*PltRelSec));
  2644. return unwrapOrError(FileName,
  2645. Obj.getRelocationSymbol(Rels[Offset], PltSymTable));
  2646. }
  2647. }
  2648. const EnumEntry<unsigned> ElfMipsISAExtType[] = {
  2649. {"None", Mips::AFL_EXT_NONE},
  2650. {"Broadcom SB-1", Mips::AFL_EXT_SB1},
  2651. {"Cavium Networks Octeon", Mips::AFL_EXT_OCTEON},
  2652. {"Cavium Networks Octeon2", Mips::AFL_EXT_OCTEON2},
  2653. {"Cavium Networks OcteonP", Mips::AFL_EXT_OCTEONP},
  2654. {"Cavium Networks Octeon3", Mips::AFL_EXT_OCTEON3},
  2655. {"LSI R4010", Mips::AFL_EXT_4010},
  2656. {"Loongson 2E", Mips::AFL_EXT_LOONGSON_2E},
  2657. {"Loongson 2F", Mips::AFL_EXT_LOONGSON_2F},
  2658. {"Loongson 3A", Mips::AFL_EXT_LOONGSON_3A},
  2659. {"MIPS R4650", Mips::AFL_EXT_4650},
  2660. {"MIPS R5900", Mips::AFL_EXT_5900},
  2661. {"MIPS R10000", Mips::AFL_EXT_10000},
  2662. {"NEC VR4100", Mips::AFL_EXT_4100},
  2663. {"NEC VR4111/VR4181", Mips::AFL_EXT_4111},
  2664. {"NEC VR4120", Mips::AFL_EXT_4120},
  2665. {"NEC VR5400", Mips::AFL_EXT_5400},
  2666. {"NEC VR5500", Mips::AFL_EXT_5500},
  2667. {"RMI Xlr", Mips::AFL_EXT_XLR},
  2668. {"Toshiba R3900", Mips::AFL_EXT_3900}
  2669. };
  2670. const EnumEntry<unsigned> ElfMipsASEFlags[] = {
  2671. {"DSP", Mips::AFL_ASE_DSP},
  2672. {"DSPR2", Mips::AFL_ASE_DSPR2},
  2673. {"Enhanced VA Scheme", Mips::AFL_ASE_EVA},
  2674. {"MCU", Mips::AFL_ASE_MCU},
  2675. {"MDMX", Mips::AFL_ASE_MDMX},
  2676. {"MIPS-3D", Mips::AFL_ASE_MIPS3D},
  2677. {"MT", Mips::AFL_ASE_MT},
  2678. {"SmartMIPS", Mips::AFL_ASE_SMARTMIPS},
  2679. {"VZ", Mips::AFL_ASE_VIRT},
  2680. {"MSA", Mips::AFL_ASE_MSA},
  2681. {"MIPS16", Mips::AFL_ASE_MIPS16},
  2682. {"microMIPS", Mips::AFL_ASE_MICROMIPS},
  2683. {"XPA", Mips::AFL_ASE_XPA},
  2684. {"CRC", Mips::AFL_ASE_CRC},
  2685. {"GINV", Mips::AFL_ASE_GINV},
  2686. };
  2687. const EnumEntry<unsigned> ElfMipsFpABIType[] = {
  2688. {"Hard or soft float", Mips::Val_GNU_MIPS_ABI_FP_ANY},
  2689. {"Hard float (double precision)", Mips::Val_GNU_MIPS_ABI_FP_DOUBLE},
  2690. {"Hard float (single precision)", Mips::Val_GNU_MIPS_ABI_FP_SINGLE},
  2691. {"Soft float", Mips::Val_GNU_MIPS_ABI_FP_SOFT},
  2692. {"Hard float (MIPS32r2 64-bit FPU 12 callee-saved)",
  2693. Mips::Val_GNU_MIPS_ABI_FP_OLD_64},
  2694. {"Hard float (32-bit CPU, Any FPU)", Mips::Val_GNU_MIPS_ABI_FP_XX},
  2695. {"Hard float (32-bit CPU, 64-bit FPU)", Mips::Val_GNU_MIPS_ABI_FP_64},
  2696. {"Hard float compat (32-bit CPU, 64-bit FPU)",
  2697. Mips::Val_GNU_MIPS_ABI_FP_64A}
  2698. };
  2699. static const EnumEntry<unsigned> ElfMipsFlags1[] {
  2700. {"ODDSPREG", Mips::AFL_FLAGS1_ODDSPREG},
  2701. };
  2702. static int getMipsRegisterSize(uint8_t Flag) {
  2703. switch (Flag) {
  2704. case Mips::AFL_REG_NONE:
  2705. return 0;
  2706. case Mips::AFL_REG_32:
  2707. return 32;
  2708. case Mips::AFL_REG_64:
  2709. return 64;
  2710. case Mips::AFL_REG_128:
  2711. return 128;
  2712. default:
  2713. return -1;
  2714. }
  2715. }
  2716. template <class ELFT>
  2717. static void printMipsReginfoData(ScopedPrinter &W,
  2718. const Elf_Mips_RegInfo<ELFT> &Reginfo) {
  2719. W.printHex("GP", Reginfo.ri_gp_value);
  2720. W.printHex("General Mask", Reginfo.ri_gprmask);
  2721. W.printHex("Co-Proc Mask0", Reginfo.ri_cprmask[0]);
  2722. W.printHex("Co-Proc Mask1", Reginfo.ri_cprmask[1]);
  2723. W.printHex("Co-Proc Mask2", Reginfo.ri_cprmask[2]);
  2724. W.printHex("Co-Proc Mask3", Reginfo.ri_cprmask[3]);
  2725. }
  2726. template <class ELFT> void ELFDumper<ELFT>::printMipsReginfo() {
  2727. const Elf_Shdr *RegInfoSec = findSectionByName(".reginfo");
  2728. if (!RegInfoSec) {
  2729. W.startLine() << "There is no .reginfo section in the file.\n";
  2730. return;
  2731. }
  2732. Expected<ArrayRef<uint8_t>> ContentsOrErr =
  2733. Obj.getSectionContents(*RegInfoSec);
  2734. if (!ContentsOrErr) {
  2735. this->reportUniqueWarning(
  2736. "unable to read the content of the .reginfo section (" +
  2737. describe(*RegInfoSec) + "): " + toString(ContentsOrErr.takeError()));
  2738. return;
  2739. }
  2740. if (ContentsOrErr->size() < sizeof(Elf_Mips_RegInfo<ELFT>)) {
  2741. this->reportUniqueWarning("the .reginfo section has an invalid size (0x" +
  2742. Twine::utohexstr(ContentsOrErr->size()) + ")");
  2743. return;
  2744. }
  2745. DictScope GS(W, "MIPS RegInfo");
  2746. printMipsReginfoData(W, *reinterpret_cast<const Elf_Mips_RegInfo<ELFT> *>(
  2747. ContentsOrErr->data()));
  2748. }
  2749. template <class ELFT>
  2750. static Expected<const Elf_Mips_Options<ELFT> *>
  2751. readMipsOptions(const uint8_t *SecBegin, ArrayRef<uint8_t> &SecData,
  2752. bool &IsSupported) {
  2753. if (SecData.size() < sizeof(Elf_Mips_Options<ELFT>))
  2754. return createError("the .MIPS.options section has an invalid size (0x" +
  2755. Twine::utohexstr(SecData.size()) + ")");
  2756. const Elf_Mips_Options<ELFT> *O =
  2757. reinterpret_cast<const Elf_Mips_Options<ELFT> *>(SecData.data());
  2758. const uint8_t Size = O->size;
  2759. if (Size > SecData.size()) {
  2760. const uint64_t Offset = SecData.data() - SecBegin;
  2761. const uint64_t SecSize = Offset + SecData.size();
  2762. return createError("a descriptor of size 0x" + Twine::utohexstr(Size) +
  2763. " at offset 0x" + Twine::utohexstr(Offset) +
  2764. " goes past the end of the .MIPS.options "
  2765. "section of size 0x" +
  2766. Twine::utohexstr(SecSize));
  2767. }
  2768. IsSupported = O->kind == ODK_REGINFO;
  2769. const size_t ExpectedSize =
  2770. sizeof(Elf_Mips_Options<ELFT>) + sizeof(Elf_Mips_RegInfo<ELFT>);
  2771. if (IsSupported)
  2772. if (Size < ExpectedSize)
  2773. return createError(
  2774. "a .MIPS.options entry of kind " +
  2775. Twine(getElfMipsOptionsOdkType(O->kind)) +
  2776. " has an invalid size (0x" + Twine::utohexstr(Size) +
  2777. "), the expected size is 0x" + Twine::utohexstr(ExpectedSize));
  2778. SecData = SecData.drop_front(Size);
  2779. return O;
  2780. }
  2781. template <class ELFT> void ELFDumper<ELFT>::printMipsOptions() {
  2782. const Elf_Shdr *MipsOpts = findSectionByName(".MIPS.options");
  2783. if (!MipsOpts) {
  2784. W.startLine() << "There is no .MIPS.options section in the file.\n";
  2785. return;
  2786. }
  2787. DictScope GS(W, "MIPS Options");
  2788. ArrayRef<uint8_t> Data =
  2789. unwrapOrError(ObjF.getFileName(), Obj.getSectionContents(*MipsOpts));
  2790. const uint8_t *const SecBegin = Data.begin();
  2791. while (!Data.empty()) {
  2792. bool IsSupported;
  2793. Expected<const Elf_Mips_Options<ELFT> *> OptsOrErr =
  2794. readMipsOptions<ELFT>(SecBegin, Data, IsSupported);
  2795. if (!OptsOrErr) {
  2796. reportUniqueWarning(OptsOrErr.takeError());
  2797. break;
  2798. }
  2799. unsigned Kind = (*OptsOrErr)->kind;
  2800. const char *Type = getElfMipsOptionsOdkType(Kind);
  2801. if (!IsSupported) {
  2802. W.startLine() << "Unsupported MIPS options tag: " << Type << " (" << Kind
  2803. << ")\n";
  2804. continue;
  2805. }
  2806. DictScope GS(W, Type);
  2807. if (Kind == ODK_REGINFO)
  2808. printMipsReginfoData(W, (*OptsOrErr)->getRegInfo());
  2809. else
  2810. llvm_unreachable("unexpected .MIPS.options section descriptor kind");
  2811. }
  2812. }
  2813. template <class ELFT> void ELFDumper<ELFT>::printStackMap() const {
  2814. const Elf_Shdr *StackMapSection = findSectionByName(".llvm_stackmaps");
  2815. if (!StackMapSection)
  2816. return;
  2817. auto Warn = [&](Error &&E) {
  2818. this->reportUniqueWarning("unable to read the stack map from " +
  2819. describe(*StackMapSection) + ": " +
  2820. toString(std::move(E)));
  2821. };
  2822. Expected<ArrayRef<uint8_t>> ContentOrErr =
  2823. Obj.getSectionContents(*StackMapSection);
  2824. if (!ContentOrErr) {
  2825. Warn(ContentOrErr.takeError());
  2826. return;
  2827. }
  2828. if (Error E = StackMapParser<ELFT::TargetEndianness>::validateHeader(
  2829. *ContentOrErr)) {
  2830. Warn(std::move(E));
  2831. return;
  2832. }
  2833. prettyPrintStackMap(W, StackMapParser<ELFT::TargetEndianness>(*ContentOrErr));
  2834. }
  2835. template <class ELFT>
  2836. void ELFDumper<ELFT>::printReloc(const Relocation<ELFT> &R, unsigned RelIndex,
  2837. const Elf_Shdr &Sec, const Elf_Shdr *SymTab) {
  2838. Expected<RelSymbol<ELFT>> Target = getRelocationTarget(R, SymTab);
  2839. if (!Target)
  2840. reportUniqueWarning("unable to print relocation " + Twine(RelIndex) +
  2841. " in " + describe(Sec) + ": " +
  2842. toString(Target.takeError()));
  2843. else
  2844. printRelRelaReloc(R, *Target);
  2845. }
  2846. static inline void printFields(formatted_raw_ostream &OS, StringRef Str1,
  2847. StringRef Str2) {
  2848. OS.PadToColumn(2u);
  2849. OS << Str1;
  2850. OS.PadToColumn(37u);
  2851. OS << Str2 << "\n";
  2852. OS.flush();
  2853. }
  2854. template <class ELFT>
  2855. static std::string getSectionHeadersNumString(const ELFFile<ELFT> &Obj,
  2856. StringRef FileName) {
  2857. const typename ELFT::Ehdr &ElfHeader = Obj.getHeader();
  2858. if (ElfHeader.e_shnum != 0)
  2859. return to_string(ElfHeader.e_shnum);
  2860. Expected<ArrayRef<typename ELFT::Shdr>> ArrOrErr = Obj.sections();
  2861. if (!ArrOrErr) {
  2862. // In this case we can ignore an error, because we have already reported a
  2863. // warning about the broken section header table earlier.
  2864. consumeError(ArrOrErr.takeError());
  2865. return "<?>";
  2866. }
  2867. if (ArrOrErr->empty())
  2868. return "0";
  2869. return "0 (" + to_string((*ArrOrErr)[0].sh_size) + ")";
  2870. }
  2871. template <class ELFT>
  2872. static std::string getSectionHeaderTableIndexString(const ELFFile<ELFT> &Obj,
  2873. StringRef FileName) {
  2874. const typename ELFT::Ehdr &ElfHeader = Obj.getHeader();
  2875. if (ElfHeader.e_shstrndx != SHN_XINDEX)
  2876. return to_string(ElfHeader.e_shstrndx);
  2877. Expected<ArrayRef<typename ELFT::Shdr>> ArrOrErr = Obj.sections();
  2878. if (!ArrOrErr) {
  2879. // In this case we can ignore an error, because we have already reported a
  2880. // warning about the broken section header table earlier.
  2881. consumeError(ArrOrErr.takeError());
  2882. return "<?>";
  2883. }
  2884. if (ArrOrErr->empty())
  2885. return "65535 (corrupt: out of range)";
  2886. return to_string(ElfHeader.e_shstrndx) + " (" +
  2887. to_string((*ArrOrErr)[0].sh_link) + ")";
  2888. }
  2889. static const EnumEntry<unsigned> *getObjectFileEnumEntry(unsigned Type) {
  2890. auto It = llvm::find_if(ElfObjectFileType, [&](const EnumEntry<unsigned> &E) {
  2891. return E.Value == Type;
  2892. });
  2893. if (It != makeArrayRef(ElfObjectFileType).end())
  2894. return It;
  2895. return nullptr;
  2896. }
  2897. template <class ELFT>
  2898. void GNUELFDumper<ELFT>::printFileSummary(StringRef FileStr, ObjectFile &Obj,
  2899. ArrayRef<std::string> InputFilenames,
  2900. const Archive *A) {
  2901. if (InputFilenames.size() > 1 || A) {
  2902. this->W.startLine() << "\n";
  2903. this->W.printString("File", FileStr);
  2904. }
  2905. }
  2906. template <class ELFT> void GNUELFDumper<ELFT>::printFileHeaders() {
  2907. const Elf_Ehdr &e = this->Obj.getHeader();
  2908. OS << "ELF Header:\n";
  2909. OS << " Magic: ";
  2910. std::string Str;
  2911. for (int i = 0; i < ELF::EI_NIDENT; i++)
  2912. OS << format(" %02x", static_cast<int>(e.e_ident[i]));
  2913. OS << "\n";
  2914. Str = enumToString(e.e_ident[ELF::EI_CLASS], makeArrayRef(ElfClass));
  2915. printFields(OS, "Class:", Str);
  2916. Str = enumToString(e.e_ident[ELF::EI_DATA], makeArrayRef(ElfDataEncoding));
  2917. printFields(OS, "Data:", Str);
  2918. OS.PadToColumn(2u);
  2919. OS << "Version:";
  2920. OS.PadToColumn(37u);
  2921. OS << to_hexString(e.e_ident[ELF::EI_VERSION]);
  2922. if (e.e_version == ELF::EV_CURRENT)
  2923. OS << " (current)";
  2924. OS << "\n";
  2925. Str = enumToString(e.e_ident[ELF::EI_OSABI], makeArrayRef(ElfOSABI));
  2926. printFields(OS, "OS/ABI:", Str);
  2927. printFields(OS,
  2928. "ABI Version:", std::to_string(e.e_ident[ELF::EI_ABIVERSION]));
  2929. if (const EnumEntry<unsigned> *E = getObjectFileEnumEntry(e.e_type)) {
  2930. Str = E->AltName.str();
  2931. } else {
  2932. if (e.e_type >= ET_LOPROC)
  2933. Str = "Processor Specific: (" + to_hexString(e.e_type, false) + ")";
  2934. else if (e.e_type >= ET_LOOS)
  2935. Str = "OS Specific: (" + to_hexString(e.e_type, false) + ")";
  2936. else
  2937. Str = "<unknown>: " + to_hexString(e.e_type, false);
  2938. }
  2939. printFields(OS, "Type:", Str);
  2940. Str = enumToString(e.e_machine, makeArrayRef(ElfMachineType));
  2941. printFields(OS, "Machine:", Str);
  2942. Str = "0x" + to_hexString(e.e_version);
  2943. printFields(OS, "Version:", Str);
  2944. Str = "0x" + to_hexString(e.e_entry);
  2945. printFields(OS, "Entry point address:", Str);
  2946. Str = to_string(e.e_phoff) + " (bytes into file)";
  2947. printFields(OS, "Start of program headers:", Str);
  2948. Str = to_string(e.e_shoff) + " (bytes into file)";
  2949. printFields(OS, "Start of section headers:", Str);
  2950. std::string ElfFlags;
  2951. if (e.e_machine == EM_MIPS)
  2952. ElfFlags =
  2953. printFlags(e.e_flags, makeArrayRef(ElfHeaderMipsFlags),
  2954. unsigned(ELF::EF_MIPS_ARCH), unsigned(ELF::EF_MIPS_ABI),
  2955. unsigned(ELF::EF_MIPS_MACH));
  2956. else if (e.e_machine == EM_RISCV)
  2957. ElfFlags = printFlags(e.e_flags, makeArrayRef(ElfHeaderRISCVFlags));
  2958. else if (e.e_machine == EM_AVR)
  2959. ElfFlags = printFlags(e.e_flags, makeArrayRef(ElfHeaderAVRFlags),
  2960. unsigned(ELF::EF_AVR_ARCH_MASK));
  2961. Str = "0x" + to_hexString(e.e_flags);
  2962. if (!ElfFlags.empty())
  2963. Str = Str + ", " + ElfFlags;
  2964. printFields(OS, "Flags:", Str);
  2965. Str = to_string(e.e_ehsize) + " (bytes)";
  2966. printFields(OS, "Size of this header:", Str);
  2967. Str = to_string(e.e_phentsize) + " (bytes)";
  2968. printFields(OS, "Size of program headers:", Str);
  2969. Str = to_string(e.e_phnum);
  2970. printFields(OS, "Number of program headers:", Str);
  2971. Str = to_string(e.e_shentsize) + " (bytes)";
  2972. printFields(OS, "Size of section headers:", Str);
  2973. Str = getSectionHeadersNumString(this->Obj, this->FileName);
  2974. printFields(OS, "Number of section headers:", Str);
  2975. Str = getSectionHeaderTableIndexString(this->Obj, this->FileName);
  2976. printFields(OS, "Section header string table index:", Str);
  2977. }
  2978. template <class ELFT> std::vector<GroupSection> ELFDumper<ELFT>::getGroups() {
  2979. auto GetSignature = [&](const Elf_Sym &Sym, unsigned SymNdx,
  2980. const Elf_Shdr &Symtab) -> StringRef {
  2981. Expected<StringRef> StrTableOrErr = Obj.getStringTableForSymtab(Symtab);
  2982. if (!StrTableOrErr) {
  2983. reportUniqueWarning("unable to get the string table for " +
  2984. describe(Symtab) + ": " +
  2985. toString(StrTableOrErr.takeError()));
  2986. return "<?>";
  2987. }
  2988. StringRef Strings = *StrTableOrErr;
  2989. if (Sym.st_name >= Strings.size()) {
  2990. reportUniqueWarning("unable to get the name of the symbol with index " +
  2991. Twine(SymNdx) + ": st_name (0x" +
  2992. Twine::utohexstr(Sym.st_name) +
  2993. ") is past the end of the string table of size 0x" +
  2994. Twine::utohexstr(Strings.size()));
  2995. return "<?>";
  2996. }
  2997. return StrTableOrErr->data() + Sym.st_name;
  2998. };
  2999. std::vector<GroupSection> Ret;
  3000. uint64_t I = 0;
  3001. for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
  3002. ++I;
  3003. if (Sec.sh_type != ELF::SHT_GROUP)
  3004. continue;
  3005. StringRef Signature = "<?>";
  3006. if (Expected<const Elf_Shdr *> SymtabOrErr = Obj.getSection(Sec.sh_link)) {
  3007. if (Expected<const Elf_Sym *> SymOrErr =
  3008. Obj.template getEntry<Elf_Sym>(**SymtabOrErr, Sec.sh_info))
  3009. Signature = GetSignature(**SymOrErr, Sec.sh_info, **SymtabOrErr);
  3010. else
  3011. reportUniqueWarning("unable to get the signature symbol for " +
  3012. describe(Sec) + ": " +
  3013. toString(SymOrErr.takeError()));
  3014. } else {
  3015. reportUniqueWarning("unable to get the symbol table for " +
  3016. describe(Sec) + ": " +
  3017. toString(SymtabOrErr.takeError()));
  3018. }
  3019. ArrayRef<Elf_Word> Data;
  3020. if (Expected<ArrayRef<Elf_Word>> ContentsOrErr =
  3021. Obj.template getSectionContentsAsArray<Elf_Word>(Sec)) {
  3022. if (ContentsOrErr->empty())
  3023. reportUniqueWarning("unable to read the section group flag from the " +
  3024. describe(Sec) + ": the section is empty");
  3025. else
  3026. Data = *ContentsOrErr;
  3027. } else {
  3028. reportUniqueWarning("unable to get the content of the " + describe(Sec) +
  3029. ": " + toString(ContentsOrErr.takeError()));
  3030. }
  3031. Ret.push_back({getPrintableSectionName(Sec),
  3032. maybeDemangle(Signature),
  3033. Sec.sh_name,
  3034. I - 1,
  3035. Sec.sh_link,
  3036. Sec.sh_info,
  3037. Data.empty() ? Elf_Word(0) : Data[0],
  3038. {}});
  3039. if (Data.empty())
  3040. continue;
  3041. std::vector<GroupMember> &GM = Ret.back().Members;
  3042. for (uint32_t Ndx : Data.slice(1)) {
  3043. if (Expected<const Elf_Shdr *> SecOrErr = Obj.getSection(Ndx)) {
  3044. GM.push_back({getPrintableSectionName(**SecOrErr), Ndx});
  3045. } else {
  3046. reportUniqueWarning("unable to get the section with index " +
  3047. Twine(Ndx) + " when dumping the " + describe(Sec) +
  3048. ": " + toString(SecOrErr.takeError()));
  3049. GM.push_back({"<?>", Ndx});
  3050. }
  3051. }
  3052. }
  3053. return Ret;
  3054. }
  3055. static DenseMap<uint64_t, const GroupSection *>
  3056. mapSectionsToGroups(ArrayRef<GroupSection> Groups) {
  3057. DenseMap<uint64_t, const GroupSection *> Ret;
  3058. for (const GroupSection &G : Groups)
  3059. for (const GroupMember &GM : G.Members)
  3060. Ret.insert({GM.Index, &G});
  3061. return Ret;
  3062. }
  3063. template <class ELFT> void GNUELFDumper<ELFT>::printGroupSections() {
  3064. std::vector<GroupSection> V = this->getGroups();
  3065. DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(V);
  3066. for (const GroupSection &G : V) {
  3067. OS << "\n"
  3068. << getGroupType(G.Type) << " group section ["
  3069. << format_decimal(G.Index, 5) << "] `" << G.Name << "' [" << G.Signature
  3070. << "] contains " << G.Members.size() << " sections:\n"
  3071. << " [Index] Name\n";
  3072. for (const GroupMember &GM : G.Members) {
  3073. const GroupSection *MainGroup = Map[GM.Index];
  3074. if (MainGroup != &G)
  3075. this->reportUniqueWarning(
  3076. "section with index " + Twine(GM.Index) +
  3077. ", included in the group section with index " +
  3078. Twine(MainGroup->Index) +
  3079. ", was also found in the group section with index " +
  3080. Twine(G.Index));
  3081. OS << " [" << format_decimal(GM.Index, 5) << "] " << GM.Name << "\n";
  3082. }
  3083. }
  3084. if (V.empty())
  3085. OS << "There are no section groups in this file.\n";
  3086. }
  3087. template <class ELFT>
  3088. void GNUELFDumper<ELFT>::printRelrReloc(const Elf_Relr &R) {
  3089. OS << to_string(format_hex_no_prefix(R, ELFT::Is64Bits ? 16 : 8)) << "\n";
  3090. }
  3091. template <class ELFT>
  3092. void GNUELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R,
  3093. const RelSymbol<ELFT> &RelSym) {
  3094. // First two fields are bit width dependent. The rest of them are fixed width.
  3095. unsigned Bias = ELFT::Is64Bits ? 8 : 0;
  3096. Field Fields[5] = {0, 10 + Bias, 19 + 2 * Bias, 42 + 2 * Bias, 53 + 2 * Bias};
  3097. unsigned Width = ELFT::Is64Bits ? 16 : 8;
  3098. Fields[0].Str = to_string(format_hex_no_prefix(R.Offset, Width));
  3099. Fields[1].Str = to_string(format_hex_no_prefix(R.Info, Width));
  3100. SmallString<32> RelocName;
  3101. this->Obj.getRelocationTypeName(R.Type, RelocName);
  3102. Fields[2].Str = RelocName.c_str();
  3103. if (RelSym.Sym)
  3104. Fields[3].Str =
  3105. to_string(format_hex_no_prefix(RelSym.Sym->getValue(), Width));
  3106. Fields[4].Str = std::string(RelSym.Name);
  3107. for (const Field &F : Fields)
  3108. printField(F);
  3109. std::string Addend;
  3110. if (Optional<int64_t> A = R.Addend) {
  3111. int64_t RelAddend = *A;
  3112. if (!RelSym.Name.empty()) {
  3113. if (RelAddend < 0) {
  3114. Addend = " - ";
  3115. RelAddend = std::abs(RelAddend);
  3116. } else {
  3117. Addend = " + ";
  3118. }
  3119. }
  3120. Addend += to_hexString(RelAddend, false);
  3121. }
  3122. OS << Addend << "\n";
  3123. }
  3124. template <class ELFT>
  3125. static void printRelocHeaderFields(formatted_raw_ostream &OS, unsigned SType) {
  3126. bool IsRela = SType == ELF::SHT_RELA || SType == ELF::SHT_ANDROID_RELA;
  3127. bool IsRelr = SType == ELF::SHT_RELR || SType == ELF::SHT_ANDROID_RELR;
  3128. if (ELFT::Is64Bits)
  3129. OS << " ";
  3130. else
  3131. OS << " ";
  3132. if (IsRelr && opts::RawRelr)
  3133. OS << "Data ";
  3134. else
  3135. OS << "Offset";
  3136. if (ELFT::Is64Bits)
  3137. OS << " Info Type"
  3138. << " Symbol's Value Symbol's Name";
  3139. else
  3140. OS << " Info Type Sym. Value Symbol's Name";
  3141. if (IsRela)
  3142. OS << " + Addend";
  3143. OS << "\n";
  3144. }
  3145. template <class ELFT>
  3146. void GNUELFDumper<ELFT>::printDynamicRelocHeader(unsigned Type, StringRef Name,
  3147. const DynRegionInfo &Reg) {
  3148. uint64_t Offset = Reg.Addr - this->Obj.base();
  3149. OS << "\n'" << Name.str().c_str() << "' relocation section at offset 0x"
  3150. << to_hexString(Offset, false) << " contains " << Reg.Size << " bytes:\n";
  3151. printRelocHeaderFields<ELFT>(OS, Type);
  3152. }
  3153. template <class ELFT>
  3154. static bool isRelocationSec(const typename ELFT::Shdr &Sec) {
  3155. return Sec.sh_type == ELF::SHT_REL || Sec.sh_type == ELF::SHT_RELA ||
  3156. Sec.sh_type == ELF::SHT_RELR || Sec.sh_type == ELF::SHT_ANDROID_REL ||
  3157. Sec.sh_type == ELF::SHT_ANDROID_RELA ||
  3158. Sec.sh_type == ELF::SHT_ANDROID_RELR;
  3159. }
  3160. template <class ELFT> void GNUELFDumper<ELFT>::printRelocations() {
  3161. auto GetEntriesNum = [&](const Elf_Shdr &Sec) -> Expected<size_t> {
  3162. // Android's packed relocation section needs to be unpacked first
  3163. // to get the actual number of entries.
  3164. if (Sec.sh_type == ELF::SHT_ANDROID_REL ||
  3165. Sec.sh_type == ELF::SHT_ANDROID_RELA) {
  3166. Expected<std::vector<typename ELFT::Rela>> RelasOrErr =
  3167. this->Obj.android_relas(Sec);
  3168. if (!RelasOrErr)
  3169. return RelasOrErr.takeError();
  3170. return RelasOrErr->size();
  3171. }
  3172. if (!opts::RawRelr && (Sec.sh_type == ELF::SHT_RELR ||
  3173. Sec.sh_type == ELF::SHT_ANDROID_RELR)) {
  3174. Expected<Elf_Relr_Range> RelrsOrErr = this->Obj.relrs(Sec);
  3175. if (!RelrsOrErr)
  3176. return RelrsOrErr.takeError();
  3177. return this->Obj.decode_relrs(*RelrsOrErr).size();
  3178. }
  3179. return Sec.getEntityCount();
  3180. };
  3181. bool HasRelocSections = false;
  3182. for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
  3183. if (!isRelocationSec<ELFT>(Sec))
  3184. continue;
  3185. HasRelocSections = true;
  3186. std::string EntriesNum = "<?>";
  3187. if (Expected<size_t> NumOrErr = GetEntriesNum(Sec))
  3188. EntriesNum = std::to_string(*NumOrErr);
  3189. else
  3190. this->reportUniqueWarning("unable to get the number of relocations in " +
  3191. this->describe(Sec) + ": " +
  3192. toString(NumOrErr.takeError()));
  3193. uintX_t Offset = Sec.sh_offset;
  3194. StringRef Name = this->getPrintableSectionName(Sec);
  3195. OS << "\nRelocation section '" << Name << "' at offset 0x"
  3196. << to_hexString(Offset, false) << " contains " << EntriesNum
  3197. << " entries:\n";
  3198. printRelocHeaderFields<ELFT>(OS, Sec.sh_type);
  3199. this->printRelocationsHelper(Sec);
  3200. }
  3201. if (!HasRelocSections)
  3202. OS << "\nThere are no relocations in this file.\n";
  3203. }
  3204. // Print the offset of a particular section from anyone of the ranges:
  3205. // [SHT_LOOS, SHT_HIOS], [SHT_LOPROC, SHT_HIPROC], [SHT_LOUSER, SHT_HIUSER].
  3206. // If 'Type' does not fall within any of those ranges, then a string is
  3207. // returned as '<unknown>' followed by the type value.
  3208. static std::string getSectionTypeOffsetString(unsigned Type) {
  3209. if (Type >= SHT_LOOS && Type <= SHT_HIOS)
  3210. return "LOOS+0x" + to_hexString(Type - SHT_LOOS);
  3211. else if (Type >= SHT_LOPROC && Type <= SHT_HIPROC)
  3212. return "LOPROC+0x" + to_hexString(Type - SHT_LOPROC);
  3213. else if (Type >= SHT_LOUSER && Type <= SHT_HIUSER)
  3214. return "LOUSER+0x" + to_hexString(Type - SHT_LOUSER);
  3215. return "0x" + to_hexString(Type) + ": <unknown>";
  3216. }
  3217. static std::string getSectionTypeString(unsigned Machine, unsigned Type) {
  3218. StringRef Name = getELFSectionTypeName(Machine, Type);
  3219. // Handle SHT_GNU_* type names.
  3220. if (Name.startswith("SHT_GNU_")) {
  3221. if (Name == "SHT_GNU_HASH")
  3222. return "GNU_HASH";
  3223. // E.g. SHT_GNU_verneed -> VERNEED.
  3224. return Name.drop_front(8).upper();
  3225. }
  3226. if (Name == "SHT_SYMTAB_SHNDX")
  3227. return "SYMTAB SECTION INDICES";
  3228. if (Name.startswith("SHT_"))
  3229. return Name.drop_front(4).str();
  3230. return getSectionTypeOffsetString(Type);
  3231. }
  3232. static void printSectionDescription(formatted_raw_ostream &OS,
  3233. unsigned EMachine) {
  3234. OS << "Key to Flags:\n";
  3235. OS << " W (write), A (alloc), X (execute), M (merge), S (strings), I "
  3236. "(info),\n";
  3237. OS << " L (link order), O (extra OS processing required), G (group), T "
  3238. "(TLS),\n";
  3239. OS << " C (compressed), x (unknown), o (OS specific), E (exclude),\n";
  3240. OS << " R (retain)";
  3241. if (EMachine == EM_X86_64)
  3242. OS << ", l (large)";
  3243. else if (EMachine == EM_ARM)
  3244. OS << ", y (purecode)";
  3245. OS << ", p (processor specific)\n";
  3246. }
  3247. template <class ELFT> void GNUELFDumper<ELFT>::printSectionHeaders() {
  3248. unsigned Bias = ELFT::Is64Bits ? 0 : 8;
  3249. ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections());
  3250. OS << "There are " << to_string(Sections.size())
  3251. << " section headers, starting at offset "
  3252. << "0x" << to_hexString(this->Obj.getHeader().e_shoff, false) << ":\n\n";
  3253. OS << "Section Headers:\n";
  3254. Field Fields[11] = {
  3255. {"[Nr]", 2}, {"Name", 7}, {"Type", 25},
  3256. {"Address", 41}, {"Off", 58 - Bias}, {"Size", 65 - Bias},
  3257. {"ES", 72 - Bias}, {"Flg", 75 - Bias}, {"Lk", 79 - Bias},
  3258. {"Inf", 82 - Bias}, {"Al", 86 - Bias}};
  3259. for (const Field &F : Fields)
  3260. printField(F);
  3261. OS << "\n";
  3262. StringRef SecStrTable;
  3263. if (Expected<StringRef> SecStrTableOrErr =
  3264. this->Obj.getSectionStringTable(Sections, this->WarningHandler))
  3265. SecStrTable = *SecStrTableOrErr;
  3266. else
  3267. this->reportUniqueWarning(SecStrTableOrErr.takeError());
  3268. size_t SectionIndex = 0;
  3269. for (const Elf_Shdr &Sec : Sections) {
  3270. Fields[0].Str = to_string(SectionIndex);
  3271. if (SecStrTable.empty())
  3272. Fields[1].Str = "<no-strings>";
  3273. else
  3274. Fields[1].Str = std::string(unwrapOrError<StringRef>(
  3275. this->FileName, this->Obj.getSectionName(Sec, SecStrTable)));
  3276. Fields[2].Str =
  3277. getSectionTypeString(this->Obj.getHeader().e_machine, Sec.sh_type);
  3278. Fields[3].Str =
  3279. to_string(format_hex_no_prefix(Sec.sh_addr, ELFT::Is64Bits ? 16 : 8));
  3280. Fields[4].Str = to_string(format_hex_no_prefix(Sec.sh_offset, 6));
  3281. Fields[5].Str = to_string(format_hex_no_prefix(Sec.sh_size, 6));
  3282. Fields[6].Str = to_string(format_hex_no_prefix(Sec.sh_entsize, 2));
  3283. Fields[7].Str = getGNUFlags(this->Obj.getHeader().e_machine, Sec.sh_flags);
  3284. Fields[8].Str = to_string(Sec.sh_link);
  3285. Fields[9].Str = to_string(Sec.sh_info);
  3286. Fields[10].Str = to_string(Sec.sh_addralign);
  3287. OS.PadToColumn(Fields[0].Column);
  3288. OS << "[" << right_justify(Fields[0].Str, 2) << "]";
  3289. for (int i = 1; i < 7; i++)
  3290. printField(Fields[i]);
  3291. OS.PadToColumn(Fields[7].Column);
  3292. OS << right_justify(Fields[7].Str, 3);
  3293. OS.PadToColumn(Fields[8].Column);
  3294. OS << right_justify(Fields[8].Str, 2);
  3295. OS.PadToColumn(Fields[9].Column);
  3296. OS << right_justify(Fields[9].Str, 3);
  3297. OS.PadToColumn(Fields[10].Column);
  3298. OS << right_justify(Fields[10].Str, 2);
  3299. OS << "\n";
  3300. ++SectionIndex;
  3301. }
  3302. printSectionDescription(OS, this->Obj.getHeader().e_machine);
  3303. }
  3304. template <class ELFT>
  3305. void GNUELFDumper<ELFT>::printSymtabMessage(const Elf_Shdr *Symtab,
  3306. size_t Entries,
  3307. bool NonVisibilityBitsUsed) const {
  3308. StringRef Name;
  3309. if (Symtab)
  3310. Name = this->getPrintableSectionName(*Symtab);
  3311. if (!Name.empty())
  3312. OS << "\nSymbol table '" << Name << "'";
  3313. else
  3314. OS << "\nSymbol table for image";
  3315. OS << " contains " << Entries << " entries:\n";
  3316. if (ELFT::Is64Bits)
  3317. OS << " Num: Value Size Type Bind Vis";
  3318. else
  3319. OS << " Num: Value Size Type Bind Vis";
  3320. if (NonVisibilityBitsUsed)
  3321. OS << " ";
  3322. OS << " Ndx Name\n";
  3323. }
  3324. template <class ELFT>
  3325. std::string
  3326. GNUELFDumper<ELFT>::getSymbolSectionNdx(const Elf_Sym &Symbol,
  3327. unsigned SymIndex,
  3328. DataRegion<Elf_Word> ShndxTable) const {
  3329. unsigned SectionIndex = Symbol.st_shndx;
  3330. switch (SectionIndex) {
  3331. case ELF::SHN_UNDEF:
  3332. return "UND";
  3333. case ELF::SHN_ABS:
  3334. return "ABS";
  3335. case ELF::SHN_COMMON:
  3336. return "COM";
  3337. case ELF::SHN_XINDEX: {
  3338. Expected<uint32_t> IndexOrErr =
  3339. object::getExtendedSymbolTableIndex<ELFT>(Symbol, SymIndex, ShndxTable);
  3340. if (!IndexOrErr) {
  3341. assert(Symbol.st_shndx == SHN_XINDEX &&
  3342. "getExtendedSymbolTableIndex should only fail due to an invalid "
  3343. "SHT_SYMTAB_SHNDX table/reference");
  3344. this->reportUniqueWarning(IndexOrErr.takeError());
  3345. return "RSV[0xffff]";
  3346. }
  3347. return to_string(format_decimal(*IndexOrErr, 3));
  3348. }
  3349. default:
  3350. // Find if:
  3351. // Processor specific
  3352. if (SectionIndex >= ELF::SHN_LOPROC && SectionIndex <= ELF::SHN_HIPROC)
  3353. return std::string("PRC[0x") +
  3354. to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
  3355. // OS specific
  3356. if (SectionIndex >= ELF::SHN_LOOS && SectionIndex <= ELF::SHN_HIOS)
  3357. return std::string("OS[0x") +
  3358. to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
  3359. // Architecture reserved:
  3360. if (SectionIndex >= ELF::SHN_LORESERVE &&
  3361. SectionIndex <= ELF::SHN_HIRESERVE)
  3362. return std::string("RSV[0x") +
  3363. to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
  3364. // A normal section with an index
  3365. return to_string(format_decimal(SectionIndex, 3));
  3366. }
  3367. }
  3368. template <class ELFT>
  3369. void GNUELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
  3370. DataRegion<Elf_Word> ShndxTable,
  3371. Optional<StringRef> StrTable,
  3372. bool IsDynamic,
  3373. bool NonVisibilityBitsUsed) const {
  3374. unsigned Bias = ELFT::Is64Bits ? 8 : 0;
  3375. Field Fields[8] = {0, 8, 17 + Bias, 23 + Bias,
  3376. 31 + Bias, 38 + Bias, 48 + Bias, 51 + Bias};
  3377. Fields[0].Str = to_string(format_decimal(SymIndex, 6)) + ":";
  3378. Fields[1].Str =
  3379. to_string(format_hex_no_prefix(Symbol.st_value, ELFT::Is64Bits ? 16 : 8));
  3380. Fields[2].Str = to_string(format_decimal(Symbol.st_size, 5));
  3381. unsigned char SymbolType = Symbol.getType();
  3382. if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
  3383. SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
  3384. Fields[3].Str = enumToString(SymbolType, makeArrayRef(AMDGPUSymbolTypes));
  3385. else
  3386. Fields[3].Str = enumToString(SymbolType, makeArrayRef(ElfSymbolTypes));
  3387. Fields[4].Str =
  3388. enumToString(Symbol.getBinding(), makeArrayRef(ElfSymbolBindings));
  3389. Fields[5].Str =
  3390. enumToString(Symbol.getVisibility(), makeArrayRef(ElfSymbolVisibilities));
  3391. if (Symbol.st_other & ~0x3) {
  3392. if (this->Obj.getHeader().e_machine == ELF::EM_AARCH64) {
  3393. uint8_t Other = Symbol.st_other & ~0x3;
  3394. if (Other & STO_AARCH64_VARIANT_PCS) {
  3395. Other &= ~STO_AARCH64_VARIANT_PCS;
  3396. Fields[5].Str += " [VARIANT_PCS";
  3397. if (Other != 0)
  3398. Fields[5].Str.append(" | " + to_hexString(Other, false));
  3399. Fields[5].Str.append("]");
  3400. }
  3401. } else if (this->Obj.getHeader().e_machine == ELF::EM_RISCV) {
  3402. uint8_t Other = Symbol.st_other & ~0x3;
  3403. if (Other & STO_RISCV_VARIANT_CC) {
  3404. Other &= ~STO_RISCV_VARIANT_CC;
  3405. Fields[5].Str += " [VARIANT_CC";
  3406. if (Other != 0)
  3407. Fields[5].Str.append(" | " + to_hexString(Other, false));
  3408. Fields[5].Str.append("]");
  3409. }
  3410. } else {
  3411. Fields[5].Str +=
  3412. " [<other: " + to_string(format_hex(Symbol.st_other, 2)) + ">]";
  3413. }
  3414. }
  3415. Fields[6].Column += NonVisibilityBitsUsed ? 13 : 0;
  3416. Fields[6].Str = getSymbolSectionNdx(Symbol, SymIndex, ShndxTable);
  3417. Fields[7].Str = this->getFullSymbolName(Symbol, SymIndex, ShndxTable,
  3418. StrTable, IsDynamic);
  3419. for (const Field &Entry : Fields)
  3420. printField(Entry);
  3421. OS << "\n";
  3422. }
  3423. template <class ELFT>
  3424. void GNUELFDumper<ELFT>::printHashedSymbol(const Elf_Sym *Symbol,
  3425. unsigned SymIndex,
  3426. DataRegion<Elf_Word> ShndxTable,
  3427. StringRef StrTable,
  3428. uint32_t Bucket) {
  3429. unsigned Bias = ELFT::Is64Bits ? 8 : 0;
  3430. Field Fields[9] = {0, 6, 11, 20 + Bias, 25 + Bias,
  3431. 34 + Bias, 41 + Bias, 49 + Bias, 53 + Bias};
  3432. Fields[0].Str = to_string(format_decimal(SymIndex, 5));
  3433. Fields[1].Str = to_string(format_decimal(Bucket, 3)) + ":";
  3434. Fields[2].Str = to_string(
  3435. format_hex_no_prefix(Symbol->st_value, ELFT::Is64Bits ? 16 : 8));
  3436. Fields[3].Str = to_string(format_decimal(Symbol->st_size, 5));
  3437. unsigned char SymbolType = Symbol->getType();
  3438. if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
  3439. SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
  3440. Fields[4].Str = enumToString(SymbolType, makeArrayRef(AMDGPUSymbolTypes));
  3441. else
  3442. Fields[4].Str = enumToString(SymbolType, makeArrayRef(ElfSymbolTypes));
  3443. Fields[5].Str =
  3444. enumToString(Symbol->getBinding(), makeArrayRef(ElfSymbolBindings));
  3445. Fields[6].Str = enumToString(Symbol->getVisibility(),
  3446. makeArrayRef(ElfSymbolVisibilities));
  3447. Fields[7].Str = getSymbolSectionNdx(*Symbol, SymIndex, ShndxTable);
  3448. Fields[8].Str =
  3449. this->getFullSymbolName(*Symbol, SymIndex, ShndxTable, StrTable, true);
  3450. for (const Field &Entry : Fields)
  3451. printField(Entry);
  3452. OS << "\n";
  3453. }
  3454. template <class ELFT>
  3455. void GNUELFDumper<ELFT>::printSymbols(bool PrintSymbols,
  3456. bool PrintDynamicSymbols) {
  3457. if (!PrintSymbols && !PrintDynamicSymbols)
  3458. return;
  3459. // GNU readelf prints both the .dynsym and .symtab with --symbols.
  3460. this->printSymbolsHelper(true);
  3461. if (PrintSymbols)
  3462. this->printSymbolsHelper(false);
  3463. }
  3464. template <class ELFT>
  3465. void GNUELFDumper<ELFT>::printHashTableSymbols(const Elf_Hash &SysVHash) {
  3466. if (this->DynamicStringTable.empty())
  3467. return;
  3468. if (ELFT::Is64Bits)
  3469. OS << " Num Buc: Value Size Type Bind Vis Ndx Name";
  3470. else
  3471. OS << " Num Buc: Value Size Type Bind Vis Ndx Name";
  3472. OS << "\n";
  3473. Elf_Sym_Range DynSyms = this->dynamic_symbols();
  3474. const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0];
  3475. if (!FirstSym) {
  3476. this->reportUniqueWarning(
  3477. Twine("unable to print symbols for the .hash table: the "
  3478. "dynamic symbol table ") +
  3479. (this->DynSymRegion ? "is empty" : "was not found"));
  3480. return;
  3481. }
  3482. DataRegion<Elf_Word> ShndxTable(
  3483. (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
  3484. auto Buckets = SysVHash.buckets();
  3485. auto Chains = SysVHash.chains();
  3486. for (uint32_t Buc = 0; Buc < SysVHash.nbucket; Buc++) {
  3487. if (Buckets[Buc] == ELF::STN_UNDEF)
  3488. continue;
  3489. BitVector Visited(SysVHash.nchain);
  3490. for (uint32_t Ch = Buckets[Buc]; Ch < SysVHash.nchain; Ch = Chains[Ch]) {
  3491. if (Ch == ELF::STN_UNDEF)
  3492. break;
  3493. if (Visited[Ch]) {
  3494. this->reportUniqueWarning(".hash section is invalid: bucket " +
  3495. Twine(Ch) +
  3496. ": a cycle was detected in the linked chain");
  3497. break;
  3498. }
  3499. printHashedSymbol(FirstSym + Ch, Ch, ShndxTable, this->DynamicStringTable,
  3500. Buc);
  3501. Visited[Ch] = true;
  3502. }
  3503. }
  3504. }
  3505. template <class ELFT>
  3506. void GNUELFDumper<ELFT>::printGnuHashTableSymbols(const Elf_GnuHash &GnuHash) {
  3507. if (this->DynamicStringTable.empty())
  3508. return;
  3509. Elf_Sym_Range DynSyms = this->dynamic_symbols();
  3510. const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0];
  3511. if (!FirstSym) {
  3512. this->reportUniqueWarning(
  3513. Twine("unable to print symbols for the .gnu.hash table: the "
  3514. "dynamic symbol table ") +
  3515. (this->DynSymRegion ? "is empty" : "was not found"));
  3516. return;
  3517. }
  3518. auto GetSymbol = [&](uint64_t SymIndex,
  3519. uint64_t SymsTotal) -> const Elf_Sym * {
  3520. if (SymIndex >= SymsTotal) {
  3521. this->reportUniqueWarning(
  3522. "unable to print hashed symbol with index " + Twine(SymIndex) +
  3523. ", which is greater than or equal to the number of dynamic symbols "
  3524. "(" +
  3525. Twine::utohexstr(SymsTotal) + ")");
  3526. return nullptr;
  3527. }
  3528. return FirstSym + SymIndex;
  3529. };
  3530. Expected<ArrayRef<Elf_Word>> ValuesOrErr =
  3531. getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHash);
  3532. ArrayRef<Elf_Word> Values;
  3533. if (!ValuesOrErr)
  3534. this->reportUniqueWarning("unable to get hash values for the SHT_GNU_HASH "
  3535. "section: " +
  3536. toString(ValuesOrErr.takeError()));
  3537. else
  3538. Values = *ValuesOrErr;
  3539. DataRegion<Elf_Word> ShndxTable(
  3540. (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
  3541. ArrayRef<Elf_Word> Buckets = GnuHash.buckets();
  3542. for (uint32_t Buc = 0; Buc < GnuHash.nbuckets; Buc++) {
  3543. if (Buckets[Buc] == ELF::STN_UNDEF)
  3544. continue;
  3545. uint32_t Index = Buckets[Buc];
  3546. // Print whole chain.
  3547. while (true) {
  3548. uint32_t SymIndex = Index++;
  3549. if (const Elf_Sym *Sym = GetSymbol(SymIndex, DynSyms.size()))
  3550. printHashedSymbol(Sym, SymIndex, ShndxTable, this->DynamicStringTable,
  3551. Buc);
  3552. else
  3553. break;
  3554. if (SymIndex < GnuHash.symndx) {
  3555. this->reportUniqueWarning(
  3556. "unable to read the hash value for symbol with index " +
  3557. Twine(SymIndex) +
  3558. ", which is less than the index of the first hashed symbol (" +
  3559. Twine(GnuHash.symndx) + ")");
  3560. break;
  3561. }
  3562. // Chain ends at symbol with stopper bit.
  3563. if ((Values[SymIndex - GnuHash.symndx] & 1) == 1)
  3564. break;
  3565. }
  3566. }
  3567. }
  3568. template <class ELFT> void GNUELFDumper<ELFT>::printHashSymbols() {
  3569. if (this->HashTable) {
  3570. OS << "\n Symbol table of .hash for image:\n";
  3571. if (Error E = checkHashTable<ELFT>(*this, this->HashTable))
  3572. this->reportUniqueWarning(std::move(E));
  3573. else
  3574. printHashTableSymbols(*this->HashTable);
  3575. }
  3576. // Try printing the .gnu.hash table.
  3577. if (this->GnuHashTable) {
  3578. OS << "\n Symbol table of .gnu.hash for image:\n";
  3579. if (ELFT::Is64Bits)
  3580. OS << " Num Buc: Value Size Type Bind Vis Ndx Name";
  3581. else
  3582. OS << " Num Buc: Value Size Type Bind Vis Ndx Name";
  3583. OS << "\n";
  3584. if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable))
  3585. this->reportUniqueWarning(std::move(E));
  3586. else
  3587. printGnuHashTableSymbols(*this->GnuHashTable);
  3588. }
  3589. }
  3590. template <class ELFT> void GNUELFDumper<ELFT>::printSectionDetails() {
  3591. ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections());
  3592. OS << "There are " << to_string(Sections.size())
  3593. << " section headers, starting at offset "
  3594. << "0x" << to_hexString(this->Obj.getHeader().e_shoff, false) << ":\n\n";
  3595. OS << "Section Headers:\n";
  3596. auto PrintFields = [&](ArrayRef<Field> V) {
  3597. for (const Field &F : V)
  3598. printField(F);
  3599. OS << "\n";
  3600. };
  3601. PrintFields({{"[Nr]", 2}, {"Name", 7}});
  3602. constexpr bool Is64 = ELFT::Is64Bits;
  3603. PrintFields({{"Type", 7},
  3604. {Is64 ? "Address" : "Addr", 23},
  3605. {"Off", Is64 ? 40 : 32},
  3606. {"Size", Is64 ? 47 : 39},
  3607. {"ES", Is64 ? 54 : 46},
  3608. {"Lk", Is64 ? 59 : 51},
  3609. {"Inf", Is64 ? 62 : 54},
  3610. {"Al", Is64 ? 66 : 57}});
  3611. PrintFields({{"Flags", 7}});
  3612. StringRef SecStrTable;
  3613. if (Expected<StringRef> SecStrTableOrErr =
  3614. this->Obj.getSectionStringTable(Sections, this->WarningHandler))
  3615. SecStrTable = *SecStrTableOrErr;
  3616. else
  3617. this->reportUniqueWarning(SecStrTableOrErr.takeError());
  3618. size_t SectionIndex = 0;
  3619. const unsigned AddrSize = Is64 ? 16 : 8;
  3620. for (const Elf_Shdr &S : Sections) {
  3621. StringRef Name = "<?>";
  3622. if (Expected<StringRef> NameOrErr =
  3623. this->Obj.getSectionName(S, SecStrTable))
  3624. Name = *NameOrErr;
  3625. else
  3626. this->reportUniqueWarning(NameOrErr.takeError());
  3627. OS.PadToColumn(2);
  3628. OS << "[" << right_justify(to_string(SectionIndex), 2) << "]";
  3629. PrintFields({{Name, 7}});
  3630. PrintFields(
  3631. {{getSectionTypeString(this->Obj.getHeader().e_machine, S.sh_type), 7},
  3632. {to_string(format_hex_no_prefix(S.sh_addr, AddrSize)), 23},
  3633. {to_string(format_hex_no_prefix(S.sh_offset, 6)), Is64 ? 39 : 32},
  3634. {to_string(format_hex_no_prefix(S.sh_size, 6)), Is64 ? 47 : 39},
  3635. {to_string(format_hex_no_prefix(S.sh_entsize, 2)), Is64 ? 54 : 46},
  3636. {to_string(S.sh_link), Is64 ? 59 : 51},
  3637. {to_string(S.sh_info), Is64 ? 63 : 55},
  3638. {to_string(S.sh_addralign), Is64 ? 66 : 58}});
  3639. OS.PadToColumn(7);
  3640. OS << "[" << to_string(format_hex_no_prefix(S.sh_flags, AddrSize)) << "]: ";
  3641. DenseMap<unsigned, StringRef> FlagToName = {
  3642. {SHF_WRITE, "WRITE"}, {SHF_ALLOC, "ALLOC"},
  3643. {SHF_EXECINSTR, "EXEC"}, {SHF_MERGE, "MERGE"},
  3644. {SHF_STRINGS, "STRINGS"}, {SHF_INFO_LINK, "INFO LINK"},
  3645. {SHF_LINK_ORDER, "LINK ORDER"}, {SHF_OS_NONCONFORMING, "OS NONCONF"},
  3646. {SHF_GROUP, "GROUP"}, {SHF_TLS, "TLS"},
  3647. {SHF_COMPRESSED, "COMPRESSED"}, {SHF_EXCLUDE, "EXCLUDE"}};
  3648. uint64_t Flags = S.sh_flags;
  3649. uint64_t UnknownFlags = 0;
  3650. ListSeparator LS;
  3651. while (Flags) {
  3652. // Take the least significant bit as a flag.
  3653. uint64_t Flag = Flags & -Flags;
  3654. Flags -= Flag;
  3655. auto It = FlagToName.find(Flag);
  3656. if (It != FlagToName.end())
  3657. OS << LS << It->second;
  3658. else
  3659. UnknownFlags |= Flag;
  3660. }
  3661. auto PrintUnknownFlags = [&](uint64_t Mask, StringRef Name) {
  3662. uint64_t FlagsToPrint = UnknownFlags & Mask;
  3663. if (!FlagsToPrint)
  3664. return;
  3665. OS << LS << Name << " ("
  3666. << to_string(format_hex_no_prefix(FlagsToPrint, AddrSize)) << ")";
  3667. UnknownFlags &= ~Mask;
  3668. };
  3669. PrintUnknownFlags(SHF_MASKOS, "OS");
  3670. PrintUnknownFlags(SHF_MASKPROC, "PROC");
  3671. PrintUnknownFlags(uint64_t(-1), "UNKNOWN");
  3672. OS << "\n";
  3673. ++SectionIndex;
  3674. }
  3675. }
  3676. static inline std::string printPhdrFlags(unsigned Flag) {
  3677. std::string Str;
  3678. Str = (Flag & PF_R) ? "R" : " ";
  3679. Str += (Flag & PF_W) ? "W" : " ";
  3680. Str += (Flag & PF_X) ? "E" : " ";
  3681. return Str;
  3682. }
  3683. template <class ELFT>
  3684. static bool checkTLSSections(const typename ELFT::Phdr &Phdr,
  3685. const typename ELFT::Shdr &Sec) {
  3686. if (Sec.sh_flags & ELF::SHF_TLS) {
  3687. // .tbss must only be shown in the PT_TLS segment.
  3688. if (Sec.sh_type == ELF::SHT_NOBITS)
  3689. return Phdr.p_type == ELF::PT_TLS;
  3690. // SHF_TLS sections are only shown in PT_TLS, PT_LOAD or PT_GNU_RELRO
  3691. // segments.
  3692. return (Phdr.p_type == ELF::PT_TLS) || (Phdr.p_type == ELF::PT_LOAD) ||
  3693. (Phdr.p_type == ELF::PT_GNU_RELRO);
  3694. }
  3695. // PT_TLS must only have SHF_TLS sections.
  3696. return Phdr.p_type != ELF::PT_TLS;
  3697. }
  3698. template <class ELFT>
  3699. static bool checkOffsets(const typename ELFT::Phdr &Phdr,
  3700. const typename ELFT::Shdr &Sec) {
  3701. // SHT_NOBITS sections don't need to have an offset inside the segment.
  3702. if (Sec.sh_type == ELF::SHT_NOBITS)
  3703. return true;
  3704. if (Sec.sh_offset < Phdr.p_offset)
  3705. return false;
  3706. // Only non-empty sections can be at the end of a segment.
  3707. if (Sec.sh_size == 0)
  3708. return (Sec.sh_offset + 1 <= Phdr.p_offset + Phdr.p_filesz);
  3709. return Sec.sh_offset + Sec.sh_size <= Phdr.p_offset + Phdr.p_filesz;
  3710. }
  3711. // Check that an allocatable section belongs to a virtual address
  3712. // space of a segment.
  3713. template <class ELFT>
  3714. static bool checkVMA(const typename ELFT::Phdr &Phdr,
  3715. const typename ELFT::Shdr &Sec) {
  3716. if (!(Sec.sh_flags & ELF::SHF_ALLOC))
  3717. return true;
  3718. if (Sec.sh_addr < Phdr.p_vaddr)
  3719. return false;
  3720. bool IsTbss =
  3721. (Sec.sh_type == ELF::SHT_NOBITS) && ((Sec.sh_flags & ELF::SHF_TLS) != 0);
  3722. // .tbss is special, it only has memory in PT_TLS and has NOBITS properties.
  3723. bool IsTbssInNonTLS = IsTbss && Phdr.p_type != ELF::PT_TLS;
  3724. // Only non-empty sections can be at the end of a segment.
  3725. if (Sec.sh_size == 0 || IsTbssInNonTLS)
  3726. return Sec.sh_addr + 1 <= Phdr.p_vaddr + Phdr.p_memsz;
  3727. return Sec.sh_addr + Sec.sh_size <= Phdr.p_vaddr + Phdr.p_memsz;
  3728. }
  3729. template <class ELFT>
  3730. static bool checkPTDynamic(const typename ELFT::Phdr &Phdr,
  3731. const typename ELFT::Shdr &Sec) {
  3732. if (Phdr.p_type != ELF::PT_DYNAMIC || Phdr.p_memsz == 0 || Sec.sh_size != 0)
  3733. return true;
  3734. // We get here when we have an empty section. Only non-empty sections can be
  3735. // at the start or at the end of PT_DYNAMIC.
  3736. // Is section within the phdr both based on offset and VMA?
  3737. bool CheckOffset = (Sec.sh_type == ELF::SHT_NOBITS) ||
  3738. (Sec.sh_offset > Phdr.p_offset &&
  3739. Sec.sh_offset < Phdr.p_offset + Phdr.p_filesz);
  3740. bool CheckVA = !(Sec.sh_flags & ELF::SHF_ALLOC) ||
  3741. (Sec.sh_addr > Phdr.p_vaddr && Sec.sh_addr < Phdr.p_memsz);
  3742. return CheckOffset && CheckVA;
  3743. }
  3744. template <class ELFT>
  3745. void GNUELFDumper<ELFT>::printProgramHeaders(
  3746. bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) {
  3747. if (PrintProgramHeaders)
  3748. printProgramHeaders();
  3749. // Display the section mapping along with the program headers, unless
  3750. // -section-mapping is explicitly set to false.
  3751. if (PrintSectionMapping != cl::BOU_FALSE)
  3752. printSectionMapping();
  3753. }
  3754. template <class ELFT> void GNUELFDumper<ELFT>::printProgramHeaders() {
  3755. unsigned Bias = ELFT::Is64Bits ? 8 : 0;
  3756. const Elf_Ehdr &Header = this->Obj.getHeader();
  3757. Field Fields[8] = {2, 17, 26, 37 + Bias,
  3758. 48 + Bias, 56 + Bias, 64 + Bias, 68 + Bias};
  3759. OS << "\nElf file type is "
  3760. << enumToString(Header.e_type, makeArrayRef(ElfObjectFileType)) << "\n"
  3761. << "Entry point " << format_hex(Header.e_entry, 3) << "\n"
  3762. << "There are " << Header.e_phnum << " program headers,"
  3763. << " starting at offset " << Header.e_phoff << "\n\n"
  3764. << "Program Headers:\n";
  3765. if (ELFT::Is64Bits)
  3766. OS << " Type Offset VirtAddr PhysAddr "
  3767. << " FileSiz MemSiz Flg Align\n";
  3768. else
  3769. OS << " Type Offset VirtAddr PhysAddr FileSiz "
  3770. << "MemSiz Flg Align\n";
  3771. unsigned Width = ELFT::Is64Bits ? 18 : 10;
  3772. unsigned SizeWidth = ELFT::Is64Bits ? 8 : 7;
  3773. Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
  3774. if (!PhdrsOrErr) {
  3775. this->reportUniqueWarning("unable to dump program headers: " +
  3776. toString(PhdrsOrErr.takeError()));
  3777. return;
  3778. }
  3779. for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
  3780. Fields[0].Str = getGNUPtType(Header.e_machine, Phdr.p_type);
  3781. Fields[1].Str = to_string(format_hex(Phdr.p_offset, 8));
  3782. Fields[2].Str = to_string(format_hex(Phdr.p_vaddr, Width));
  3783. Fields[3].Str = to_string(format_hex(Phdr.p_paddr, Width));
  3784. Fields[4].Str = to_string(format_hex(Phdr.p_filesz, SizeWidth));
  3785. Fields[5].Str = to_string(format_hex(Phdr.p_memsz, SizeWidth));
  3786. Fields[6].Str = printPhdrFlags(Phdr.p_flags);
  3787. Fields[7].Str = to_string(format_hex(Phdr.p_align, 1));
  3788. for (const Field &F : Fields)
  3789. printField(F);
  3790. if (Phdr.p_type == ELF::PT_INTERP) {
  3791. OS << "\n";
  3792. auto ReportBadInterp = [&](const Twine &Msg) {
  3793. this->reportUniqueWarning(
  3794. "unable to read program interpreter name at offset 0x" +
  3795. Twine::utohexstr(Phdr.p_offset) + ": " + Msg);
  3796. };
  3797. if (Phdr.p_offset >= this->Obj.getBufSize()) {
  3798. ReportBadInterp("it goes past the end of the file (0x" +
  3799. Twine::utohexstr(this->Obj.getBufSize()) + ")");
  3800. continue;
  3801. }
  3802. const char *Data =
  3803. reinterpret_cast<const char *>(this->Obj.base()) + Phdr.p_offset;
  3804. size_t MaxSize = this->Obj.getBufSize() - Phdr.p_offset;
  3805. size_t Len = strnlen(Data, MaxSize);
  3806. if (Len == MaxSize) {
  3807. ReportBadInterp("it is not null-terminated");
  3808. continue;
  3809. }
  3810. OS << " [Requesting program interpreter: ";
  3811. OS << StringRef(Data, Len) << "]";
  3812. }
  3813. OS << "\n";
  3814. }
  3815. }
  3816. template <class ELFT> void GNUELFDumper<ELFT>::printSectionMapping() {
  3817. OS << "\n Section to Segment mapping:\n Segment Sections...\n";
  3818. DenseSet<const Elf_Shdr *> BelongsToSegment;
  3819. int Phnum = 0;
  3820. Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
  3821. if (!PhdrsOrErr) {
  3822. this->reportUniqueWarning(
  3823. "can't read program headers to build section to segment mapping: " +
  3824. toString(PhdrsOrErr.takeError()));
  3825. return;
  3826. }
  3827. for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
  3828. std::string Sections;
  3829. OS << format(" %2.2d ", Phnum++);
  3830. // Check if each section is in a segment and then print mapping.
  3831. for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
  3832. if (Sec.sh_type == ELF::SHT_NULL)
  3833. continue;
  3834. // readelf additionally makes sure it does not print zero sized sections
  3835. // at end of segments and for PT_DYNAMIC both start and end of section
  3836. // .tbss must only be shown in PT_TLS section.
  3837. if (checkTLSSections<ELFT>(Phdr, Sec) && checkOffsets<ELFT>(Phdr, Sec) &&
  3838. checkVMA<ELFT>(Phdr, Sec) && checkPTDynamic<ELFT>(Phdr, Sec)) {
  3839. Sections +=
  3840. unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() +
  3841. " ";
  3842. BelongsToSegment.insert(&Sec);
  3843. }
  3844. }
  3845. OS << Sections << "\n";
  3846. OS.flush();
  3847. }
  3848. // Display sections that do not belong to a segment.
  3849. std::string Sections;
  3850. for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
  3851. if (BelongsToSegment.find(&Sec) == BelongsToSegment.end())
  3852. Sections +=
  3853. unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() +
  3854. ' ';
  3855. }
  3856. if (!Sections.empty()) {
  3857. OS << " None " << Sections << '\n';
  3858. OS.flush();
  3859. }
  3860. }
  3861. namespace {
  3862. template <class ELFT>
  3863. RelSymbol<ELFT> getSymbolForReloc(const ELFDumper<ELFT> &Dumper,
  3864. const Relocation<ELFT> &Reloc) {
  3865. using Elf_Sym = typename ELFT::Sym;
  3866. auto WarnAndReturn = [&](const Elf_Sym *Sym,
  3867. const Twine &Reason) -> RelSymbol<ELFT> {
  3868. Dumper.reportUniqueWarning(
  3869. "unable to get name of the dynamic symbol with index " +
  3870. Twine(Reloc.Symbol) + ": " + Reason);
  3871. return {Sym, "<corrupt>"};
  3872. };
  3873. ArrayRef<Elf_Sym> Symbols = Dumper.dynamic_symbols();
  3874. const Elf_Sym *FirstSym = Symbols.begin();
  3875. if (!FirstSym)
  3876. return WarnAndReturn(nullptr, "no dynamic symbol table found");
  3877. // We might have an object without a section header. In this case the size of
  3878. // Symbols is zero, because there is no way to know the size of the dynamic
  3879. // table. We should allow this case and not print a warning.
  3880. if (!Symbols.empty() && Reloc.Symbol >= Symbols.size())
  3881. return WarnAndReturn(
  3882. nullptr,
  3883. "index is greater than or equal to the number of dynamic symbols (" +
  3884. Twine(Symbols.size()) + ")");
  3885. const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
  3886. const uint64_t FileSize = Obj.getBufSize();
  3887. const uint64_t SymOffset = ((const uint8_t *)FirstSym - Obj.base()) +
  3888. (uint64_t)Reloc.Symbol * sizeof(Elf_Sym);
  3889. if (SymOffset + sizeof(Elf_Sym) > FileSize)
  3890. return WarnAndReturn(nullptr, "symbol at 0x" + Twine::utohexstr(SymOffset) +
  3891. " goes past the end of the file (0x" +
  3892. Twine::utohexstr(FileSize) + ")");
  3893. const Elf_Sym *Sym = FirstSym + Reloc.Symbol;
  3894. Expected<StringRef> ErrOrName = Sym->getName(Dumper.getDynamicStringTable());
  3895. if (!ErrOrName)
  3896. return WarnAndReturn(Sym, toString(ErrOrName.takeError()));
  3897. return {Sym == FirstSym ? nullptr : Sym, maybeDemangle(*ErrOrName)};
  3898. }
  3899. } // namespace
  3900. template <class ELFT>
  3901. static size_t getMaxDynamicTagSize(const ELFFile<ELFT> &Obj,
  3902. typename ELFT::DynRange Tags) {
  3903. size_t Max = 0;
  3904. for (const typename ELFT::Dyn &Dyn : Tags)
  3905. Max = std::max(Max, Obj.getDynamicTagAsString(Dyn.d_tag).size());
  3906. return Max;
  3907. }
  3908. template <class ELFT> void GNUELFDumper<ELFT>::printDynamicTable() {
  3909. Elf_Dyn_Range Table = this->dynamic_table();
  3910. if (Table.empty())
  3911. return;
  3912. OS << "Dynamic section at offset "
  3913. << format_hex(reinterpret_cast<const uint8_t *>(this->DynamicTable.Addr) -
  3914. this->Obj.base(),
  3915. 1)
  3916. << " contains " << Table.size() << " entries:\n";
  3917. // The type name is surrounded with round brackets, hence add 2.
  3918. size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table) + 2;
  3919. // The "Name/Value" column should be indented from the "Type" column by N
  3920. // spaces, where N = MaxTagSize - length of "Type" (4) + trailing
  3921. // space (1) = 3.
  3922. OS << " Tag" + std::string(ELFT::Is64Bits ? 16 : 8, ' ') + "Type"
  3923. << std::string(MaxTagSize - 3, ' ') << "Name/Value\n";
  3924. std::string ValueFmt = " %-" + std::to_string(MaxTagSize) + "s ";
  3925. for (auto Entry : Table) {
  3926. uintX_t Tag = Entry.getTag();
  3927. std::string Type =
  3928. std::string("(") + this->Obj.getDynamicTagAsString(Tag) + ")";
  3929. std::string Value = this->getDynamicEntry(Tag, Entry.getVal());
  3930. OS << " " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10)
  3931. << format(ValueFmt.c_str(), Type.c_str()) << Value << "\n";
  3932. }
  3933. }
  3934. template <class ELFT> void GNUELFDumper<ELFT>::printDynamicRelocations() {
  3935. this->printDynamicRelocationsHelper();
  3936. }
  3937. template <class ELFT>
  3938. void ELFDumper<ELFT>::printDynamicReloc(const Relocation<ELFT> &R) {
  3939. printRelRelaReloc(R, getSymbolForReloc(*this, R));
  3940. }
  3941. template <class ELFT>
  3942. void ELFDumper<ELFT>::printRelocationsHelper(const Elf_Shdr &Sec) {
  3943. this->forEachRelocationDo(
  3944. Sec, opts::RawRelr,
  3945. [&](const Relocation<ELFT> &R, unsigned Ndx, const Elf_Shdr &Sec,
  3946. const Elf_Shdr *SymTab) { printReloc(R, Ndx, Sec, SymTab); },
  3947. [&](const Elf_Relr &R) { printRelrReloc(R); });
  3948. }
  3949. template <class ELFT> void ELFDumper<ELFT>::printDynamicRelocationsHelper() {
  3950. const bool IsMips64EL = this->Obj.isMips64EL();
  3951. if (this->DynRelaRegion.Size > 0) {
  3952. printDynamicRelocHeader(ELF::SHT_RELA, "RELA", this->DynRelaRegion);
  3953. for (const Elf_Rela &Rela :
  3954. this->DynRelaRegion.template getAsArrayRef<Elf_Rela>())
  3955. printDynamicReloc(Relocation<ELFT>(Rela, IsMips64EL));
  3956. }
  3957. if (this->DynRelRegion.Size > 0) {
  3958. printDynamicRelocHeader(ELF::SHT_REL, "REL", this->DynRelRegion);
  3959. for (const Elf_Rel &Rel :
  3960. this->DynRelRegion.template getAsArrayRef<Elf_Rel>())
  3961. printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
  3962. }
  3963. if (this->DynRelrRegion.Size > 0) {
  3964. printDynamicRelocHeader(ELF::SHT_REL, "RELR", this->DynRelrRegion);
  3965. Elf_Relr_Range Relrs =
  3966. this->DynRelrRegion.template getAsArrayRef<Elf_Relr>();
  3967. for (const Elf_Rel &Rel : Obj.decode_relrs(Relrs))
  3968. printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
  3969. }
  3970. if (this->DynPLTRelRegion.Size) {
  3971. if (this->DynPLTRelRegion.EntSize == sizeof(Elf_Rela)) {
  3972. printDynamicRelocHeader(ELF::SHT_RELA, "PLT", this->DynPLTRelRegion);
  3973. for (const Elf_Rela &Rela :
  3974. this->DynPLTRelRegion.template getAsArrayRef<Elf_Rela>())
  3975. printDynamicReloc(Relocation<ELFT>(Rela, IsMips64EL));
  3976. } else {
  3977. printDynamicRelocHeader(ELF::SHT_REL, "PLT", this->DynPLTRelRegion);
  3978. for (const Elf_Rel &Rel :
  3979. this->DynPLTRelRegion.template getAsArrayRef<Elf_Rel>())
  3980. printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
  3981. }
  3982. }
  3983. }
  3984. template <class ELFT>
  3985. void GNUELFDumper<ELFT>::printGNUVersionSectionProlog(
  3986. const typename ELFT::Shdr &Sec, const Twine &Label, unsigned EntriesNum) {
  3987. // Don't inline the SecName, because it might report a warning to stderr and
  3988. // corrupt the output.
  3989. StringRef SecName = this->getPrintableSectionName(Sec);
  3990. OS << Label << " section '" << SecName << "' "
  3991. << "contains " << EntriesNum << " entries:\n";
  3992. StringRef LinkedSecName = "<corrupt>";
  3993. if (Expected<const typename ELFT::Shdr *> LinkedSecOrErr =
  3994. this->Obj.getSection(Sec.sh_link))
  3995. LinkedSecName = this->getPrintableSectionName(**LinkedSecOrErr);
  3996. else
  3997. this->reportUniqueWarning("invalid section linked to " +
  3998. this->describe(Sec) + ": " +
  3999. toString(LinkedSecOrErr.takeError()));
  4000. OS << " Addr: " << format_hex_no_prefix(Sec.sh_addr, 16)
  4001. << " Offset: " << format_hex(Sec.sh_offset, 8)
  4002. << " Link: " << Sec.sh_link << " (" << LinkedSecName << ")\n";
  4003. }
  4004. template <class ELFT>
  4005. void GNUELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) {
  4006. if (!Sec)
  4007. return;
  4008. printGNUVersionSectionProlog(*Sec, "Version symbols",
  4009. Sec->sh_size / sizeof(Elf_Versym));
  4010. Expected<ArrayRef<Elf_Versym>> VerTableOrErr =
  4011. this->getVersionTable(*Sec, /*SymTab=*/nullptr,
  4012. /*StrTab=*/nullptr, /*SymTabSec=*/nullptr);
  4013. if (!VerTableOrErr) {
  4014. this->reportUniqueWarning(VerTableOrErr.takeError());
  4015. return;
  4016. }
  4017. SmallVector<Optional<VersionEntry>, 0> *VersionMap = nullptr;
  4018. if (Expected<SmallVector<Optional<VersionEntry>, 0> *> MapOrErr =
  4019. this->getVersionMap())
  4020. VersionMap = *MapOrErr;
  4021. else
  4022. this->reportUniqueWarning(MapOrErr.takeError());
  4023. ArrayRef<Elf_Versym> VerTable = *VerTableOrErr;
  4024. std::vector<StringRef> Versions;
  4025. for (size_t I = 0, E = VerTable.size(); I < E; ++I) {
  4026. unsigned Ndx = VerTable[I].vs_index;
  4027. if (Ndx == VER_NDX_LOCAL || Ndx == VER_NDX_GLOBAL) {
  4028. Versions.emplace_back(Ndx == VER_NDX_LOCAL ? "*local*" : "*global*");
  4029. continue;
  4030. }
  4031. if (!VersionMap) {
  4032. Versions.emplace_back("<corrupt>");
  4033. continue;
  4034. }
  4035. bool IsDefault;
  4036. Expected<StringRef> NameOrErr = this->Obj.getSymbolVersionByIndex(
  4037. Ndx, IsDefault, *VersionMap, /*IsSymHidden=*/None);
  4038. if (!NameOrErr) {
  4039. this->reportUniqueWarning("unable to get a version for entry " +
  4040. Twine(I) + " of " + this->describe(*Sec) +
  4041. ": " + toString(NameOrErr.takeError()));
  4042. Versions.emplace_back("<corrupt>");
  4043. continue;
  4044. }
  4045. Versions.emplace_back(*NameOrErr);
  4046. }
  4047. // readelf prints 4 entries per line.
  4048. uint64_t Entries = VerTable.size();
  4049. for (uint64_t VersymRow = 0; VersymRow < Entries; VersymRow += 4) {
  4050. OS << " " << format_hex_no_prefix(VersymRow, 3) << ":";
  4051. for (uint64_t I = 0; (I < 4) && (I + VersymRow) < Entries; ++I) {
  4052. unsigned Ndx = VerTable[VersymRow + I].vs_index;
  4053. OS << format("%4x%c", Ndx & VERSYM_VERSION,
  4054. Ndx & VERSYM_HIDDEN ? 'h' : ' ');
  4055. OS << left_justify("(" + std::string(Versions[VersymRow + I]) + ")", 13);
  4056. }
  4057. OS << '\n';
  4058. }
  4059. OS << '\n';
  4060. }
  4061. static std::string versionFlagToString(unsigned Flags) {
  4062. if (Flags == 0)
  4063. return "none";
  4064. std::string Ret;
  4065. auto AddFlag = [&Ret, &Flags](unsigned Flag, StringRef Name) {
  4066. if (!(Flags & Flag))
  4067. return;
  4068. if (!Ret.empty())
  4069. Ret += " | ";
  4070. Ret += Name;
  4071. Flags &= ~Flag;
  4072. };
  4073. AddFlag(VER_FLG_BASE, "BASE");
  4074. AddFlag(VER_FLG_WEAK, "WEAK");
  4075. AddFlag(VER_FLG_INFO, "INFO");
  4076. AddFlag(~0, "<unknown>");
  4077. return Ret;
  4078. }
  4079. template <class ELFT>
  4080. void GNUELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) {
  4081. if (!Sec)
  4082. return;
  4083. printGNUVersionSectionProlog(*Sec, "Version definition", Sec->sh_info);
  4084. Expected<std::vector<VerDef>> V = this->Obj.getVersionDefinitions(*Sec);
  4085. if (!V) {
  4086. this->reportUniqueWarning(V.takeError());
  4087. return;
  4088. }
  4089. for (const VerDef &Def : *V) {
  4090. OS << format(" 0x%04x: Rev: %u Flags: %s Index: %u Cnt: %u Name: %s\n",
  4091. Def.Offset, Def.Version,
  4092. versionFlagToString(Def.Flags).c_str(), Def.Ndx, Def.Cnt,
  4093. Def.Name.data());
  4094. unsigned I = 0;
  4095. for (const VerdAux &Aux : Def.AuxV)
  4096. OS << format(" 0x%04x: Parent %u: %s\n", Aux.Offset, ++I,
  4097. Aux.Name.data());
  4098. }
  4099. OS << '\n';
  4100. }
  4101. template <class ELFT>
  4102. void GNUELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) {
  4103. if (!Sec)
  4104. return;
  4105. unsigned VerneedNum = Sec->sh_info;
  4106. printGNUVersionSectionProlog(*Sec, "Version needs", VerneedNum);
  4107. Expected<std::vector<VerNeed>> V =
  4108. this->Obj.getVersionDependencies(*Sec, this->WarningHandler);
  4109. if (!V) {
  4110. this->reportUniqueWarning(V.takeError());
  4111. return;
  4112. }
  4113. for (const VerNeed &VN : *V) {
  4114. OS << format(" 0x%04x: Version: %u File: %s Cnt: %u\n", VN.Offset,
  4115. VN.Version, VN.File.data(), VN.Cnt);
  4116. for (const VernAux &Aux : VN.AuxV)
  4117. OS << format(" 0x%04x: Name: %s Flags: %s Version: %u\n", Aux.Offset,
  4118. Aux.Name.data(), versionFlagToString(Aux.Flags).c_str(),
  4119. Aux.Other);
  4120. }
  4121. OS << '\n';
  4122. }
  4123. template <class ELFT>
  4124. void GNUELFDumper<ELFT>::printHashHistogram(const Elf_Hash &HashTable) {
  4125. size_t NBucket = HashTable.nbucket;
  4126. size_t NChain = HashTable.nchain;
  4127. ArrayRef<Elf_Word> Buckets = HashTable.buckets();
  4128. ArrayRef<Elf_Word> Chains = HashTable.chains();
  4129. size_t TotalSyms = 0;
  4130. // If hash table is correct, we have at least chains with 0 length
  4131. size_t MaxChain = 1;
  4132. size_t CumulativeNonZero = 0;
  4133. if (NChain == 0 || NBucket == 0)
  4134. return;
  4135. std::vector<size_t> ChainLen(NBucket, 0);
  4136. // Go over all buckets and and note chain lengths of each bucket (total
  4137. // unique chain lengths).
  4138. for (size_t B = 0; B < NBucket; B++) {
  4139. BitVector Visited(NChain);
  4140. for (size_t C = Buckets[B]; C < NChain; C = Chains[C]) {
  4141. if (C == ELF::STN_UNDEF)
  4142. break;
  4143. if (Visited[C]) {
  4144. this->reportUniqueWarning(".hash section is invalid: bucket " +
  4145. Twine(C) +
  4146. ": a cycle was detected in the linked chain");
  4147. break;
  4148. }
  4149. Visited[C] = true;
  4150. if (MaxChain <= ++ChainLen[B])
  4151. MaxChain++;
  4152. }
  4153. TotalSyms += ChainLen[B];
  4154. }
  4155. if (!TotalSyms)
  4156. return;
  4157. std::vector<size_t> Count(MaxChain, 0);
  4158. // Count how long is the chain for each bucket
  4159. for (size_t B = 0; B < NBucket; B++)
  4160. ++Count[ChainLen[B]];
  4161. // Print Number of buckets with each chain lengths and their cumulative
  4162. // coverage of the symbols
  4163. OS << "Histogram for bucket list length (total of " << NBucket
  4164. << " buckets)\n"
  4165. << " Length Number % of total Coverage\n";
  4166. for (size_t I = 0; I < MaxChain; I++) {
  4167. CumulativeNonZero += Count[I] * I;
  4168. OS << format("%7lu %-10lu (%5.1f%%) %5.1f%%\n", I, Count[I],
  4169. (Count[I] * 100.0) / NBucket,
  4170. (CumulativeNonZero * 100.0) / TotalSyms);
  4171. }
  4172. }
  4173. template <class ELFT>
  4174. void GNUELFDumper<ELFT>::printGnuHashHistogram(
  4175. const Elf_GnuHash &GnuHashTable) {
  4176. Expected<ArrayRef<Elf_Word>> ChainsOrErr =
  4177. getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHashTable);
  4178. if (!ChainsOrErr) {
  4179. this->reportUniqueWarning("unable to print the GNU hash table histogram: " +
  4180. toString(ChainsOrErr.takeError()));
  4181. return;
  4182. }
  4183. ArrayRef<Elf_Word> Chains = *ChainsOrErr;
  4184. size_t Symndx = GnuHashTable.symndx;
  4185. size_t TotalSyms = 0;
  4186. size_t MaxChain = 1;
  4187. size_t CumulativeNonZero = 0;
  4188. size_t NBucket = GnuHashTable.nbuckets;
  4189. if (Chains.empty() || NBucket == 0)
  4190. return;
  4191. ArrayRef<Elf_Word> Buckets = GnuHashTable.buckets();
  4192. std::vector<size_t> ChainLen(NBucket, 0);
  4193. for (size_t B = 0; B < NBucket; B++) {
  4194. if (!Buckets[B])
  4195. continue;
  4196. size_t Len = 1;
  4197. for (size_t C = Buckets[B] - Symndx;
  4198. C < Chains.size() && (Chains[C] & 1) == 0; C++)
  4199. if (MaxChain < ++Len)
  4200. MaxChain++;
  4201. ChainLen[B] = Len;
  4202. TotalSyms += Len;
  4203. }
  4204. MaxChain++;
  4205. if (!TotalSyms)
  4206. return;
  4207. std::vector<size_t> Count(MaxChain, 0);
  4208. for (size_t B = 0; B < NBucket; B++)
  4209. ++Count[ChainLen[B]];
  4210. // Print Number of buckets with each chain lengths and their cumulative
  4211. // coverage of the symbols
  4212. OS << "Histogram for `.gnu.hash' bucket list length (total of " << NBucket
  4213. << " buckets)\n"
  4214. << " Length Number % of total Coverage\n";
  4215. for (size_t I = 0; I < MaxChain; I++) {
  4216. CumulativeNonZero += Count[I] * I;
  4217. OS << format("%7lu %-10lu (%5.1f%%) %5.1f%%\n", I, Count[I],
  4218. (Count[I] * 100.0) / NBucket,
  4219. (CumulativeNonZero * 100.0) / TotalSyms);
  4220. }
  4221. }
  4222. // Hash histogram shows statistics of how efficient the hash was for the
  4223. // dynamic symbol table. The table shows the number of hash buckets for
  4224. // different lengths of chains as an absolute number and percentage of the total
  4225. // buckets, and the cumulative coverage of symbols for each set of buckets.
  4226. template <class ELFT> void GNUELFDumper<ELFT>::printHashHistograms() {
  4227. // Print histogram for the .hash section.
  4228. if (this->HashTable) {
  4229. if (Error E = checkHashTable<ELFT>(*this, this->HashTable))
  4230. this->reportUniqueWarning(std::move(E));
  4231. else
  4232. printHashHistogram(*this->HashTable);
  4233. }
  4234. // Print histogram for the .gnu.hash section.
  4235. if (this->GnuHashTable) {
  4236. if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable))
  4237. this->reportUniqueWarning(std::move(E));
  4238. else
  4239. printGnuHashHistogram(*this->GnuHashTable);
  4240. }
  4241. }
  4242. template <class ELFT> void GNUELFDumper<ELFT>::printCGProfile() {
  4243. OS << "GNUStyle::printCGProfile not implemented\n";
  4244. }
  4245. template <class ELFT> void GNUELFDumper<ELFT>::printBBAddrMaps() {
  4246. OS << "GNUStyle::printBBAddrMaps not implemented\n";
  4247. }
  4248. static Expected<std::vector<uint64_t>> toULEB128Array(ArrayRef<uint8_t> Data) {
  4249. std::vector<uint64_t> Ret;
  4250. const uint8_t *Cur = Data.begin();
  4251. const uint8_t *End = Data.end();
  4252. while (Cur != End) {
  4253. unsigned Size;
  4254. const char *Err;
  4255. Ret.push_back(decodeULEB128(Cur, &Size, End, &Err));
  4256. if (Err)
  4257. return createError(Err);
  4258. Cur += Size;
  4259. }
  4260. return Ret;
  4261. }
  4262. template <class ELFT>
  4263. static Expected<std::vector<uint64_t>>
  4264. decodeAddrsigSection(const ELFFile<ELFT> &Obj, const typename ELFT::Shdr &Sec) {
  4265. Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Sec);
  4266. if (!ContentsOrErr)
  4267. return ContentsOrErr.takeError();
  4268. if (Expected<std::vector<uint64_t>> SymsOrErr =
  4269. toULEB128Array(*ContentsOrErr))
  4270. return *SymsOrErr;
  4271. else
  4272. return createError("unable to decode " + describe(Obj, Sec) + ": " +
  4273. toString(SymsOrErr.takeError()));
  4274. }
  4275. template <class ELFT> void GNUELFDumper<ELFT>::printAddrsig() {
  4276. if (!this->DotAddrsigSec)
  4277. return;
  4278. Expected<std::vector<uint64_t>> SymsOrErr =
  4279. decodeAddrsigSection(this->Obj, *this->DotAddrsigSec);
  4280. if (!SymsOrErr) {
  4281. this->reportUniqueWarning(SymsOrErr.takeError());
  4282. return;
  4283. }
  4284. StringRef Name = this->getPrintableSectionName(*this->DotAddrsigSec);
  4285. OS << "\nAddress-significant symbols section '" << Name << "'"
  4286. << " contains " << SymsOrErr->size() << " entries:\n";
  4287. OS << " Num: Name\n";
  4288. Field Fields[2] = {0, 8};
  4289. size_t SymIndex = 0;
  4290. for (uint64_t Sym : *SymsOrErr) {
  4291. Fields[0].Str = to_string(format_decimal(++SymIndex, 6)) + ":";
  4292. Fields[1].Str = this->getStaticSymbolName(Sym);
  4293. for (const Field &Entry : Fields)
  4294. printField(Entry);
  4295. OS << "\n";
  4296. }
  4297. }
  4298. template <typename ELFT>
  4299. static std::string getGNUProperty(uint32_t Type, uint32_t DataSize,
  4300. ArrayRef<uint8_t> Data) {
  4301. std::string str;
  4302. raw_string_ostream OS(str);
  4303. uint32_t PrData;
  4304. auto DumpBit = [&](uint32_t Flag, StringRef Name) {
  4305. if (PrData & Flag) {
  4306. PrData &= ~Flag;
  4307. OS << Name;
  4308. if (PrData)
  4309. OS << ", ";
  4310. }
  4311. };
  4312. switch (Type) {
  4313. default:
  4314. OS << format("<application-specific type 0x%x>", Type);
  4315. return OS.str();
  4316. case GNU_PROPERTY_STACK_SIZE: {
  4317. OS << "stack size: ";
  4318. if (DataSize == sizeof(typename ELFT::uint))
  4319. OS << formatv("{0:x}",
  4320. (uint64_t)(*(const typename ELFT::Addr *)Data.data()));
  4321. else
  4322. OS << format("<corrupt length: 0x%x>", DataSize);
  4323. return OS.str();
  4324. }
  4325. case GNU_PROPERTY_NO_COPY_ON_PROTECTED:
  4326. OS << "no copy on protected";
  4327. if (DataSize)
  4328. OS << format(" <corrupt length: 0x%x>", DataSize);
  4329. return OS.str();
  4330. case GNU_PROPERTY_AARCH64_FEATURE_1_AND:
  4331. case GNU_PROPERTY_X86_FEATURE_1_AND:
  4332. OS << ((Type == GNU_PROPERTY_AARCH64_FEATURE_1_AND) ? "aarch64 feature: "
  4333. : "x86 feature: ");
  4334. if (DataSize != 4) {
  4335. OS << format("<corrupt length: 0x%x>", DataSize);
  4336. return OS.str();
  4337. }
  4338. PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data());
  4339. if (PrData == 0) {
  4340. OS << "<None>";
  4341. return OS.str();
  4342. }
  4343. if (Type == GNU_PROPERTY_AARCH64_FEATURE_1_AND) {
  4344. DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_BTI, "BTI");
  4345. DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_PAC, "PAC");
  4346. } else {
  4347. DumpBit(GNU_PROPERTY_X86_FEATURE_1_IBT, "IBT");
  4348. DumpBit(GNU_PROPERTY_X86_FEATURE_1_SHSTK, "SHSTK");
  4349. }
  4350. if (PrData)
  4351. OS << format("<unknown flags: 0x%x>", PrData);
  4352. return OS.str();
  4353. case GNU_PROPERTY_X86_FEATURE_2_NEEDED:
  4354. case GNU_PROPERTY_X86_FEATURE_2_USED:
  4355. OS << "x86 feature "
  4356. << (Type == GNU_PROPERTY_X86_FEATURE_2_NEEDED ? "needed: " : "used: ");
  4357. if (DataSize != 4) {
  4358. OS << format("<corrupt length: 0x%x>", DataSize);
  4359. return OS.str();
  4360. }
  4361. PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data());
  4362. if (PrData == 0) {
  4363. OS << "<None>";
  4364. return OS.str();
  4365. }
  4366. DumpBit(GNU_PROPERTY_X86_FEATURE_2_X86, "x86");
  4367. DumpBit(GNU_PROPERTY_X86_FEATURE_2_X87, "x87");
  4368. DumpBit(GNU_PROPERTY_X86_FEATURE_2_MMX, "MMX");
  4369. DumpBit(GNU_PROPERTY_X86_FEATURE_2_XMM, "XMM");
  4370. DumpBit(GNU_PROPERTY_X86_FEATURE_2_YMM, "YMM");
  4371. DumpBit(GNU_PROPERTY_X86_FEATURE_2_ZMM, "ZMM");
  4372. DumpBit(GNU_PROPERTY_X86_FEATURE_2_FXSR, "FXSR");
  4373. DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVE, "XSAVE");
  4374. DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEOPT, "XSAVEOPT");
  4375. DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEC, "XSAVEC");
  4376. if (PrData)
  4377. OS << format("<unknown flags: 0x%x>", PrData);
  4378. return OS.str();
  4379. case GNU_PROPERTY_X86_ISA_1_NEEDED:
  4380. case GNU_PROPERTY_X86_ISA_1_USED:
  4381. OS << "x86 ISA "
  4382. << (Type == GNU_PROPERTY_X86_ISA_1_NEEDED ? "needed: " : "used: ");
  4383. if (DataSize != 4) {
  4384. OS << format("<corrupt length: 0x%x>", DataSize);
  4385. return OS.str();
  4386. }
  4387. PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data());
  4388. if (PrData == 0) {
  4389. OS << "<None>";
  4390. return OS.str();
  4391. }
  4392. DumpBit(GNU_PROPERTY_X86_ISA_1_BASELINE, "x86-64-baseline");
  4393. DumpBit(GNU_PROPERTY_X86_ISA_1_V2, "x86-64-v2");
  4394. DumpBit(GNU_PROPERTY_X86_ISA_1_V3, "x86-64-v3");
  4395. DumpBit(GNU_PROPERTY_X86_ISA_1_V4, "x86-64-v4");
  4396. if (PrData)
  4397. OS << format("<unknown flags: 0x%x>", PrData);
  4398. return OS.str();
  4399. }
  4400. }
  4401. template <typename ELFT>
  4402. static SmallVector<std::string, 4> getGNUPropertyList(ArrayRef<uint8_t> Arr) {
  4403. using Elf_Word = typename ELFT::Word;
  4404. SmallVector<std::string, 4> Properties;
  4405. while (Arr.size() >= 8) {
  4406. uint32_t Type = *reinterpret_cast<const Elf_Word *>(Arr.data());
  4407. uint32_t DataSize = *reinterpret_cast<const Elf_Word *>(Arr.data() + 4);
  4408. Arr = Arr.drop_front(8);
  4409. // Take padding size into account if present.
  4410. uint64_t PaddedSize = alignTo(DataSize, sizeof(typename ELFT::uint));
  4411. std::string str;
  4412. raw_string_ostream OS(str);
  4413. if (Arr.size() < PaddedSize) {
  4414. OS << format("<corrupt type (0x%x) datasz: 0x%x>", Type, DataSize);
  4415. Properties.push_back(OS.str());
  4416. break;
  4417. }
  4418. Properties.push_back(
  4419. getGNUProperty<ELFT>(Type, DataSize, Arr.take_front(PaddedSize)));
  4420. Arr = Arr.drop_front(PaddedSize);
  4421. }
  4422. if (!Arr.empty())
  4423. Properties.push_back("<corrupted GNU_PROPERTY_TYPE_0>");
  4424. return Properties;
  4425. }
  4426. struct GNUAbiTag {
  4427. std::string OSName;
  4428. std::string ABI;
  4429. bool IsValid;
  4430. };
  4431. template <typename ELFT> static GNUAbiTag getGNUAbiTag(ArrayRef<uint8_t> Desc) {
  4432. typedef typename ELFT::Word Elf_Word;
  4433. ArrayRef<Elf_Word> Words(reinterpret_cast<const Elf_Word *>(Desc.begin()),
  4434. reinterpret_cast<const Elf_Word *>(Desc.end()));
  4435. if (Words.size() < 4)
  4436. return {"", "", /*IsValid=*/false};
  4437. static const char *OSNames[] = {
  4438. "Linux", "Hurd", "Solaris", "FreeBSD", "NetBSD", "Syllable", "NaCl",
  4439. };
  4440. StringRef OSName = "Unknown";
  4441. if (Words[0] < array_lengthof(OSNames))
  4442. OSName = OSNames[Words[0]];
  4443. uint32_t Major = Words[1], Minor = Words[2], Patch = Words[3];
  4444. std::string str;
  4445. raw_string_ostream ABI(str);
  4446. ABI << Major << "." << Minor << "." << Patch;
  4447. return {std::string(OSName), ABI.str(), /*IsValid=*/true};
  4448. }
  4449. static std::string getGNUBuildId(ArrayRef<uint8_t> Desc) {
  4450. std::string str;
  4451. raw_string_ostream OS(str);
  4452. for (uint8_t B : Desc)
  4453. OS << format_hex_no_prefix(B, 2);
  4454. return OS.str();
  4455. }
  4456. static StringRef getDescAsStringRef(ArrayRef<uint8_t> Desc) {
  4457. return StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
  4458. }
  4459. template <typename ELFT>
  4460. static bool printGNUNote(raw_ostream &OS, uint32_t NoteType,
  4461. ArrayRef<uint8_t> Desc) {
  4462. // Return true if we were able to pretty-print the note, false otherwise.
  4463. switch (NoteType) {
  4464. default:
  4465. return false;
  4466. case ELF::NT_GNU_ABI_TAG: {
  4467. const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc);
  4468. if (!AbiTag.IsValid)
  4469. OS << " <corrupt GNU_ABI_TAG>";
  4470. else
  4471. OS << " OS: " << AbiTag.OSName << ", ABI: " << AbiTag.ABI;
  4472. break;
  4473. }
  4474. case ELF::NT_GNU_BUILD_ID: {
  4475. OS << " Build ID: " << getGNUBuildId(Desc);
  4476. break;
  4477. }
  4478. case ELF::NT_GNU_GOLD_VERSION:
  4479. OS << " Version: " << getDescAsStringRef(Desc);
  4480. break;
  4481. case ELF::NT_GNU_PROPERTY_TYPE_0:
  4482. OS << " Properties:";
  4483. for (const std::string &Property : getGNUPropertyList<ELFT>(Desc))
  4484. OS << " " << Property << "\n";
  4485. break;
  4486. }
  4487. OS << '\n';
  4488. return true;
  4489. }
  4490. template <typename ELFT>
  4491. static bool printLLVMOMPOFFLOADNote(raw_ostream &OS, uint32_t NoteType,
  4492. ArrayRef<uint8_t> Desc) {
  4493. switch (NoteType) {
  4494. default:
  4495. return false;
  4496. case ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION:
  4497. OS << " Version: " << getDescAsStringRef(Desc);
  4498. break;
  4499. case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER:
  4500. OS << " Producer: " << getDescAsStringRef(Desc);
  4501. break;
  4502. case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION:
  4503. OS << " Producer version: " << getDescAsStringRef(Desc);
  4504. break;
  4505. }
  4506. OS << '\n';
  4507. return true;
  4508. }
  4509. const EnumEntry<unsigned> FreeBSDFeatureCtlFlags[] = {
  4510. {"ASLR_DISABLE", NT_FREEBSD_FCTL_ASLR_DISABLE},
  4511. {"PROTMAX_DISABLE", NT_FREEBSD_FCTL_PROTMAX_DISABLE},
  4512. {"STKGAP_DISABLE", NT_FREEBSD_FCTL_STKGAP_DISABLE},
  4513. {"WXNEEDED", NT_FREEBSD_FCTL_WXNEEDED},
  4514. {"LA48", NT_FREEBSD_FCTL_LA48},
  4515. {"ASG_DISABLE", NT_FREEBSD_FCTL_ASG_DISABLE},
  4516. };
  4517. struct FreeBSDNote {
  4518. std::string Type;
  4519. std::string Value;
  4520. };
  4521. template <typename ELFT>
  4522. static Optional<FreeBSDNote>
  4523. getFreeBSDNote(uint32_t NoteType, ArrayRef<uint8_t> Desc, bool IsCore) {
  4524. if (IsCore)
  4525. return None; // No pretty-printing yet.
  4526. switch (NoteType) {
  4527. case ELF::NT_FREEBSD_ABI_TAG:
  4528. if (Desc.size() != 4)
  4529. return None;
  4530. return FreeBSDNote{
  4531. "ABI tag",
  4532. utostr(support::endian::read32<ELFT::TargetEndianness>(Desc.data()))};
  4533. case ELF::NT_FREEBSD_ARCH_TAG:
  4534. return FreeBSDNote{"Arch tag", toStringRef(Desc).str()};
  4535. case ELF::NT_FREEBSD_FEATURE_CTL: {
  4536. if (Desc.size() != 4)
  4537. return None;
  4538. unsigned Value =
  4539. support::endian::read32<ELFT::TargetEndianness>(Desc.data());
  4540. std::string FlagsStr;
  4541. raw_string_ostream OS(FlagsStr);
  4542. printFlags(Value, makeArrayRef(FreeBSDFeatureCtlFlags), OS);
  4543. if (OS.str().empty())
  4544. OS << "0x" << utohexstr(Value);
  4545. else
  4546. OS << "(0x" << utohexstr(Value) << ")";
  4547. return FreeBSDNote{"Feature flags", OS.str()};
  4548. }
  4549. default:
  4550. return None;
  4551. }
  4552. }
  4553. struct AMDNote {
  4554. std::string Type;
  4555. std::string Value;
  4556. };
  4557. template <typename ELFT>
  4558. static AMDNote getAMDNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) {
  4559. switch (NoteType) {
  4560. default:
  4561. return {"", ""};
  4562. case ELF::NT_AMD_HSA_CODE_OBJECT_VERSION: {
  4563. struct CodeObjectVersion {
  4564. uint32_t MajorVersion;
  4565. uint32_t MinorVersion;
  4566. };
  4567. if (Desc.size() != sizeof(CodeObjectVersion))
  4568. return {"AMD HSA Code Object Version",
  4569. "Invalid AMD HSA Code Object Version"};
  4570. std::string VersionString;
  4571. raw_string_ostream StrOS(VersionString);
  4572. auto Version = reinterpret_cast<const CodeObjectVersion *>(Desc.data());
  4573. StrOS << "[Major: " << Version->MajorVersion
  4574. << ", Minor: " << Version->MinorVersion << "]";
  4575. return {"AMD HSA Code Object Version", VersionString};
  4576. }
  4577. case ELF::NT_AMD_HSA_HSAIL: {
  4578. struct HSAILProperties {
  4579. uint32_t HSAILMajorVersion;
  4580. uint32_t HSAILMinorVersion;
  4581. uint8_t Profile;
  4582. uint8_t MachineModel;
  4583. uint8_t DefaultFloatRound;
  4584. };
  4585. if (Desc.size() != sizeof(HSAILProperties))
  4586. return {"AMD HSA HSAIL Properties", "Invalid AMD HSA HSAIL Properties"};
  4587. auto Properties = reinterpret_cast<const HSAILProperties *>(Desc.data());
  4588. std::string HSAILPropetiesString;
  4589. raw_string_ostream StrOS(HSAILPropetiesString);
  4590. StrOS << "[HSAIL Major: " << Properties->HSAILMajorVersion
  4591. << ", HSAIL Minor: " << Properties->HSAILMinorVersion
  4592. << ", Profile: " << uint32_t(Properties->Profile)
  4593. << ", Machine Model: " << uint32_t(Properties->MachineModel)
  4594. << ", Default Float Round: "
  4595. << uint32_t(Properties->DefaultFloatRound) << "]";
  4596. return {"AMD HSA HSAIL Properties", HSAILPropetiesString};
  4597. }
  4598. case ELF::NT_AMD_HSA_ISA_VERSION: {
  4599. struct IsaVersion {
  4600. uint16_t VendorNameSize;
  4601. uint16_t ArchitectureNameSize;
  4602. uint32_t Major;
  4603. uint32_t Minor;
  4604. uint32_t Stepping;
  4605. };
  4606. if (Desc.size() < sizeof(IsaVersion))
  4607. return {"AMD HSA ISA Version", "Invalid AMD HSA ISA Version"};
  4608. auto Isa = reinterpret_cast<const IsaVersion *>(Desc.data());
  4609. if (Desc.size() < sizeof(IsaVersion) +
  4610. Isa->VendorNameSize + Isa->ArchitectureNameSize ||
  4611. Isa->VendorNameSize == 0 || Isa->ArchitectureNameSize == 0)
  4612. return {"AMD HSA ISA Version", "Invalid AMD HSA ISA Version"};
  4613. std::string IsaString;
  4614. raw_string_ostream StrOS(IsaString);
  4615. StrOS << "[Vendor: "
  4616. << StringRef((const char*)Desc.data() + sizeof(IsaVersion), Isa->VendorNameSize - 1)
  4617. << ", Architecture: "
  4618. << StringRef((const char*)Desc.data() + sizeof(IsaVersion) + Isa->VendorNameSize,
  4619. Isa->ArchitectureNameSize - 1)
  4620. << ", Major: " << Isa->Major << ", Minor: " << Isa->Minor
  4621. << ", Stepping: " << Isa->Stepping << "]";
  4622. return {"AMD HSA ISA Version", IsaString};
  4623. }
  4624. case ELF::NT_AMD_HSA_METADATA: {
  4625. if (Desc.size() == 0)
  4626. return {"AMD HSA Metadata", ""};
  4627. return {
  4628. "AMD HSA Metadata",
  4629. std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size() - 1)};
  4630. }
  4631. case ELF::NT_AMD_HSA_ISA_NAME: {
  4632. if (Desc.size() == 0)
  4633. return {"AMD HSA ISA Name", ""};
  4634. return {
  4635. "AMD HSA ISA Name",
  4636. std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size())};
  4637. }
  4638. case ELF::NT_AMD_PAL_METADATA: {
  4639. struct PALMetadata {
  4640. uint32_t Key;
  4641. uint32_t Value;
  4642. };
  4643. if (Desc.size() % sizeof(PALMetadata) != 0)
  4644. return {"AMD PAL Metadata", "Invalid AMD PAL Metadata"};
  4645. auto Isa = reinterpret_cast<const PALMetadata *>(Desc.data());
  4646. std::string MetadataString;
  4647. raw_string_ostream StrOS(MetadataString);
  4648. for (size_t I = 0, E = Desc.size() / sizeof(PALMetadata); I < E; ++I) {
  4649. StrOS << "[" << Isa[I].Key << ": " << Isa[I].Value << "]";
  4650. }
  4651. return {"AMD PAL Metadata", MetadataString};
  4652. }
  4653. }
  4654. }
  4655. struct AMDGPUNote {
  4656. std::string Type;
  4657. std::string Value;
  4658. };
  4659. template <typename ELFT>
  4660. static AMDGPUNote getAMDGPUNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) {
  4661. switch (NoteType) {
  4662. default:
  4663. return {"", ""};
  4664. case ELF::NT_AMDGPU_METADATA: {
  4665. StringRef MsgPackString =
  4666. StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
  4667. msgpack::Document MsgPackDoc;
  4668. if (!MsgPackDoc.readFromBlob(MsgPackString, /*Multi=*/false))
  4669. return {"", ""};
  4670. AMDGPU::HSAMD::V3::MetadataVerifier Verifier(true);
  4671. std::string MetadataString;
  4672. if (!Verifier.verify(MsgPackDoc.getRoot()))
  4673. MetadataString = "Invalid AMDGPU Metadata\n";
  4674. raw_string_ostream StrOS(MetadataString);
  4675. if (MsgPackDoc.getRoot().isScalar()) {
  4676. // TODO: passing a scalar root to toYAML() asserts:
  4677. // (PolymorphicTraits<T>::getKind(Val) != NodeKind::Scalar &&
  4678. // "plain scalar documents are not supported")
  4679. // To avoid this crash we print the raw data instead.
  4680. return {"", ""};
  4681. }
  4682. MsgPackDoc.toYAML(StrOS);
  4683. return {"AMDGPU Metadata", StrOS.str()};
  4684. }
  4685. }
  4686. }
  4687. struct CoreFileMapping {
  4688. uint64_t Start, End, Offset;
  4689. StringRef Filename;
  4690. };
  4691. struct CoreNote {
  4692. uint64_t PageSize;
  4693. std::vector<CoreFileMapping> Mappings;
  4694. };
  4695. static Expected<CoreNote> readCoreNote(DataExtractor Desc) {
  4696. // Expected format of the NT_FILE note description:
  4697. // 1. # of file mappings (call it N)
  4698. // 2. Page size
  4699. // 3. N (start, end, offset) triples
  4700. // 4. N packed filenames (null delimited)
  4701. // Each field is an Elf_Addr, except for filenames which are char* strings.
  4702. CoreNote Ret;
  4703. const int Bytes = Desc.getAddressSize();
  4704. if (!Desc.isValidOffsetForAddress(2))
  4705. return createError("the note of size 0x" + Twine::utohexstr(Desc.size()) +
  4706. " is too short, expected at least 0x" +
  4707. Twine::utohexstr(Bytes * 2));
  4708. if (Desc.getData().back() != 0)
  4709. return createError("the note is not NUL terminated");
  4710. uint64_t DescOffset = 0;
  4711. uint64_t FileCount = Desc.getAddress(&DescOffset);
  4712. Ret.PageSize = Desc.getAddress(&DescOffset);
  4713. if (!Desc.isValidOffsetForAddress(3 * FileCount * Bytes))
  4714. return createError("unable to read file mappings (found " +
  4715. Twine(FileCount) + "): the note of size 0x" +
  4716. Twine::utohexstr(Desc.size()) + " is too short");
  4717. uint64_t FilenamesOffset = 0;
  4718. DataExtractor Filenames(
  4719. Desc.getData().drop_front(DescOffset + 3 * FileCount * Bytes),
  4720. Desc.isLittleEndian(), Desc.getAddressSize());
  4721. Ret.Mappings.resize(FileCount);
  4722. size_t I = 0;
  4723. for (CoreFileMapping &Mapping : Ret.Mappings) {
  4724. ++I;
  4725. if (!Filenames.isValidOffsetForDataOfSize(FilenamesOffset, 1))
  4726. return createError(
  4727. "unable to read the file name for the mapping with index " +
  4728. Twine(I) + ": the note of size 0x" + Twine::utohexstr(Desc.size()) +
  4729. " is truncated");
  4730. Mapping.Start = Desc.getAddress(&DescOffset);
  4731. Mapping.End = Desc.getAddress(&DescOffset);
  4732. Mapping.Offset = Desc.getAddress(&DescOffset);
  4733. Mapping.Filename = Filenames.getCStrRef(&FilenamesOffset);
  4734. }
  4735. return Ret;
  4736. }
  4737. template <typename ELFT>
  4738. static void printCoreNote(raw_ostream &OS, const CoreNote &Note) {
  4739. // Length of "0x<address>" string.
  4740. const int FieldWidth = ELFT::Is64Bits ? 18 : 10;
  4741. OS << " Page size: " << format_decimal(Note.PageSize, 0) << '\n';
  4742. OS << " " << right_justify("Start", FieldWidth) << " "
  4743. << right_justify("End", FieldWidth) << " "
  4744. << right_justify("Page Offset", FieldWidth) << '\n';
  4745. for (const CoreFileMapping &Mapping : Note.Mappings) {
  4746. OS << " " << format_hex(Mapping.Start, FieldWidth) << " "
  4747. << format_hex(Mapping.End, FieldWidth) << " "
  4748. << format_hex(Mapping.Offset, FieldWidth) << "\n "
  4749. << Mapping.Filename << '\n';
  4750. }
  4751. }
  4752. const NoteType GenericNoteTypes[] = {
  4753. {ELF::NT_VERSION, "NT_VERSION (version)"},
  4754. {ELF::NT_ARCH, "NT_ARCH (architecture)"},
  4755. {ELF::NT_GNU_BUILD_ATTRIBUTE_OPEN, "OPEN"},
  4756. {ELF::NT_GNU_BUILD_ATTRIBUTE_FUNC, "func"},
  4757. };
  4758. const NoteType GNUNoteTypes[] = {
  4759. {ELF::NT_GNU_ABI_TAG, "NT_GNU_ABI_TAG (ABI version tag)"},
  4760. {ELF::NT_GNU_HWCAP, "NT_GNU_HWCAP (DSO-supplied software HWCAP info)"},
  4761. {ELF::NT_GNU_BUILD_ID, "NT_GNU_BUILD_ID (unique build ID bitstring)"},
  4762. {ELF::NT_GNU_GOLD_VERSION, "NT_GNU_GOLD_VERSION (gold version)"},
  4763. {ELF::NT_GNU_PROPERTY_TYPE_0, "NT_GNU_PROPERTY_TYPE_0 (property note)"},
  4764. };
  4765. const NoteType FreeBSDCoreNoteTypes[] = {
  4766. {ELF::NT_FREEBSD_THRMISC, "NT_THRMISC (thrmisc structure)"},
  4767. {ELF::NT_FREEBSD_PROCSTAT_PROC, "NT_PROCSTAT_PROC (proc data)"},
  4768. {ELF::NT_FREEBSD_PROCSTAT_FILES, "NT_PROCSTAT_FILES (files data)"},
  4769. {ELF::NT_FREEBSD_PROCSTAT_VMMAP, "NT_PROCSTAT_VMMAP (vmmap data)"},
  4770. {ELF::NT_FREEBSD_PROCSTAT_GROUPS, "NT_PROCSTAT_GROUPS (groups data)"},
  4771. {ELF::NT_FREEBSD_PROCSTAT_UMASK, "NT_PROCSTAT_UMASK (umask data)"},
  4772. {ELF::NT_FREEBSD_PROCSTAT_RLIMIT, "NT_PROCSTAT_RLIMIT (rlimit data)"},
  4773. {ELF::NT_FREEBSD_PROCSTAT_OSREL, "NT_PROCSTAT_OSREL (osreldate data)"},
  4774. {ELF::NT_FREEBSD_PROCSTAT_PSSTRINGS,
  4775. "NT_PROCSTAT_PSSTRINGS (ps_strings data)"},
  4776. {ELF::NT_FREEBSD_PROCSTAT_AUXV, "NT_PROCSTAT_AUXV (auxv data)"},
  4777. };
  4778. const NoteType FreeBSDNoteTypes[] = {
  4779. {ELF::NT_FREEBSD_ABI_TAG, "NT_FREEBSD_ABI_TAG (ABI version tag)"},
  4780. {ELF::NT_FREEBSD_NOINIT_TAG, "NT_FREEBSD_NOINIT_TAG (no .init tag)"},
  4781. {ELF::NT_FREEBSD_ARCH_TAG, "NT_FREEBSD_ARCH_TAG (architecture tag)"},
  4782. {ELF::NT_FREEBSD_FEATURE_CTL,
  4783. "NT_FREEBSD_FEATURE_CTL (FreeBSD feature control)"},
  4784. };
  4785. const NoteType NetBSDCoreNoteTypes[] = {
  4786. {ELF::NT_NETBSDCORE_PROCINFO,
  4787. "NT_NETBSDCORE_PROCINFO (procinfo structure)"},
  4788. {ELF::NT_NETBSDCORE_AUXV, "NT_NETBSDCORE_AUXV (ELF auxiliary vector data)"},
  4789. {ELF::NT_NETBSDCORE_LWPSTATUS, "PT_LWPSTATUS (ptrace_lwpstatus structure)"},
  4790. };
  4791. const NoteType OpenBSDCoreNoteTypes[] = {
  4792. {ELF::NT_OPENBSD_PROCINFO, "NT_OPENBSD_PROCINFO (procinfo structure)"},
  4793. {ELF::NT_OPENBSD_AUXV, "NT_OPENBSD_AUXV (ELF auxiliary vector data)"},
  4794. {ELF::NT_OPENBSD_REGS, "NT_OPENBSD_REGS (regular registers)"},
  4795. {ELF::NT_OPENBSD_FPREGS, "NT_OPENBSD_FPREGS (floating point registers)"},
  4796. {ELF::NT_OPENBSD_WCOOKIE, "NT_OPENBSD_WCOOKIE (window cookie)"},
  4797. };
  4798. const NoteType AMDNoteTypes[] = {
  4799. {ELF::NT_AMD_HSA_CODE_OBJECT_VERSION,
  4800. "NT_AMD_HSA_CODE_OBJECT_VERSION (AMD HSA Code Object Version)"},
  4801. {ELF::NT_AMD_HSA_HSAIL, "NT_AMD_HSA_HSAIL (AMD HSA HSAIL Properties)"},
  4802. {ELF::NT_AMD_HSA_ISA_VERSION, "NT_AMD_HSA_ISA_VERSION (AMD HSA ISA Version)"},
  4803. {ELF::NT_AMD_HSA_METADATA, "NT_AMD_HSA_METADATA (AMD HSA Metadata)"},
  4804. {ELF::NT_AMD_HSA_ISA_NAME, "NT_AMD_HSA_ISA_NAME (AMD HSA ISA Name)"},
  4805. {ELF::NT_AMD_PAL_METADATA, "NT_AMD_PAL_METADATA (AMD PAL Metadata)"},
  4806. };
  4807. const NoteType AMDGPUNoteTypes[] = {
  4808. {ELF::NT_AMDGPU_METADATA, "NT_AMDGPU_METADATA (AMDGPU Metadata)"},
  4809. };
  4810. const NoteType LLVMOMPOFFLOADNoteTypes[] = {
  4811. {ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION,
  4812. "NT_LLVM_OPENMP_OFFLOAD_VERSION (image format version)"},
  4813. {ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER,
  4814. "NT_LLVM_OPENMP_OFFLOAD_PRODUCER (producing toolchain)"},
  4815. {ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION,
  4816. "NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION (producing toolchain version)"},
  4817. };
  4818. const NoteType CoreNoteTypes[] = {
  4819. {ELF::NT_PRSTATUS, "NT_PRSTATUS (prstatus structure)"},
  4820. {ELF::NT_FPREGSET, "NT_FPREGSET (floating point registers)"},
  4821. {ELF::NT_PRPSINFO, "NT_PRPSINFO (prpsinfo structure)"},
  4822. {ELF::NT_TASKSTRUCT, "NT_TASKSTRUCT (task structure)"},
  4823. {ELF::NT_AUXV, "NT_AUXV (auxiliary vector)"},
  4824. {ELF::NT_PSTATUS, "NT_PSTATUS (pstatus structure)"},
  4825. {ELF::NT_FPREGS, "NT_FPREGS (floating point registers)"},
  4826. {ELF::NT_PSINFO, "NT_PSINFO (psinfo structure)"},
  4827. {ELF::NT_LWPSTATUS, "NT_LWPSTATUS (lwpstatus_t structure)"},
  4828. {ELF::NT_LWPSINFO, "NT_LWPSINFO (lwpsinfo_t structure)"},
  4829. {ELF::NT_WIN32PSTATUS, "NT_WIN32PSTATUS (win32_pstatus structure)"},
  4830. {ELF::NT_PPC_VMX, "NT_PPC_VMX (ppc Altivec registers)"},
  4831. {ELF::NT_PPC_VSX, "NT_PPC_VSX (ppc VSX registers)"},
  4832. {ELF::NT_PPC_TAR, "NT_PPC_TAR (ppc TAR register)"},
  4833. {ELF::NT_PPC_PPR, "NT_PPC_PPR (ppc PPR register)"},
  4834. {ELF::NT_PPC_DSCR, "NT_PPC_DSCR (ppc DSCR register)"},
  4835. {ELF::NT_PPC_EBB, "NT_PPC_EBB (ppc EBB registers)"},
  4836. {ELF::NT_PPC_PMU, "NT_PPC_PMU (ppc PMU registers)"},
  4837. {ELF::NT_PPC_TM_CGPR, "NT_PPC_TM_CGPR (ppc checkpointed GPR registers)"},
  4838. {ELF::NT_PPC_TM_CFPR,
  4839. "NT_PPC_TM_CFPR (ppc checkpointed floating point registers)"},
  4840. {ELF::NT_PPC_TM_CVMX,
  4841. "NT_PPC_TM_CVMX (ppc checkpointed Altivec registers)"},
  4842. {ELF::NT_PPC_TM_CVSX, "NT_PPC_TM_CVSX (ppc checkpointed VSX registers)"},
  4843. {ELF::NT_PPC_TM_SPR, "NT_PPC_TM_SPR (ppc TM special purpose registers)"},
  4844. {ELF::NT_PPC_TM_CTAR, "NT_PPC_TM_CTAR (ppc checkpointed TAR register)"},
  4845. {ELF::NT_PPC_TM_CPPR, "NT_PPC_TM_CPPR (ppc checkpointed PPR register)"},
  4846. {ELF::NT_PPC_TM_CDSCR, "NT_PPC_TM_CDSCR (ppc checkpointed DSCR register)"},
  4847. {ELF::NT_386_TLS, "NT_386_TLS (x86 TLS information)"},
  4848. {ELF::NT_386_IOPERM, "NT_386_IOPERM (x86 I/O permissions)"},
  4849. {ELF::NT_X86_XSTATE, "NT_X86_XSTATE (x86 XSAVE extended state)"},
  4850. {ELF::NT_S390_HIGH_GPRS, "NT_S390_HIGH_GPRS (s390 upper register halves)"},
  4851. {ELF::NT_S390_TIMER, "NT_S390_TIMER (s390 timer register)"},
  4852. {ELF::NT_S390_TODCMP, "NT_S390_TODCMP (s390 TOD comparator register)"},
  4853. {ELF::NT_S390_TODPREG, "NT_S390_TODPREG (s390 TOD programmable register)"},
  4854. {ELF::NT_S390_CTRS, "NT_S390_CTRS (s390 control registers)"},
  4855. {ELF::NT_S390_PREFIX, "NT_S390_PREFIX (s390 prefix register)"},
  4856. {ELF::NT_S390_LAST_BREAK,
  4857. "NT_S390_LAST_BREAK (s390 last breaking event address)"},
  4858. {ELF::NT_S390_SYSTEM_CALL,
  4859. "NT_S390_SYSTEM_CALL (s390 system call restart data)"},
  4860. {ELF::NT_S390_TDB, "NT_S390_TDB (s390 transaction diagnostic block)"},
  4861. {ELF::NT_S390_VXRS_LOW,
  4862. "NT_S390_VXRS_LOW (s390 vector registers 0-15 upper half)"},
  4863. {ELF::NT_S390_VXRS_HIGH, "NT_S390_VXRS_HIGH (s390 vector registers 16-31)"},
  4864. {ELF::NT_S390_GS_CB, "NT_S390_GS_CB (s390 guarded-storage registers)"},
  4865. {ELF::NT_S390_GS_BC,
  4866. "NT_S390_GS_BC (s390 guarded-storage broadcast control)"},
  4867. {ELF::NT_ARM_VFP, "NT_ARM_VFP (arm VFP registers)"},
  4868. {ELF::NT_ARM_TLS, "NT_ARM_TLS (AArch TLS registers)"},
  4869. {ELF::NT_ARM_HW_BREAK,
  4870. "NT_ARM_HW_BREAK (AArch hardware breakpoint registers)"},
  4871. {ELF::NT_ARM_HW_WATCH,
  4872. "NT_ARM_HW_WATCH (AArch hardware watchpoint registers)"},
  4873. {ELF::NT_FILE, "NT_FILE (mapped files)"},
  4874. {ELF::NT_PRXFPREG, "NT_PRXFPREG (user_xfpregs structure)"},
  4875. {ELF::NT_SIGINFO, "NT_SIGINFO (siginfo_t data)"},
  4876. };
  4877. template <class ELFT>
  4878. StringRef getNoteTypeName(const typename ELFT::Note &Note, unsigned ELFType) {
  4879. uint32_t Type = Note.getType();
  4880. auto FindNote = [&](ArrayRef<NoteType> V) -> StringRef {
  4881. for (const NoteType &N : V)
  4882. if (N.ID == Type)
  4883. return N.Name;
  4884. return "";
  4885. };
  4886. StringRef Name = Note.getName();
  4887. if (Name == "GNU")
  4888. return FindNote(GNUNoteTypes);
  4889. if (Name == "FreeBSD") {
  4890. if (ELFType == ELF::ET_CORE) {
  4891. // FreeBSD also places the generic core notes in the FreeBSD namespace.
  4892. StringRef Result = FindNote(FreeBSDCoreNoteTypes);
  4893. if (!Result.empty())
  4894. return Result;
  4895. return FindNote(CoreNoteTypes);
  4896. } else {
  4897. return FindNote(FreeBSDNoteTypes);
  4898. }
  4899. }
  4900. if (ELFType == ELF::ET_CORE && Name.startswith("NetBSD-CORE")) {
  4901. StringRef Result = FindNote(NetBSDCoreNoteTypes);
  4902. if (!Result.empty())
  4903. return Result;
  4904. return FindNote(CoreNoteTypes);
  4905. }
  4906. if (ELFType == ELF::ET_CORE && Name.startswith("OpenBSD")) {
  4907. // OpenBSD also places the generic core notes in the OpenBSD namespace.
  4908. StringRef Result = FindNote(OpenBSDCoreNoteTypes);
  4909. if (!Result.empty())
  4910. return Result;
  4911. return FindNote(CoreNoteTypes);
  4912. }
  4913. if (Name == "AMD")
  4914. return FindNote(AMDNoteTypes);
  4915. if (Name == "AMDGPU")
  4916. return FindNote(AMDGPUNoteTypes);
  4917. if (Name == "LLVMOMPOFFLOAD")
  4918. return FindNote(LLVMOMPOFFLOADNoteTypes);
  4919. if (ELFType == ELF::ET_CORE)
  4920. return FindNote(CoreNoteTypes);
  4921. return FindNote(GenericNoteTypes);
  4922. }
  4923. template <class ELFT>
  4924. static void printNotesHelper(
  4925. const ELFDumper<ELFT> &Dumper,
  4926. llvm::function_ref<void(Optional<StringRef>, typename ELFT::Off,
  4927. typename ELFT::Addr)>
  4928. StartNotesFn,
  4929. llvm::function_ref<Error(const typename ELFT::Note &, bool)> ProcessNoteFn,
  4930. llvm::function_ref<void()> FinishNotesFn) {
  4931. const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
  4932. bool IsCoreFile = Obj.getHeader().e_type == ELF::ET_CORE;
  4933. ArrayRef<typename ELFT::Shdr> Sections = cantFail(Obj.sections());
  4934. if (!IsCoreFile && !Sections.empty()) {
  4935. for (const typename ELFT::Shdr &S : Sections) {
  4936. if (S.sh_type != SHT_NOTE)
  4937. continue;
  4938. StartNotesFn(expectedToOptional(Obj.getSectionName(S)), S.sh_offset,
  4939. S.sh_size);
  4940. Error Err = Error::success();
  4941. size_t I = 0;
  4942. for (const typename ELFT::Note Note : Obj.notes(S, Err)) {
  4943. if (Error E = ProcessNoteFn(Note, IsCoreFile))
  4944. Dumper.reportUniqueWarning(
  4945. "unable to read note with index " + Twine(I) + " from the " +
  4946. describe(Obj, S) + ": " + toString(std::move(E)));
  4947. ++I;
  4948. }
  4949. if (Err)
  4950. Dumper.reportUniqueWarning("unable to read notes from the " +
  4951. describe(Obj, S) + ": " +
  4952. toString(std::move(Err)));
  4953. FinishNotesFn();
  4954. }
  4955. return;
  4956. }
  4957. Expected<ArrayRef<typename ELFT::Phdr>> PhdrsOrErr = Obj.program_headers();
  4958. if (!PhdrsOrErr) {
  4959. Dumper.reportUniqueWarning(
  4960. "unable to read program headers to locate the PT_NOTE segment: " +
  4961. toString(PhdrsOrErr.takeError()));
  4962. return;
  4963. }
  4964. for (size_t I = 0, E = (*PhdrsOrErr).size(); I != E; ++I) {
  4965. const typename ELFT::Phdr &P = (*PhdrsOrErr)[I];
  4966. if (P.p_type != PT_NOTE)
  4967. continue;
  4968. StartNotesFn(/*SecName=*/None, P.p_offset, P.p_filesz);
  4969. Error Err = Error::success();
  4970. size_t Index = 0;
  4971. for (const typename ELFT::Note Note : Obj.notes(P, Err)) {
  4972. if (Error E = ProcessNoteFn(Note, IsCoreFile))
  4973. Dumper.reportUniqueWarning("unable to read note with index " +
  4974. Twine(Index) +
  4975. " from the PT_NOTE segment with index " +
  4976. Twine(I) + ": " + toString(std::move(E)));
  4977. ++Index;
  4978. }
  4979. if (Err)
  4980. Dumper.reportUniqueWarning(
  4981. "unable to read notes from the PT_NOTE segment with index " +
  4982. Twine(I) + ": " + toString(std::move(Err)));
  4983. FinishNotesFn();
  4984. }
  4985. }
  4986. template <class ELFT> void GNUELFDumper<ELFT>::printNotes() {
  4987. bool IsFirstHeader = true;
  4988. auto PrintHeader = [&](Optional<StringRef> SecName,
  4989. const typename ELFT::Off Offset,
  4990. const typename ELFT::Addr Size) {
  4991. // Print a newline between notes sections to match GNU readelf.
  4992. if (!IsFirstHeader) {
  4993. OS << '\n';
  4994. } else {
  4995. IsFirstHeader = false;
  4996. }
  4997. OS << "Displaying notes found ";
  4998. if (SecName)
  4999. OS << "in: " << *SecName << "\n";
  5000. else
  5001. OS << "at file offset " << format_hex(Offset, 10) << " with length "
  5002. << format_hex(Size, 10) << ":\n";
  5003. OS << " Owner Data size \tDescription\n";
  5004. };
  5005. auto ProcessNote = [&](const Elf_Note &Note, bool IsCore) -> Error {
  5006. StringRef Name = Note.getName();
  5007. ArrayRef<uint8_t> Descriptor = Note.getDesc();
  5008. Elf_Word Type = Note.getType();
  5009. // Print the note owner/type.
  5010. OS << " " << left_justify(Name, 20) << ' '
  5011. << format_hex(Descriptor.size(), 10) << '\t';
  5012. StringRef NoteType =
  5013. getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type);
  5014. if (!NoteType.empty())
  5015. OS << NoteType << '\n';
  5016. else
  5017. OS << "Unknown note type: (" << format_hex(Type, 10) << ")\n";
  5018. // Print the description, or fallback to printing raw bytes for unknown
  5019. // owners/if we fail to pretty-print the contents.
  5020. if (Name == "GNU") {
  5021. if (printGNUNote<ELFT>(OS, Type, Descriptor))
  5022. return Error::success();
  5023. } else if (Name == "FreeBSD") {
  5024. if (Optional<FreeBSDNote> N =
  5025. getFreeBSDNote<ELFT>(Type, Descriptor, IsCore)) {
  5026. OS << " " << N->Type << ": " << N->Value << '\n';
  5027. return Error::success();
  5028. }
  5029. } else if (Name == "AMD") {
  5030. const AMDNote N = getAMDNote<ELFT>(Type, Descriptor);
  5031. if (!N.Type.empty()) {
  5032. OS << " " << N.Type << ":\n " << N.Value << '\n';
  5033. return Error::success();
  5034. }
  5035. } else if (Name == "AMDGPU") {
  5036. const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor);
  5037. if (!N.Type.empty()) {
  5038. OS << " " << N.Type << ":\n " << N.Value << '\n';
  5039. return Error::success();
  5040. }
  5041. } else if (Name == "LLVMOMPOFFLOAD") {
  5042. if (printLLVMOMPOFFLOADNote<ELFT>(OS, Type, Descriptor))
  5043. return Error::success();
  5044. } else if (Name == "CORE") {
  5045. if (Type == ELF::NT_FILE) {
  5046. DataExtractor DescExtractor(Descriptor,
  5047. ELFT::TargetEndianness == support::little,
  5048. sizeof(Elf_Addr));
  5049. if (Expected<CoreNote> NoteOrErr = readCoreNote(DescExtractor)) {
  5050. printCoreNote<ELFT>(OS, *NoteOrErr);
  5051. return Error::success();
  5052. } else {
  5053. return NoteOrErr.takeError();
  5054. }
  5055. }
  5056. }
  5057. if (!Descriptor.empty()) {
  5058. OS << " description data:";
  5059. for (uint8_t B : Descriptor)
  5060. OS << " " << format("%02x", B);
  5061. OS << '\n';
  5062. }
  5063. return Error::success();
  5064. };
  5065. printNotesHelper(*this, PrintHeader, ProcessNote, []() {});
  5066. }
  5067. template <class ELFT> void GNUELFDumper<ELFT>::printELFLinkerOptions() {
  5068. OS << "printELFLinkerOptions not implemented!\n";
  5069. }
  5070. template <class ELFT>
  5071. void ELFDumper<ELFT>::printDependentLibsHelper(
  5072. function_ref<void(const Elf_Shdr &)> OnSectionStart,
  5073. function_ref<void(StringRef, uint64_t)> OnLibEntry) {
  5074. auto Warn = [this](unsigned SecNdx, StringRef Msg) {
  5075. this->reportUniqueWarning("SHT_LLVM_DEPENDENT_LIBRARIES section at index " +
  5076. Twine(SecNdx) + " is broken: " + Msg);
  5077. };
  5078. unsigned I = -1;
  5079. for (const Elf_Shdr &Shdr : cantFail(Obj.sections())) {
  5080. ++I;
  5081. if (Shdr.sh_type != ELF::SHT_LLVM_DEPENDENT_LIBRARIES)
  5082. continue;
  5083. OnSectionStart(Shdr);
  5084. Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Shdr);
  5085. if (!ContentsOrErr) {
  5086. Warn(I, toString(ContentsOrErr.takeError()));
  5087. continue;
  5088. }
  5089. ArrayRef<uint8_t> Contents = *ContentsOrErr;
  5090. if (!Contents.empty() && Contents.back() != 0) {
  5091. Warn(I, "the content is not null-terminated");
  5092. continue;
  5093. }
  5094. for (const uint8_t *I = Contents.begin(), *E = Contents.end(); I < E;) {
  5095. StringRef Lib((const char *)I);
  5096. OnLibEntry(Lib, I - Contents.begin());
  5097. I += Lib.size() + 1;
  5098. }
  5099. }
  5100. }
  5101. template <class ELFT>
  5102. void ELFDumper<ELFT>::forEachRelocationDo(
  5103. const Elf_Shdr &Sec, bool RawRelr,
  5104. llvm::function_ref<void(const Relocation<ELFT> &, unsigned,
  5105. const Elf_Shdr &, const Elf_Shdr *)>
  5106. RelRelaFn,
  5107. llvm::function_ref<void(const Elf_Relr &)> RelrFn) {
  5108. auto Warn = [&](Error &&E,
  5109. const Twine &Prefix = "unable to read relocations from") {
  5110. this->reportUniqueWarning(Prefix + " " + describe(Sec) + ": " +
  5111. toString(std::move(E)));
  5112. };
  5113. // SHT_RELR/SHT_ANDROID_RELR sections do not have an associated symbol table.
  5114. // For them we should not treat the value of the sh_link field as an index of
  5115. // a symbol table.
  5116. const Elf_Shdr *SymTab;
  5117. if (Sec.sh_type != ELF::SHT_RELR && Sec.sh_type != ELF::SHT_ANDROID_RELR) {
  5118. Expected<const Elf_Shdr *> SymTabOrErr = Obj.getSection(Sec.sh_link);
  5119. if (!SymTabOrErr) {
  5120. Warn(SymTabOrErr.takeError(), "unable to locate a symbol table for");
  5121. return;
  5122. }
  5123. SymTab = *SymTabOrErr;
  5124. }
  5125. unsigned RelNdx = 0;
  5126. const bool IsMips64EL = this->Obj.isMips64EL();
  5127. switch (Sec.sh_type) {
  5128. case ELF::SHT_REL:
  5129. if (Expected<Elf_Rel_Range> RangeOrErr = Obj.rels(Sec)) {
  5130. for (const Elf_Rel &R : *RangeOrErr)
  5131. RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
  5132. } else {
  5133. Warn(RangeOrErr.takeError());
  5134. }
  5135. break;
  5136. case ELF::SHT_RELA:
  5137. if (Expected<Elf_Rela_Range> RangeOrErr = Obj.relas(Sec)) {
  5138. for (const Elf_Rela &R : *RangeOrErr)
  5139. RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
  5140. } else {
  5141. Warn(RangeOrErr.takeError());
  5142. }
  5143. break;
  5144. case ELF::SHT_RELR:
  5145. case ELF::SHT_ANDROID_RELR: {
  5146. Expected<Elf_Relr_Range> RangeOrErr = Obj.relrs(Sec);
  5147. if (!RangeOrErr) {
  5148. Warn(RangeOrErr.takeError());
  5149. break;
  5150. }
  5151. if (RawRelr) {
  5152. for (const Elf_Relr &R : *RangeOrErr)
  5153. RelrFn(R);
  5154. break;
  5155. }
  5156. for (const Elf_Rel &R : Obj.decode_relrs(*RangeOrErr))
  5157. RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec,
  5158. /*SymTab=*/nullptr);
  5159. break;
  5160. }
  5161. case ELF::SHT_ANDROID_REL:
  5162. case ELF::SHT_ANDROID_RELA:
  5163. if (Expected<std::vector<Elf_Rela>> RelasOrErr = Obj.android_relas(Sec)) {
  5164. for (const Elf_Rela &R : *RelasOrErr)
  5165. RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
  5166. } else {
  5167. Warn(RelasOrErr.takeError());
  5168. }
  5169. break;
  5170. }
  5171. }
  5172. template <class ELFT>
  5173. StringRef ELFDumper<ELFT>::getPrintableSectionName(const Elf_Shdr &Sec) const {
  5174. StringRef Name = "<?>";
  5175. if (Expected<StringRef> SecNameOrErr =
  5176. Obj.getSectionName(Sec, this->WarningHandler))
  5177. Name = *SecNameOrErr;
  5178. else
  5179. this->reportUniqueWarning("unable to get the name of " + describe(Sec) +
  5180. ": " + toString(SecNameOrErr.takeError()));
  5181. return Name;
  5182. }
  5183. template <class ELFT> void GNUELFDumper<ELFT>::printDependentLibs() {
  5184. bool SectionStarted = false;
  5185. struct NameOffset {
  5186. StringRef Name;
  5187. uint64_t Offset;
  5188. };
  5189. std::vector<NameOffset> SecEntries;
  5190. NameOffset Current;
  5191. auto PrintSection = [&]() {
  5192. OS << "Dependent libraries section " << Current.Name << " at offset "
  5193. << format_hex(Current.Offset, 1) << " contains " << SecEntries.size()
  5194. << " entries:\n";
  5195. for (NameOffset Entry : SecEntries)
  5196. OS << " [" << format("%6" PRIx64, Entry.Offset) << "] " << Entry.Name
  5197. << "\n";
  5198. OS << "\n";
  5199. SecEntries.clear();
  5200. };
  5201. auto OnSectionStart = [&](const Elf_Shdr &Shdr) {
  5202. if (SectionStarted)
  5203. PrintSection();
  5204. SectionStarted = true;
  5205. Current.Offset = Shdr.sh_offset;
  5206. Current.Name = this->getPrintableSectionName(Shdr);
  5207. };
  5208. auto OnLibEntry = [&](StringRef Lib, uint64_t Offset) {
  5209. SecEntries.push_back(NameOffset{Lib, Offset});
  5210. };
  5211. this->printDependentLibsHelper(OnSectionStart, OnLibEntry);
  5212. if (SectionStarted)
  5213. PrintSection();
  5214. }
  5215. template <class ELFT>
  5216. SmallVector<uint32_t> ELFDumper<ELFT>::getSymbolIndexesForFunctionAddress(
  5217. uint64_t SymValue, Optional<const Elf_Shdr *> FunctionSec) {
  5218. SmallVector<uint32_t> SymbolIndexes;
  5219. if (!this->AddressToIndexMap.hasValue()) {
  5220. // Populate the address to index map upon the first invocation of this
  5221. // function.
  5222. this->AddressToIndexMap.emplace();
  5223. if (this->DotSymtabSec) {
  5224. if (Expected<Elf_Sym_Range> SymsOrError =
  5225. Obj.symbols(this->DotSymtabSec)) {
  5226. uint32_t Index = (uint32_t)-1;
  5227. for (const Elf_Sym &Sym : *SymsOrError) {
  5228. ++Index;
  5229. if (Sym.st_shndx == ELF::SHN_UNDEF || Sym.getType() != ELF::STT_FUNC)
  5230. continue;
  5231. Expected<uint64_t> SymAddrOrErr =
  5232. ObjF.toSymbolRef(this->DotSymtabSec, Index).getAddress();
  5233. if (!SymAddrOrErr) {
  5234. std::string Name = this->getStaticSymbolName(Index);
  5235. reportUniqueWarning("unable to get address of symbol '" + Name +
  5236. "': " + toString(SymAddrOrErr.takeError()));
  5237. return SymbolIndexes;
  5238. }
  5239. (*this->AddressToIndexMap)[*SymAddrOrErr].push_back(Index);
  5240. }
  5241. } else {
  5242. reportUniqueWarning("unable to read the symbol table: " +
  5243. toString(SymsOrError.takeError()));
  5244. }
  5245. }
  5246. }
  5247. auto Symbols = this->AddressToIndexMap->find(SymValue);
  5248. if (Symbols == this->AddressToIndexMap->end())
  5249. return SymbolIndexes;
  5250. for (uint32_t Index : Symbols->second) {
  5251. // Check if the symbol is in the right section. FunctionSec == None
  5252. // means "any section".
  5253. if (FunctionSec) {
  5254. const Elf_Sym &Sym = *cantFail(Obj.getSymbol(this->DotSymtabSec, Index));
  5255. if (Expected<const Elf_Shdr *> SecOrErr =
  5256. Obj.getSection(Sym, this->DotSymtabSec,
  5257. this->getShndxTable(this->DotSymtabSec))) {
  5258. if (*FunctionSec != *SecOrErr)
  5259. continue;
  5260. } else {
  5261. std::string Name = this->getStaticSymbolName(Index);
  5262. // Note: it is impossible to trigger this error currently, it is
  5263. // untested.
  5264. reportUniqueWarning("unable to get section of symbol '" + Name +
  5265. "': " + toString(SecOrErr.takeError()));
  5266. return SymbolIndexes;
  5267. }
  5268. }
  5269. SymbolIndexes.push_back(Index);
  5270. }
  5271. return SymbolIndexes;
  5272. }
  5273. template <class ELFT>
  5274. bool ELFDumper<ELFT>::printFunctionStackSize(
  5275. uint64_t SymValue, Optional<const Elf_Shdr *> FunctionSec,
  5276. const Elf_Shdr &StackSizeSec, DataExtractor Data, uint64_t *Offset) {
  5277. SmallVector<uint32_t> FuncSymIndexes =
  5278. this->getSymbolIndexesForFunctionAddress(SymValue, FunctionSec);
  5279. if (FuncSymIndexes.empty())
  5280. reportUniqueWarning(
  5281. "could not identify function symbol for stack size entry in " +
  5282. describe(StackSizeSec));
  5283. // Extract the size. The expectation is that Offset is pointing to the right
  5284. // place, i.e. past the function address.
  5285. Error Err = Error::success();
  5286. uint64_t StackSize = Data.getULEB128(Offset, &Err);
  5287. if (Err) {
  5288. reportUniqueWarning("could not extract a valid stack size from " +
  5289. describe(StackSizeSec) + ": " +
  5290. toString(std::move(Err)));
  5291. return false;
  5292. }
  5293. if (FuncSymIndexes.empty()) {
  5294. printStackSizeEntry(StackSize, {"?"});
  5295. } else {
  5296. SmallVector<std::string> FuncSymNames;
  5297. for (uint32_t Index : FuncSymIndexes)
  5298. FuncSymNames.push_back(this->getStaticSymbolName(Index));
  5299. printStackSizeEntry(StackSize, FuncSymNames);
  5300. }
  5301. return true;
  5302. }
  5303. template <class ELFT>
  5304. void GNUELFDumper<ELFT>::printStackSizeEntry(uint64_t Size,
  5305. ArrayRef<std::string> FuncNames) {
  5306. OS.PadToColumn(2);
  5307. OS << format_decimal(Size, 11);
  5308. OS.PadToColumn(18);
  5309. OS << join(FuncNames.begin(), FuncNames.end(), ", ") << "\n";
  5310. }
  5311. template <class ELFT>
  5312. void ELFDumper<ELFT>::printStackSize(const Relocation<ELFT> &R,
  5313. const Elf_Shdr &RelocSec, unsigned Ndx,
  5314. const Elf_Shdr *SymTab,
  5315. const Elf_Shdr *FunctionSec,
  5316. const Elf_Shdr &StackSizeSec,
  5317. const RelocationResolver &Resolver,
  5318. DataExtractor Data) {
  5319. // This function ignores potentially erroneous input, unless it is directly
  5320. // related to stack size reporting.
  5321. const Elf_Sym *Sym = nullptr;
  5322. Expected<RelSymbol<ELFT>> TargetOrErr = this->getRelocationTarget(R, SymTab);
  5323. if (!TargetOrErr)
  5324. reportUniqueWarning("unable to get the target of relocation with index " +
  5325. Twine(Ndx) + " in " + describe(RelocSec) + ": " +
  5326. toString(TargetOrErr.takeError()));
  5327. else
  5328. Sym = TargetOrErr->Sym;
  5329. uint64_t RelocSymValue = 0;
  5330. if (Sym) {
  5331. Expected<const Elf_Shdr *> SectionOrErr =
  5332. this->Obj.getSection(*Sym, SymTab, this->getShndxTable(SymTab));
  5333. if (!SectionOrErr) {
  5334. reportUniqueWarning(
  5335. "cannot identify the section for relocation symbol '" +
  5336. (*TargetOrErr).Name + "': " + toString(SectionOrErr.takeError()));
  5337. } else if (*SectionOrErr != FunctionSec) {
  5338. reportUniqueWarning("relocation symbol '" + (*TargetOrErr).Name +
  5339. "' is not in the expected section");
  5340. // Pretend that the symbol is in the correct section and report its
  5341. // stack size anyway.
  5342. FunctionSec = *SectionOrErr;
  5343. }
  5344. RelocSymValue = Sym->st_value;
  5345. }
  5346. uint64_t Offset = R.Offset;
  5347. if (!Data.isValidOffsetForDataOfSize(Offset, sizeof(Elf_Addr) + 1)) {
  5348. reportUniqueWarning("found invalid relocation offset (0x" +
  5349. Twine::utohexstr(Offset) + ") into " +
  5350. describe(StackSizeSec) +
  5351. " while trying to extract a stack size entry");
  5352. return;
  5353. }
  5354. uint64_t SymValue =
  5355. Resolver(R.Type, Offset, RelocSymValue, Data.getAddress(&Offset),
  5356. R.Addend.getValueOr(0));
  5357. this->printFunctionStackSize(SymValue, FunctionSec, StackSizeSec, Data,
  5358. &Offset);
  5359. }
  5360. template <class ELFT>
  5361. void ELFDumper<ELFT>::printNonRelocatableStackSizes(
  5362. std::function<void()> PrintHeader) {
  5363. // This function ignores potentially erroneous input, unless it is directly
  5364. // related to stack size reporting.
  5365. for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
  5366. if (this->getPrintableSectionName(Sec) != ".stack_sizes")
  5367. continue;
  5368. PrintHeader();
  5369. ArrayRef<uint8_t> Contents =
  5370. unwrapOrError(this->FileName, Obj.getSectionContents(Sec));
  5371. DataExtractor Data(Contents, Obj.isLE(), sizeof(Elf_Addr));
  5372. uint64_t Offset = 0;
  5373. while (Offset < Contents.size()) {
  5374. // The function address is followed by a ULEB representing the stack
  5375. // size. Check for an extra byte before we try to process the entry.
  5376. if (!Data.isValidOffsetForDataOfSize(Offset, sizeof(Elf_Addr) + 1)) {
  5377. reportUniqueWarning(
  5378. describe(Sec) +
  5379. " ended while trying to extract a stack size entry");
  5380. break;
  5381. }
  5382. uint64_t SymValue = Data.getAddress(&Offset);
  5383. if (!printFunctionStackSize(SymValue, /*FunctionSec=*/None, Sec, Data,
  5384. &Offset))
  5385. break;
  5386. }
  5387. }
  5388. }
  5389. template <class ELFT>
  5390. void ELFDumper<ELFT>::getSectionAndRelocations(
  5391. std::function<bool(const Elf_Shdr &)> IsMatch,
  5392. llvm::MapVector<const Elf_Shdr *, const Elf_Shdr *> &SecToRelocMap) {
  5393. for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
  5394. if (IsMatch(Sec))
  5395. if (SecToRelocMap.insert(std::make_pair(&Sec, (const Elf_Shdr *)nullptr))
  5396. .second)
  5397. continue;
  5398. if (Sec.sh_type != ELF::SHT_RELA && Sec.sh_type != ELF::SHT_REL)
  5399. continue;
  5400. Expected<const Elf_Shdr *> RelSecOrErr = Obj.getSection(Sec.sh_info);
  5401. if (!RelSecOrErr) {
  5402. reportUniqueWarning(describe(Sec) +
  5403. ": failed to get a relocated section: " +
  5404. toString(RelSecOrErr.takeError()));
  5405. continue;
  5406. }
  5407. const Elf_Shdr *ContentsSec = *RelSecOrErr;
  5408. if (IsMatch(*ContentsSec))
  5409. SecToRelocMap[ContentsSec] = &Sec;
  5410. }
  5411. }
  5412. template <class ELFT>
  5413. void ELFDumper<ELFT>::printRelocatableStackSizes(
  5414. std::function<void()> PrintHeader) {
  5415. // Build a map between stack size sections and their corresponding relocation
  5416. // sections.
  5417. llvm::MapVector<const Elf_Shdr *, const Elf_Shdr *> StackSizeRelocMap;
  5418. auto IsMatch = [&](const Elf_Shdr &Sec) -> bool {
  5419. StringRef SectionName;
  5420. if (Expected<StringRef> NameOrErr = Obj.getSectionName(Sec))
  5421. SectionName = *NameOrErr;
  5422. else
  5423. consumeError(NameOrErr.takeError());
  5424. return SectionName == ".stack_sizes";
  5425. };
  5426. getSectionAndRelocations(IsMatch, StackSizeRelocMap);
  5427. for (const auto &StackSizeMapEntry : StackSizeRelocMap) {
  5428. PrintHeader();
  5429. const Elf_Shdr *StackSizesELFSec = StackSizeMapEntry.first;
  5430. const Elf_Shdr *RelocSec = StackSizeMapEntry.second;
  5431. // Warn about stack size sections without a relocation section.
  5432. if (!RelocSec) {
  5433. reportWarning(createError(".stack_sizes (" + describe(*StackSizesELFSec) +
  5434. ") does not have a corresponding "
  5435. "relocation section"),
  5436. FileName);
  5437. continue;
  5438. }
  5439. // A .stack_sizes section header's sh_link field is supposed to point
  5440. // to the section that contains the functions whose stack sizes are
  5441. // described in it.
  5442. const Elf_Shdr *FunctionSec = unwrapOrError(
  5443. this->FileName, Obj.getSection(StackSizesELFSec->sh_link));
  5444. SupportsRelocation IsSupportedFn;
  5445. RelocationResolver Resolver;
  5446. std::tie(IsSupportedFn, Resolver) = getRelocationResolver(this->ObjF);
  5447. ArrayRef<uint8_t> Contents =
  5448. unwrapOrError(this->FileName, Obj.getSectionContents(*StackSizesELFSec));
  5449. DataExtractor Data(Contents, Obj.isLE(), sizeof(Elf_Addr));
  5450. forEachRelocationDo(
  5451. *RelocSec, /*RawRelr=*/false,
  5452. [&](const Relocation<ELFT> &R, unsigned Ndx, const Elf_Shdr &Sec,
  5453. const Elf_Shdr *SymTab) {
  5454. if (!IsSupportedFn || !IsSupportedFn(R.Type)) {
  5455. reportUniqueWarning(
  5456. describe(*RelocSec) +
  5457. " contains an unsupported relocation with index " + Twine(Ndx) +
  5458. ": " + Obj.getRelocationTypeName(R.Type));
  5459. return;
  5460. }
  5461. this->printStackSize(R, *RelocSec, Ndx, SymTab, FunctionSec,
  5462. *StackSizesELFSec, Resolver, Data);
  5463. },
  5464. [](const Elf_Relr &) {
  5465. llvm_unreachable("can't get here, because we only support "
  5466. "SHT_REL/SHT_RELA sections");
  5467. });
  5468. }
  5469. }
  5470. template <class ELFT>
  5471. void GNUELFDumper<ELFT>::printStackSizes() {
  5472. bool HeaderHasBeenPrinted = false;
  5473. auto PrintHeader = [&]() {
  5474. if (HeaderHasBeenPrinted)
  5475. return;
  5476. OS << "\nStack Sizes:\n";
  5477. OS.PadToColumn(9);
  5478. OS << "Size";
  5479. OS.PadToColumn(18);
  5480. OS << "Functions\n";
  5481. HeaderHasBeenPrinted = true;
  5482. };
  5483. // For non-relocatable objects, look directly for sections whose name starts
  5484. // with .stack_sizes and process the contents.
  5485. if (this->Obj.getHeader().e_type == ELF::ET_REL)
  5486. this->printRelocatableStackSizes(PrintHeader);
  5487. else
  5488. this->printNonRelocatableStackSizes(PrintHeader);
  5489. }
  5490. template <class ELFT>
  5491. void GNUELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) {
  5492. size_t Bias = ELFT::Is64Bits ? 8 : 0;
  5493. auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) {
  5494. OS.PadToColumn(2);
  5495. OS << format_hex_no_prefix(Parser.getGotAddress(E), 8 + Bias);
  5496. OS.PadToColumn(11 + Bias);
  5497. OS << format_decimal(Parser.getGotOffset(E), 6) << "(gp)";
  5498. OS.PadToColumn(22 + Bias);
  5499. OS << format_hex_no_prefix(*E, 8 + Bias);
  5500. OS.PadToColumn(31 + 2 * Bias);
  5501. OS << Purpose << "\n";
  5502. };
  5503. OS << (Parser.IsStatic ? "Static GOT:\n" : "Primary GOT:\n");
  5504. OS << " Canonical gp value: "
  5505. << format_hex_no_prefix(Parser.getGp(), 8 + Bias) << "\n\n";
  5506. OS << " Reserved entries:\n";
  5507. if (ELFT::Is64Bits)
  5508. OS << " Address Access Initial Purpose\n";
  5509. else
  5510. OS << " Address Access Initial Purpose\n";
  5511. PrintEntry(Parser.getGotLazyResolver(), "Lazy resolver");
  5512. if (Parser.getGotModulePointer())
  5513. PrintEntry(Parser.getGotModulePointer(), "Module pointer (GNU extension)");
  5514. if (!Parser.getLocalEntries().empty()) {
  5515. OS << "\n";
  5516. OS << " Local entries:\n";
  5517. if (ELFT::Is64Bits)
  5518. OS << " Address Access Initial\n";
  5519. else
  5520. OS << " Address Access Initial\n";
  5521. for (auto &E : Parser.getLocalEntries())
  5522. PrintEntry(&E, "");
  5523. }
  5524. if (Parser.IsStatic)
  5525. return;
  5526. if (!Parser.getGlobalEntries().empty()) {
  5527. OS << "\n";
  5528. OS << " Global entries:\n";
  5529. if (ELFT::Is64Bits)
  5530. OS << " Address Access Initial Sym.Val."
  5531. << " Type Ndx Name\n";
  5532. else
  5533. OS << " Address Access Initial Sym.Val. Type Ndx Name\n";
  5534. DataRegion<Elf_Word> ShndxTable(
  5535. (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
  5536. for (auto &E : Parser.getGlobalEntries()) {
  5537. const Elf_Sym &Sym = *Parser.getGotSym(&E);
  5538. const Elf_Sym &FirstSym = this->dynamic_symbols()[0];
  5539. std::string SymName = this->getFullSymbolName(
  5540. Sym, &Sym - &FirstSym, ShndxTable, this->DynamicStringTable, false);
  5541. OS.PadToColumn(2);
  5542. OS << to_string(format_hex_no_prefix(Parser.getGotAddress(&E), 8 + Bias));
  5543. OS.PadToColumn(11 + Bias);
  5544. OS << to_string(format_decimal(Parser.getGotOffset(&E), 6)) + "(gp)";
  5545. OS.PadToColumn(22 + Bias);
  5546. OS << to_string(format_hex_no_prefix(E, 8 + Bias));
  5547. OS.PadToColumn(31 + 2 * Bias);
  5548. OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias));
  5549. OS.PadToColumn(40 + 3 * Bias);
  5550. OS << enumToString(Sym.getType(), makeArrayRef(ElfSymbolTypes));
  5551. OS.PadToColumn(48 + 3 * Bias);
  5552. OS << getSymbolSectionNdx(Sym, &Sym - this->dynamic_symbols().begin(),
  5553. ShndxTable);
  5554. OS.PadToColumn(52 + 3 * Bias);
  5555. OS << SymName << "\n";
  5556. }
  5557. }
  5558. if (!Parser.getOtherEntries().empty())
  5559. OS << "\n Number of TLS and multi-GOT entries "
  5560. << Parser.getOtherEntries().size() << "\n";
  5561. }
  5562. template <class ELFT>
  5563. void GNUELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) {
  5564. size_t Bias = ELFT::Is64Bits ? 8 : 0;
  5565. auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) {
  5566. OS.PadToColumn(2);
  5567. OS << format_hex_no_prefix(Parser.getPltAddress(E), 8 + Bias);
  5568. OS.PadToColumn(11 + Bias);
  5569. OS << format_hex_no_prefix(*E, 8 + Bias);
  5570. OS.PadToColumn(20 + 2 * Bias);
  5571. OS << Purpose << "\n";
  5572. };
  5573. OS << "PLT GOT:\n\n";
  5574. OS << " Reserved entries:\n";
  5575. OS << " Address Initial Purpose\n";
  5576. PrintEntry(Parser.getPltLazyResolver(), "PLT lazy resolver");
  5577. if (Parser.getPltModulePointer())
  5578. PrintEntry(Parser.getPltModulePointer(), "Module pointer");
  5579. if (!Parser.getPltEntries().empty()) {
  5580. OS << "\n";
  5581. OS << " Entries:\n";
  5582. OS << " Address Initial Sym.Val. Type Ndx Name\n";
  5583. DataRegion<Elf_Word> ShndxTable(
  5584. (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
  5585. for (auto &E : Parser.getPltEntries()) {
  5586. const Elf_Sym &Sym = *Parser.getPltSym(&E);
  5587. const Elf_Sym &FirstSym = *cantFail(
  5588. this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0));
  5589. std::string SymName = this->getFullSymbolName(
  5590. Sym, &Sym - &FirstSym, ShndxTable, this->DynamicStringTable, false);
  5591. OS.PadToColumn(2);
  5592. OS << to_string(format_hex_no_prefix(Parser.getPltAddress(&E), 8 + Bias));
  5593. OS.PadToColumn(11 + Bias);
  5594. OS << to_string(format_hex_no_prefix(E, 8 + Bias));
  5595. OS.PadToColumn(20 + 2 * Bias);
  5596. OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias));
  5597. OS.PadToColumn(29 + 3 * Bias);
  5598. OS << enumToString(Sym.getType(), makeArrayRef(ElfSymbolTypes));
  5599. OS.PadToColumn(37 + 3 * Bias);
  5600. OS << getSymbolSectionNdx(Sym, &Sym - this->dynamic_symbols().begin(),
  5601. ShndxTable);
  5602. OS.PadToColumn(41 + 3 * Bias);
  5603. OS << SymName << "\n";
  5604. }
  5605. }
  5606. }
  5607. template <class ELFT>
  5608. Expected<const Elf_Mips_ABIFlags<ELFT> *>
  5609. getMipsAbiFlagsSection(const ELFDumper<ELFT> &Dumper) {
  5610. const typename ELFT::Shdr *Sec = Dumper.findSectionByName(".MIPS.abiflags");
  5611. if (Sec == nullptr)
  5612. return nullptr;
  5613. constexpr StringRef ErrPrefix = "unable to read the .MIPS.abiflags section: ";
  5614. Expected<ArrayRef<uint8_t>> DataOrErr =
  5615. Dumper.getElfObject().getELFFile().getSectionContents(*Sec);
  5616. if (!DataOrErr)
  5617. return createError(ErrPrefix + toString(DataOrErr.takeError()));
  5618. if (DataOrErr->size() != sizeof(Elf_Mips_ABIFlags<ELFT>))
  5619. return createError(ErrPrefix + "it has a wrong size (" +
  5620. Twine(DataOrErr->size()) + ")");
  5621. return reinterpret_cast<const Elf_Mips_ABIFlags<ELFT> *>(DataOrErr->data());
  5622. }
  5623. template <class ELFT> void GNUELFDumper<ELFT>::printMipsABIFlags() {
  5624. const Elf_Mips_ABIFlags<ELFT> *Flags = nullptr;
  5625. if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr =
  5626. getMipsAbiFlagsSection(*this))
  5627. Flags = *SecOrErr;
  5628. else
  5629. this->reportUniqueWarning(SecOrErr.takeError());
  5630. if (!Flags)
  5631. return;
  5632. OS << "MIPS ABI Flags Version: " << Flags->version << "\n\n";
  5633. OS << "ISA: MIPS" << int(Flags->isa_level);
  5634. if (Flags->isa_rev > 1)
  5635. OS << "r" << int(Flags->isa_rev);
  5636. OS << "\n";
  5637. OS << "GPR size: " << getMipsRegisterSize(Flags->gpr_size) << "\n";
  5638. OS << "CPR1 size: " << getMipsRegisterSize(Flags->cpr1_size) << "\n";
  5639. OS << "CPR2 size: " << getMipsRegisterSize(Flags->cpr2_size) << "\n";
  5640. OS << "FP ABI: "
  5641. << enumToString(Flags->fp_abi, makeArrayRef(ElfMipsFpABIType)) << "\n";
  5642. OS << "ISA Extension: "
  5643. << enumToString(Flags->isa_ext, makeArrayRef(ElfMipsISAExtType)) << "\n";
  5644. if (Flags->ases == 0)
  5645. OS << "ASEs: None\n";
  5646. else
  5647. // FIXME: Print each flag on a separate line.
  5648. OS << "ASEs: " << printFlags(Flags->ases, makeArrayRef(ElfMipsASEFlags))
  5649. << "\n";
  5650. OS << "FLAGS 1: " << format_hex_no_prefix(Flags->flags1, 8, false) << "\n";
  5651. OS << "FLAGS 2: " << format_hex_no_prefix(Flags->flags2, 8, false) << "\n";
  5652. OS << "\n";
  5653. }
  5654. template <class ELFT> void LLVMELFDumper<ELFT>::printFileHeaders() {
  5655. const Elf_Ehdr &E = this->Obj.getHeader();
  5656. {
  5657. DictScope D(W, "ElfHeader");
  5658. {
  5659. DictScope D(W, "Ident");
  5660. W.printBinary("Magic", makeArrayRef(E.e_ident).slice(ELF::EI_MAG0, 4));
  5661. W.printEnum("Class", E.e_ident[ELF::EI_CLASS], makeArrayRef(ElfClass));
  5662. W.printEnum("DataEncoding", E.e_ident[ELF::EI_DATA],
  5663. makeArrayRef(ElfDataEncoding));
  5664. W.printNumber("FileVersion", E.e_ident[ELF::EI_VERSION]);
  5665. auto OSABI = makeArrayRef(ElfOSABI);
  5666. if (E.e_ident[ELF::EI_OSABI] >= ELF::ELFOSABI_FIRST_ARCH &&
  5667. E.e_ident[ELF::EI_OSABI] <= ELF::ELFOSABI_LAST_ARCH) {
  5668. switch (E.e_machine) {
  5669. case ELF::EM_AMDGPU:
  5670. OSABI = makeArrayRef(AMDGPUElfOSABI);
  5671. break;
  5672. case ELF::EM_ARM:
  5673. OSABI = makeArrayRef(ARMElfOSABI);
  5674. break;
  5675. case ELF::EM_TI_C6000:
  5676. OSABI = makeArrayRef(C6000ElfOSABI);
  5677. break;
  5678. }
  5679. }
  5680. W.printEnum("OS/ABI", E.e_ident[ELF::EI_OSABI], OSABI);
  5681. W.printNumber("ABIVersion", E.e_ident[ELF::EI_ABIVERSION]);
  5682. W.printBinary("Unused", makeArrayRef(E.e_ident).slice(ELF::EI_PAD));
  5683. }
  5684. std::string TypeStr;
  5685. if (const EnumEntry<unsigned> *Ent = getObjectFileEnumEntry(E.e_type)) {
  5686. TypeStr = Ent->Name.str();
  5687. } else {
  5688. if (E.e_type >= ET_LOPROC)
  5689. TypeStr = "Processor Specific";
  5690. else if (E.e_type >= ET_LOOS)
  5691. TypeStr = "OS Specific";
  5692. else
  5693. TypeStr = "Unknown";
  5694. }
  5695. W.printString("Type", TypeStr + " (0x" + to_hexString(E.e_type) + ")");
  5696. W.printEnum("Machine", E.e_machine, makeArrayRef(ElfMachineType));
  5697. W.printNumber("Version", E.e_version);
  5698. W.printHex("Entry", E.e_entry);
  5699. W.printHex("ProgramHeaderOffset", E.e_phoff);
  5700. W.printHex("SectionHeaderOffset", E.e_shoff);
  5701. if (E.e_machine == EM_MIPS)
  5702. W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderMipsFlags),
  5703. unsigned(ELF::EF_MIPS_ARCH), unsigned(ELF::EF_MIPS_ABI),
  5704. unsigned(ELF::EF_MIPS_MACH));
  5705. else if (E.e_machine == EM_AMDGPU) {
  5706. switch (E.e_ident[ELF::EI_ABIVERSION]) {
  5707. default:
  5708. W.printHex("Flags", E.e_flags);
  5709. break;
  5710. case 0:
  5711. // ELFOSABI_AMDGPU_PAL, ELFOSABI_AMDGPU_MESA3D support *_V3 flags.
  5712. LLVM_FALLTHROUGH;
  5713. case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
  5714. W.printFlags("Flags", E.e_flags,
  5715. makeArrayRef(ElfHeaderAMDGPUFlagsABIVersion3),
  5716. unsigned(ELF::EF_AMDGPU_MACH));
  5717. break;
  5718. case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
  5719. case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
  5720. W.printFlags("Flags", E.e_flags,
  5721. makeArrayRef(ElfHeaderAMDGPUFlagsABIVersion4),
  5722. unsigned(ELF::EF_AMDGPU_MACH),
  5723. unsigned(ELF::EF_AMDGPU_FEATURE_XNACK_V4),
  5724. unsigned(ELF::EF_AMDGPU_FEATURE_SRAMECC_V4));
  5725. break;
  5726. }
  5727. } else if (E.e_machine == EM_RISCV)
  5728. W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderRISCVFlags));
  5729. else if (E.e_machine == EM_AVR)
  5730. W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderAVRFlags),
  5731. unsigned(ELF::EF_AVR_ARCH_MASK));
  5732. else
  5733. W.printFlags("Flags", E.e_flags);
  5734. W.printNumber("HeaderSize", E.e_ehsize);
  5735. W.printNumber("ProgramHeaderEntrySize", E.e_phentsize);
  5736. W.printNumber("ProgramHeaderCount", E.e_phnum);
  5737. W.printNumber("SectionHeaderEntrySize", E.e_shentsize);
  5738. W.printString("SectionHeaderCount",
  5739. getSectionHeadersNumString(this->Obj, this->FileName));
  5740. W.printString("StringTableSectionIndex",
  5741. getSectionHeaderTableIndexString(this->Obj, this->FileName));
  5742. }
  5743. }
  5744. template <class ELFT> void LLVMELFDumper<ELFT>::printGroupSections() {
  5745. DictScope Lists(W, "Groups");
  5746. std::vector<GroupSection> V = this->getGroups();
  5747. DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(V);
  5748. for (const GroupSection &G : V) {
  5749. DictScope D(W, "Group");
  5750. W.printNumber("Name", G.Name, G.ShName);
  5751. W.printNumber("Index", G.Index);
  5752. W.printNumber("Link", G.Link);
  5753. W.printNumber("Info", G.Info);
  5754. W.printHex("Type", getGroupType(G.Type), G.Type);
  5755. W.startLine() << "Signature: " << G.Signature << "\n";
  5756. ListScope L(W, "Section(s) in group");
  5757. for (const GroupMember &GM : G.Members) {
  5758. const GroupSection *MainGroup = Map[GM.Index];
  5759. if (MainGroup != &G)
  5760. this->reportUniqueWarning(
  5761. "section with index " + Twine(GM.Index) +
  5762. ", included in the group section with index " +
  5763. Twine(MainGroup->Index) +
  5764. ", was also found in the group section with index " +
  5765. Twine(G.Index));
  5766. W.startLine() << GM.Name << " (" << GM.Index << ")\n";
  5767. }
  5768. }
  5769. if (V.empty())
  5770. W.startLine() << "There are no group sections in the file.\n";
  5771. }
  5772. template <class ELFT> void LLVMELFDumper<ELFT>::printRelocations() {
  5773. ListScope D(W, "Relocations");
  5774. for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
  5775. if (!isRelocationSec<ELFT>(Sec))
  5776. continue;
  5777. StringRef Name = this->getPrintableSectionName(Sec);
  5778. unsigned SecNdx = &Sec - &cantFail(this->Obj.sections()).front();
  5779. W.startLine() << "Section (" << SecNdx << ") " << Name << " {\n";
  5780. W.indent();
  5781. this->printRelocationsHelper(Sec);
  5782. W.unindent();
  5783. W.startLine() << "}\n";
  5784. }
  5785. }
  5786. template <class ELFT>
  5787. void LLVMELFDumper<ELFT>::printRelrReloc(const Elf_Relr &R) {
  5788. W.startLine() << W.hex(R) << "\n";
  5789. }
  5790. template <class ELFT>
  5791. void LLVMELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R,
  5792. const RelSymbol<ELFT> &RelSym) {
  5793. StringRef SymbolName = RelSym.Name;
  5794. SmallString<32> RelocName;
  5795. this->Obj.getRelocationTypeName(R.Type, RelocName);
  5796. if (opts::ExpandRelocs) {
  5797. DictScope Group(W, "Relocation");
  5798. W.printHex("Offset", R.Offset);
  5799. W.printNumber("Type", RelocName, R.Type);
  5800. W.printNumber("Symbol", !SymbolName.empty() ? SymbolName : "-", R.Symbol);
  5801. if (R.Addend)
  5802. W.printHex("Addend", (uintX_t)*R.Addend);
  5803. } else {
  5804. raw_ostream &OS = W.startLine();
  5805. OS << W.hex(R.Offset) << " " << RelocName << " "
  5806. << (!SymbolName.empty() ? SymbolName : "-");
  5807. if (R.Addend)
  5808. OS << " " << W.hex((uintX_t)*R.Addend);
  5809. OS << "\n";
  5810. }
  5811. }
  5812. template <class ELFT> void LLVMELFDumper<ELFT>::printSectionHeaders() {
  5813. ListScope SectionsD(W, "Sections");
  5814. int SectionIndex = -1;
  5815. std::vector<EnumEntry<unsigned>> FlagsList =
  5816. getSectionFlagsForTarget(this->Obj.getHeader().e_machine);
  5817. for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
  5818. DictScope SectionD(W, "Section");
  5819. W.printNumber("Index", ++SectionIndex);
  5820. W.printNumber("Name", this->getPrintableSectionName(Sec), Sec.sh_name);
  5821. W.printHex("Type",
  5822. object::getELFSectionTypeName(this->Obj.getHeader().e_machine,
  5823. Sec.sh_type),
  5824. Sec.sh_type);
  5825. W.printFlags("Flags", Sec.sh_flags, makeArrayRef(FlagsList));
  5826. W.printHex("Address", Sec.sh_addr);
  5827. W.printHex("Offset", Sec.sh_offset);
  5828. W.printNumber("Size", Sec.sh_size);
  5829. W.printNumber("Link", Sec.sh_link);
  5830. W.printNumber("Info", Sec.sh_info);
  5831. W.printNumber("AddressAlignment", Sec.sh_addralign);
  5832. W.printNumber("EntrySize", Sec.sh_entsize);
  5833. if (opts::SectionRelocations) {
  5834. ListScope D(W, "Relocations");
  5835. this->printRelocationsHelper(Sec);
  5836. }
  5837. if (opts::SectionSymbols) {
  5838. ListScope D(W, "Symbols");
  5839. if (this->DotSymtabSec) {
  5840. StringRef StrTable = unwrapOrError(
  5841. this->FileName,
  5842. this->Obj.getStringTableForSymtab(*this->DotSymtabSec));
  5843. ArrayRef<Elf_Word> ShndxTable = this->getShndxTable(this->DotSymtabSec);
  5844. typename ELFT::SymRange Symbols = unwrapOrError(
  5845. this->FileName, this->Obj.symbols(this->DotSymtabSec));
  5846. for (const Elf_Sym &Sym : Symbols) {
  5847. const Elf_Shdr *SymSec = unwrapOrError(
  5848. this->FileName,
  5849. this->Obj.getSection(Sym, this->DotSymtabSec, ShndxTable));
  5850. if (SymSec == &Sec)
  5851. printSymbol(Sym, &Sym - &Symbols[0], ShndxTable, StrTable, false,
  5852. false);
  5853. }
  5854. }
  5855. }
  5856. if (opts::SectionData && Sec.sh_type != ELF::SHT_NOBITS) {
  5857. ArrayRef<uint8_t> Data =
  5858. unwrapOrError(this->FileName, this->Obj.getSectionContents(Sec));
  5859. W.printBinaryBlock(
  5860. "SectionData",
  5861. StringRef(reinterpret_cast<const char *>(Data.data()), Data.size()));
  5862. }
  5863. }
  5864. }
  5865. template <class ELFT>
  5866. void LLVMELFDumper<ELFT>::printSymbolSection(
  5867. const Elf_Sym &Symbol, unsigned SymIndex,
  5868. DataRegion<Elf_Word> ShndxTable) const {
  5869. auto GetSectionSpecialType = [&]() -> Optional<StringRef> {
  5870. if (Symbol.isUndefined())
  5871. return StringRef("Undefined");
  5872. if (Symbol.isProcessorSpecific())
  5873. return StringRef("Processor Specific");
  5874. if (Symbol.isOSSpecific())
  5875. return StringRef("Operating System Specific");
  5876. if (Symbol.isAbsolute())
  5877. return StringRef("Absolute");
  5878. if (Symbol.isCommon())
  5879. return StringRef("Common");
  5880. if (Symbol.isReserved() && Symbol.st_shndx != SHN_XINDEX)
  5881. return StringRef("Reserved");
  5882. return None;
  5883. };
  5884. if (Optional<StringRef> Type = GetSectionSpecialType()) {
  5885. W.printHex("Section", *Type, Symbol.st_shndx);
  5886. return;
  5887. }
  5888. Expected<unsigned> SectionIndex =
  5889. this->getSymbolSectionIndex(Symbol, SymIndex, ShndxTable);
  5890. if (!SectionIndex) {
  5891. assert(Symbol.st_shndx == SHN_XINDEX &&
  5892. "getSymbolSectionIndex should only fail due to an invalid "
  5893. "SHT_SYMTAB_SHNDX table/reference");
  5894. this->reportUniqueWarning(SectionIndex.takeError());
  5895. W.printHex("Section", "Reserved", SHN_XINDEX);
  5896. return;
  5897. }
  5898. Expected<StringRef> SectionName =
  5899. this->getSymbolSectionName(Symbol, *SectionIndex);
  5900. if (!SectionName) {
  5901. // Don't report an invalid section name if the section headers are missing.
  5902. // In such situations, all sections will be "invalid".
  5903. if (!this->ObjF.sections().empty())
  5904. this->reportUniqueWarning(SectionName.takeError());
  5905. else
  5906. consumeError(SectionName.takeError());
  5907. W.printHex("Section", "<?>", *SectionIndex);
  5908. } else {
  5909. W.printHex("Section", *SectionName, *SectionIndex);
  5910. }
  5911. }
  5912. template <class ELFT>
  5913. void LLVMELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
  5914. DataRegion<Elf_Word> ShndxTable,
  5915. Optional<StringRef> StrTable,
  5916. bool IsDynamic,
  5917. bool /*NonVisibilityBitsUsed*/) const {
  5918. std::string FullSymbolName = this->getFullSymbolName(
  5919. Symbol, SymIndex, ShndxTable, StrTable, IsDynamic);
  5920. unsigned char SymbolType = Symbol.getType();
  5921. DictScope D(W, "Symbol");
  5922. W.printNumber("Name", FullSymbolName, Symbol.st_name);
  5923. W.printHex("Value", Symbol.st_value);
  5924. W.printNumber("Size", Symbol.st_size);
  5925. W.printEnum("Binding", Symbol.getBinding(), makeArrayRef(ElfSymbolBindings));
  5926. if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
  5927. SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
  5928. W.printEnum("Type", SymbolType, makeArrayRef(AMDGPUSymbolTypes));
  5929. else
  5930. W.printEnum("Type", SymbolType, makeArrayRef(ElfSymbolTypes));
  5931. if (Symbol.st_other == 0)
  5932. // Usually st_other flag is zero. Do not pollute the output
  5933. // by flags enumeration in that case.
  5934. W.printNumber("Other", 0);
  5935. else {
  5936. std::vector<EnumEntry<unsigned>> SymOtherFlags(std::begin(ElfSymOtherFlags),
  5937. std::end(ElfSymOtherFlags));
  5938. if (this->Obj.getHeader().e_machine == EM_MIPS) {
  5939. // Someones in their infinite wisdom decided to make STO_MIPS_MIPS16
  5940. // flag overlapped with other ST_MIPS_xxx flags. So consider both
  5941. // cases separately.
  5942. if ((Symbol.st_other & STO_MIPS_MIPS16) == STO_MIPS_MIPS16)
  5943. SymOtherFlags.insert(SymOtherFlags.end(),
  5944. std::begin(ElfMips16SymOtherFlags),
  5945. std::end(ElfMips16SymOtherFlags));
  5946. else
  5947. SymOtherFlags.insert(SymOtherFlags.end(),
  5948. std::begin(ElfMipsSymOtherFlags),
  5949. std::end(ElfMipsSymOtherFlags));
  5950. } else if (this->Obj.getHeader().e_machine == EM_AARCH64) {
  5951. SymOtherFlags.insert(SymOtherFlags.end(),
  5952. std::begin(ElfAArch64SymOtherFlags),
  5953. std::end(ElfAArch64SymOtherFlags));
  5954. } else if (this->Obj.getHeader().e_machine == EM_RISCV) {
  5955. SymOtherFlags.insert(SymOtherFlags.end(),
  5956. std::begin(ElfRISCVSymOtherFlags),
  5957. std::end(ElfRISCVSymOtherFlags));
  5958. }
  5959. W.printFlags("Other", Symbol.st_other, makeArrayRef(SymOtherFlags), 0x3u);
  5960. }
  5961. printSymbolSection(Symbol, SymIndex, ShndxTable);
  5962. }
  5963. template <class ELFT>
  5964. void LLVMELFDumper<ELFT>::printSymbols(bool PrintSymbols,
  5965. bool PrintDynamicSymbols) {
  5966. if (PrintSymbols) {
  5967. ListScope Group(W, "Symbols");
  5968. this->printSymbolsHelper(false);
  5969. }
  5970. if (PrintDynamicSymbols) {
  5971. ListScope Group(W, "DynamicSymbols");
  5972. this->printSymbolsHelper(true);
  5973. }
  5974. }
  5975. template <class ELFT> void LLVMELFDumper<ELFT>::printDynamicTable() {
  5976. Elf_Dyn_Range Table = this->dynamic_table();
  5977. if (Table.empty())
  5978. return;
  5979. W.startLine() << "DynamicSection [ (" << Table.size() << " entries)\n";
  5980. size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table);
  5981. // The "Name/Value" column should be indented from the "Type" column by N
  5982. // spaces, where N = MaxTagSize - length of "Type" (4) + trailing
  5983. // space (1) = -3.
  5984. W.startLine() << " Tag" << std::string(ELFT::Is64Bits ? 16 : 8, ' ')
  5985. << "Type" << std::string(MaxTagSize - 3, ' ') << "Name/Value\n";
  5986. std::string ValueFmt = "%-" + std::to_string(MaxTagSize) + "s ";
  5987. for (auto Entry : Table) {
  5988. uintX_t Tag = Entry.getTag();
  5989. std::string Value = this->getDynamicEntry(Tag, Entry.getVal());
  5990. W.startLine() << " " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10, true)
  5991. << " "
  5992. << format(ValueFmt.c_str(),
  5993. this->Obj.getDynamicTagAsString(Tag).c_str())
  5994. << Value << "\n";
  5995. }
  5996. W.startLine() << "]\n";
  5997. }
  5998. template <class ELFT> void LLVMELFDumper<ELFT>::printDynamicRelocations() {
  5999. W.startLine() << "Dynamic Relocations {\n";
  6000. W.indent();
  6001. this->printDynamicRelocationsHelper();
  6002. W.unindent();
  6003. W.startLine() << "}\n";
  6004. }
  6005. template <class ELFT>
  6006. void LLVMELFDumper<ELFT>::printProgramHeaders(
  6007. bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) {
  6008. if (PrintProgramHeaders)
  6009. printProgramHeaders();
  6010. if (PrintSectionMapping == cl::BOU_TRUE)
  6011. printSectionMapping();
  6012. }
  6013. template <class ELFT> void LLVMELFDumper<ELFT>::printProgramHeaders() {
  6014. ListScope L(W, "ProgramHeaders");
  6015. Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
  6016. if (!PhdrsOrErr) {
  6017. this->reportUniqueWarning("unable to dump program headers: " +
  6018. toString(PhdrsOrErr.takeError()));
  6019. return;
  6020. }
  6021. for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
  6022. DictScope P(W, "ProgramHeader");
  6023. StringRef Type =
  6024. segmentTypeToString(this->Obj.getHeader().e_machine, Phdr.p_type);
  6025. W.printHex("Type", Type.empty() ? "Unknown" : Type, Phdr.p_type);
  6026. W.printHex("Offset", Phdr.p_offset);
  6027. W.printHex("VirtualAddress", Phdr.p_vaddr);
  6028. W.printHex("PhysicalAddress", Phdr.p_paddr);
  6029. W.printNumber("FileSize", Phdr.p_filesz);
  6030. W.printNumber("MemSize", Phdr.p_memsz);
  6031. W.printFlags("Flags", Phdr.p_flags, makeArrayRef(ElfSegmentFlags));
  6032. W.printNumber("Alignment", Phdr.p_align);
  6033. }
  6034. }
  6035. template <class ELFT>
  6036. void LLVMELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) {
  6037. ListScope SS(W, "VersionSymbols");
  6038. if (!Sec)
  6039. return;
  6040. StringRef StrTable;
  6041. ArrayRef<Elf_Sym> Syms;
  6042. const Elf_Shdr *SymTabSec;
  6043. Expected<ArrayRef<Elf_Versym>> VerTableOrErr =
  6044. this->getVersionTable(*Sec, &Syms, &StrTable, &SymTabSec);
  6045. if (!VerTableOrErr) {
  6046. this->reportUniqueWarning(VerTableOrErr.takeError());
  6047. return;
  6048. }
  6049. if (StrTable.empty() || Syms.empty() || Syms.size() != VerTableOrErr->size())
  6050. return;
  6051. ArrayRef<Elf_Word> ShNdxTable = this->getShndxTable(SymTabSec);
  6052. for (size_t I = 0, E = Syms.size(); I < E; ++I) {
  6053. DictScope S(W, "Symbol");
  6054. W.printNumber("Version", (*VerTableOrErr)[I].vs_index & VERSYM_VERSION);
  6055. W.printString("Name",
  6056. this->getFullSymbolName(Syms[I], I, ShNdxTable, StrTable,
  6057. /*IsDynamic=*/true));
  6058. }
  6059. }
  6060. const EnumEntry<unsigned> SymVersionFlags[] = {
  6061. {"Base", "BASE", VER_FLG_BASE},
  6062. {"Weak", "WEAK", VER_FLG_WEAK},
  6063. {"Info", "INFO", VER_FLG_INFO}};
  6064. template <class ELFT>
  6065. void LLVMELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) {
  6066. ListScope SD(W, "VersionDefinitions");
  6067. if (!Sec)
  6068. return;
  6069. Expected<std::vector<VerDef>> V = this->Obj.getVersionDefinitions(*Sec);
  6070. if (!V) {
  6071. this->reportUniqueWarning(V.takeError());
  6072. return;
  6073. }
  6074. for (const VerDef &D : *V) {
  6075. DictScope Def(W, "Definition");
  6076. W.printNumber("Version", D.Version);
  6077. W.printFlags("Flags", D.Flags, makeArrayRef(SymVersionFlags));
  6078. W.printNumber("Index", D.Ndx);
  6079. W.printNumber("Hash", D.Hash);
  6080. W.printString("Name", D.Name.c_str());
  6081. W.printList(
  6082. "Predecessors", D.AuxV,
  6083. [](raw_ostream &OS, const VerdAux &Aux) { OS << Aux.Name.c_str(); });
  6084. }
  6085. }
  6086. template <class ELFT>
  6087. void LLVMELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) {
  6088. ListScope SD(W, "VersionRequirements");
  6089. if (!Sec)
  6090. return;
  6091. Expected<std::vector<VerNeed>> V =
  6092. this->Obj.getVersionDependencies(*Sec, this->WarningHandler);
  6093. if (!V) {
  6094. this->reportUniqueWarning(V.takeError());
  6095. return;
  6096. }
  6097. for (const VerNeed &VN : *V) {
  6098. DictScope Entry(W, "Dependency");
  6099. W.printNumber("Version", VN.Version);
  6100. W.printNumber("Count", VN.Cnt);
  6101. W.printString("FileName", VN.File.c_str());
  6102. ListScope L(W, "Entries");
  6103. for (const VernAux &Aux : VN.AuxV) {
  6104. DictScope Entry(W, "Entry");
  6105. W.printNumber("Hash", Aux.Hash);
  6106. W.printFlags("Flags", Aux.Flags, makeArrayRef(SymVersionFlags));
  6107. W.printNumber("Index", Aux.Other);
  6108. W.printString("Name", Aux.Name.c_str());
  6109. }
  6110. }
  6111. }
  6112. template <class ELFT> void LLVMELFDumper<ELFT>::printHashHistograms() {
  6113. W.startLine() << "Hash Histogram not implemented!\n";
  6114. }
  6115. // Returns true if rel/rela section exists, and populates SymbolIndices.
  6116. // Otherwise returns false.
  6117. template <class ELFT>
  6118. static bool getSymbolIndices(const typename ELFT::Shdr *CGRelSection,
  6119. const ELFFile<ELFT> &Obj,
  6120. const LLVMELFDumper<ELFT> *Dumper,
  6121. SmallVector<uint32_t, 128> &SymbolIndices) {
  6122. if (!CGRelSection) {
  6123. Dumper->reportUniqueWarning(
  6124. "relocation section for a call graph section doesn't exist");
  6125. return false;
  6126. }
  6127. if (CGRelSection->sh_type == SHT_REL) {
  6128. typename ELFT::RelRange CGProfileRel;
  6129. Expected<typename ELFT::RelRange> CGProfileRelOrError =
  6130. Obj.rels(*CGRelSection);
  6131. if (!CGProfileRelOrError) {
  6132. Dumper->reportUniqueWarning("unable to load relocations for "
  6133. "SHT_LLVM_CALL_GRAPH_PROFILE section: " +
  6134. toString(CGProfileRelOrError.takeError()));
  6135. return false;
  6136. }
  6137. CGProfileRel = *CGProfileRelOrError;
  6138. for (const typename ELFT::Rel &Rel : CGProfileRel)
  6139. SymbolIndices.push_back(Rel.getSymbol(Obj.isMips64EL()));
  6140. } else {
  6141. // MC unconditionally produces SHT_REL, but GNU strip/objcopy may convert
  6142. // the format to SHT_RELA
  6143. // (https://sourceware.org/bugzilla/show_bug.cgi?id=28035)
  6144. typename ELFT::RelaRange CGProfileRela;
  6145. Expected<typename ELFT::RelaRange> CGProfileRelaOrError =
  6146. Obj.relas(*CGRelSection);
  6147. if (!CGProfileRelaOrError) {
  6148. Dumper->reportUniqueWarning("unable to load relocations for "
  6149. "SHT_LLVM_CALL_GRAPH_PROFILE section: " +
  6150. toString(CGProfileRelaOrError.takeError()));
  6151. return false;
  6152. }
  6153. CGProfileRela = *CGProfileRelaOrError;
  6154. for (const typename ELFT::Rela &Rela : CGProfileRela)
  6155. SymbolIndices.push_back(Rela.getSymbol(Obj.isMips64EL()));
  6156. }
  6157. return true;
  6158. }
  6159. template <class ELFT> void LLVMELFDumper<ELFT>::printCGProfile() {
  6160. llvm::MapVector<const Elf_Shdr *, const Elf_Shdr *> SecToRelocMap;
  6161. auto IsMatch = [](const Elf_Shdr &Sec) -> bool {
  6162. return Sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE;
  6163. };
  6164. this->getSectionAndRelocations(IsMatch, SecToRelocMap);
  6165. for (const auto &CGMapEntry : SecToRelocMap) {
  6166. const Elf_Shdr *CGSection = CGMapEntry.first;
  6167. const Elf_Shdr *CGRelSection = CGMapEntry.second;
  6168. Expected<ArrayRef<Elf_CGProfile>> CGProfileOrErr =
  6169. this->Obj.template getSectionContentsAsArray<Elf_CGProfile>(*CGSection);
  6170. if (!CGProfileOrErr) {
  6171. this->reportUniqueWarning(
  6172. "unable to load the SHT_LLVM_CALL_GRAPH_PROFILE section: " +
  6173. toString(CGProfileOrErr.takeError()));
  6174. return;
  6175. }
  6176. SmallVector<uint32_t, 128> SymbolIndices;
  6177. bool UseReloc =
  6178. getSymbolIndices<ELFT>(CGRelSection, this->Obj, this, SymbolIndices);
  6179. if (UseReloc && SymbolIndices.size() != CGProfileOrErr->size() * 2) {
  6180. this->reportUniqueWarning(
  6181. "number of from/to pairs does not match number of frequencies");
  6182. UseReloc = false;
  6183. }
  6184. ListScope L(W, "CGProfile");
  6185. for (uint32_t I = 0, Size = CGProfileOrErr->size(); I != Size; ++I) {
  6186. const Elf_CGProfile &CGPE = (*CGProfileOrErr)[I];
  6187. DictScope D(W, "CGProfileEntry");
  6188. if (UseReloc) {
  6189. uint32_t From = SymbolIndices[I * 2];
  6190. uint32_t To = SymbolIndices[I * 2 + 1];
  6191. W.printNumber("From", this->getStaticSymbolName(From), From);
  6192. W.printNumber("To", this->getStaticSymbolName(To), To);
  6193. }
  6194. W.printNumber("Weight", CGPE.cgp_weight);
  6195. }
  6196. }
  6197. }
  6198. template <class ELFT> void LLVMELFDumper<ELFT>::printBBAddrMaps() {
  6199. bool IsRelocatable = this->Obj.getHeader().e_type == ELF::ET_REL;
  6200. for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
  6201. if (Sec.sh_type != SHT_LLVM_BB_ADDR_MAP)
  6202. continue;
  6203. Optional<const Elf_Shdr *> FunctionSec = None;
  6204. if (IsRelocatable)
  6205. FunctionSec =
  6206. unwrapOrError(this->FileName, this->Obj.getSection(Sec.sh_link));
  6207. ListScope L(W, "BBAddrMap");
  6208. Expected<std::vector<BBAddrMap>> BBAddrMapOrErr =
  6209. this->Obj.decodeBBAddrMap(Sec);
  6210. if (!BBAddrMapOrErr) {
  6211. this->reportUniqueWarning("unable to dump " + this->describe(Sec) + ": " +
  6212. toString(BBAddrMapOrErr.takeError()));
  6213. continue;
  6214. }
  6215. for (const BBAddrMap &AM : *BBAddrMapOrErr) {
  6216. DictScope D(W, "Function");
  6217. W.printHex("At", AM.Addr);
  6218. SmallVector<uint32_t> FuncSymIndex =
  6219. this->getSymbolIndexesForFunctionAddress(AM.Addr, FunctionSec);
  6220. std::string FuncName = "<?>";
  6221. if (FuncSymIndex.empty())
  6222. this->reportUniqueWarning(
  6223. "could not identify function symbol for address (0x" +
  6224. Twine::utohexstr(AM.Addr) + ") in " + this->describe(Sec));
  6225. else
  6226. FuncName = this->getStaticSymbolName(FuncSymIndex.front());
  6227. W.printString("Name", FuncName);
  6228. ListScope L(W, "BB entries");
  6229. for (const BBAddrMap::BBEntry &BBE : AM.BBEntries) {
  6230. DictScope L(W);
  6231. W.printHex("Offset", BBE.Offset);
  6232. W.printHex("Size", BBE.Size);
  6233. W.printBoolean("HasReturn", BBE.HasReturn);
  6234. W.printBoolean("HasTailCall", BBE.HasTailCall);
  6235. W.printBoolean("IsEHPad", BBE.IsEHPad);
  6236. W.printBoolean("CanFallThrough", BBE.CanFallThrough);
  6237. }
  6238. }
  6239. }
  6240. }
  6241. template <class ELFT> void LLVMELFDumper<ELFT>::printAddrsig() {
  6242. ListScope L(W, "Addrsig");
  6243. if (!this->DotAddrsigSec)
  6244. return;
  6245. Expected<std::vector<uint64_t>> SymsOrErr =
  6246. decodeAddrsigSection(this->Obj, *this->DotAddrsigSec);
  6247. if (!SymsOrErr) {
  6248. this->reportUniqueWarning(SymsOrErr.takeError());
  6249. return;
  6250. }
  6251. for (uint64_t Sym : *SymsOrErr)
  6252. W.printNumber("Sym", this->getStaticSymbolName(Sym), Sym);
  6253. }
  6254. template <typename ELFT>
  6255. static bool printGNUNoteLLVMStyle(uint32_t NoteType, ArrayRef<uint8_t> Desc,
  6256. ScopedPrinter &W) {
  6257. // Return true if we were able to pretty-print the note, false otherwise.
  6258. switch (NoteType) {
  6259. default:
  6260. return false;
  6261. case ELF::NT_GNU_ABI_TAG: {
  6262. const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc);
  6263. if (!AbiTag.IsValid) {
  6264. W.printString("ABI", "<corrupt GNU_ABI_TAG>");
  6265. return false;
  6266. } else {
  6267. W.printString("OS", AbiTag.OSName);
  6268. W.printString("ABI", AbiTag.ABI);
  6269. }
  6270. break;
  6271. }
  6272. case ELF::NT_GNU_BUILD_ID: {
  6273. W.printString("Build ID", getGNUBuildId(Desc));
  6274. break;
  6275. }
  6276. case ELF::NT_GNU_GOLD_VERSION:
  6277. W.printString("Version", getDescAsStringRef(Desc));
  6278. break;
  6279. case ELF::NT_GNU_PROPERTY_TYPE_0:
  6280. ListScope D(W, "Property");
  6281. for (const std::string &Property : getGNUPropertyList<ELFT>(Desc))
  6282. W.printString(Property);
  6283. break;
  6284. }
  6285. return true;
  6286. }
  6287. template <typename ELFT>
  6288. static bool printLLVMOMPOFFLOADNoteLLVMStyle(uint32_t NoteType,
  6289. ArrayRef<uint8_t> Desc,
  6290. ScopedPrinter &W) {
  6291. switch (NoteType) {
  6292. default:
  6293. return false;
  6294. case ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION:
  6295. W.printString("Version", getDescAsStringRef(Desc));
  6296. break;
  6297. case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER:
  6298. W.printString("Producer", getDescAsStringRef(Desc));
  6299. break;
  6300. case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION:
  6301. W.printString("Producer version", getDescAsStringRef(Desc));
  6302. break;
  6303. }
  6304. return true;
  6305. }
  6306. static void printCoreNoteLLVMStyle(const CoreNote &Note, ScopedPrinter &W) {
  6307. W.printNumber("Page Size", Note.PageSize);
  6308. for (const CoreFileMapping &Mapping : Note.Mappings) {
  6309. ListScope D(W, "Mapping");
  6310. W.printHex("Start", Mapping.Start);
  6311. W.printHex("End", Mapping.End);
  6312. W.printHex("Offset", Mapping.Offset);
  6313. W.printString("Filename", Mapping.Filename);
  6314. }
  6315. }
  6316. template <class ELFT> void LLVMELFDumper<ELFT>::printNotes() {
  6317. ListScope L(W, "Notes");
  6318. std::unique_ptr<DictScope> NoteScope;
  6319. auto StartNotes = [&](Optional<StringRef> SecName,
  6320. const typename ELFT::Off Offset,
  6321. const typename ELFT::Addr Size) {
  6322. NoteScope = std::make_unique<DictScope>(W, "NoteSection");
  6323. W.printString("Name", SecName ? *SecName : "<?>");
  6324. W.printHex("Offset", Offset);
  6325. W.printHex("Size", Size);
  6326. };
  6327. auto EndNotes = [&] { NoteScope.reset(); };
  6328. auto ProcessNote = [&](const Elf_Note &Note, bool IsCore) -> Error {
  6329. DictScope D2(W, "Note");
  6330. StringRef Name = Note.getName();
  6331. ArrayRef<uint8_t> Descriptor = Note.getDesc();
  6332. Elf_Word Type = Note.getType();
  6333. // Print the note owner/type.
  6334. W.printString("Owner", Name);
  6335. W.printHex("Data size", Descriptor.size());
  6336. StringRef NoteType =
  6337. getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type);
  6338. if (!NoteType.empty())
  6339. W.printString("Type", NoteType);
  6340. else
  6341. W.printString("Type",
  6342. "Unknown (" + to_string(format_hex(Type, 10)) + ")");
  6343. // Print the description, or fallback to printing raw bytes for unknown
  6344. // owners/if we fail to pretty-print the contents.
  6345. if (Name == "GNU") {
  6346. if (printGNUNoteLLVMStyle<ELFT>(Type, Descriptor, W))
  6347. return Error::success();
  6348. } else if (Name == "FreeBSD") {
  6349. if (Optional<FreeBSDNote> N =
  6350. getFreeBSDNote<ELFT>(Type, Descriptor, IsCore)) {
  6351. W.printString(N->Type, N->Value);
  6352. return Error::success();
  6353. }
  6354. } else if (Name == "AMD") {
  6355. const AMDNote N = getAMDNote<ELFT>(Type, Descriptor);
  6356. if (!N.Type.empty()) {
  6357. W.printString(N.Type, N.Value);
  6358. return Error::success();
  6359. }
  6360. } else if (Name == "AMDGPU") {
  6361. const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor);
  6362. if (!N.Type.empty()) {
  6363. W.printString(N.Type, N.Value);
  6364. return Error::success();
  6365. }
  6366. } else if (Name == "LLVMOMPOFFLOAD") {
  6367. if (printLLVMOMPOFFLOADNoteLLVMStyle<ELFT>(Type, Descriptor, W))
  6368. return Error::success();
  6369. } else if (Name == "CORE") {
  6370. if (Type == ELF::NT_FILE) {
  6371. DataExtractor DescExtractor(Descriptor,
  6372. ELFT::TargetEndianness == support::little,
  6373. sizeof(Elf_Addr));
  6374. if (Expected<CoreNote> N = readCoreNote(DescExtractor)) {
  6375. printCoreNoteLLVMStyle(*N, W);
  6376. return Error::success();
  6377. } else {
  6378. return N.takeError();
  6379. }
  6380. }
  6381. }
  6382. if (!Descriptor.empty()) {
  6383. W.printBinaryBlock("Description data", Descriptor);
  6384. }
  6385. return Error::success();
  6386. };
  6387. printNotesHelper(*this, StartNotes, ProcessNote, EndNotes);
  6388. }
  6389. template <class ELFT> void LLVMELFDumper<ELFT>::printELFLinkerOptions() {
  6390. ListScope L(W, "LinkerOptions");
  6391. unsigned I = -1;
  6392. for (const Elf_Shdr &Shdr : cantFail(this->Obj.sections())) {
  6393. ++I;
  6394. if (Shdr.sh_type != ELF::SHT_LLVM_LINKER_OPTIONS)
  6395. continue;
  6396. Expected<ArrayRef<uint8_t>> ContentsOrErr =
  6397. this->Obj.getSectionContents(Shdr);
  6398. if (!ContentsOrErr) {
  6399. this->reportUniqueWarning("unable to read the content of the "
  6400. "SHT_LLVM_LINKER_OPTIONS section: " +
  6401. toString(ContentsOrErr.takeError()));
  6402. continue;
  6403. }
  6404. if (ContentsOrErr->empty())
  6405. continue;
  6406. if (ContentsOrErr->back() != 0) {
  6407. this->reportUniqueWarning("SHT_LLVM_LINKER_OPTIONS section at index " +
  6408. Twine(I) +
  6409. " is broken: the "
  6410. "content is not null-terminated");
  6411. continue;
  6412. }
  6413. SmallVector<StringRef, 16> Strings;
  6414. toStringRef(ContentsOrErr->drop_back()).split(Strings, '\0');
  6415. if (Strings.size() % 2 != 0) {
  6416. this->reportUniqueWarning(
  6417. "SHT_LLVM_LINKER_OPTIONS section at index " + Twine(I) +
  6418. " is broken: an incomplete "
  6419. "key-value pair was found. The last possible key was: \"" +
  6420. Strings.back() + "\"");
  6421. continue;
  6422. }
  6423. for (size_t I = 0; I < Strings.size(); I += 2)
  6424. W.printString(Strings[I], Strings[I + 1]);
  6425. }
  6426. }
  6427. template <class ELFT> void LLVMELFDumper<ELFT>::printDependentLibs() {
  6428. ListScope L(W, "DependentLibs");
  6429. this->printDependentLibsHelper(
  6430. [](const Elf_Shdr &) {},
  6431. [this](StringRef Lib, uint64_t) { W.printString(Lib); });
  6432. }
  6433. template <class ELFT> void LLVMELFDumper<ELFT>::printStackSizes() {
  6434. ListScope L(W, "StackSizes");
  6435. if (this->Obj.getHeader().e_type == ELF::ET_REL)
  6436. this->printRelocatableStackSizes([]() {});
  6437. else
  6438. this->printNonRelocatableStackSizes([]() {});
  6439. }
  6440. template <class ELFT>
  6441. void LLVMELFDumper<ELFT>::printStackSizeEntry(uint64_t Size,
  6442. ArrayRef<std::string> FuncNames) {
  6443. DictScope D(W, "Entry");
  6444. W.printList("Functions", FuncNames);
  6445. W.printHex("Size", Size);
  6446. }
  6447. template <class ELFT>
  6448. void LLVMELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) {
  6449. auto PrintEntry = [&](const Elf_Addr *E) {
  6450. W.printHex("Address", Parser.getGotAddress(E));
  6451. W.printNumber("Access", Parser.getGotOffset(E));
  6452. W.printHex("Initial", *E);
  6453. };
  6454. DictScope GS(W, Parser.IsStatic ? "Static GOT" : "Primary GOT");
  6455. W.printHex("Canonical gp value", Parser.getGp());
  6456. {
  6457. ListScope RS(W, "Reserved entries");
  6458. {
  6459. DictScope D(W, "Entry");
  6460. PrintEntry(Parser.getGotLazyResolver());
  6461. W.printString("Purpose", StringRef("Lazy resolver"));
  6462. }
  6463. if (Parser.getGotModulePointer()) {
  6464. DictScope D(W, "Entry");
  6465. PrintEntry(Parser.getGotModulePointer());
  6466. W.printString("Purpose", StringRef("Module pointer (GNU extension)"));
  6467. }
  6468. }
  6469. {
  6470. ListScope LS(W, "Local entries");
  6471. for (auto &E : Parser.getLocalEntries()) {
  6472. DictScope D(W, "Entry");
  6473. PrintEntry(&E);
  6474. }
  6475. }
  6476. if (Parser.IsStatic)
  6477. return;
  6478. {
  6479. ListScope GS(W, "Global entries");
  6480. for (auto &E : Parser.getGlobalEntries()) {
  6481. DictScope D(W, "Entry");
  6482. PrintEntry(&E);
  6483. const Elf_Sym &Sym = *Parser.getGotSym(&E);
  6484. W.printHex("Value", Sym.st_value);
  6485. W.printEnum("Type", Sym.getType(), makeArrayRef(ElfSymbolTypes));
  6486. const unsigned SymIndex = &Sym - this->dynamic_symbols().begin();
  6487. DataRegion<Elf_Word> ShndxTable(
  6488. (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
  6489. printSymbolSection(Sym, SymIndex, ShndxTable);
  6490. std::string SymName = this->getFullSymbolName(
  6491. Sym, SymIndex, ShndxTable, this->DynamicStringTable, true);
  6492. W.printNumber("Name", SymName, Sym.st_name);
  6493. }
  6494. }
  6495. W.printNumber("Number of TLS and multi-GOT entries",
  6496. uint64_t(Parser.getOtherEntries().size()));
  6497. }
  6498. template <class ELFT>
  6499. void LLVMELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) {
  6500. auto PrintEntry = [&](const Elf_Addr *E) {
  6501. W.printHex("Address", Parser.getPltAddress(E));
  6502. W.printHex("Initial", *E);
  6503. };
  6504. DictScope GS(W, "PLT GOT");
  6505. {
  6506. ListScope RS(W, "Reserved entries");
  6507. {
  6508. DictScope D(W, "Entry");
  6509. PrintEntry(Parser.getPltLazyResolver());
  6510. W.printString("Purpose", StringRef("PLT lazy resolver"));
  6511. }
  6512. if (auto E = Parser.getPltModulePointer()) {
  6513. DictScope D(W, "Entry");
  6514. PrintEntry(E);
  6515. W.printString("Purpose", StringRef("Module pointer"));
  6516. }
  6517. }
  6518. {
  6519. ListScope LS(W, "Entries");
  6520. DataRegion<Elf_Word> ShndxTable(
  6521. (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
  6522. for (auto &E : Parser.getPltEntries()) {
  6523. DictScope D(W, "Entry");
  6524. PrintEntry(&E);
  6525. const Elf_Sym &Sym = *Parser.getPltSym(&E);
  6526. W.printHex("Value", Sym.st_value);
  6527. W.printEnum("Type", Sym.getType(), makeArrayRef(ElfSymbolTypes));
  6528. printSymbolSection(Sym, &Sym - this->dynamic_symbols().begin(),
  6529. ShndxTable);
  6530. const Elf_Sym *FirstSym = cantFail(
  6531. this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0));
  6532. std::string SymName = this->getFullSymbolName(
  6533. Sym, &Sym - FirstSym, ShndxTable, Parser.getPltStrTable(), true);
  6534. W.printNumber("Name", SymName, Sym.st_name);
  6535. }
  6536. }
  6537. }
  6538. template <class ELFT> void LLVMELFDumper<ELFT>::printMipsABIFlags() {
  6539. const Elf_Mips_ABIFlags<ELFT> *Flags;
  6540. if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr =
  6541. getMipsAbiFlagsSection(*this)) {
  6542. Flags = *SecOrErr;
  6543. if (!Flags) {
  6544. W.startLine() << "There is no .MIPS.abiflags section in the file.\n";
  6545. return;
  6546. }
  6547. } else {
  6548. this->reportUniqueWarning(SecOrErr.takeError());
  6549. return;
  6550. }
  6551. raw_ostream &OS = W.getOStream();
  6552. DictScope GS(W, "MIPS ABI Flags");
  6553. W.printNumber("Version", Flags->version);
  6554. W.startLine() << "ISA: ";
  6555. if (Flags->isa_rev <= 1)
  6556. OS << format("MIPS%u", Flags->isa_level);
  6557. else
  6558. OS << format("MIPS%ur%u", Flags->isa_level, Flags->isa_rev);
  6559. OS << "\n";
  6560. W.printEnum("ISA Extension", Flags->isa_ext, makeArrayRef(ElfMipsISAExtType));
  6561. W.printFlags("ASEs", Flags->ases, makeArrayRef(ElfMipsASEFlags));
  6562. W.printEnum("FP ABI", Flags->fp_abi, makeArrayRef(ElfMipsFpABIType));
  6563. W.printNumber("GPR size", getMipsRegisterSize(Flags->gpr_size));
  6564. W.printNumber("CPR1 size", getMipsRegisterSize(Flags->cpr1_size));
  6565. W.printNumber("CPR2 size", getMipsRegisterSize(Flags->cpr2_size));
  6566. W.printFlags("Flags 1", Flags->flags1, makeArrayRef(ElfMipsFlags1));
  6567. W.printHex("Flags 2", Flags->flags2);
  6568. }
  6569. template <class ELFT>
  6570. void JSONELFDumper<ELFT>::printFileSummary(StringRef FileStr, ObjectFile &Obj,
  6571. ArrayRef<std::string> InputFilenames,
  6572. const Archive *A) {
  6573. FileScope = std::make_unique<DictScope>(this->W, FileStr);
  6574. DictScope D(this->W, "FileSummary");
  6575. this->W.printString("File", FileStr);
  6576. this->W.printString("Format", Obj.getFileFormatName());
  6577. this->W.printString("Arch", Triple::getArchTypeName(Obj.getArch()));
  6578. this->W.printString(
  6579. "AddressSize",
  6580. std::string(formatv("{0}bit", 8 * Obj.getBytesInAddress())));
  6581. this->printLoadName();
  6582. }