ELFDumper.cpp 240 KB

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