ELFDumper.cpp 272 KB

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