layout.cc 198 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463
  1. // layout.cc -- lay out output file sections for gold
  2. // Copyright (C) 2006-2022 Free Software Foundation, Inc.
  3. // Written by Ian Lance Taylor <iant@google.com>.
  4. // This file is part of gold.
  5. // This program is free software; you can redistribute it and/or modify
  6. // it under the terms of the GNU General Public License as published by
  7. // the Free Software Foundation; either version 3 of the License, or
  8. // (at your option) any later version.
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
  16. // MA 02110-1301, USA.
  17. #include "gold.h"
  18. #include <cerrno>
  19. #include <cstring>
  20. #include <algorithm>
  21. #include <iostream>
  22. #include <fstream>
  23. #include <utility>
  24. #include <fcntl.h>
  25. #include <fnmatch.h>
  26. #include <unistd.h>
  27. #include "libiberty.h"
  28. #include "md5.h"
  29. #include "sha1.h"
  30. #ifdef __MINGW32__
  31. #include <windows.h>
  32. #include <rpcdce.h>
  33. #endif
  34. #include "parameters.h"
  35. #include "options.h"
  36. #include "mapfile.h"
  37. #include "script.h"
  38. #include "script-sections.h"
  39. #include "output.h"
  40. #include "symtab.h"
  41. #include "dynobj.h"
  42. #include "ehframe.h"
  43. #include "gdb-index.h"
  44. #include "compressed_output.h"
  45. #include "reduced_debug_output.h"
  46. #include "object.h"
  47. #include "reloc.h"
  48. #include "descriptors.h"
  49. #include "plugin.h"
  50. #include "incremental.h"
  51. #include "layout.h"
  52. namespace gold
  53. {
  54. // Class Free_list.
  55. // The total number of free lists used.
  56. unsigned int Free_list::num_lists = 0;
  57. // The total number of free list nodes used.
  58. unsigned int Free_list::num_nodes = 0;
  59. // The total number of calls to Free_list::remove.
  60. unsigned int Free_list::num_removes = 0;
  61. // The total number of nodes visited during calls to Free_list::remove.
  62. unsigned int Free_list::num_remove_visits = 0;
  63. // The total number of calls to Free_list::allocate.
  64. unsigned int Free_list::num_allocates = 0;
  65. // The total number of nodes visited during calls to Free_list::allocate.
  66. unsigned int Free_list::num_allocate_visits = 0;
  67. // Initialize the free list. Creates a single free list node that
  68. // describes the entire region of length LEN. If EXTEND is true,
  69. // allocate() is allowed to extend the region beyond its initial
  70. // length.
  71. void
  72. Free_list::init(off_t len, bool extend)
  73. {
  74. this->list_.push_front(Free_list_node(0, len));
  75. this->last_remove_ = this->list_.begin();
  76. this->extend_ = extend;
  77. this->length_ = len;
  78. ++Free_list::num_lists;
  79. ++Free_list::num_nodes;
  80. }
  81. // Remove a chunk from the free list. Because we start with a single
  82. // node that covers the entire section, and remove chunks from it one
  83. // at a time, we do not need to coalesce chunks or handle cases that
  84. // span more than one free node. We expect to remove chunks from the
  85. // free list in order, and we expect to have only a few chunks of free
  86. // space left (corresponding to files that have changed since the last
  87. // incremental link), so a simple linear list should provide sufficient
  88. // performance.
  89. void
  90. Free_list::remove(off_t start, off_t end)
  91. {
  92. if (start == end)
  93. return;
  94. gold_assert(start < end);
  95. ++Free_list::num_removes;
  96. Iterator p = this->last_remove_;
  97. if (p->start_ > start)
  98. p = this->list_.begin();
  99. for (; p != this->list_.end(); ++p)
  100. {
  101. ++Free_list::num_remove_visits;
  102. // Find a node that wholly contains the indicated region.
  103. if (p->start_ <= start && p->end_ >= end)
  104. {
  105. // Case 1: the indicated region spans the whole node.
  106. // Add some fuzz to avoid creating tiny free chunks.
  107. if (p->start_ + 3 >= start && p->end_ <= end + 3)
  108. p = this->list_.erase(p);
  109. // Case 2: remove a chunk from the start of the node.
  110. else if (p->start_ + 3 >= start)
  111. p->start_ = end;
  112. // Case 3: remove a chunk from the end of the node.
  113. else if (p->end_ <= end + 3)
  114. p->end_ = start;
  115. // Case 4: remove a chunk from the middle, and split
  116. // the node into two.
  117. else
  118. {
  119. Free_list_node newnode(p->start_, start);
  120. p->start_ = end;
  121. this->list_.insert(p, newnode);
  122. ++Free_list::num_nodes;
  123. }
  124. this->last_remove_ = p;
  125. return;
  126. }
  127. }
  128. // Did not find a node containing the given chunk. This could happen
  129. // because a small chunk was already removed due to the fuzz.
  130. gold_debug(DEBUG_INCREMENTAL,
  131. "Free_list::remove(%d,%d) not found",
  132. static_cast<int>(start), static_cast<int>(end));
  133. }
  134. // Allocate a chunk of size LEN from the free list. Returns -1ULL
  135. // if a sufficiently large chunk of free space is not found.
  136. // We use a simple first-fit algorithm.
  137. off_t
  138. Free_list::allocate(off_t len, uint64_t align, off_t minoff)
  139. {
  140. gold_debug(DEBUG_INCREMENTAL,
  141. "Free_list::allocate(%08lx, %d, %08lx)",
  142. static_cast<long>(len), static_cast<int>(align),
  143. static_cast<long>(minoff));
  144. if (len == 0)
  145. return align_address(minoff, align);
  146. ++Free_list::num_allocates;
  147. // We usually want to drop free chunks smaller than 4 bytes.
  148. // If we need to guarantee a minimum hole size, though, we need
  149. // to keep track of all free chunks.
  150. const int fuzz = this->min_hole_ > 0 ? 0 : 3;
  151. for (Iterator p = this->list_.begin(); p != this->list_.end(); ++p)
  152. {
  153. ++Free_list::num_allocate_visits;
  154. off_t start = p->start_ > minoff ? p->start_ : minoff;
  155. start = align_address(start, align);
  156. off_t end = start + len;
  157. if (end > p->end_ && p->end_ == this->length_ && this->extend_)
  158. {
  159. this->length_ = end;
  160. p->end_ = end;
  161. }
  162. if (end == p->end_ || (end <= p->end_ - this->min_hole_))
  163. {
  164. if (p->start_ + fuzz >= start && p->end_ <= end + fuzz)
  165. this->list_.erase(p);
  166. else if (p->start_ + fuzz >= start)
  167. p->start_ = end;
  168. else if (p->end_ <= end + fuzz)
  169. p->end_ = start;
  170. else
  171. {
  172. Free_list_node newnode(p->start_, start);
  173. p->start_ = end;
  174. this->list_.insert(p, newnode);
  175. ++Free_list::num_nodes;
  176. }
  177. return start;
  178. }
  179. }
  180. if (this->extend_)
  181. {
  182. off_t start = align_address(this->length_, align);
  183. this->length_ = start + len;
  184. return start;
  185. }
  186. return -1;
  187. }
  188. // Dump the free list (for debugging).
  189. void
  190. Free_list::dump()
  191. {
  192. gold_info("Free list:\n start end length\n");
  193. for (Iterator p = this->list_.begin(); p != this->list_.end(); ++p)
  194. gold_info(" %08lx %08lx %08lx", static_cast<long>(p->start_),
  195. static_cast<long>(p->end_),
  196. static_cast<long>(p->end_ - p->start_));
  197. }
  198. // Print the statistics for the free lists.
  199. void
  200. Free_list::print_stats()
  201. {
  202. fprintf(stderr, _("%s: total free lists: %u\n"),
  203. program_name, Free_list::num_lists);
  204. fprintf(stderr, _("%s: total free list nodes: %u\n"),
  205. program_name, Free_list::num_nodes);
  206. fprintf(stderr, _("%s: calls to Free_list::remove: %u\n"),
  207. program_name, Free_list::num_removes);
  208. fprintf(stderr, _("%s: nodes visited: %u\n"),
  209. program_name, Free_list::num_remove_visits);
  210. fprintf(stderr, _("%s: calls to Free_list::allocate: %u\n"),
  211. program_name, Free_list::num_allocates);
  212. fprintf(stderr, _("%s: nodes visited: %u\n"),
  213. program_name, Free_list::num_allocate_visits);
  214. }
  215. // A Hash_task computes the MD5 checksum of an array of char.
  216. class Hash_task : public Task
  217. {
  218. public:
  219. Hash_task(Output_file* of,
  220. size_t offset,
  221. size_t size,
  222. unsigned char* dst,
  223. Task_token* final_blocker)
  224. : of_(of), offset_(offset), size_(size), dst_(dst),
  225. final_blocker_(final_blocker)
  226. { }
  227. void
  228. run(Workqueue*)
  229. {
  230. const unsigned char* iv =
  231. this->of_->get_input_view(this->offset_, this->size_);
  232. md5_buffer(reinterpret_cast<const char*>(iv), this->size_, this->dst_);
  233. this->of_->free_input_view(this->offset_, this->size_, iv);
  234. }
  235. Task_token*
  236. is_runnable()
  237. { return NULL; }
  238. // Unblock FINAL_BLOCKER_ when done.
  239. void
  240. locks(Task_locker* tl)
  241. { tl->add(this, this->final_blocker_); }
  242. std::string
  243. get_name() const
  244. { return "Hash_task"; }
  245. private:
  246. Output_file* of_;
  247. const size_t offset_;
  248. const size_t size_;
  249. unsigned char* const dst_;
  250. Task_token* const final_blocker_;
  251. };
  252. // Layout::Relaxation_debug_check methods.
  253. // Check that sections and special data are in reset states.
  254. // We do not save states for Output_sections and special Output_data.
  255. // So we check that they have not assigned any addresses or offsets.
  256. // clean_up_after_relaxation simply resets their addresses and offsets.
  257. void
  258. Layout::Relaxation_debug_check::check_output_data_for_reset_values(
  259. const Layout::Section_list& sections,
  260. const Layout::Data_list& special_outputs,
  261. const Layout::Data_list& relax_outputs)
  262. {
  263. for(Layout::Section_list::const_iterator p = sections.begin();
  264. p != sections.end();
  265. ++p)
  266. gold_assert((*p)->address_and_file_offset_have_reset_values());
  267. for(Layout::Data_list::const_iterator p = special_outputs.begin();
  268. p != special_outputs.end();
  269. ++p)
  270. gold_assert((*p)->address_and_file_offset_have_reset_values());
  271. gold_assert(relax_outputs.empty());
  272. }
  273. // Save information of SECTIONS for checking later.
  274. void
  275. Layout::Relaxation_debug_check::read_sections(
  276. const Layout::Section_list& sections)
  277. {
  278. for(Layout::Section_list::const_iterator p = sections.begin();
  279. p != sections.end();
  280. ++p)
  281. {
  282. Output_section* os = *p;
  283. Section_info info;
  284. info.output_section = os;
  285. info.address = os->is_address_valid() ? os->address() : 0;
  286. info.data_size = os->is_data_size_valid() ? os->data_size() : -1;
  287. info.offset = os->is_offset_valid()? os->offset() : -1 ;
  288. this->section_infos_.push_back(info);
  289. }
  290. }
  291. // Verify SECTIONS using previously recorded information.
  292. void
  293. Layout::Relaxation_debug_check::verify_sections(
  294. const Layout::Section_list& sections)
  295. {
  296. size_t i = 0;
  297. for(Layout::Section_list::const_iterator p = sections.begin();
  298. p != sections.end();
  299. ++p, ++i)
  300. {
  301. Output_section* os = *p;
  302. uint64_t address = os->is_address_valid() ? os->address() : 0;
  303. off_t data_size = os->is_data_size_valid() ? os->data_size() : -1;
  304. off_t offset = os->is_offset_valid()? os->offset() : -1 ;
  305. if (i >= this->section_infos_.size())
  306. {
  307. gold_fatal("Section_info of %s missing.\n", os->name());
  308. }
  309. const Section_info& info = this->section_infos_[i];
  310. if (os != info.output_section)
  311. gold_fatal("Section order changed. Expecting %s but see %s\n",
  312. info.output_section->name(), os->name());
  313. if (address != info.address
  314. || data_size != info.data_size
  315. || offset != info.offset)
  316. gold_fatal("Section %s changed.\n", os->name());
  317. }
  318. }
  319. // Layout_task_runner methods.
  320. // Lay out the sections. This is called after all the input objects
  321. // have been read.
  322. void
  323. Layout_task_runner::run(Workqueue* workqueue, const Task* task)
  324. {
  325. // See if any of the input definitions violate the One Definition Rule.
  326. // TODO: if this is too slow, do this as a task, rather than inline.
  327. this->symtab_->detect_odr_violations(task, this->options_.output_file_name());
  328. Layout* layout = this->layout_;
  329. off_t file_size = layout->finalize(this->input_objects_,
  330. this->symtab_,
  331. this->target_,
  332. task);
  333. // Now we know the final size of the output file and we know where
  334. // each piece of information goes.
  335. if (this->mapfile_ != NULL)
  336. {
  337. this->mapfile_->print_discarded_sections(this->input_objects_);
  338. layout->print_to_mapfile(this->mapfile_);
  339. }
  340. Output_file* of;
  341. if (layout->incremental_base() == NULL)
  342. {
  343. of = new Output_file(parameters->options().output_file_name());
  344. if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
  345. of->set_is_temporary();
  346. of->open(file_size);
  347. }
  348. else
  349. {
  350. of = layout->incremental_base()->output_file();
  351. // Apply the incremental relocations for symbols whose values
  352. // have changed. We do this before we resize the file and start
  353. // writing anything else to it, so that we can read the old
  354. // incremental information from the file before (possibly)
  355. // overwriting it.
  356. if (parameters->incremental_update())
  357. layout->incremental_base()->apply_incremental_relocs(this->symtab_,
  358. this->layout_,
  359. of);
  360. of->resize(file_size);
  361. }
  362. // Queue up the final set of tasks.
  363. gold::queue_final_tasks(this->options_, this->input_objects_,
  364. this->symtab_, layout, workqueue, of);
  365. }
  366. // Layout methods.
  367. Layout::Layout(int number_of_input_files, Script_options* script_options)
  368. : number_of_input_files_(number_of_input_files),
  369. script_options_(script_options),
  370. namepool_(),
  371. sympool_(),
  372. dynpool_(),
  373. signatures_(),
  374. section_name_map_(),
  375. segment_list_(),
  376. section_list_(),
  377. unattached_section_list_(),
  378. special_output_list_(),
  379. relax_output_list_(),
  380. section_headers_(NULL),
  381. tls_segment_(NULL),
  382. relro_segment_(NULL),
  383. interp_segment_(NULL),
  384. increase_relro_(0),
  385. symtab_section_(NULL),
  386. symtab_xindex_(NULL),
  387. dynsym_section_(NULL),
  388. dynsym_xindex_(NULL),
  389. dynamic_section_(NULL),
  390. dynamic_symbol_(NULL),
  391. dynamic_data_(NULL),
  392. eh_frame_section_(NULL),
  393. eh_frame_data_(NULL),
  394. added_eh_frame_data_(false),
  395. eh_frame_hdr_section_(NULL),
  396. gdb_index_data_(NULL),
  397. build_id_note_(NULL),
  398. debug_abbrev_(NULL),
  399. debug_info_(NULL),
  400. group_signatures_(),
  401. output_file_size_(-1),
  402. have_added_input_section_(false),
  403. sections_are_attached_(false),
  404. input_requires_executable_stack_(false),
  405. input_with_gnu_stack_note_(false),
  406. input_without_gnu_stack_note_(false),
  407. has_static_tls_(false),
  408. any_postprocessing_sections_(false),
  409. resized_signatures_(false),
  410. have_stabstr_section_(false),
  411. section_ordering_specified_(false),
  412. unique_segment_for_sections_specified_(false),
  413. incremental_inputs_(NULL),
  414. record_output_section_data_from_script_(false),
  415. lto_slim_object_(false),
  416. script_output_section_data_list_(),
  417. segment_states_(NULL),
  418. relaxation_debug_check_(NULL),
  419. section_order_map_(),
  420. section_segment_map_(),
  421. input_section_position_(),
  422. input_section_glob_(),
  423. incremental_base_(NULL),
  424. free_list_(),
  425. gnu_properties_()
  426. {
  427. // Make space for more than enough segments for a typical file.
  428. // This is just for efficiency--it's OK if we wind up needing more.
  429. this->segment_list_.reserve(12);
  430. // We expect two unattached Output_data objects: the file header and
  431. // the segment headers.
  432. this->special_output_list_.reserve(2);
  433. // Initialize structure needed for an incremental build.
  434. if (parameters->incremental())
  435. this->incremental_inputs_ = new Incremental_inputs;
  436. // The section name pool is worth optimizing in all cases, because
  437. // it is small, but there are often overlaps due to .rel sections.
  438. this->namepool_.set_optimize();
  439. }
  440. // For incremental links, record the base file to be modified.
  441. void
  442. Layout::set_incremental_base(Incremental_binary* base)
  443. {
  444. this->incremental_base_ = base;
  445. this->free_list_.init(base->output_file()->filesize(), true);
  446. }
  447. // Hash a key we use to look up an output section mapping.
  448. size_t
  449. Layout::Hash_key::operator()(const Layout::Key& k) const
  450. {
  451. return k.first + k.second.first + k.second.second;
  452. }
  453. // These are the debug sections that are actually used by gdb.
  454. // Currently, we've checked versions of gdb up to and including 7.4.
  455. // We only check the part of the name that follows ".debug_" or
  456. // ".zdebug_".
  457. static const char* gdb_sections[] =
  458. {
  459. "abbrev",
  460. "addr", // Fission extension
  461. // "aranges", // not used by gdb as of 7.4
  462. "frame",
  463. "gdb_scripts",
  464. "info",
  465. "types",
  466. "line",
  467. "loc",
  468. "macinfo",
  469. "macro",
  470. // "pubnames", // not used by gdb as of 7.4
  471. // "pubtypes", // not used by gdb as of 7.4
  472. // "gnu_pubnames", // Fission extension
  473. // "gnu_pubtypes", // Fission extension
  474. "ranges",
  475. "str",
  476. "str_offsets",
  477. };
  478. // This is the minimum set of sections needed for line numbers.
  479. static const char* lines_only_debug_sections[] =
  480. {
  481. "abbrev",
  482. // "addr", // Fission extension
  483. // "aranges", // not used by gdb as of 7.4
  484. // "frame",
  485. // "gdb_scripts",
  486. "info",
  487. // "types",
  488. "line",
  489. // "loc",
  490. // "macinfo",
  491. // "macro",
  492. // "pubnames", // not used by gdb as of 7.4
  493. // "pubtypes", // not used by gdb as of 7.4
  494. // "gnu_pubnames", // Fission extension
  495. // "gnu_pubtypes", // Fission extension
  496. // "ranges",
  497. "str",
  498. "str_offsets", // Fission extension
  499. };
  500. // These sections are the DWARF fast-lookup tables, and are not needed
  501. // when building a .gdb_index section.
  502. static const char* gdb_fast_lookup_sections[] =
  503. {
  504. "aranges",
  505. "pubnames",
  506. "gnu_pubnames",
  507. "pubtypes",
  508. "gnu_pubtypes",
  509. };
  510. // Returns whether the given debug section is in the list of
  511. // debug-sections-used-by-some-version-of-gdb. SUFFIX is the
  512. // portion of the name following ".debug_" or ".zdebug_".
  513. static inline bool
  514. is_gdb_debug_section(const char* suffix)
  515. {
  516. // We can do this faster: binary search or a hashtable. But why bother?
  517. for (size_t i = 0; i < sizeof(gdb_sections)/sizeof(*gdb_sections); ++i)
  518. if (strcmp(suffix, gdb_sections[i]) == 0)
  519. return true;
  520. return false;
  521. }
  522. // Returns whether the given section is needed for lines-only debugging.
  523. static inline bool
  524. is_lines_only_debug_section(const char* suffix)
  525. {
  526. // We can do this faster: binary search or a hashtable. But why bother?
  527. for (size_t i = 0;
  528. i < sizeof(lines_only_debug_sections)/sizeof(*lines_only_debug_sections);
  529. ++i)
  530. if (strcmp(suffix, lines_only_debug_sections[i]) == 0)
  531. return true;
  532. return false;
  533. }
  534. // Returns whether the given section is a fast-lookup section that
  535. // will not be needed when building a .gdb_index section.
  536. static inline bool
  537. is_gdb_fast_lookup_section(const char* suffix)
  538. {
  539. // We can do this faster: binary search or a hashtable. But why bother?
  540. for (size_t i = 0;
  541. i < sizeof(gdb_fast_lookup_sections)/sizeof(*gdb_fast_lookup_sections);
  542. ++i)
  543. if (strcmp(suffix, gdb_fast_lookup_sections[i]) == 0)
  544. return true;
  545. return false;
  546. }
  547. // Sometimes we compress sections. This is typically done for
  548. // sections that are not part of normal program execution (such as
  549. // .debug_* sections), and where the readers of these sections know
  550. // how to deal with compressed sections. This routine doesn't say for
  551. // certain whether we'll compress -- it depends on commandline options
  552. // as well -- just whether this section is a candidate for compression.
  553. // (The Output_compressed_section class decides whether to compress
  554. // a given section, and picks the name of the compressed section.)
  555. static bool
  556. is_compressible_debug_section(const char* secname)
  557. {
  558. return (is_prefix_of(".debug", secname));
  559. }
  560. // We may see compressed debug sections in input files. Return TRUE
  561. // if this is the name of a compressed debug section.
  562. bool
  563. is_compressed_debug_section(const char* secname)
  564. {
  565. return (is_prefix_of(".zdebug", secname));
  566. }
  567. std::string
  568. corresponding_uncompressed_section_name(std::string secname)
  569. {
  570. gold_assert(secname[0] == '.' && secname[1] == 'z');
  571. std::string ret(".");
  572. ret.append(secname, 2, std::string::npos);
  573. return ret;
  574. }
  575. // Whether to include this section in the link.
  576. template<int size, bool big_endian>
  577. bool
  578. Layout::include_section(Sized_relobj_file<size, big_endian>*, const char* name,
  579. const elfcpp::Shdr<size, big_endian>& shdr)
  580. {
  581. if (!parameters->options().relocatable()
  582. && (shdr.get_sh_flags() & elfcpp::SHF_EXCLUDE))
  583. return false;
  584. elfcpp::Elf_Word sh_type = shdr.get_sh_type();
  585. if ((sh_type >= elfcpp::SHT_LOOS && sh_type <= elfcpp::SHT_HIOS)
  586. || (sh_type >= elfcpp::SHT_LOPROC && sh_type <= elfcpp::SHT_HIPROC))
  587. return parameters->target().should_include_section(sh_type);
  588. switch (sh_type)
  589. {
  590. case elfcpp::SHT_NULL:
  591. case elfcpp::SHT_SYMTAB:
  592. case elfcpp::SHT_DYNSYM:
  593. case elfcpp::SHT_HASH:
  594. case elfcpp::SHT_DYNAMIC:
  595. case elfcpp::SHT_SYMTAB_SHNDX:
  596. return false;
  597. case elfcpp::SHT_STRTAB:
  598. // Discard the sections which have special meanings in the ELF
  599. // ABI. Keep others (e.g., .stabstr). We could also do this by
  600. // checking the sh_link fields of the appropriate sections.
  601. return (strcmp(name, ".dynstr") != 0
  602. && strcmp(name, ".strtab") != 0
  603. && strcmp(name, ".shstrtab") != 0);
  604. case elfcpp::SHT_RELA:
  605. case elfcpp::SHT_REL:
  606. case elfcpp::SHT_GROUP:
  607. // If we are emitting relocations these should be handled
  608. // elsewhere.
  609. gold_assert(!parameters->options().relocatable());
  610. return false;
  611. case elfcpp::SHT_PROGBITS:
  612. if (parameters->options().strip_debug()
  613. && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
  614. {
  615. if (is_debug_info_section(name))
  616. return false;
  617. }
  618. if (parameters->options().strip_debug_non_line()
  619. && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
  620. {
  621. // Debugging sections can only be recognized by name.
  622. if (is_prefix_of(".debug_", name)
  623. && !is_lines_only_debug_section(name + 7))
  624. return false;
  625. if (is_prefix_of(".zdebug_", name)
  626. && !is_lines_only_debug_section(name + 8))
  627. return false;
  628. }
  629. if (parameters->options().strip_debug_gdb()
  630. && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
  631. {
  632. // Debugging sections can only be recognized by name.
  633. if (is_prefix_of(".debug_", name)
  634. && !is_gdb_debug_section(name + 7))
  635. return false;
  636. if (is_prefix_of(".zdebug_", name)
  637. && !is_gdb_debug_section(name + 8))
  638. return false;
  639. }
  640. if (parameters->options().gdb_index()
  641. && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
  642. {
  643. // When building .gdb_index, we can strip .debug_pubnames,
  644. // .debug_pubtypes, and .debug_aranges sections.
  645. if (is_prefix_of(".debug_", name)
  646. && is_gdb_fast_lookup_section(name + 7))
  647. return false;
  648. if (is_prefix_of(".zdebug_", name)
  649. && is_gdb_fast_lookup_section(name + 8))
  650. return false;
  651. }
  652. if (parameters->options().strip_lto_sections()
  653. && !parameters->options().relocatable()
  654. && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
  655. {
  656. // Ignore LTO sections containing intermediate code.
  657. if (is_prefix_of(".gnu.lto_", name))
  658. return false;
  659. }
  660. // The GNU linker strips .gnu_debuglink sections, so we do too.
  661. // This is a feature used to keep debugging information in
  662. // separate files.
  663. if (strcmp(name, ".gnu_debuglink") == 0)
  664. return false;
  665. return true;
  666. default:
  667. return true;
  668. }
  669. }
  670. // Return an output section named NAME, or NULL if there is none.
  671. Output_section*
  672. Layout::find_output_section(const char* name) const
  673. {
  674. for (Section_list::const_iterator p = this->section_list_.begin();
  675. p != this->section_list_.end();
  676. ++p)
  677. if (strcmp((*p)->name(), name) == 0)
  678. return *p;
  679. return NULL;
  680. }
  681. // Return an output segment of type TYPE, with segment flags SET set
  682. // and segment flags CLEAR clear. Return NULL if there is none.
  683. Output_segment*
  684. Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
  685. elfcpp::Elf_Word clear) const
  686. {
  687. for (Segment_list::const_iterator p = this->segment_list_.begin();
  688. p != this->segment_list_.end();
  689. ++p)
  690. if (static_cast<elfcpp::PT>((*p)->type()) == type
  691. && ((*p)->flags() & set) == set
  692. && ((*p)->flags() & clear) == 0)
  693. return *p;
  694. return NULL;
  695. }
  696. // When we put a .ctors or .dtors section with more than one word into
  697. // a .init_array or .fini_array section, we need to reverse the words
  698. // in the .ctors/.dtors section. This is because .init_array executes
  699. // constructors front to back, where .ctors executes them back to
  700. // front, and vice-versa for .fini_array/.dtors. Although we do want
  701. // to remap .ctors/.dtors into .init_array/.fini_array because it can
  702. // be more efficient, we don't want to change the order in which
  703. // constructors/destructors are run. This set just keeps track of
  704. // these sections which need to be reversed. It is only changed by
  705. // Layout::layout. It should be a private member of Layout, but that
  706. // would require layout.h to #include object.h to get the definition
  707. // of Section_id.
  708. static Unordered_set<Section_id, Section_id_hash> ctors_sections_in_init_array;
  709. // Return whether OBJECT/SHNDX is a .ctors/.dtors section mapped to a
  710. // .init_array/.fini_array section.
  711. bool
  712. Layout::is_ctors_in_init_array(Relobj* relobj, unsigned int shndx) const
  713. {
  714. return (ctors_sections_in_init_array.find(Section_id(relobj, shndx))
  715. != ctors_sections_in_init_array.end());
  716. }
  717. // Return the output section to use for section NAME with type TYPE
  718. // and section flags FLAGS. NAME must be canonicalized in the string
  719. // pool, and NAME_KEY is the key. ORDER is where this should appear
  720. // in the output sections. IS_RELRO is true for a relro section.
  721. Output_section*
  722. Layout::get_output_section(const char* name, Stringpool::Key name_key,
  723. elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
  724. Output_section_order order, bool is_relro)
  725. {
  726. elfcpp::Elf_Word lookup_type = type;
  727. // For lookup purposes, treat INIT_ARRAY, FINI_ARRAY, and
  728. // PREINIT_ARRAY like PROGBITS. This ensures that we combine
  729. // .init_array, .fini_array, and .preinit_array sections by name
  730. // whatever their type in the input file. We do this because the
  731. // types are not always right in the input files.
  732. if (lookup_type == elfcpp::SHT_INIT_ARRAY
  733. || lookup_type == elfcpp::SHT_FINI_ARRAY
  734. || lookup_type == elfcpp::SHT_PREINIT_ARRAY)
  735. lookup_type = elfcpp::SHT_PROGBITS;
  736. elfcpp::Elf_Xword lookup_flags = flags;
  737. // Ignoring SHF_WRITE and SHF_EXECINSTR here means that we combine
  738. // read-write with read-only sections. Some other ELF linkers do
  739. // not do this. FIXME: Perhaps there should be an option
  740. // controlling this.
  741. lookup_flags &= ~(elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
  742. const Key key(name_key, std::make_pair(lookup_type, lookup_flags));
  743. const std::pair<Key, Output_section*> v(key, NULL);
  744. std::pair<Section_name_map::iterator, bool> ins(
  745. this->section_name_map_.insert(v));
  746. if (!ins.second)
  747. return ins.first->second;
  748. else
  749. {
  750. // This is the first time we've seen this name/type/flags
  751. // combination. For compatibility with the GNU linker, we
  752. // combine sections with contents and zero flags with sections
  753. // with non-zero flags. This is a workaround for cases where
  754. // assembler code forgets to set section flags. FIXME: Perhaps
  755. // there should be an option to control this.
  756. Output_section* os = NULL;
  757. if (lookup_type == elfcpp::SHT_PROGBITS)
  758. {
  759. if (flags == 0)
  760. {
  761. Output_section* same_name = this->find_output_section(name);
  762. if (same_name != NULL
  763. && (same_name->type() == elfcpp::SHT_PROGBITS
  764. || same_name->type() == elfcpp::SHT_INIT_ARRAY
  765. || same_name->type() == elfcpp::SHT_FINI_ARRAY
  766. || same_name->type() == elfcpp::SHT_PREINIT_ARRAY)
  767. && (same_name->flags() & elfcpp::SHF_TLS) == 0)
  768. os = same_name;
  769. }
  770. else if ((flags & elfcpp::SHF_TLS) == 0)
  771. {
  772. elfcpp::Elf_Xword zero_flags = 0;
  773. const Key zero_key(name_key, std::make_pair(lookup_type,
  774. zero_flags));
  775. Section_name_map::iterator p =
  776. this->section_name_map_.find(zero_key);
  777. if (p != this->section_name_map_.end())
  778. os = p->second;
  779. }
  780. }
  781. if (os == NULL)
  782. os = this->make_output_section(name, type, flags, order, is_relro);
  783. ins.first->second = os;
  784. return os;
  785. }
  786. }
  787. // Returns TRUE iff NAME (an input section from RELOBJ) will
  788. // be mapped to an output section that should be KEPT.
  789. bool
  790. Layout::keep_input_section(const Relobj* relobj, const char* name)
  791. {
  792. if (! this->script_options_->saw_sections_clause())
  793. return false;
  794. Script_sections* ss = this->script_options_->script_sections();
  795. const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
  796. Output_section** output_section_slot;
  797. Script_sections::Section_type script_section_type;
  798. bool keep;
  799. name = ss->output_section_name(file_name, name, &output_section_slot,
  800. &script_section_type, &keep, true);
  801. return name != NULL && keep;
  802. }
  803. // Clear the input section flags that should not be copied to the
  804. // output section.
  805. elfcpp::Elf_Xword
  806. Layout::get_output_section_flags(elfcpp::Elf_Xword input_section_flags)
  807. {
  808. // Some flags in the input section should not be automatically
  809. // copied to the output section.
  810. input_section_flags &= ~ (elfcpp::SHF_INFO_LINK
  811. | elfcpp::SHF_GROUP
  812. | elfcpp::SHF_COMPRESSED
  813. | elfcpp::SHF_MERGE
  814. | elfcpp::SHF_STRINGS);
  815. // We only clear the SHF_LINK_ORDER flag in for
  816. // a non-relocatable link.
  817. if (!parameters->options().relocatable())
  818. input_section_flags &= ~elfcpp::SHF_LINK_ORDER;
  819. return input_section_flags;
  820. }
  821. // Pick the output section to use for section NAME, in input file
  822. // RELOBJ, with type TYPE and flags FLAGS. RELOBJ may be NULL for a
  823. // linker created section. IS_INPUT_SECTION is true if we are
  824. // choosing an output section for an input section found in a input
  825. // file. ORDER is where this section should appear in the output
  826. // sections. IS_RELRO is true for a relro section. This will return
  827. // NULL if the input section should be discarded. MATCH_INPUT_SPEC
  828. // is true if the section name should be matched against input specs
  829. // in a linker script.
  830. Output_section*
  831. Layout::choose_output_section(const Relobj* relobj, const char* name,
  832. elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
  833. bool is_input_section, Output_section_order order,
  834. bool is_relro, bool is_reloc,
  835. bool match_input_spec)
  836. {
  837. // We should not see any input sections after we have attached
  838. // sections to segments.
  839. gold_assert(!is_input_section || !this->sections_are_attached_);
  840. flags = this->get_output_section_flags(flags);
  841. if (this->script_options_->saw_sections_clause() && !is_reloc)
  842. {
  843. // We are using a SECTIONS clause, so the output section is
  844. // chosen based only on the name.
  845. Script_sections* ss = this->script_options_->script_sections();
  846. const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
  847. Output_section** output_section_slot;
  848. Script_sections::Section_type script_section_type;
  849. const char* orig_name = name;
  850. bool keep;
  851. name = ss->output_section_name(file_name, name, &output_section_slot,
  852. &script_section_type, &keep,
  853. match_input_spec);
  854. if (name == NULL)
  855. {
  856. gold_debug(DEBUG_SCRIPT, _("Unable to create output section '%s' "
  857. "because it is not allowed by the "
  858. "SECTIONS clause of the linker script"),
  859. orig_name);
  860. // The SECTIONS clause says to discard this input section.
  861. return NULL;
  862. }
  863. // We can only handle script section types ST_NONE and ST_NOLOAD.
  864. switch (script_section_type)
  865. {
  866. case Script_sections::ST_NONE:
  867. break;
  868. case Script_sections::ST_NOLOAD:
  869. flags &= elfcpp::SHF_ALLOC;
  870. break;
  871. default:
  872. gold_unreachable();
  873. }
  874. // If this is an orphan section--one not mentioned in the linker
  875. // script--then OUTPUT_SECTION_SLOT will be NULL, and we do the
  876. // default processing below.
  877. if (output_section_slot != NULL)
  878. {
  879. if (*output_section_slot != NULL)
  880. {
  881. (*output_section_slot)->update_flags_for_input_section(flags);
  882. return *output_section_slot;
  883. }
  884. // We don't put sections found in the linker script into
  885. // SECTION_NAME_MAP_. That keeps us from getting confused
  886. // if an orphan section is mapped to a section with the same
  887. // name as one in the linker script.
  888. name = this->namepool_.add(name, false, NULL);
  889. Output_section* os = this->make_output_section(name, type, flags,
  890. order, is_relro);
  891. os->set_found_in_sections_clause();
  892. // Special handling for NOLOAD sections.
  893. if (script_section_type == Script_sections::ST_NOLOAD)
  894. {
  895. os->set_is_noload();
  896. // The constructor of Output_section sets addresses of non-ALLOC
  897. // sections to 0 by default. We don't want that for NOLOAD
  898. // sections even if they have no SHF_ALLOC flag.
  899. if ((os->flags() & elfcpp::SHF_ALLOC) == 0
  900. && os->is_address_valid())
  901. {
  902. gold_assert(os->address() == 0
  903. && !os->is_offset_valid()
  904. && !os->is_data_size_valid());
  905. os->reset_address_and_file_offset();
  906. }
  907. }
  908. *output_section_slot = os;
  909. return os;
  910. }
  911. }
  912. // FIXME: Handle SHF_OS_NONCONFORMING somewhere.
  913. size_t len = strlen(name);
  914. std::string uncompressed_name;
  915. // Compressed debug sections should be mapped to the corresponding
  916. // uncompressed section.
  917. if (is_compressed_debug_section(name))
  918. {
  919. uncompressed_name =
  920. corresponding_uncompressed_section_name(std::string(name, len));
  921. name = uncompressed_name.c_str();
  922. len = uncompressed_name.length();
  923. }
  924. // Turn NAME from the name of the input section into the name of the
  925. // output section.
  926. if (is_input_section
  927. && !this->script_options_->saw_sections_clause()
  928. && !parameters->options().relocatable())
  929. {
  930. const char *orig_name = name;
  931. name = parameters->target().output_section_name(relobj, name, &len);
  932. if (name == NULL)
  933. name = Layout::output_section_name(relobj, orig_name, &len);
  934. }
  935. Stringpool::Key name_key;
  936. name = this->namepool_.add_with_length(name, len, true, &name_key);
  937. // Find or make the output section. The output section is selected
  938. // based on the section name, type, and flags.
  939. return this->get_output_section(name, name_key, type, flags, order, is_relro);
  940. }
  941. // For incremental links, record the initial fixed layout of a section
  942. // from the base file, and return a pointer to the Output_section.
  943. template<int size, bool big_endian>
  944. Output_section*
  945. Layout::init_fixed_output_section(const char* name,
  946. elfcpp::Shdr<size, big_endian>& shdr)
  947. {
  948. unsigned int sh_type = shdr.get_sh_type();
  949. // We preserve the layout of PROGBITS, NOBITS, INIT_ARRAY, FINI_ARRAY,
  950. // PRE_INIT_ARRAY, and NOTE sections.
  951. // All others will be created from scratch and reallocated.
  952. if (!can_incremental_update(sh_type))
  953. return NULL;
  954. // If we're generating a .gdb_index section, we need to regenerate
  955. // it from scratch.
  956. if (parameters->options().gdb_index()
  957. && sh_type == elfcpp::SHT_PROGBITS
  958. && strcmp(name, ".gdb_index") == 0)
  959. return NULL;
  960. typename elfcpp::Elf_types<size>::Elf_Addr sh_addr = shdr.get_sh_addr();
  961. typename elfcpp::Elf_types<size>::Elf_Off sh_offset = shdr.get_sh_offset();
  962. typename elfcpp::Elf_types<size>::Elf_WXword sh_size = shdr.get_sh_size();
  963. typename elfcpp::Elf_types<size>::Elf_WXword sh_flags =
  964. this->get_output_section_flags(shdr.get_sh_flags());
  965. typename elfcpp::Elf_types<size>::Elf_WXword sh_addralign =
  966. shdr.get_sh_addralign();
  967. // Make the output section.
  968. Stringpool::Key name_key;
  969. name = this->namepool_.add(name, true, &name_key);
  970. Output_section* os = this->get_output_section(name, name_key, sh_type,
  971. sh_flags, ORDER_INVALID, false);
  972. os->set_fixed_layout(sh_addr, sh_offset, sh_size, sh_addralign);
  973. if (sh_type != elfcpp::SHT_NOBITS)
  974. this->free_list_.remove(sh_offset, sh_offset + sh_size);
  975. return os;
  976. }
  977. // Return the index by which an input section should be ordered. This
  978. // is used to sort some .text sections, for compatibility with GNU ld.
  979. int
  980. Layout::special_ordering_of_input_section(const char* name)
  981. {
  982. // The GNU linker has some special handling for some sections that
  983. // wind up in the .text section. Sections that start with these
  984. // prefixes must appear first, and must appear in the order listed
  985. // here.
  986. static const char* const text_section_sort[] =
  987. {
  988. ".text.unlikely",
  989. ".text.exit",
  990. ".text.startup",
  991. ".text.hot",
  992. ".text.sorted"
  993. };
  994. for (size_t i = 0;
  995. i < sizeof(text_section_sort) / sizeof(text_section_sort[0]);
  996. i++)
  997. if (is_prefix_of(text_section_sort[i], name))
  998. return i;
  999. return -1;
  1000. }
  1001. // Return the output section to use for input section SHNDX, with name
  1002. // NAME, with header HEADER, from object OBJECT. RELOC_SHNDX is the
  1003. // index of a relocation section which applies to this section, or 0
  1004. // if none, or -1U if more than one. RELOC_TYPE is the type of the
  1005. // relocation section if there is one. Set *OFF to the offset of this
  1006. // input section without the output section. Return NULL if the
  1007. // section should be discarded. Set *OFF to -1 if the section
  1008. // contents should not be written directly to the output file, but
  1009. // will instead receive special handling.
  1010. template<int size, bool big_endian>
  1011. Output_section*
  1012. Layout::layout(Sized_relobj_file<size, big_endian>* object, unsigned int shndx,
  1013. const char* name, const elfcpp::Shdr<size, big_endian>& shdr,
  1014. unsigned int sh_type, unsigned int reloc_shndx,
  1015. unsigned int, off_t* off)
  1016. {
  1017. *off = 0;
  1018. if (!this->include_section(object, name, shdr))
  1019. return NULL;
  1020. // In a relocatable link a grouped section must not be combined with
  1021. // any other sections.
  1022. Output_section* os;
  1023. if (parameters->options().relocatable()
  1024. && (shdr.get_sh_flags() & elfcpp::SHF_GROUP) != 0)
  1025. {
  1026. // Some flags in the input section should not be automatically
  1027. // copied to the output section.
  1028. elfcpp::Elf_Xword sh_flags = (shdr.get_sh_flags()
  1029. & ~ elfcpp::SHF_COMPRESSED);
  1030. name = this->namepool_.add(name, true, NULL);
  1031. os = this->make_output_section(name, sh_type, sh_flags, ORDER_INVALID,
  1032. false);
  1033. }
  1034. else
  1035. {
  1036. // Get the section flags and mask out any flags that do not
  1037. // take part in section matching.
  1038. elfcpp::Elf_Xword sh_flags
  1039. = (this->get_output_section_flags(shdr.get_sh_flags())
  1040. & ~object->osabi().ignored_sh_flags());
  1041. // All ".text.unlikely.*" sections can be moved to a unique
  1042. // segment with --text-unlikely-segment option.
  1043. bool text_unlikely_segment
  1044. = (parameters->options().text_unlikely_segment()
  1045. && is_prefix_of(".text.unlikely",
  1046. object->section_name(shndx).c_str()));
  1047. if (text_unlikely_segment)
  1048. {
  1049. Stringpool::Key name_key;
  1050. const char* os_name = this->namepool_.add(".text.unlikely", true,
  1051. &name_key);
  1052. os = this->get_output_section(os_name, name_key, sh_type, sh_flags,
  1053. ORDER_INVALID, false);
  1054. // Map this output section to a unique segment. This is done to
  1055. // separate "text" that is not likely to be executed from "text"
  1056. // that is likely executed.
  1057. os->set_is_unique_segment();
  1058. }
  1059. else
  1060. {
  1061. // Plugins can choose to place one or more subsets of sections in
  1062. // unique segments and this is done by mapping these section subsets
  1063. // to unique output sections. Check if this section needs to be
  1064. // remapped to a unique output section.
  1065. Section_segment_map::iterator it
  1066. = this->section_segment_map_.find(Const_section_id(object, shndx));
  1067. if (it == this->section_segment_map_.end())
  1068. {
  1069. os = this->choose_output_section(object, name, sh_type,
  1070. sh_flags, true, ORDER_INVALID,
  1071. false, false, true);
  1072. }
  1073. else
  1074. {
  1075. // We know the name of the output section, directly call
  1076. // get_output_section here by-passing choose_output_section.
  1077. const char* os_name = it->second->name;
  1078. Stringpool::Key name_key;
  1079. os_name = this->namepool_.add(os_name, true, &name_key);
  1080. os = this->get_output_section(os_name, name_key, sh_type,
  1081. sh_flags, ORDER_INVALID, false);
  1082. if (!os->is_unique_segment())
  1083. {
  1084. os->set_is_unique_segment();
  1085. os->set_extra_segment_flags(it->second->flags);
  1086. os->set_segment_alignment(it->second->align);
  1087. }
  1088. }
  1089. }
  1090. if (os == NULL)
  1091. return NULL;
  1092. }
  1093. // By default the GNU linker sorts input sections whose names match
  1094. // .ctors.*, .dtors.*, .init_array.*, or .fini_array.*. The
  1095. // sections are sorted by name. This is used to implement
  1096. // constructor priority ordering. We are compatible. When we put
  1097. // .ctor sections in .init_array and .dtor sections in .fini_array,
  1098. // we must also sort plain .ctor and .dtor sections.
  1099. if (!this->script_options_->saw_sections_clause()
  1100. && !parameters->options().relocatable()
  1101. && (is_prefix_of(".ctors.", name)
  1102. || is_prefix_of(".dtors.", name)
  1103. || is_prefix_of(".init_array.", name)
  1104. || is_prefix_of(".fini_array.", name)
  1105. || (parameters->options().ctors_in_init_array()
  1106. && (strcmp(name, ".ctors") == 0
  1107. || strcmp(name, ".dtors") == 0))))
  1108. os->set_must_sort_attached_input_sections();
  1109. // By default the GNU linker sorts some special text sections ahead
  1110. // of others. We are compatible.
  1111. if (parameters->options().text_reorder()
  1112. && !this->script_options_->saw_sections_clause()
  1113. && !this->is_section_ordering_specified()
  1114. && !parameters->options().relocatable()
  1115. && Layout::special_ordering_of_input_section(name) >= 0)
  1116. os->set_must_sort_attached_input_sections();
  1117. // If this is a .ctors or .ctors.* section being mapped to a
  1118. // .init_array section, or a .dtors or .dtors.* section being mapped
  1119. // to a .fini_array section, we will need to reverse the words if
  1120. // there is more than one. Record this section for later. See
  1121. // ctors_sections_in_init_array above.
  1122. if (!this->script_options_->saw_sections_clause()
  1123. && !parameters->options().relocatable()
  1124. && shdr.get_sh_size() > size / 8
  1125. && (((strcmp(name, ".ctors") == 0
  1126. || is_prefix_of(".ctors.", name))
  1127. && strcmp(os->name(), ".init_array") == 0)
  1128. || ((strcmp(name, ".dtors") == 0
  1129. || is_prefix_of(".dtors.", name))
  1130. && strcmp(os->name(), ".fini_array") == 0)))
  1131. ctors_sections_in_init_array.insert(Section_id(object, shndx));
  1132. // FIXME: Handle SHF_LINK_ORDER somewhere.
  1133. elfcpp::Elf_Xword orig_flags = os->flags();
  1134. *off = os->add_input_section(this, object, shndx, name, shdr, reloc_shndx,
  1135. this->script_options_->saw_sections_clause());
  1136. // If the flags changed, we may have to change the order.
  1137. if ((orig_flags & elfcpp::SHF_ALLOC) != 0)
  1138. {
  1139. orig_flags &= (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
  1140. elfcpp::Elf_Xword new_flags =
  1141. os->flags() & (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
  1142. if (orig_flags != new_flags)
  1143. os->set_order(this->default_section_order(os, false));
  1144. }
  1145. this->have_added_input_section_ = true;
  1146. return os;
  1147. }
  1148. // Maps section SECN to SEGMENT s.
  1149. void
  1150. Layout::insert_section_segment_map(Const_section_id secn,
  1151. Unique_segment_info *s)
  1152. {
  1153. gold_assert(this->unique_segment_for_sections_specified_);
  1154. this->section_segment_map_[secn] = s;
  1155. }
  1156. // Handle a relocation section when doing a relocatable link.
  1157. template<int size, bool big_endian>
  1158. Output_section*
  1159. Layout::layout_reloc(Sized_relobj_file<size, big_endian>*,
  1160. unsigned int,
  1161. const elfcpp::Shdr<size, big_endian>& shdr,
  1162. Output_section* data_section,
  1163. Relocatable_relocs* rr)
  1164. {
  1165. gold_assert(parameters->options().relocatable()
  1166. || parameters->options().emit_relocs());
  1167. int sh_type = shdr.get_sh_type();
  1168. std::string name;
  1169. if (sh_type == elfcpp::SHT_REL)
  1170. name = ".rel";
  1171. else if (sh_type == elfcpp::SHT_RELA)
  1172. name = ".rela";
  1173. else
  1174. gold_unreachable();
  1175. name += data_section->name();
  1176. // If the output data section already has a reloc section, use that;
  1177. // otherwise, make a new one.
  1178. Output_section* os = data_section->reloc_section();
  1179. if (os == NULL)
  1180. {
  1181. const char* n = this->namepool_.add(name.c_str(), true, NULL);
  1182. os = this->make_output_section(n, sh_type, shdr.get_sh_flags(),
  1183. ORDER_INVALID, false);
  1184. os->set_should_link_to_symtab();
  1185. os->set_info_section(data_section);
  1186. data_section->set_reloc_section(os);
  1187. }
  1188. Output_section_data* posd;
  1189. if (sh_type == elfcpp::SHT_REL)
  1190. {
  1191. os->set_entsize(elfcpp::Elf_sizes<size>::rel_size);
  1192. posd = new Output_relocatable_relocs<elfcpp::SHT_REL,
  1193. size,
  1194. big_endian>(rr);
  1195. }
  1196. else if (sh_type == elfcpp::SHT_RELA)
  1197. {
  1198. os->set_entsize(elfcpp::Elf_sizes<size>::rela_size);
  1199. posd = new Output_relocatable_relocs<elfcpp::SHT_RELA,
  1200. size,
  1201. big_endian>(rr);
  1202. }
  1203. else
  1204. gold_unreachable();
  1205. os->add_output_section_data(posd);
  1206. rr->set_output_data(posd);
  1207. return os;
  1208. }
  1209. // Handle a group section when doing a relocatable link.
  1210. template<int size, bool big_endian>
  1211. void
  1212. Layout::layout_group(Symbol_table* symtab,
  1213. Sized_relobj_file<size, big_endian>* object,
  1214. unsigned int,
  1215. const char* group_section_name,
  1216. const char* signature,
  1217. const elfcpp::Shdr<size, big_endian>& shdr,
  1218. elfcpp::Elf_Word flags,
  1219. std::vector<unsigned int>* shndxes)
  1220. {
  1221. gold_assert(parameters->options().relocatable());
  1222. gold_assert(shdr.get_sh_type() == elfcpp::SHT_GROUP);
  1223. group_section_name = this->namepool_.add(group_section_name, true, NULL);
  1224. Output_section* os = this->make_output_section(group_section_name,
  1225. elfcpp::SHT_GROUP,
  1226. shdr.get_sh_flags(),
  1227. ORDER_INVALID, false);
  1228. // We need to find a symbol with the signature in the symbol table.
  1229. // If we don't find one now, we need to look again later.
  1230. Symbol* sym = symtab->lookup(signature, NULL);
  1231. if (sym != NULL)
  1232. os->set_info_symndx(sym);
  1233. else
  1234. {
  1235. // Reserve some space to minimize reallocations.
  1236. if (this->group_signatures_.empty())
  1237. this->group_signatures_.reserve(this->number_of_input_files_ * 16);
  1238. // We will wind up using a symbol whose name is the signature.
  1239. // So just put the signature in the symbol name pool to save it.
  1240. signature = symtab->canonicalize_name(signature);
  1241. this->group_signatures_.push_back(Group_signature(os, signature));
  1242. }
  1243. os->set_should_link_to_symtab();
  1244. os->set_entsize(4);
  1245. section_size_type entry_count =
  1246. convert_to_section_size_type(shdr.get_sh_size() / 4);
  1247. Output_section_data* posd =
  1248. new Output_data_group<size, big_endian>(object, entry_count, flags,
  1249. shndxes);
  1250. os->add_output_section_data(posd);
  1251. }
  1252. // Special GNU handling of sections name .eh_frame. They will
  1253. // normally hold exception frame data as defined by the C++ ABI
  1254. // (http://codesourcery.com/cxx-abi/).
  1255. template<int size, bool big_endian>
  1256. Output_section*
  1257. Layout::layout_eh_frame(Sized_relobj_file<size, big_endian>* object,
  1258. const unsigned char* symbols,
  1259. off_t symbols_size,
  1260. const unsigned char* symbol_names,
  1261. off_t symbol_names_size,
  1262. unsigned int shndx,
  1263. const elfcpp::Shdr<size, big_endian>& shdr,
  1264. unsigned int reloc_shndx, unsigned int reloc_type,
  1265. off_t* off)
  1266. {
  1267. const unsigned int unwind_section_type =
  1268. parameters->target().unwind_section_type();
  1269. gold_assert(shdr.get_sh_type() == elfcpp::SHT_PROGBITS
  1270. || shdr.get_sh_type() == unwind_section_type);
  1271. gold_assert((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0);
  1272. Output_section* os = this->make_eh_frame_section(object);
  1273. if (os == NULL)
  1274. return NULL;
  1275. gold_assert(this->eh_frame_section_ == os);
  1276. elfcpp::Elf_Xword orig_flags = os->flags();
  1277. Eh_frame::Eh_frame_section_disposition disp =
  1278. Eh_frame::EH_UNRECOGNIZED_SECTION;
  1279. if (!parameters->incremental())
  1280. {
  1281. disp = this->eh_frame_data_->add_ehframe_input_section(object,
  1282. symbols,
  1283. symbols_size,
  1284. symbol_names,
  1285. symbol_names_size,
  1286. shndx,
  1287. reloc_shndx,
  1288. reloc_type);
  1289. }
  1290. if (disp == Eh_frame::EH_OPTIMIZABLE_SECTION)
  1291. {
  1292. os->update_flags_for_input_section(shdr.get_sh_flags());
  1293. // A writable .eh_frame section is a RELRO section.
  1294. if ((orig_flags & (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR))
  1295. != (os->flags() & (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR)))
  1296. {
  1297. os->set_is_relro();
  1298. os->set_order(ORDER_RELRO);
  1299. }
  1300. *off = -1;
  1301. return os;
  1302. }
  1303. if (disp == Eh_frame::EH_END_MARKER_SECTION && !this->added_eh_frame_data_)
  1304. {
  1305. // We found the end marker section, so now we can add the set of
  1306. // optimized sections to the output section. We need to postpone
  1307. // adding this until we've found a section we can optimize so that
  1308. // the .eh_frame section in crtbeginT.o winds up at the start of
  1309. // the output section.
  1310. os->add_output_section_data(this->eh_frame_data_);
  1311. this->added_eh_frame_data_ = true;
  1312. }
  1313. // We couldn't handle this .eh_frame section for some reason.
  1314. // Add it as a normal section.
  1315. bool saw_sections_clause = this->script_options_->saw_sections_clause();
  1316. *off = os->add_input_section(this, object, shndx, ".eh_frame", shdr,
  1317. reloc_shndx, saw_sections_clause);
  1318. this->have_added_input_section_ = true;
  1319. if ((orig_flags & (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR))
  1320. != (os->flags() & (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR)))
  1321. os->set_order(this->default_section_order(os, false));
  1322. return os;
  1323. }
  1324. void
  1325. Layout::finalize_eh_frame_section()
  1326. {
  1327. // If we never found an end marker section, we need to add the
  1328. // optimized eh sections to the output section now.
  1329. if (!parameters->incremental()
  1330. && this->eh_frame_section_ != NULL
  1331. && !this->added_eh_frame_data_)
  1332. {
  1333. this->eh_frame_section_->add_output_section_data(this->eh_frame_data_);
  1334. this->added_eh_frame_data_ = true;
  1335. }
  1336. }
  1337. // Create and return the magic .eh_frame section. Create
  1338. // .eh_frame_hdr also if appropriate. OBJECT is the object with the
  1339. // input .eh_frame section; it may be NULL.
  1340. Output_section*
  1341. Layout::make_eh_frame_section(const Relobj* object)
  1342. {
  1343. const unsigned int unwind_section_type =
  1344. parameters->target().unwind_section_type();
  1345. Output_section* os = this->choose_output_section(object, ".eh_frame",
  1346. unwind_section_type,
  1347. elfcpp::SHF_ALLOC, false,
  1348. ORDER_EHFRAME, false, false,
  1349. false);
  1350. if (os == NULL)
  1351. return NULL;
  1352. if (this->eh_frame_section_ == NULL)
  1353. {
  1354. this->eh_frame_section_ = os;
  1355. this->eh_frame_data_ = new Eh_frame();
  1356. // For incremental linking, we do not optimize .eh_frame sections
  1357. // or create a .eh_frame_hdr section.
  1358. if (parameters->options().eh_frame_hdr() && !parameters->incremental())
  1359. {
  1360. Output_section* hdr_os =
  1361. this->choose_output_section(NULL, ".eh_frame_hdr",
  1362. unwind_section_type,
  1363. elfcpp::SHF_ALLOC, false,
  1364. ORDER_EHFRAME, false, false,
  1365. false);
  1366. if (hdr_os != NULL)
  1367. {
  1368. Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os,
  1369. this->eh_frame_data_);
  1370. hdr_os->add_output_section_data(hdr_posd);
  1371. hdr_os->set_after_input_sections();
  1372. if (!this->script_options_->saw_phdrs_clause())
  1373. {
  1374. Output_segment* hdr_oseg;
  1375. hdr_oseg = this->make_output_segment(elfcpp::PT_GNU_EH_FRAME,
  1376. elfcpp::PF_R);
  1377. hdr_oseg->add_output_section_to_nonload(hdr_os,
  1378. elfcpp::PF_R);
  1379. }
  1380. this->eh_frame_data_->set_eh_frame_hdr(hdr_posd);
  1381. }
  1382. }
  1383. }
  1384. return os;
  1385. }
  1386. // Add an exception frame for a PLT. This is called from target code.
  1387. void
  1388. Layout::add_eh_frame_for_plt(Output_data* plt, const unsigned char* cie_data,
  1389. size_t cie_length, const unsigned char* fde_data,
  1390. size_t fde_length)
  1391. {
  1392. if (parameters->incremental())
  1393. {
  1394. // FIXME: Maybe this could work some day....
  1395. return;
  1396. }
  1397. Output_section* os = this->make_eh_frame_section(NULL);
  1398. if (os == NULL)
  1399. return;
  1400. this->eh_frame_data_->add_ehframe_for_plt(plt, cie_data, cie_length,
  1401. fde_data, fde_length);
  1402. if (!this->added_eh_frame_data_)
  1403. {
  1404. os->add_output_section_data(this->eh_frame_data_);
  1405. this->added_eh_frame_data_ = true;
  1406. }
  1407. }
  1408. // Remove all post-map .eh_frame information for a PLT.
  1409. void
  1410. Layout::remove_eh_frame_for_plt(Output_data* plt, const unsigned char* cie_data,
  1411. size_t cie_length)
  1412. {
  1413. if (parameters->incremental())
  1414. {
  1415. // FIXME: Maybe this could work some day....
  1416. return;
  1417. }
  1418. this->eh_frame_data_->remove_ehframe_for_plt(plt, cie_data, cie_length);
  1419. }
  1420. // Scan a .debug_info or .debug_types section, and add summary
  1421. // information to the .gdb_index section.
  1422. template<int size, bool big_endian>
  1423. void
  1424. Layout::add_to_gdb_index(bool is_type_unit,
  1425. Sized_relobj<size, big_endian>* object,
  1426. const unsigned char* symbols,
  1427. off_t symbols_size,
  1428. unsigned int shndx,
  1429. unsigned int reloc_shndx,
  1430. unsigned int reloc_type)
  1431. {
  1432. if (this->gdb_index_data_ == NULL)
  1433. {
  1434. Output_section* os = this->choose_output_section(NULL, ".gdb_index",
  1435. elfcpp::SHT_PROGBITS, 0,
  1436. false, ORDER_INVALID,
  1437. false, false, false);
  1438. if (os == NULL)
  1439. return;
  1440. this->gdb_index_data_ = new Gdb_index(os);
  1441. os->add_output_section_data(this->gdb_index_data_);
  1442. os->set_after_input_sections();
  1443. }
  1444. this->gdb_index_data_->scan_debug_info(is_type_unit, object, symbols,
  1445. symbols_size, shndx, reloc_shndx,
  1446. reloc_type);
  1447. }
  1448. // Add POSD to an output section using NAME, TYPE, and FLAGS. Return
  1449. // the output section.
  1450. Output_section*
  1451. Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
  1452. elfcpp::Elf_Xword flags,
  1453. Output_section_data* posd,
  1454. Output_section_order order, bool is_relro)
  1455. {
  1456. Output_section* os = this->choose_output_section(NULL, name, type, flags,
  1457. false, order, is_relro,
  1458. false, false);
  1459. if (os != NULL)
  1460. os->add_output_section_data(posd);
  1461. return os;
  1462. }
  1463. // Map section flags to segment flags.
  1464. elfcpp::Elf_Word
  1465. Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
  1466. {
  1467. elfcpp::Elf_Word ret = elfcpp::PF_R;
  1468. if ((flags & elfcpp::SHF_WRITE) != 0)
  1469. ret |= elfcpp::PF_W;
  1470. if ((flags & elfcpp::SHF_EXECINSTR) != 0)
  1471. ret |= elfcpp::PF_X;
  1472. return ret;
  1473. }
  1474. // Make a new Output_section, and attach it to segments as
  1475. // appropriate. ORDER is the order in which this section should
  1476. // appear in the output segment. IS_RELRO is true if this is a relro
  1477. // (read-only after relocations) section.
  1478. Output_section*
  1479. Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
  1480. elfcpp::Elf_Xword flags,
  1481. Output_section_order order, bool is_relro)
  1482. {
  1483. Output_section* os;
  1484. if ((flags & elfcpp::SHF_ALLOC) == 0
  1485. && strcmp(parameters->options().compress_debug_sections(), "none") != 0
  1486. && is_compressible_debug_section(name))
  1487. os = new Output_compressed_section(&parameters->options(), name, type,
  1488. flags);
  1489. else if ((flags & elfcpp::SHF_ALLOC) == 0
  1490. && parameters->options().strip_debug_non_line()
  1491. && strcmp(".debug_abbrev", name) == 0)
  1492. {
  1493. os = this->debug_abbrev_ = new Output_reduced_debug_abbrev_section(
  1494. name, type, flags);
  1495. if (this->debug_info_)
  1496. this->debug_info_->set_abbreviations(this->debug_abbrev_);
  1497. }
  1498. else if ((flags & elfcpp::SHF_ALLOC) == 0
  1499. && parameters->options().strip_debug_non_line()
  1500. && strcmp(".debug_info", name) == 0)
  1501. {
  1502. os = this->debug_info_ = new Output_reduced_debug_info_section(
  1503. name, type, flags);
  1504. if (this->debug_abbrev_)
  1505. this->debug_info_->set_abbreviations(this->debug_abbrev_);
  1506. }
  1507. else
  1508. {
  1509. // Sometimes .init_array*, .preinit_array* and .fini_array* do
  1510. // not have correct section types. Force them here.
  1511. if (type == elfcpp::SHT_PROGBITS)
  1512. {
  1513. if (is_prefix_of(".init_array", name))
  1514. type = elfcpp::SHT_INIT_ARRAY;
  1515. else if (is_prefix_of(".preinit_array", name))
  1516. type = elfcpp::SHT_PREINIT_ARRAY;
  1517. else if (is_prefix_of(".fini_array", name))
  1518. type = elfcpp::SHT_FINI_ARRAY;
  1519. }
  1520. // FIXME: const_cast is ugly.
  1521. Target* target = const_cast<Target*>(&parameters->target());
  1522. os = target->make_output_section(name, type, flags);
  1523. }
  1524. // With -z relro, we have to recognize the special sections by name.
  1525. // There is no other way.
  1526. bool is_relro_local = false;
  1527. if (!this->script_options_->saw_sections_clause()
  1528. && parameters->options().relro()
  1529. && (flags & elfcpp::SHF_ALLOC) != 0
  1530. && (flags & elfcpp::SHF_WRITE) != 0)
  1531. {
  1532. if (type == elfcpp::SHT_PROGBITS)
  1533. {
  1534. if ((flags & elfcpp::SHF_TLS) != 0)
  1535. is_relro = true;
  1536. else if (strcmp(name, ".data.rel.ro") == 0)
  1537. is_relro = true;
  1538. else if (strcmp(name, ".data.rel.ro.local") == 0)
  1539. {
  1540. is_relro = true;
  1541. is_relro_local = true;
  1542. }
  1543. else if (strcmp(name, ".ctors") == 0
  1544. || strcmp(name, ".dtors") == 0
  1545. || strcmp(name, ".jcr") == 0)
  1546. is_relro = true;
  1547. }
  1548. else if (type == elfcpp::SHT_INIT_ARRAY
  1549. || type == elfcpp::SHT_FINI_ARRAY
  1550. || type == elfcpp::SHT_PREINIT_ARRAY)
  1551. is_relro = true;
  1552. }
  1553. if (is_relro)
  1554. os->set_is_relro();
  1555. if (order == ORDER_INVALID && (flags & elfcpp::SHF_ALLOC) != 0)
  1556. order = this->default_section_order(os, is_relro_local);
  1557. os->set_order(order);
  1558. parameters->target().new_output_section(os);
  1559. this->section_list_.push_back(os);
  1560. // The GNU linker by default sorts some sections by priority, so we
  1561. // do the same. We need to know that this might happen before we
  1562. // attach any input sections.
  1563. if (!this->script_options_->saw_sections_clause()
  1564. && !parameters->options().relocatable()
  1565. && (strcmp(name, ".init_array") == 0
  1566. || strcmp(name, ".fini_array") == 0
  1567. || (!parameters->options().ctors_in_init_array()
  1568. && (strcmp(name, ".ctors") == 0
  1569. || strcmp(name, ".dtors") == 0))))
  1570. os->set_may_sort_attached_input_sections();
  1571. // The GNU linker by default sorts .text.{unlikely,exit,startup,hot}
  1572. // sections before other .text sections. We are compatible. We
  1573. // need to know that this might happen before we attach any input
  1574. // sections.
  1575. if (parameters->options().text_reorder()
  1576. && !this->script_options_->saw_sections_clause()
  1577. && !this->is_section_ordering_specified()
  1578. && !parameters->options().relocatable()
  1579. && strcmp(name, ".text") == 0)
  1580. os->set_may_sort_attached_input_sections();
  1581. // GNU linker sorts section by name with --sort-section=name.
  1582. if (strcmp(parameters->options().sort_section(), "name") == 0)
  1583. os->set_must_sort_attached_input_sections();
  1584. // Check for .stab*str sections, as .stab* sections need to link to
  1585. // them.
  1586. if (type == elfcpp::SHT_STRTAB
  1587. && !this->have_stabstr_section_
  1588. && strncmp(name, ".stab", 5) == 0
  1589. && strcmp(name + strlen(name) - 3, "str") == 0)
  1590. this->have_stabstr_section_ = true;
  1591. // During a full incremental link, we add patch space to most
  1592. // PROGBITS and NOBITS sections. Flag those that may be
  1593. // arbitrarily padded.
  1594. if ((type == elfcpp::SHT_PROGBITS || type == elfcpp::SHT_NOBITS)
  1595. && order != ORDER_INTERP
  1596. && order != ORDER_INIT
  1597. && order != ORDER_PLT
  1598. && order != ORDER_FINI
  1599. && order != ORDER_RELRO_LAST
  1600. && order != ORDER_NON_RELRO_FIRST
  1601. && strcmp(name, ".eh_frame") != 0
  1602. && strcmp(name, ".ctors") != 0
  1603. && strcmp(name, ".dtors") != 0
  1604. && strcmp(name, ".jcr") != 0)
  1605. {
  1606. os->set_is_patch_space_allowed();
  1607. // Certain sections require "holes" to be filled with
  1608. // specific fill patterns. These fill patterns may have
  1609. // a minimum size, so we must prevent allocations from the
  1610. // free list that leave a hole smaller than the minimum.
  1611. if (strcmp(name, ".debug_info") == 0)
  1612. os->set_free_space_fill(new Output_fill_debug_info(false));
  1613. else if (strcmp(name, ".debug_types") == 0)
  1614. os->set_free_space_fill(new Output_fill_debug_info(true));
  1615. else if (strcmp(name, ".debug_line") == 0)
  1616. os->set_free_space_fill(new Output_fill_debug_line());
  1617. }
  1618. // If we have already attached the sections to segments, then we
  1619. // need to attach this one now. This happens for sections created
  1620. // directly by the linker.
  1621. if (this->sections_are_attached_)
  1622. this->attach_section_to_segment(&parameters->target(), os);
  1623. return os;
  1624. }
  1625. // Return the default order in which a section should be placed in an
  1626. // output segment. This function captures a lot of the ideas in
  1627. // ld/scripttempl/elf.sc in the GNU linker. Note that the order of a
  1628. // linker created section is normally set when the section is created;
  1629. // this function is used for input sections.
  1630. Output_section_order
  1631. Layout::default_section_order(Output_section* os, bool is_relro_local)
  1632. {
  1633. gold_assert((os->flags() & elfcpp::SHF_ALLOC) != 0);
  1634. bool is_write = (os->flags() & elfcpp::SHF_WRITE) != 0;
  1635. bool is_execinstr = (os->flags() & elfcpp::SHF_EXECINSTR) != 0;
  1636. bool is_bss = false;
  1637. switch (os->type())
  1638. {
  1639. default:
  1640. case elfcpp::SHT_PROGBITS:
  1641. break;
  1642. case elfcpp::SHT_NOBITS:
  1643. is_bss = true;
  1644. break;
  1645. case elfcpp::SHT_RELA:
  1646. case elfcpp::SHT_REL:
  1647. if (!is_write)
  1648. return ORDER_DYNAMIC_RELOCS;
  1649. break;
  1650. case elfcpp::SHT_HASH:
  1651. case elfcpp::SHT_DYNAMIC:
  1652. case elfcpp::SHT_SHLIB:
  1653. case elfcpp::SHT_DYNSYM:
  1654. case elfcpp::SHT_GNU_HASH:
  1655. case elfcpp::SHT_GNU_verdef:
  1656. case elfcpp::SHT_GNU_verneed:
  1657. case elfcpp::SHT_GNU_versym:
  1658. if (!is_write)
  1659. return ORDER_DYNAMIC_LINKER;
  1660. break;
  1661. case elfcpp::SHT_NOTE:
  1662. return is_write ? ORDER_RW_NOTE : ORDER_RO_NOTE;
  1663. }
  1664. if ((os->flags() & elfcpp::SHF_TLS) != 0)
  1665. return is_bss ? ORDER_TLS_BSS : ORDER_TLS_DATA;
  1666. if (!is_bss && !is_write)
  1667. {
  1668. if (is_execinstr)
  1669. {
  1670. if (strcmp(os->name(), ".init") == 0)
  1671. return ORDER_INIT;
  1672. else if (strcmp(os->name(), ".fini") == 0)
  1673. return ORDER_FINI;
  1674. else if (parameters->options().keep_text_section_prefix())
  1675. {
  1676. // -z,keep-text-section-prefix introduces additional
  1677. // output sections.
  1678. if (strcmp(os->name(), ".text.hot") == 0)
  1679. return ORDER_TEXT_HOT;
  1680. else if (strcmp(os->name(), ".text.startup") == 0)
  1681. return ORDER_TEXT_STARTUP;
  1682. else if (strcmp(os->name(), ".text.exit") == 0)
  1683. return ORDER_TEXT_EXIT;
  1684. else if (strcmp(os->name(), ".text.unlikely") == 0)
  1685. return ORDER_TEXT_UNLIKELY;
  1686. }
  1687. }
  1688. return is_execinstr ? ORDER_TEXT : ORDER_READONLY;
  1689. }
  1690. if (os->is_relro())
  1691. return is_relro_local ? ORDER_RELRO_LOCAL : ORDER_RELRO;
  1692. if (os->is_small_section())
  1693. return is_bss ? ORDER_SMALL_BSS : ORDER_SMALL_DATA;
  1694. if (os->is_large_section())
  1695. return is_bss ? ORDER_LARGE_BSS : ORDER_LARGE_DATA;
  1696. return is_bss ? ORDER_BSS : ORDER_DATA;
  1697. }
  1698. // Attach output sections to segments. This is called after we have
  1699. // seen all the input sections.
  1700. void
  1701. Layout::attach_sections_to_segments(const Target* target)
  1702. {
  1703. for (Section_list::iterator p = this->section_list_.begin();
  1704. p != this->section_list_.end();
  1705. ++p)
  1706. this->attach_section_to_segment(target, *p);
  1707. this->sections_are_attached_ = true;
  1708. }
  1709. // Attach an output section to a segment.
  1710. void
  1711. Layout::attach_section_to_segment(const Target* target, Output_section* os)
  1712. {
  1713. if ((os->flags() & elfcpp::SHF_ALLOC) == 0)
  1714. this->unattached_section_list_.push_back(os);
  1715. else
  1716. this->attach_allocated_section_to_segment(target, os);
  1717. }
  1718. // Attach an allocated output section to a segment.
  1719. void
  1720. Layout::attach_allocated_section_to_segment(const Target* target,
  1721. Output_section* os)
  1722. {
  1723. elfcpp::Elf_Xword flags = os->flags();
  1724. gold_assert((flags & elfcpp::SHF_ALLOC) != 0);
  1725. if (parameters->options().relocatable())
  1726. return;
  1727. // If we have a SECTIONS clause, we can't handle the attachment to
  1728. // segments until after we've seen all the sections.
  1729. if (this->script_options_->saw_sections_clause())
  1730. return;
  1731. gold_assert(!this->script_options_->saw_phdrs_clause());
  1732. // This output section goes into a PT_LOAD segment.
  1733. elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
  1734. // If this output section's segment has extra flags that need to be set,
  1735. // coming from a linker plugin, do that.
  1736. seg_flags |= os->extra_segment_flags();
  1737. // Check for --section-start.
  1738. uint64_t addr;
  1739. bool is_address_set = parameters->options().section_start(os->name(), &addr);
  1740. // In general the only thing we really care about for PT_LOAD
  1741. // segments is whether or not they are writable or executable,
  1742. // so that is how we search for them.
  1743. // Large data sections also go into their own PT_LOAD segment.
  1744. // People who need segments sorted on some other basis will
  1745. // have to use a linker script.
  1746. Segment_list::const_iterator p;
  1747. if (!os->is_unique_segment())
  1748. {
  1749. for (p = this->segment_list_.begin();
  1750. p != this->segment_list_.end();
  1751. ++p)
  1752. {
  1753. if ((*p)->type() != elfcpp::PT_LOAD)
  1754. continue;
  1755. if ((*p)->is_unique_segment())
  1756. continue;
  1757. if (!parameters->options().omagic()
  1758. && ((*p)->flags() & elfcpp::PF_W) != (seg_flags & elfcpp::PF_W))
  1759. continue;
  1760. if ((target->isolate_execinstr() || parameters->options().rosegment())
  1761. && ((*p)->flags() & elfcpp::PF_X) != (seg_flags & elfcpp::PF_X))
  1762. continue;
  1763. // If -Tbss was specified, we need to separate the data and BSS
  1764. // segments.
  1765. if (parameters->options().user_set_Tbss())
  1766. {
  1767. if ((os->type() == elfcpp::SHT_NOBITS)
  1768. == (*p)->has_any_data_sections())
  1769. continue;
  1770. }
  1771. if (os->is_large_data_section() && !(*p)->is_large_data_segment())
  1772. continue;
  1773. if (is_address_set)
  1774. {
  1775. if ((*p)->are_addresses_set())
  1776. continue;
  1777. (*p)->add_initial_output_data(os);
  1778. (*p)->update_flags_for_output_section(seg_flags);
  1779. (*p)->set_addresses(addr, addr);
  1780. break;
  1781. }
  1782. (*p)->add_output_section_to_load(this, os, seg_flags);
  1783. break;
  1784. }
  1785. }
  1786. if (p == this->segment_list_.end()
  1787. || os->is_unique_segment())
  1788. {
  1789. Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
  1790. seg_flags);
  1791. if (os->is_large_data_section())
  1792. oseg->set_is_large_data_segment();
  1793. oseg->add_output_section_to_load(this, os, seg_flags);
  1794. if (is_address_set)
  1795. oseg->set_addresses(addr, addr);
  1796. // Check if segment should be marked unique. For segments marked
  1797. // unique by linker plugins, set the new alignment if specified.
  1798. if (os->is_unique_segment())
  1799. {
  1800. oseg->set_is_unique_segment();
  1801. if (os->segment_alignment() != 0)
  1802. oseg->set_minimum_p_align(os->segment_alignment());
  1803. }
  1804. }
  1805. // If we see a loadable SHT_NOTE section, we create a PT_NOTE
  1806. // segment.
  1807. if (os->type() == elfcpp::SHT_NOTE)
  1808. {
  1809. uint64_t os_align = os->addralign();
  1810. // See if we already have an equivalent PT_NOTE segment.
  1811. for (p = this->segment_list_.begin();
  1812. p != segment_list_.end();
  1813. ++p)
  1814. {
  1815. if ((*p)->type() == elfcpp::PT_NOTE
  1816. && (*p)->align() == os_align
  1817. && (((*p)->flags() & elfcpp::PF_W)
  1818. == (seg_flags & elfcpp::PF_W)))
  1819. {
  1820. (*p)->add_output_section_to_nonload(os, seg_flags);
  1821. break;
  1822. }
  1823. }
  1824. if (p == this->segment_list_.end())
  1825. {
  1826. Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
  1827. seg_flags);
  1828. oseg->add_output_section_to_nonload(os, seg_flags);
  1829. oseg->set_align(os_align);
  1830. }
  1831. }
  1832. // If we see a loadable SHF_TLS section, we create a PT_TLS
  1833. // segment. There can only be one such segment.
  1834. if ((flags & elfcpp::SHF_TLS) != 0)
  1835. {
  1836. if (this->tls_segment_ == NULL)
  1837. this->make_output_segment(elfcpp::PT_TLS, seg_flags);
  1838. this->tls_segment_->add_output_section_to_nonload(os, seg_flags);
  1839. }
  1840. // If -z relro is in effect, and we see a relro section, we create a
  1841. // PT_GNU_RELRO segment. There can only be one such segment.
  1842. if (os->is_relro() && parameters->options().relro())
  1843. {
  1844. gold_assert(seg_flags == (elfcpp::PF_R | elfcpp::PF_W));
  1845. if (this->relro_segment_ == NULL)
  1846. this->make_output_segment(elfcpp::PT_GNU_RELRO, seg_flags);
  1847. this->relro_segment_->add_output_section_to_nonload(os, seg_flags);
  1848. }
  1849. // If we see a section named .interp, put it into a PT_INTERP
  1850. // segment. This seems broken to me, but this is what GNU ld does,
  1851. // and glibc expects it.
  1852. if (strcmp(os->name(), ".interp") == 0
  1853. && !this->script_options_->saw_phdrs_clause())
  1854. {
  1855. if (this->interp_segment_ == NULL)
  1856. this->make_output_segment(elfcpp::PT_INTERP, seg_flags);
  1857. else
  1858. gold_warning(_("multiple '.interp' sections in input files "
  1859. "may cause confusing PT_INTERP segment"));
  1860. this->interp_segment_->add_output_section_to_nonload(os, seg_flags);
  1861. }
  1862. }
  1863. // Make an output section for a script.
  1864. Output_section*
  1865. Layout::make_output_section_for_script(
  1866. const char* name,
  1867. Script_sections::Section_type section_type)
  1868. {
  1869. name = this->namepool_.add(name, false, NULL);
  1870. elfcpp::Elf_Xword sh_flags = elfcpp::SHF_ALLOC;
  1871. if (section_type == Script_sections::ST_NOLOAD)
  1872. sh_flags = 0;
  1873. Output_section* os = this->make_output_section(name, elfcpp::SHT_PROGBITS,
  1874. sh_flags, ORDER_INVALID,
  1875. false);
  1876. os->set_found_in_sections_clause();
  1877. if (section_type == Script_sections::ST_NOLOAD)
  1878. os->set_is_noload();
  1879. return os;
  1880. }
  1881. // Return the number of segments we expect to see.
  1882. size_t
  1883. Layout::expected_segment_count() const
  1884. {
  1885. size_t ret = this->segment_list_.size();
  1886. // If we didn't see a SECTIONS clause in a linker script, we should
  1887. // already have the complete list of segments. Otherwise we ask the
  1888. // SECTIONS clause how many segments it expects, and add in the ones
  1889. // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
  1890. if (!this->script_options_->saw_sections_clause())
  1891. return ret;
  1892. else
  1893. {
  1894. const Script_sections* ss = this->script_options_->script_sections();
  1895. return ret + ss->expected_segment_count(this);
  1896. }
  1897. }
  1898. // Handle the .note.GNU-stack section at layout time. SEEN_GNU_STACK
  1899. // is whether we saw a .note.GNU-stack section in the object file.
  1900. // GNU_STACK_FLAGS is the section flags. The flags give the
  1901. // protection required for stack memory. We record this in an
  1902. // executable as a PT_GNU_STACK segment. If an object file does not
  1903. // have a .note.GNU-stack segment, we must assume that it is an old
  1904. // object. On some targets that will force an executable stack.
  1905. void
  1906. Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags,
  1907. const Object* obj)
  1908. {
  1909. if (!seen_gnu_stack)
  1910. {
  1911. this->input_without_gnu_stack_note_ = true;
  1912. if (parameters->options().warn_execstack()
  1913. && parameters->target().is_default_stack_executable())
  1914. gold_warning(_("%s: missing .note.GNU-stack section"
  1915. " implies executable stack"),
  1916. obj->name().c_str());
  1917. }
  1918. else
  1919. {
  1920. this->input_with_gnu_stack_note_ = true;
  1921. if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
  1922. {
  1923. this->input_requires_executable_stack_ = true;
  1924. if (parameters->options().warn_execstack())
  1925. gold_warning(_("%s: requires executable stack"),
  1926. obj->name().c_str());
  1927. }
  1928. }
  1929. }
  1930. // Read a value with given size and endianness.
  1931. static inline uint64_t
  1932. read_sized_value(size_t size, const unsigned char* buf, bool is_big_endian,
  1933. const Object* object)
  1934. {
  1935. uint64_t val = 0;
  1936. if (size == 4)
  1937. {
  1938. if (is_big_endian)
  1939. val = elfcpp::Swap<32, true>::readval(buf);
  1940. else
  1941. val = elfcpp::Swap<32, false>::readval(buf);
  1942. }
  1943. else if (size == 8)
  1944. {
  1945. if (is_big_endian)
  1946. val = elfcpp::Swap<64, true>::readval(buf);
  1947. else
  1948. val = elfcpp::Swap<64, false>::readval(buf);
  1949. }
  1950. else
  1951. {
  1952. gold_warning(_("%s: in .note.gnu.property section, "
  1953. "pr_datasz must be 4 or 8"),
  1954. object->name().c_str());
  1955. }
  1956. return val;
  1957. }
  1958. // Write a value with given size and endianness.
  1959. static inline void
  1960. write_sized_value(uint64_t value, size_t size, unsigned char* buf,
  1961. bool is_big_endian)
  1962. {
  1963. if (size == 4)
  1964. {
  1965. if (is_big_endian)
  1966. elfcpp::Swap<32, true>::writeval(buf, static_cast<uint32_t>(value));
  1967. else
  1968. elfcpp::Swap<32, false>::writeval(buf, static_cast<uint32_t>(value));
  1969. }
  1970. else if (size == 8)
  1971. {
  1972. if (is_big_endian)
  1973. elfcpp::Swap<64, true>::writeval(buf, value);
  1974. else
  1975. elfcpp::Swap<64, false>::writeval(buf, value);
  1976. }
  1977. else
  1978. {
  1979. // We will have already complained about this.
  1980. }
  1981. }
  1982. // Handle the .note.gnu.property section at layout time.
  1983. void
  1984. Layout::layout_gnu_property(unsigned int note_type,
  1985. unsigned int pr_type,
  1986. size_t pr_datasz,
  1987. const unsigned char* pr_data,
  1988. const Object* object)
  1989. {
  1990. // We currently support only the one note type.
  1991. gold_assert(note_type == elfcpp::NT_GNU_PROPERTY_TYPE_0);
  1992. if (pr_type >= elfcpp::GNU_PROPERTY_LOPROC
  1993. && pr_type < elfcpp::GNU_PROPERTY_HIPROC)
  1994. {
  1995. // Target-dependent property value; call the target to record.
  1996. const int size = parameters->target().get_size();
  1997. const bool is_big_endian = parameters->target().is_big_endian();
  1998. if (size == 32)
  1999. {
  2000. if (is_big_endian)
  2001. {
  2002. #ifdef HAVE_TARGET_32_BIG
  2003. parameters->sized_target<32, true>()->
  2004. record_gnu_property(note_type, pr_type, pr_datasz, pr_data,
  2005. object);
  2006. #else
  2007. gold_unreachable();
  2008. #endif
  2009. }
  2010. else
  2011. {
  2012. #ifdef HAVE_TARGET_32_LITTLE
  2013. parameters->sized_target<32, false>()->
  2014. record_gnu_property(note_type, pr_type, pr_datasz, pr_data,
  2015. object);
  2016. #else
  2017. gold_unreachable();
  2018. #endif
  2019. }
  2020. }
  2021. else if (size == 64)
  2022. {
  2023. if (is_big_endian)
  2024. {
  2025. #ifdef HAVE_TARGET_64_BIG
  2026. parameters->sized_target<64, true>()->
  2027. record_gnu_property(note_type, pr_type, pr_datasz, pr_data,
  2028. object);
  2029. #else
  2030. gold_unreachable();
  2031. #endif
  2032. }
  2033. else
  2034. {
  2035. #ifdef HAVE_TARGET_64_LITTLE
  2036. parameters->sized_target<64, false>()->
  2037. record_gnu_property(note_type, pr_type, pr_datasz, pr_data,
  2038. object);
  2039. #else
  2040. gold_unreachable();
  2041. #endif
  2042. }
  2043. }
  2044. else
  2045. gold_unreachable();
  2046. return;
  2047. }
  2048. Gnu_properties::iterator pprop = this->gnu_properties_.find(pr_type);
  2049. if (pprop == this->gnu_properties_.end())
  2050. {
  2051. Gnu_property prop;
  2052. prop.pr_datasz = pr_datasz;
  2053. prop.pr_data = new unsigned char[pr_datasz];
  2054. memcpy(prop.pr_data, pr_data, pr_datasz);
  2055. this->gnu_properties_[pr_type] = prop;
  2056. }
  2057. else
  2058. {
  2059. const bool is_big_endian = parameters->target().is_big_endian();
  2060. switch (pr_type)
  2061. {
  2062. case elfcpp::GNU_PROPERTY_STACK_SIZE:
  2063. // Record the maximum value seen.
  2064. {
  2065. uint64_t val1 = read_sized_value(pprop->second.pr_datasz,
  2066. pprop->second.pr_data,
  2067. is_big_endian, object);
  2068. uint64_t val2 = read_sized_value(pr_datasz, pr_data,
  2069. is_big_endian, object);
  2070. if (val2 > val1)
  2071. write_sized_value(val2, pprop->second.pr_datasz,
  2072. pprop->second.pr_data, is_big_endian);
  2073. }
  2074. break;
  2075. case elfcpp::GNU_PROPERTY_NO_COPY_ON_PROTECTED:
  2076. // No data to merge.
  2077. break;
  2078. default:
  2079. gold_warning(_("%s: unknown program property type %d "
  2080. "in .note.gnu.property section"),
  2081. object->name().c_str(), pr_type);
  2082. }
  2083. }
  2084. }
  2085. // Merge per-object properties with program properties.
  2086. // This lets the target identify objects that are missing certain
  2087. // properties, in cases where properties must be ANDed together.
  2088. void
  2089. Layout::merge_gnu_properties(const Object* object)
  2090. {
  2091. const int size = parameters->target().get_size();
  2092. const bool is_big_endian = parameters->target().is_big_endian();
  2093. if (size == 32)
  2094. {
  2095. if (is_big_endian)
  2096. {
  2097. #ifdef HAVE_TARGET_32_BIG
  2098. parameters->sized_target<32, true>()->merge_gnu_properties(object);
  2099. #else
  2100. gold_unreachable();
  2101. #endif
  2102. }
  2103. else
  2104. {
  2105. #ifdef HAVE_TARGET_32_LITTLE
  2106. parameters->sized_target<32, false>()->merge_gnu_properties(object);
  2107. #else
  2108. gold_unreachable();
  2109. #endif
  2110. }
  2111. }
  2112. else if (size == 64)
  2113. {
  2114. if (is_big_endian)
  2115. {
  2116. #ifdef HAVE_TARGET_64_BIG
  2117. parameters->sized_target<64, true>()->merge_gnu_properties(object);
  2118. #else
  2119. gold_unreachable();
  2120. #endif
  2121. }
  2122. else
  2123. {
  2124. #ifdef HAVE_TARGET_64_LITTLE
  2125. parameters->sized_target<64, false>()->merge_gnu_properties(object);
  2126. #else
  2127. gold_unreachable();
  2128. #endif
  2129. }
  2130. }
  2131. else
  2132. gold_unreachable();
  2133. }
  2134. // Add a target-specific property for the output .note.gnu.property section.
  2135. void
  2136. Layout::add_gnu_property(unsigned int note_type,
  2137. unsigned int pr_type,
  2138. size_t pr_datasz,
  2139. const unsigned char* pr_data)
  2140. {
  2141. gold_assert(note_type == elfcpp::NT_GNU_PROPERTY_TYPE_0);
  2142. Gnu_property prop;
  2143. prop.pr_datasz = pr_datasz;
  2144. prop.pr_data = new unsigned char[pr_datasz];
  2145. memcpy(prop.pr_data, pr_data, pr_datasz);
  2146. this->gnu_properties_[pr_type] = prop;
  2147. }
  2148. // Create automatic note sections.
  2149. void
  2150. Layout::create_notes()
  2151. {
  2152. this->create_gnu_properties_note();
  2153. this->create_gold_note();
  2154. this->create_stack_segment();
  2155. this->create_build_id();
  2156. }
  2157. // Create the dynamic sections which are needed before we read the
  2158. // relocs.
  2159. void
  2160. Layout::create_initial_dynamic_sections(Symbol_table* symtab)
  2161. {
  2162. if (parameters->doing_static_link())
  2163. return;
  2164. this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
  2165. elfcpp::SHT_DYNAMIC,
  2166. (elfcpp::SHF_ALLOC
  2167. | elfcpp::SHF_WRITE),
  2168. false, ORDER_RELRO,
  2169. true, false, false);
  2170. // A linker script may discard .dynamic, so check for NULL.
  2171. if (this->dynamic_section_ != NULL)
  2172. {
  2173. this->dynamic_symbol_ =
  2174. symtab->define_in_output_data("_DYNAMIC", NULL,
  2175. Symbol_table::PREDEFINED,
  2176. this->dynamic_section_, 0, 0,
  2177. elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
  2178. elfcpp::STV_HIDDEN, 0, false, false);
  2179. this->dynamic_data_ = new Output_data_dynamic(&this->dynpool_);
  2180. this->dynamic_section_->add_output_section_data(this->dynamic_data_);
  2181. }
  2182. }
  2183. // For each output section whose name can be represented as C symbol,
  2184. // define __start and __stop symbols for the section. This is a GNU
  2185. // extension.
  2186. void
  2187. Layout::define_section_symbols(Symbol_table* symtab)
  2188. {
  2189. const elfcpp::STV visibility = parameters->options().start_stop_visibility_enum();
  2190. for (Section_list::const_iterator p = this->section_list_.begin();
  2191. p != this->section_list_.end();
  2192. ++p)
  2193. {
  2194. const char* const name = (*p)->name();
  2195. if (is_cident(name))
  2196. {
  2197. const std::string name_string(name);
  2198. const std::string start_name(cident_section_start_prefix
  2199. + name_string);
  2200. const std::string stop_name(cident_section_stop_prefix
  2201. + name_string);
  2202. symtab->define_in_output_data(start_name.c_str(),
  2203. NULL, // version
  2204. Symbol_table::PREDEFINED,
  2205. *p,
  2206. 0, // value
  2207. 0, // symsize
  2208. elfcpp::STT_NOTYPE,
  2209. elfcpp::STB_GLOBAL,
  2210. visibility,
  2211. 0, // nonvis
  2212. false, // offset_is_from_end
  2213. true); // only_if_ref
  2214. symtab->define_in_output_data(stop_name.c_str(),
  2215. NULL, // version
  2216. Symbol_table::PREDEFINED,
  2217. *p,
  2218. 0, // value
  2219. 0, // symsize
  2220. elfcpp::STT_NOTYPE,
  2221. elfcpp::STB_GLOBAL,
  2222. visibility,
  2223. 0, // nonvis
  2224. true, // offset_is_from_end
  2225. true); // only_if_ref
  2226. }
  2227. }
  2228. }
  2229. // Define symbols for group signatures.
  2230. void
  2231. Layout::define_group_signatures(Symbol_table* symtab)
  2232. {
  2233. for (Group_signatures::iterator p = this->group_signatures_.begin();
  2234. p != this->group_signatures_.end();
  2235. ++p)
  2236. {
  2237. Symbol* sym = symtab->lookup(p->signature, NULL);
  2238. if (sym != NULL)
  2239. p->section->set_info_symndx(sym);
  2240. else
  2241. {
  2242. // Force the name of the group section to the group
  2243. // signature, and use the group's section symbol as the
  2244. // signature symbol.
  2245. if (strcmp(p->section->name(), p->signature) != 0)
  2246. {
  2247. const char* name = this->namepool_.add(p->signature,
  2248. true, NULL);
  2249. p->section->set_name(name);
  2250. }
  2251. p->section->set_needs_symtab_index();
  2252. p->section->set_info_section_symndx(p->section);
  2253. }
  2254. }
  2255. this->group_signatures_.clear();
  2256. }
  2257. // Find the first read-only PT_LOAD segment, creating one if
  2258. // necessary.
  2259. Output_segment*
  2260. Layout::find_first_load_seg(const Target* target)
  2261. {
  2262. Output_segment* best = NULL;
  2263. for (Segment_list::const_iterator p = this->segment_list_.begin();
  2264. p != this->segment_list_.end();
  2265. ++p)
  2266. {
  2267. if ((*p)->type() == elfcpp::PT_LOAD
  2268. && ((*p)->flags() & elfcpp::PF_R) != 0
  2269. && (parameters->options().omagic()
  2270. || ((*p)->flags() & elfcpp::PF_W) == 0)
  2271. && (!target->isolate_execinstr()
  2272. || ((*p)->flags() & elfcpp::PF_X) == 0))
  2273. {
  2274. if (best == NULL || this->segment_precedes(*p, best))
  2275. best = *p;
  2276. }
  2277. }
  2278. if (best != NULL)
  2279. return best;
  2280. gold_assert(!this->script_options_->saw_phdrs_clause());
  2281. Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
  2282. elfcpp::PF_R);
  2283. return load_seg;
  2284. }
  2285. // Save states of all current output segments. Store saved states
  2286. // in SEGMENT_STATES.
  2287. void
  2288. Layout::save_segments(Segment_states* segment_states)
  2289. {
  2290. for (Segment_list::const_iterator p = this->segment_list_.begin();
  2291. p != this->segment_list_.end();
  2292. ++p)
  2293. {
  2294. Output_segment* segment = *p;
  2295. // Shallow copy.
  2296. Output_segment* copy = new Output_segment(*segment);
  2297. (*segment_states)[segment] = copy;
  2298. }
  2299. }
  2300. // Restore states of output segments and delete any segment not found in
  2301. // SEGMENT_STATES.
  2302. void
  2303. Layout::restore_segments(const Segment_states* segment_states)
  2304. {
  2305. // Go through the segment list and remove any segment added in the
  2306. // relaxation loop.
  2307. this->tls_segment_ = NULL;
  2308. this->relro_segment_ = NULL;
  2309. Segment_list::iterator list_iter = this->segment_list_.begin();
  2310. while (list_iter != this->segment_list_.end())
  2311. {
  2312. Output_segment* segment = *list_iter;
  2313. Segment_states::const_iterator states_iter =
  2314. segment_states->find(segment);
  2315. if (states_iter != segment_states->end())
  2316. {
  2317. const Output_segment* copy = states_iter->second;
  2318. // Shallow copy to restore states.
  2319. *segment = *copy;
  2320. // Also fix up TLS and RELRO segment pointers as appropriate.
  2321. if (segment->type() == elfcpp::PT_TLS)
  2322. this->tls_segment_ = segment;
  2323. else if (segment->type() == elfcpp::PT_GNU_RELRO)
  2324. this->relro_segment_ = segment;
  2325. ++list_iter;
  2326. }
  2327. else
  2328. {
  2329. list_iter = this->segment_list_.erase(list_iter);
  2330. // This is a segment created during section layout. It should be
  2331. // safe to remove it since we should have removed all pointers to it.
  2332. delete segment;
  2333. }
  2334. }
  2335. }
  2336. // Clean up after relaxation so that sections can be laid out again.
  2337. void
  2338. Layout::clean_up_after_relaxation()
  2339. {
  2340. // Restore the segments to point state just prior to the relaxation loop.
  2341. Script_sections* script_section = this->script_options_->script_sections();
  2342. script_section->release_segments();
  2343. this->restore_segments(this->segment_states_);
  2344. // Reset section addresses and file offsets
  2345. for (Section_list::iterator p = this->section_list_.begin();
  2346. p != this->section_list_.end();
  2347. ++p)
  2348. {
  2349. (*p)->restore_states();
  2350. // If an input section changes size because of relaxation,
  2351. // we need to adjust the section offsets of all input sections.
  2352. // after such a section.
  2353. if ((*p)->section_offsets_need_adjustment())
  2354. (*p)->adjust_section_offsets();
  2355. (*p)->reset_address_and_file_offset();
  2356. }
  2357. // Reset special output object address and file offsets.
  2358. for (Data_list::iterator p = this->special_output_list_.begin();
  2359. p != this->special_output_list_.end();
  2360. ++p)
  2361. (*p)->reset_address_and_file_offset();
  2362. // A linker script may have created some output section data objects.
  2363. // They are useless now.
  2364. for (Output_section_data_list::const_iterator p =
  2365. this->script_output_section_data_list_.begin();
  2366. p != this->script_output_section_data_list_.end();
  2367. ++p)
  2368. delete *p;
  2369. this->script_output_section_data_list_.clear();
  2370. // Special-case fill output objects are recreated each time through
  2371. // the relaxation loop.
  2372. this->reset_relax_output();
  2373. }
  2374. void
  2375. Layout::reset_relax_output()
  2376. {
  2377. for (Data_list::const_iterator p = this->relax_output_list_.begin();
  2378. p != this->relax_output_list_.end();
  2379. ++p)
  2380. delete *p;
  2381. this->relax_output_list_.clear();
  2382. }
  2383. // Prepare for relaxation.
  2384. void
  2385. Layout::prepare_for_relaxation()
  2386. {
  2387. // Create an relaxation debug check if in debugging mode.
  2388. if (is_debugging_enabled(DEBUG_RELAXATION))
  2389. this->relaxation_debug_check_ = new Relaxation_debug_check();
  2390. // Save segment states.
  2391. this->segment_states_ = new Segment_states();
  2392. this->save_segments(this->segment_states_);
  2393. for(Section_list::const_iterator p = this->section_list_.begin();
  2394. p != this->section_list_.end();
  2395. ++p)
  2396. (*p)->save_states();
  2397. if (is_debugging_enabled(DEBUG_RELAXATION))
  2398. this->relaxation_debug_check_->check_output_data_for_reset_values(
  2399. this->section_list_, this->special_output_list_,
  2400. this->relax_output_list_);
  2401. // Also enable recording of output section data from scripts.
  2402. this->record_output_section_data_from_script_ = true;
  2403. }
  2404. // If the user set the address of the text segment, that may not be
  2405. // compatible with putting the segment headers and file headers into
  2406. // that segment. For isolate_execinstr() targets, it's the rodata
  2407. // segment rather than text where we might put the headers.
  2408. static inline bool
  2409. load_seg_unusable_for_headers(const Target* target)
  2410. {
  2411. const General_options& options = parameters->options();
  2412. if (target->isolate_execinstr())
  2413. return (options.user_set_Trodata_segment()
  2414. && options.Trodata_segment() % target->abi_pagesize() != 0);
  2415. else
  2416. return (options.user_set_Ttext()
  2417. && options.Ttext() % target->abi_pagesize() != 0);
  2418. }
  2419. // Relaxation loop body: If target has no relaxation, this runs only once
  2420. // Otherwise, the target relaxation hook is called at the end of
  2421. // each iteration. If the hook returns true, it means re-layout of
  2422. // section is required.
  2423. //
  2424. // The number of segments created by a linking script without a PHDRS
  2425. // clause may be affected by section sizes and alignments. There is
  2426. // a remote chance that relaxation causes different number of PT_LOAD
  2427. // segments are created and sections are attached to different segments.
  2428. // Therefore, we always throw away all segments created during section
  2429. // layout. In order to be able to restart the section layout, we keep
  2430. // a copy of the segment list right before the relaxation loop and use
  2431. // that to restore the segments.
  2432. //
  2433. // PASS is the current relaxation pass number.
  2434. // SYMTAB is a symbol table.
  2435. // PLOAD_SEG is the address of a pointer for the load segment.
  2436. // PHDR_SEG is a pointer to the PHDR segment.
  2437. // SEGMENT_HEADERS points to the output segment header.
  2438. // FILE_HEADER points to the output file header.
  2439. // PSHNDX is the address to store the output section index.
  2440. off_t inline
  2441. Layout::relaxation_loop_body(
  2442. int pass,
  2443. Target* target,
  2444. Symbol_table* symtab,
  2445. Output_segment** pload_seg,
  2446. Output_segment* phdr_seg,
  2447. Output_segment_headers* segment_headers,
  2448. Output_file_header* file_header,
  2449. unsigned int* pshndx)
  2450. {
  2451. // If this is not the first iteration, we need to clean up after
  2452. // relaxation so that we can lay out the sections again.
  2453. if (pass != 0)
  2454. this->clean_up_after_relaxation();
  2455. // If there is a SECTIONS clause, put all the input sections into
  2456. // the required order.
  2457. Output_segment* load_seg;
  2458. if (this->script_options_->saw_sections_clause())
  2459. load_seg = this->set_section_addresses_from_script(symtab);
  2460. else if (parameters->options().relocatable())
  2461. load_seg = NULL;
  2462. else
  2463. load_seg = this->find_first_load_seg(target);
  2464. if (parameters->options().oformat_enum()
  2465. != General_options::OBJECT_FORMAT_ELF)
  2466. load_seg = NULL;
  2467. if (load_seg_unusable_for_headers(target))
  2468. {
  2469. load_seg = NULL;
  2470. phdr_seg = NULL;
  2471. }
  2472. gold_assert(phdr_seg == NULL
  2473. || load_seg != NULL
  2474. || this->script_options_->saw_sections_clause());
  2475. // If the address of the load segment we found has been set by
  2476. // --section-start rather than by a script, then adjust the VMA and
  2477. // LMA downward if possible to include the file and section headers.
  2478. uint64_t header_gap = 0;
  2479. if (load_seg != NULL
  2480. && load_seg->are_addresses_set()
  2481. && !this->script_options_->saw_sections_clause()
  2482. && !parameters->options().relocatable())
  2483. {
  2484. file_header->finalize_data_size();
  2485. segment_headers->finalize_data_size();
  2486. size_t sizeof_headers = (file_header->data_size()
  2487. + segment_headers->data_size());
  2488. const uint64_t abi_pagesize = target->abi_pagesize();
  2489. uint64_t hdr_paddr = load_seg->paddr() - sizeof_headers;
  2490. hdr_paddr &= ~(abi_pagesize - 1);
  2491. uint64_t subtract = load_seg->paddr() - hdr_paddr;
  2492. if (load_seg->paddr() < subtract || load_seg->vaddr() < subtract)
  2493. load_seg = NULL;
  2494. else
  2495. {
  2496. load_seg->set_addresses(load_seg->vaddr() - subtract,
  2497. load_seg->paddr() - subtract);
  2498. header_gap = subtract - sizeof_headers;
  2499. }
  2500. }
  2501. // Lay out the segment headers.
  2502. if (!parameters->options().relocatable())
  2503. {
  2504. gold_assert(segment_headers != NULL);
  2505. if (header_gap != 0 && load_seg != NULL)
  2506. {
  2507. Output_data_zero_fill* z = new Output_data_zero_fill(header_gap, 1);
  2508. load_seg->add_initial_output_data(z);
  2509. }
  2510. if (load_seg != NULL)
  2511. load_seg->add_initial_output_data(segment_headers);
  2512. if (phdr_seg != NULL)
  2513. phdr_seg->add_initial_output_data(segment_headers);
  2514. }
  2515. // Lay out the file header.
  2516. if (load_seg != NULL)
  2517. load_seg->add_initial_output_data(file_header);
  2518. if (this->script_options_->saw_phdrs_clause()
  2519. && !parameters->options().relocatable())
  2520. {
  2521. // Support use of FILEHDRS and PHDRS attachments in a PHDRS
  2522. // clause in a linker script.
  2523. Script_sections* ss = this->script_options_->script_sections();
  2524. ss->put_headers_in_phdrs(file_header, segment_headers);
  2525. }
  2526. // We set the output section indexes in set_segment_offsets and
  2527. // set_section_indexes.
  2528. *pshndx = 1;
  2529. // Set the file offsets of all the segments, and all the sections
  2530. // they contain.
  2531. off_t off;
  2532. if (!parameters->options().relocatable())
  2533. off = this->set_segment_offsets(target, load_seg, pshndx);
  2534. else
  2535. off = this->set_relocatable_section_offsets(file_header, pshndx);
  2536. // Verify that the dummy relaxation does not change anything.
  2537. if (is_debugging_enabled(DEBUG_RELAXATION))
  2538. {
  2539. if (pass == 0)
  2540. this->relaxation_debug_check_->read_sections(this->section_list_);
  2541. else
  2542. this->relaxation_debug_check_->verify_sections(this->section_list_);
  2543. }
  2544. *pload_seg = load_seg;
  2545. return off;
  2546. }
  2547. // Search the list of patterns and find the position of the given section
  2548. // name in the output section. If the section name matches a glob
  2549. // pattern and a non-glob name, then the non-glob position takes
  2550. // precedence. Return 0 if no match is found.
  2551. unsigned int
  2552. Layout::find_section_order_index(const std::string& section_name)
  2553. {
  2554. Unordered_map<std::string, unsigned int>::iterator map_it;
  2555. map_it = this->input_section_position_.find(section_name);
  2556. if (map_it != this->input_section_position_.end())
  2557. return map_it->second;
  2558. // Absolute match failed. Linear search the glob patterns.
  2559. std::vector<std::string>::iterator it;
  2560. for (it = this->input_section_glob_.begin();
  2561. it != this->input_section_glob_.end();
  2562. ++it)
  2563. {
  2564. if (fnmatch((*it).c_str(), section_name.c_str(), FNM_NOESCAPE) == 0)
  2565. {
  2566. map_it = this->input_section_position_.find(*it);
  2567. gold_assert(map_it != this->input_section_position_.end());
  2568. return map_it->second;
  2569. }
  2570. }
  2571. return 0;
  2572. }
  2573. // Read the sequence of input sections from the file specified with
  2574. // option --section-ordering-file.
  2575. void
  2576. Layout::read_layout_from_file()
  2577. {
  2578. const char* filename = parameters->options().section_ordering_file();
  2579. std::ifstream in;
  2580. std::string line;
  2581. in.open(filename);
  2582. if (!in)
  2583. gold_fatal(_("unable to open --section-ordering-file file %s: %s"),
  2584. filename, strerror(errno));
  2585. File_read::record_file_read(filename);
  2586. std::getline(in, line); // this chops off the trailing \n, if any
  2587. unsigned int position = 1;
  2588. this->set_section_ordering_specified();
  2589. while (in)
  2590. {
  2591. if (!line.empty() && line[line.length() - 1] == '\r') // Windows
  2592. line.resize(line.length() - 1);
  2593. // Ignore comments, beginning with '#'
  2594. if (line[0] == '#')
  2595. {
  2596. std::getline(in, line);
  2597. continue;
  2598. }
  2599. this->input_section_position_[line] = position;
  2600. // Store all glob patterns in a vector.
  2601. if (is_wildcard_string(line.c_str()))
  2602. this->input_section_glob_.push_back(line);
  2603. position++;
  2604. std::getline(in, line);
  2605. }
  2606. }
  2607. // Finalize the layout. When this is called, we have created all the
  2608. // output sections and all the output segments which are based on
  2609. // input sections. We have several things to do, and we have to do
  2610. // them in the right order, so that we get the right results correctly
  2611. // and efficiently.
  2612. // 1) Finalize the list of output segments and create the segment
  2613. // table header.
  2614. // 2) Finalize the dynamic symbol table and associated sections.
  2615. // 3) Determine the final file offset of all the output segments.
  2616. // 4) Determine the final file offset of all the SHF_ALLOC output
  2617. // sections.
  2618. // 5) Create the symbol table sections and the section name table
  2619. // section.
  2620. // 6) Finalize the symbol table: set symbol values to their final
  2621. // value and make a final determination of which symbols are going
  2622. // into the output symbol table.
  2623. // 7) Create the section table header.
  2624. // 8) Determine the final file offset of all the output sections which
  2625. // are not SHF_ALLOC, including the section table header.
  2626. // 9) Finalize the ELF file header.
  2627. // This function returns the size of the output file.
  2628. off_t
  2629. Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
  2630. Target* target, const Task* task)
  2631. {
  2632. unsigned int local_dynamic_count = 0;
  2633. unsigned int forced_local_dynamic_count = 0;
  2634. target->finalize_sections(this, input_objects, symtab);
  2635. this->count_local_symbols(task, input_objects);
  2636. this->link_stabs_sections();
  2637. Output_segment* phdr_seg = NULL;
  2638. if (!parameters->options().relocatable() && !parameters->doing_static_link())
  2639. {
  2640. // There was a dynamic object in the link. We need to create
  2641. // some information for the dynamic linker.
  2642. // Create the PT_PHDR segment which will hold the program
  2643. // headers.
  2644. if (!this->script_options_->saw_phdrs_clause())
  2645. phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
  2646. // Create the dynamic symbol table, including the hash table.
  2647. Output_section* dynstr;
  2648. std::vector<Symbol*> dynamic_symbols;
  2649. Versions versions(*this->script_options()->version_script_info(),
  2650. &this->dynpool_);
  2651. this->create_dynamic_symtab(input_objects, symtab, &dynstr,
  2652. &local_dynamic_count,
  2653. &forced_local_dynamic_count,
  2654. &dynamic_symbols,
  2655. &versions);
  2656. // Create the .interp section to hold the name of the
  2657. // interpreter, and put it in a PT_INTERP segment. Don't do it
  2658. // if we saw a .interp section in an input file.
  2659. if ((!parameters->options().shared()
  2660. || parameters->options().dynamic_linker() != NULL)
  2661. && this->interp_segment_ == NULL)
  2662. this->create_interp(target);
  2663. // Finish the .dynamic section to hold the dynamic data, and put
  2664. // it in a PT_DYNAMIC segment.
  2665. this->finish_dynamic_section(input_objects, symtab);
  2666. // We should have added everything we need to the dynamic string
  2667. // table.
  2668. this->dynpool_.set_string_offsets();
  2669. // Create the version sections. We can't do this until the
  2670. // dynamic string table is complete.
  2671. this->create_version_sections(&versions, symtab,
  2672. (local_dynamic_count
  2673. + forced_local_dynamic_count),
  2674. dynamic_symbols, dynstr);
  2675. // Set the size of the _DYNAMIC symbol. We can't do this until
  2676. // after we call create_version_sections.
  2677. this->set_dynamic_symbol_size(symtab);
  2678. }
  2679. // Create segment headers.
  2680. Output_segment_headers* segment_headers =
  2681. (parameters->options().relocatable()
  2682. ? NULL
  2683. : new Output_segment_headers(this->segment_list_));
  2684. // Lay out the file header.
  2685. Output_file_header* file_header = new Output_file_header(target, symtab,
  2686. segment_headers);
  2687. this->special_output_list_.push_back(file_header);
  2688. if (segment_headers != NULL)
  2689. this->special_output_list_.push_back(segment_headers);
  2690. // Find approriate places for orphan output sections if we are using
  2691. // a linker script.
  2692. if (this->script_options_->saw_sections_clause())
  2693. this->place_orphan_sections_in_script();
  2694. Output_segment* load_seg;
  2695. off_t off;
  2696. unsigned int shndx;
  2697. int pass = 0;
  2698. // Take a snapshot of the section layout as needed.
  2699. if (target->may_relax())
  2700. this->prepare_for_relaxation();
  2701. // Run the relaxation loop to lay out sections.
  2702. do
  2703. {
  2704. off = this->relaxation_loop_body(pass, target, symtab, &load_seg,
  2705. phdr_seg, segment_headers, file_header,
  2706. &shndx);
  2707. pass++;
  2708. }
  2709. while (target->may_relax()
  2710. && target->relax(pass, input_objects, symtab, this, task));
  2711. // If there is a load segment that contains the file and program headers,
  2712. // provide a symbol __ehdr_start pointing there.
  2713. // A program can use this to examine itself robustly.
  2714. Symbol *ehdr_start = symtab->lookup("__ehdr_start");
  2715. if (ehdr_start != NULL && ehdr_start->is_predefined())
  2716. {
  2717. if (load_seg != NULL)
  2718. ehdr_start->set_output_segment(load_seg, Symbol::SEGMENT_START);
  2719. else
  2720. ehdr_start->set_undefined();
  2721. }
  2722. // Set the file offsets of all the non-data sections we've seen so
  2723. // far which don't have to wait for the input sections. We need
  2724. // this in order to finalize local symbols in non-allocated
  2725. // sections.
  2726. off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
  2727. // Set the section indexes of all unallocated sections seen so far,
  2728. // in case any of them are somehow referenced by a symbol.
  2729. shndx = this->set_section_indexes(shndx);
  2730. // Create the symbol table sections.
  2731. this->create_symtab_sections(input_objects, symtab, shndx, &off,
  2732. local_dynamic_count);
  2733. if (!parameters->doing_static_link())
  2734. this->assign_local_dynsym_offsets(input_objects);
  2735. // Process any symbol assignments from a linker script. This must
  2736. // be called after the symbol table has been finalized.
  2737. this->script_options_->finalize_symbols(symtab, this);
  2738. // Create the incremental inputs sections.
  2739. if (this->incremental_inputs_)
  2740. {
  2741. this->incremental_inputs_->finalize();
  2742. this->create_incremental_info_sections(symtab);
  2743. }
  2744. // Create the .shstrtab section.
  2745. Output_section* shstrtab_section = this->create_shstrtab();
  2746. // Set the file offsets of the rest of the non-data sections which
  2747. // don't have to wait for the input sections.
  2748. off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
  2749. // Now that all sections have been created, set the section indexes
  2750. // for any sections which haven't been done yet.
  2751. shndx = this->set_section_indexes(shndx);
  2752. // Create the section table header.
  2753. this->create_shdrs(shstrtab_section, &off);
  2754. // If there are no sections which require postprocessing, we can
  2755. // handle the section names now, and avoid a resize later.
  2756. if (!this->any_postprocessing_sections_)
  2757. {
  2758. off = this->set_section_offsets(off,
  2759. POSTPROCESSING_SECTIONS_PASS);
  2760. off =
  2761. this->set_section_offsets(off,
  2762. STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
  2763. }
  2764. file_header->set_section_info(this->section_headers_, shstrtab_section);
  2765. // Now we know exactly where everything goes in the output file
  2766. // (except for non-allocated sections which require postprocessing).
  2767. Output_data::layout_complete();
  2768. this->output_file_size_ = off;
  2769. return off;
  2770. }
  2771. // Create a note header following the format defined in the ELF ABI.
  2772. // NAME is the name, NOTE_TYPE is the type, SECTION_NAME is the name
  2773. // of the section to create, DESCSZ is the size of the descriptor.
  2774. // ALLOCATE is true if the section should be allocated in memory.
  2775. // This returns the new note section. It sets *TRAILING_PADDING to
  2776. // the number of trailing zero bytes required.
  2777. Output_section*
  2778. Layout::create_note(const char* name, int note_type,
  2779. const char* section_name, size_t descsz,
  2780. bool allocate, size_t* trailing_padding)
  2781. {
  2782. // Authorities all agree that the values in a .note field should
  2783. // be aligned on 4-byte boundaries for 32-bit binaries. However,
  2784. // they differ on what the alignment is for 64-bit binaries.
  2785. // The GABI says unambiguously they take 8-byte alignment:
  2786. // http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
  2787. // Other documentation says alignment should always be 4 bytes:
  2788. // http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
  2789. // GNU ld and GNU readelf both support the latter (at least as of
  2790. // version 2.16.91), and glibc always generates the latter for
  2791. // .note.ABI-tag (as of version 1.6), so that's the one we go with
  2792. // here.
  2793. #ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION // This is not defined by default.
  2794. const int size = parameters->target().get_size();
  2795. #else
  2796. const int size = 32;
  2797. #endif
  2798. // The NT_GNU_PROPERTY_TYPE_0 note is aligned to the pointer size.
  2799. const int addralign = ((note_type == elfcpp::NT_GNU_PROPERTY_TYPE_0
  2800. ? parameters->target().get_size()
  2801. : size) / 8);
  2802. // The contents of the .note section.
  2803. size_t namesz = strlen(name) + 1;
  2804. size_t aligned_namesz = align_address(namesz, size / 8);
  2805. size_t aligned_descsz = align_address(descsz, size / 8);
  2806. size_t notehdrsz = 3 * (size / 8) + aligned_namesz;
  2807. unsigned char* buffer = new unsigned char[notehdrsz];
  2808. memset(buffer, 0, notehdrsz);
  2809. bool is_big_endian = parameters->target().is_big_endian();
  2810. if (size == 32)
  2811. {
  2812. if (!is_big_endian)
  2813. {
  2814. elfcpp::Swap<32, false>::writeval(buffer, namesz);
  2815. elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
  2816. elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
  2817. }
  2818. else
  2819. {
  2820. elfcpp::Swap<32, true>::writeval(buffer, namesz);
  2821. elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
  2822. elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
  2823. }
  2824. }
  2825. else if (size == 64)
  2826. {
  2827. if (!is_big_endian)
  2828. {
  2829. elfcpp::Swap<64, false>::writeval(buffer, namesz);
  2830. elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
  2831. elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
  2832. }
  2833. else
  2834. {
  2835. elfcpp::Swap<64, true>::writeval(buffer, namesz);
  2836. elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
  2837. elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
  2838. }
  2839. }
  2840. else
  2841. gold_unreachable();
  2842. memcpy(buffer + 3 * (size / 8), name, namesz);
  2843. elfcpp::Elf_Xword flags = 0;
  2844. Output_section_order order = ORDER_INVALID;
  2845. if (allocate)
  2846. {
  2847. flags = elfcpp::SHF_ALLOC;
  2848. order = (note_type == elfcpp::NT_GNU_PROPERTY_TYPE_0
  2849. ? ORDER_PROPERTY_NOTE : ORDER_RO_NOTE);
  2850. }
  2851. Output_section* os = this->choose_output_section(NULL, section_name,
  2852. elfcpp::SHT_NOTE,
  2853. flags, false, order, false,
  2854. false, true);
  2855. if (os == NULL)
  2856. return NULL;
  2857. Output_section_data* posd = new Output_data_const_buffer(buffer, notehdrsz,
  2858. addralign,
  2859. "** note header");
  2860. os->add_output_section_data(posd);
  2861. *trailing_padding = aligned_descsz - descsz;
  2862. return os;
  2863. }
  2864. // Create a .note.gnu.property section to record program properties
  2865. // accumulated from the input files.
  2866. void
  2867. Layout::create_gnu_properties_note()
  2868. {
  2869. parameters->target().finalize_gnu_properties(this);
  2870. if (this->gnu_properties_.empty())
  2871. return;
  2872. const unsigned int size = parameters->target().get_size();
  2873. const bool is_big_endian = parameters->target().is_big_endian();
  2874. // Compute the total size of the properties array.
  2875. size_t descsz = 0;
  2876. for (Gnu_properties::const_iterator prop = this->gnu_properties_.begin();
  2877. prop != this->gnu_properties_.end();
  2878. ++prop)
  2879. {
  2880. descsz = align_address(descsz + 8 + prop->second.pr_datasz, size / 8);
  2881. }
  2882. // Create the note section.
  2883. size_t trailing_padding;
  2884. Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_PROPERTY_TYPE_0,
  2885. ".note.gnu.property", descsz,
  2886. true, &trailing_padding);
  2887. if (os == NULL)
  2888. return;
  2889. gold_assert(trailing_padding == 0);
  2890. // Allocate and fill the properties array.
  2891. unsigned char* desc = new unsigned char[descsz];
  2892. unsigned char* p = desc;
  2893. for (Gnu_properties::const_iterator prop = this->gnu_properties_.begin();
  2894. prop != this->gnu_properties_.end();
  2895. ++prop)
  2896. {
  2897. size_t datasz = prop->second.pr_datasz;
  2898. size_t aligned_datasz = align_address(prop->second.pr_datasz, size / 8);
  2899. write_sized_value(prop->first, 4, p, is_big_endian);
  2900. write_sized_value(datasz, 4, p + 4, is_big_endian);
  2901. memcpy(p + 8, prop->second.pr_data, datasz);
  2902. if (aligned_datasz > datasz)
  2903. memset(p + 8 + datasz, 0, aligned_datasz - datasz);
  2904. p += 8 + aligned_datasz;
  2905. }
  2906. Output_section_data* posd = new Output_data_const(desc, descsz, 4);
  2907. os->add_output_section_data(posd);
  2908. }
  2909. // For an executable or shared library, create a note to record the
  2910. // version of gold used to create the binary.
  2911. void
  2912. Layout::create_gold_note()
  2913. {
  2914. if (parameters->options().relocatable()
  2915. || parameters->incremental_update())
  2916. return;
  2917. std::string desc = std::string("gold ") + gold::get_version_string();
  2918. size_t trailing_padding;
  2919. Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_GOLD_VERSION,
  2920. ".note.gnu.gold-version", desc.size(),
  2921. false, &trailing_padding);
  2922. if (os == NULL)
  2923. return;
  2924. Output_section_data* posd = new Output_data_const(desc, 4);
  2925. os->add_output_section_data(posd);
  2926. if (trailing_padding > 0)
  2927. {
  2928. posd = new Output_data_zero_fill(trailing_padding, 0);
  2929. os->add_output_section_data(posd);
  2930. }
  2931. }
  2932. // Record whether the stack should be executable. This can be set
  2933. // from the command line using the -z execstack or -z noexecstack
  2934. // options. Otherwise, if any input file has a .note.GNU-stack
  2935. // section with the SHF_EXECINSTR flag set, the stack should be
  2936. // executable. Otherwise, if at least one input file a
  2937. // .note.GNU-stack section, and some input file has no .note.GNU-stack
  2938. // section, we use the target default for whether the stack should be
  2939. // executable. If -z stack-size was used to set a p_memsz value for
  2940. // PT_GNU_STACK, we generate the segment regardless. Otherwise, we
  2941. // don't generate a stack note. When generating a object file, we
  2942. // create a .note.GNU-stack section with the appropriate marking.
  2943. // When generating an executable or shared library, we create a
  2944. // PT_GNU_STACK segment.
  2945. void
  2946. Layout::create_stack_segment()
  2947. {
  2948. bool is_stack_executable;
  2949. if (parameters->options().is_execstack_set())
  2950. {
  2951. is_stack_executable = parameters->options().is_stack_executable();
  2952. if (!is_stack_executable
  2953. && this->input_requires_executable_stack_
  2954. && parameters->options().warn_execstack())
  2955. gold_warning(_("one or more inputs require executable stack, "
  2956. "but -z noexecstack was given"));
  2957. }
  2958. else if (!this->input_with_gnu_stack_note_
  2959. && (!parameters->options().user_set_stack_size()
  2960. || parameters->options().relocatable()))
  2961. return;
  2962. else
  2963. {
  2964. if (this->input_requires_executable_stack_)
  2965. is_stack_executable = true;
  2966. else if (this->input_without_gnu_stack_note_)
  2967. is_stack_executable =
  2968. parameters->target().is_default_stack_executable();
  2969. else
  2970. is_stack_executable = false;
  2971. }
  2972. if (parameters->options().relocatable())
  2973. {
  2974. const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
  2975. elfcpp::Elf_Xword flags = 0;
  2976. if (is_stack_executable)
  2977. flags |= elfcpp::SHF_EXECINSTR;
  2978. this->make_output_section(name, elfcpp::SHT_PROGBITS, flags,
  2979. ORDER_INVALID, false);
  2980. }
  2981. else
  2982. {
  2983. if (this->script_options_->saw_phdrs_clause())
  2984. return;
  2985. int flags = elfcpp::PF_R | elfcpp::PF_W;
  2986. if (is_stack_executable)
  2987. flags |= elfcpp::PF_X;
  2988. Output_segment* seg =
  2989. this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
  2990. seg->set_size(parameters->options().stack_size());
  2991. // BFD lets targets override this default alignment, but the only
  2992. // targets that do so are ones that Gold does not support so far.
  2993. seg->set_minimum_p_align(16);
  2994. }
  2995. }
  2996. // If --build-id was used, set up the build ID note.
  2997. void
  2998. Layout::create_build_id()
  2999. {
  3000. if (!parameters->options().user_set_build_id())
  3001. return;
  3002. const char* style = parameters->options().build_id();
  3003. if (strcmp(style, "none") == 0)
  3004. return;
  3005. // Set DESCSZ to the size of the note descriptor. When possible,
  3006. // set DESC to the note descriptor contents.
  3007. size_t descsz;
  3008. std::string desc;
  3009. if (strcmp(style, "md5") == 0)
  3010. descsz = 128 / 8;
  3011. else if ((strcmp(style, "sha1") == 0) || (strcmp(style, "tree") == 0))
  3012. descsz = 160 / 8;
  3013. else if (strcmp(style, "uuid") == 0)
  3014. {
  3015. #ifndef __MINGW32__
  3016. const size_t uuidsz = 128 / 8;
  3017. char buffer[uuidsz];
  3018. memset(buffer, 0, uuidsz);
  3019. int descriptor = open_descriptor(-1, "/dev/urandom", O_RDONLY);
  3020. if (descriptor < 0)
  3021. gold_error(_("--build-id=uuid failed: could not open /dev/urandom: %s"),
  3022. strerror(errno));
  3023. else
  3024. {
  3025. ssize_t got = ::read(descriptor, buffer, uuidsz);
  3026. release_descriptor(descriptor, true);
  3027. if (got < 0)
  3028. gold_error(_("/dev/urandom: read failed: %s"), strerror(errno));
  3029. else if (static_cast<size_t>(got) != uuidsz)
  3030. gold_error(_("/dev/urandom: expected %zu bytes, got %zd bytes"),
  3031. uuidsz, got);
  3032. }
  3033. desc.assign(buffer, uuidsz);
  3034. descsz = uuidsz;
  3035. #else // __MINGW32__
  3036. UUID uuid;
  3037. typedef RPC_STATUS (RPC_ENTRY *UuidCreateFn)(UUID *Uuid);
  3038. HMODULE rpc_library = LoadLibrary("rpcrt4.dll");
  3039. if (!rpc_library)
  3040. gold_error(_("--build-id=uuid failed: could not load rpcrt4.dll"));
  3041. else
  3042. {
  3043. UuidCreateFn uuid_create = reinterpret_cast<UuidCreateFn>(
  3044. GetProcAddress(rpc_library, "UuidCreate"));
  3045. if (!uuid_create)
  3046. gold_error(_("--build-id=uuid failed: could not find UuidCreate"));
  3047. else if (uuid_create(&uuid) != RPC_S_OK)
  3048. gold_error(_("__build_id=uuid failed: call UuidCreate() failed"));
  3049. FreeLibrary(rpc_library);
  3050. }
  3051. desc.assign(reinterpret_cast<const char *>(&uuid), sizeof(UUID));
  3052. descsz = sizeof(UUID);
  3053. #endif // __MINGW32__
  3054. }
  3055. else if (strncmp(style, "0x", 2) == 0)
  3056. {
  3057. hex_init();
  3058. const char* p = style + 2;
  3059. while (*p != '\0')
  3060. {
  3061. if (hex_p(p[0]) && hex_p(p[1]))
  3062. {
  3063. char c = (hex_value(p[0]) << 4) | hex_value(p[1]);
  3064. desc += c;
  3065. p += 2;
  3066. }
  3067. else if (*p == '-' || *p == ':')
  3068. ++p;
  3069. else
  3070. gold_fatal(_("--build-id argument '%s' not a valid hex number"),
  3071. style);
  3072. }
  3073. descsz = desc.size();
  3074. }
  3075. else
  3076. gold_fatal(_("unrecognized --build-id argument '%s'"), style);
  3077. // Create the note.
  3078. size_t trailing_padding;
  3079. Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_BUILD_ID,
  3080. ".note.gnu.build-id", descsz, true,
  3081. &trailing_padding);
  3082. if (os == NULL)
  3083. return;
  3084. if (!desc.empty())
  3085. {
  3086. // We know the value already, so we fill it in now.
  3087. gold_assert(desc.size() == descsz);
  3088. Output_section_data* posd = new Output_data_const(desc, 4);
  3089. os->add_output_section_data(posd);
  3090. if (trailing_padding != 0)
  3091. {
  3092. posd = new Output_data_zero_fill(trailing_padding, 0);
  3093. os->add_output_section_data(posd);
  3094. }
  3095. }
  3096. else
  3097. {
  3098. // We need to compute a checksum after we have completed the
  3099. // link.
  3100. gold_assert(trailing_padding == 0);
  3101. this->build_id_note_ = new Output_data_zero_fill(descsz, 4);
  3102. os->add_output_section_data(this->build_id_note_);
  3103. }
  3104. }
  3105. // If we have both .stabXX and .stabXXstr sections, then the sh_link
  3106. // field of the former should point to the latter. I'm not sure who
  3107. // started this, but the GNU linker does it, and some tools depend
  3108. // upon it.
  3109. void
  3110. Layout::link_stabs_sections()
  3111. {
  3112. if (!this->have_stabstr_section_)
  3113. return;
  3114. for (Section_list::iterator p = this->section_list_.begin();
  3115. p != this->section_list_.end();
  3116. ++p)
  3117. {
  3118. if ((*p)->type() != elfcpp::SHT_STRTAB)
  3119. continue;
  3120. const char* name = (*p)->name();
  3121. if (strncmp(name, ".stab", 5) != 0)
  3122. continue;
  3123. size_t len = strlen(name);
  3124. if (strcmp(name + len - 3, "str") != 0)
  3125. continue;
  3126. std::string stab_name(name, len - 3);
  3127. Output_section* stab_sec;
  3128. stab_sec = this->find_output_section(stab_name.c_str());
  3129. if (stab_sec != NULL)
  3130. stab_sec->set_link_section(*p);
  3131. }
  3132. }
  3133. // Create .gnu_incremental_inputs and related sections needed
  3134. // for the next run of incremental linking to check what has changed.
  3135. void
  3136. Layout::create_incremental_info_sections(Symbol_table* symtab)
  3137. {
  3138. Incremental_inputs* incr = this->incremental_inputs_;
  3139. gold_assert(incr != NULL);
  3140. // Create the .gnu_incremental_inputs, _symtab, and _relocs input sections.
  3141. incr->create_data_sections(symtab);
  3142. // Add the .gnu_incremental_inputs section.
  3143. const char* incremental_inputs_name =
  3144. this->namepool_.add(".gnu_incremental_inputs", false, NULL);
  3145. Output_section* incremental_inputs_os =
  3146. this->make_output_section(incremental_inputs_name,
  3147. elfcpp::SHT_GNU_INCREMENTAL_INPUTS, 0,
  3148. ORDER_INVALID, false);
  3149. incremental_inputs_os->add_output_section_data(incr->inputs_section());
  3150. // Add the .gnu_incremental_symtab section.
  3151. const char* incremental_symtab_name =
  3152. this->namepool_.add(".gnu_incremental_symtab", false, NULL);
  3153. Output_section* incremental_symtab_os =
  3154. this->make_output_section(incremental_symtab_name,
  3155. elfcpp::SHT_GNU_INCREMENTAL_SYMTAB, 0,
  3156. ORDER_INVALID, false);
  3157. incremental_symtab_os->add_output_section_data(incr->symtab_section());
  3158. incremental_symtab_os->set_entsize(4);
  3159. // Add the .gnu_incremental_relocs section.
  3160. const char* incremental_relocs_name =
  3161. this->namepool_.add(".gnu_incremental_relocs", false, NULL);
  3162. Output_section* incremental_relocs_os =
  3163. this->make_output_section(incremental_relocs_name,
  3164. elfcpp::SHT_GNU_INCREMENTAL_RELOCS, 0,
  3165. ORDER_INVALID, false);
  3166. incremental_relocs_os->add_output_section_data(incr->relocs_section());
  3167. incremental_relocs_os->set_entsize(incr->relocs_entsize());
  3168. // Add the .gnu_incremental_got_plt section.
  3169. const char* incremental_got_plt_name =
  3170. this->namepool_.add(".gnu_incremental_got_plt", false, NULL);
  3171. Output_section* incremental_got_plt_os =
  3172. this->make_output_section(incremental_got_plt_name,
  3173. elfcpp::SHT_GNU_INCREMENTAL_GOT_PLT, 0,
  3174. ORDER_INVALID, false);
  3175. incremental_got_plt_os->add_output_section_data(incr->got_plt_section());
  3176. // Add the .gnu_incremental_strtab section.
  3177. const char* incremental_strtab_name =
  3178. this->namepool_.add(".gnu_incremental_strtab", false, NULL);
  3179. Output_section* incremental_strtab_os = this->make_output_section(incremental_strtab_name,
  3180. elfcpp::SHT_STRTAB, 0,
  3181. ORDER_INVALID, false);
  3182. Output_data_strtab* strtab_data =
  3183. new Output_data_strtab(incr->get_stringpool());
  3184. incremental_strtab_os->add_output_section_data(strtab_data);
  3185. incremental_inputs_os->set_after_input_sections();
  3186. incremental_symtab_os->set_after_input_sections();
  3187. incremental_relocs_os->set_after_input_sections();
  3188. incremental_got_plt_os->set_after_input_sections();
  3189. incremental_inputs_os->set_link_section(incremental_strtab_os);
  3190. incremental_symtab_os->set_link_section(incremental_inputs_os);
  3191. incremental_relocs_os->set_link_section(incremental_inputs_os);
  3192. incremental_got_plt_os->set_link_section(incremental_inputs_os);
  3193. }
  3194. // Return whether SEG1 should be before SEG2 in the output file. This
  3195. // is based entirely on the segment type and flags. When this is
  3196. // called the segment addresses have normally not yet been set.
  3197. bool
  3198. Layout::segment_precedes(const Output_segment* seg1,
  3199. const Output_segment* seg2)
  3200. {
  3201. // In order to produce a stable ordering if we're called with the same pointer
  3202. // return false.
  3203. if (seg1 == seg2)
  3204. return false;
  3205. elfcpp::Elf_Word type1 = seg1->type();
  3206. elfcpp::Elf_Word type2 = seg2->type();
  3207. // The single PT_PHDR segment is required to precede any loadable
  3208. // segment. We simply make it always first.
  3209. if (type1 == elfcpp::PT_PHDR)
  3210. {
  3211. gold_assert(type2 != elfcpp::PT_PHDR);
  3212. return true;
  3213. }
  3214. if (type2 == elfcpp::PT_PHDR)
  3215. return false;
  3216. // The single PT_INTERP segment is required to precede any loadable
  3217. // segment. We simply make it always second.
  3218. if (type1 == elfcpp::PT_INTERP)
  3219. {
  3220. gold_assert(type2 != elfcpp::PT_INTERP);
  3221. return true;
  3222. }
  3223. if (type2 == elfcpp::PT_INTERP)
  3224. return false;
  3225. // We then put PT_LOAD segments before any other segments.
  3226. if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
  3227. return true;
  3228. if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
  3229. return false;
  3230. // We put the PT_TLS segment last except for the PT_GNU_RELRO
  3231. // segment, because that is where the dynamic linker expects to find
  3232. // it (this is just for efficiency; other positions would also work
  3233. // correctly).
  3234. if (type1 == elfcpp::PT_TLS
  3235. && type2 != elfcpp::PT_TLS
  3236. && type2 != elfcpp::PT_GNU_RELRO)
  3237. return false;
  3238. if (type2 == elfcpp::PT_TLS
  3239. && type1 != elfcpp::PT_TLS
  3240. && type1 != elfcpp::PT_GNU_RELRO)
  3241. return true;
  3242. // We put the PT_GNU_RELRO segment last, because that is where the
  3243. // dynamic linker expects to find it (as with PT_TLS, this is just
  3244. // for efficiency).
  3245. if (type1 == elfcpp::PT_GNU_RELRO && type2 != elfcpp::PT_GNU_RELRO)
  3246. return false;
  3247. if (type2 == elfcpp::PT_GNU_RELRO && type1 != elfcpp::PT_GNU_RELRO)
  3248. return true;
  3249. const elfcpp::Elf_Word flags1 = seg1->flags();
  3250. const elfcpp::Elf_Word flags2 = seg2->flags();
  3251. // The order of non-PT_LOAD segments is unimportant. We simply sort
  3252. // by the numeric segment type and flags values. There should not
  3253. // be more than one segment with the same type and flags, except
  3254. // when a linker script specifies such.
  3255. if (type1 != elfcpp::PT_LOAD)
  3256. {
  3257. if (type1 != type2)
  3258. return type1 < type2;
  3259. uint64_t align1 = seg1->align();
  3260. uint64_t align2 = seg2->align();
  3261. // Place segments with larger alignments first.
  3262. if (align1 != align2)
  3263. return align1 > align2;
  3264. gold_assert(flags1 != flags2
  3265. || this->script_options_->saw_phdrs_clause());
  3266. return flags1 < flags2;
  3267. }
  3268. // If the addresses are set already, sort by load address.
  3269. if (seg1->are_addresses_set())
  3270. {
  3271. if (!seg2->are_addresses_set())
  3272. return true;
  3273. unsigned int section_count1 = seg1->output_section_count();
  3274. unsigned int section_count2 = seg2->output_section_count();
  3275. if (section_count1 == 0 && section_count2 > 0)
  3276. return true;
  3277. if (section_count1 > 0 && section_count2 == 0)
  3278. return false;
  3279. uint64_t paddr1 = (seg1->are_addresses_set()
  3280. ? seg1->paddr()
  3281. : seg1->first_section_load_address());
  3282. uint64_t paddr2 = (seg2->are_addresses_set()
  3283. ? seg2->paddr()
  3284. : seg2->first_section_load_address());
  3285. if (paddr1 != paddr2)
  3286. return paddr1 < paddr2;
  3287. }
  3288. else if (seg2->are_addresses_set())
  3289. return false;
  3290. // A segment which holds large data comes after a segment which does
  3291. // not hold large data.
  3292. if (seg1->is_large_data_segment())
  3293. {
  3294. if (!seg2->is_large_data_segment())
  3295. return false;
  3296. }
  3297. else if (seg2->is_large_data_segment())
  3298. return true;
  3299. // Otherwise, we sort PT_LOAD segments based on the flags. Readonly
  3300. // segments come before writable segments. Then writable segments
  3301. // with data come before writable segments without data. Then
  3302. // executable segments come before non-executable segments. Then
  3303. // the unlikely case of a non-readable segment comes before the
  3304. // normal case of a readable segment. If there are multiple
  3305. // segments with the same type and flags, we require that the
  3306. // address be set, and we sort by virtual address and then physical
  3307. // address.
  3308. if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
  3309. return (flags1 & elfcpp::PF_W) == 0;
  3310. if ((flags1 & elfcpp::PF_W) != 0
  3311. && seg1->has_any_data_sections() != seg2->has_any_data_sections())
  3312. return seg1->has_any_data_sections();
  3313. if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
  3314. return (flags1 & elfcpp::PF_X) != 0;
  3315. if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
  3316. return (flags1 & elfcpp::PF_R) == 0;
  3317. // We shouldn't get here--we shouldn't create segments which we
  3318. // can't distinguish. Unless of course we are using a weird linker
  3319. // script or overlapping --section-start options. We could also get
  3320. // here if plugins want unique segments for subsets of sections.
  3321. gold_assert(this->script_options_->saw_phdrs_clause()
  3322. || parameters->options().any_section_start()
  3323. || this->is_unique_segment_for_sections_specified()
  3324. || parameters->options().text_unlikely_segment());
  3325. return false;
  3326. }
  3327. // Increase OFF so that it is congruent to ADDR modulo ABI_PAGESIZE.
  3328. static off_t
  3329. align_file_offset(off_t off, uint64_t addr, uint64_t abi_pagesize)
  3330. {
  3331. uint64_t unsigned_off = off;
  3332. uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
  3333. | (addr & (abi_pagesize - 1)));
  3334. if (aligned_off < unsigned_off)
  3335. aligned_off += abi_pagesize;
  3336. return aligned_off;
  3337. }
  3338. // On targets where the text segment contains only executable code,
  3339. // a non-executable segment is never the text segment.
  3340. static inline bool
  3341. is_text_segment(const Target* target, const Output_segment* seg)
  3342. {
  3343. elfcpp::Elf_Xword flags = seg->flags();
  3344. if ((flags & elfcpp::PF_W) != 0)
  3345. return false;
  3346. if ((flags & elfcpp::PF_X) == 0)
  3347. return !target->isolate_execinstr();
  3348. return true;
  3349. }
  3350. // Set the file offsets of all the segments, and all the sections they
  3351. // contain. They have all been created. LOAD_SEG must be laid out
  3352. // first. Return the offset of the data to follow.
  3353. off_t
  3354. Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
  3355. unsigned int* pshndx)
  3356. {
  3357. // Sort them into the final order. We use a stable sort so that we
  3358. // don't randomize the order of indistinguishable segments created
  3359. // by linker scripts.
  3360. std::stable_sort(this->segment_list_.begin(), this->segment_list_.end(),
  3361. Layout::Compare_segments(this));
  3362. // Find the PT_LOAD segments, and set their addresses and offsets
  3363. // and their section's addresses and offsets.
  3364. uint64_t start_addr;
  3365. if (parameters->options().user_set_Ttext())
  3366. start_addr = parameters->options().Ttext();
  3367. else if (parameters->options().output_is_position_independent())
  3368. start_addr = 0;
  3369. else
  3370. start_addr = target->default_text_segment_address();
  3371. uint64_t addr = start_addr;
  3372. off_t off = 0;
  3373. // If LOAD_SEG is NULL, then the file header and segment headers
  3374. // will not be loadable. But they still need to be at offset 0 in
  3375. // the file. Set their offsets now.
  3376. if (load_seg == NULL)
  3377. {
  3378. for (Data_list::iterator p = this->special_output_list_.begin();
  3379. p != this->special_output_list_.end();
  3380. ++p)
  3381. {
  3382. off = align_address(off, (*p)->addralign());
  3383. (*p)->set_address_and_file_offset(0, off);
  3384. off += (*p)->data_size();
  3385. }
  3386. }
  3387. unsigned int increase_relro = this->increase_relro_;
  3388. if (this->script_options_->saw_sections_clause())
  3389. increase_relro = 0;
  3390. const bool check_sections = parameters->options().check_sections();
  3391. Output_segment* last_load_segment = NULL;
  3392. unsigned int shndx_begin = *pshndx;
  3393. unsigned int shndx_load_seg = *pshndx;
  3394. for (Segment_list::iterator p = this->segment_list_.begin();
  3395. p != this->segment_list_.end();
  3396. ++p)
  3397. {
  3398. if ((*p)->type() == elfcpp::PT_LOAD)
  3399. {
  3400. if (target->isolate_execinstr())
  3401. {
  3402. // When we hit the segment that should contain the
  3403. // file headers, reset the file offset so we place
  3404. // it and subsequent segments appropriately.
  3405. // We'll fix up the preceding segments below.
  3406. if (load_seg == *p)
  3407. {
  3408. if (off == 0)
  3409. load_seg = NULL;
  3410. else
  3411. {
  3412. off = 0;
  3413. shndx_load_seg = *pshndx;
  3414. }
  3415. }
  3416. }
  3417. else
  3418. {
  3419. // Verify that the file headers fall into the first segment.
  3420. if (load_seg != NULL && load_seg != *p)
  3421. gold_unreachable();
  3422. load_seg = NULL;
  3423. }
  3424. bool are_addresses_set = (*p)->are_addresses_set();
  3425. if (are_addresses_set)
  3426. {
  3427. // When it comes to setting file offsets, we care about
  3428. // the physical address.
  3429. addr = (*p)->paddr();
  3430. }
  3431. else if (parameters->options().user_set_Ttext()
  3432. && (parameters->options().omagic()
  3433. || is_text_segment(target, *p)))
  3434. {
  3435. are_addresses_set = true;
  3436. }
  3437. else if (parameters->options().user_set_Trodata_segment()
  3438. && ((*p)->flags() & (elfcpp::PF_W | elfcpp::PF_X)) == 0)
  3439. {
  3440. addr = parameters->options().Trodata_segment();
  3441. are_addresses_set = true;
  3442. }
  3443. else if (parameters->options().user_set_Tdata()
  3444. && ((*p)->flags() & elfcpp::PF_W) != 0
  3445. && (!parameters->options().user_set_Tbss()
  3446. || (*p)->has_any_data_sections()))
  3447. {
  3448. addr = parameters->options().Tdata();
  3449. are_addresses_set = true;
  3450. }
  3451. else if (parameters->options().user_set_Tbss()
  3452. && ((*p)->flags() & elfcpp::PF_W) != 0
  3453. && !(*p)->has_any_data_sections())
  3454. {
  3455. addr = parameters->options().Tbss();
  3456. are_addresses_set = true;
  3457. }
  3458. uint64_t orig_addr = addr;
  3459. uint64_t orig_off = off;
  3460. uint64_t aligned_addr = 0;
  3461. uint64_t abi_pagesize = target->abi_pagesize();
  3462. uint64_t common_pagesize = target->common_pagesize();
  3463. if (!parameters->options().nmagic()
  3464. && !parameters->options().omagic())
  3465. (*p)->set_minimum_p_align(abi_pagesize);
  3466. if (!are_addresses_set)
  3467. {
  3468. // Skip the address forward one page, maintaining the same
  3469. // position within the page. This lets us store both segments
  3470. // overlapping on a single page in the file, but the loader will
  3471. // put them on different pages in memory. We will revisit this
  3472. // decision once we know the size of the segment.
  3473. uint64_t max_align = (*p)->maximum_alignment();
  3474. if (max_align > abi_pagesize)
  3475. addr = align_address(addr, max_align);
  3476. aligned_addr = addr;
  3477. if (load_seg == *p)
  3478. {
  3479. // This is the segment that will contain the file
  3480. // headers, so its offset will have to be exactly zero.
  3481. gold_assert(orig_off == 0);
  3482. // If the target wants a fixed minimum distance from the
  3483. // text segment to the read-only segment, move up now.
  3484. uint64_t min_addr =
  3485. start_addr + (parameters->options().user_set_rosegment_gap()
  3486. ? parameters->options().rosegment_gap()
  3487. : target->rosegment_gap());
  3488. if (addr < min_addr)
  3489. addr = min_addr;
  3490. // But this is not the first segment! To make its
  3491. // address congruent with its offset, that address better
  3492. // be aligned to the ABI-mandated page size.
  3493. addr = align_address(addr, abi_pagesize);
  3494. aligned_addr = addr;
  3495. }
  3496. else
  3497. {
  3498. if ((addr & (abi_pagesize - 1)) != 0)
  3499. addr = addr + abi_pagesize;
  3500. off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
  3501. }
  3502. }
  3503. if (!parameters->options().nmagic()
  3504. && !parameters->options().omagic())
  3505. {
  3506. // Here we are also taking care of the case when
  3507. // the maximum segment alignment is larger than the page size.
  3508. off = align_file_offset(off, addr,
  3509. std::max(abi_pagesize,
  3510. (*p)->maximum_alignment()));
  3511. }
  3512. else
  3513. {
  3514. // This is -N or -n with a section script which prevents
  3515. // us from using a load segment. We need to ensure that
  3516. // the file offset is aligned to the alignment of the
  3517. // segment. This is because the linker script
  3518. // implicitly assumed a zero offset. If we don't align
  3519. // here, then the alignment of the sections in the
  3520. // linker script may not match the alignment of the
  3521. // sections in the set_section_addresses call below,
  3522. // causing an error about dot moving backward.
  3523. off = align_address(off, (*p)->maximum_alignment());
  3524. }
  3525. unsigned int shndx_hold = *pshndx;
  3526. bool has_relro = false;
  3527. uint64_t new_addr = (*p)->set_section_addresses(target, this,
  3528. false, addr,
  3529. &increase_relro,
  3530. &has_relro,
  3531. &off, pshndx);
  3532. // Now that we know the size of this segment, we may be able
  3533. // to save a page in memory, at the cost of wasting some
  3534. // file space, by instead aligning to the start of a new
  3535. // page. Here we use the real machine page size rather than
  3536. // the ABI mandated page size. If the segment has been
  3537. // aligned so that the relro data ends at a page boundary,
  3538. // we do not try to realign it.
  3539. if (!are_addresses_set
  3540. && !has_relro
  3541. && aligned_addr != addr
  3542. && !parameters->incremental())
  3543. {
  3544. uint64_t first_off = (common_pagesize
  3545. - (aligned_addr
  3546. & (common_pagesize - 1)));
  3547. uint64_t last_off = new_addr & (common_pagesize - 1);
  3548. if (first_off > 0
  3549. && last_off > 0
  3550. && ((aligned_addr & ~ (common_pagesize - 1))
  3551. != (new_addr & ~ (common_pagesize - 1)))
  3552. && first_off + last_off <= common_pagesize)
  3553. {
  3554. *pshndx = shndx_hold;
  3555. addr = align_address(aligned_addr, common_pagesize);
  3556. addr = align_address(addr, (*p)->maximum_alignment());
  3557. if ((addr & (abi_pagesize - 1)) != 0)
  3558. addr = addr + abi_pagesize;
  3559. off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
  3560. off = align_file_offset(off, addr, abi_pagesize);
  3561. increase_relro = this->increase_relro_;
  3562. if (this->script_options_->saw_sections_clause())
  3563. increase_relro = 0;
  3564. has_relro = false;
  3565. new_addr = (*p)->set_section_addresses(target, this,
  3566. true, addr,
  3567. &increase_relro,
  3568. &has_relro,
  3569. &off, pshndx);
  3570. }
  3571. }
  3572. addr = new_addr;
  3573. // Implement --check-sections. We know that the segments
  3574. // are sorted by LMA.
  3575. if (check_sections && last_load_segment != NULL)
  3576. {
  3577. gold_assert(last_load_segment->paddr() <= (*p)->paddr());
  3578. if (last_load_segment->paddr() + last_load_segment->memsz()
  3579. > (*p)->paddr())
  3580. {
  3581. unsigned long long lb1 = last_load_segment->paddr();
  3582. unsigned long long le1 = lb1 + last_load_segment->memsz();
  3583. unsigned long long lb2 = (*p)->paddr();
  3584. unsigned long long le2 = lb2 + (*p)->memsz();
  3585. gold_error(_("load segment overlap [0x%llx -> 0x%llx] and "
  3586. "[0x%llx -> 0x%llx]"),
  3587. lb1, le1, lb2, le2);
  3588. }
  3589. }
  3590. last_load_segment = *p;
  3591. }
  3592. }
  3593. if (load_seg != NULL && target->isolate_execinstr())
  3594. {
  3595. // Process the early segments again, setting their file offsets
  3596. // so they land after the segments starting at LOAD_SEG.
  3597. off = align_file_offset(off, 0, target->abi_pagesize());
  3598. this->reset_relax_output();
  3599. for (Segment_list::iterator p = this->segment_list_.begin();
  3600. *p != load_seg;
  3601. ++p)
  3602. {
  3603. if ((*p)->type() == elfcpp::PT_LOAD)
  3604. {
  3605. // We repeat the whole job of assigning addresses and
  3606. // offsets, but we really only want to change the offsets and
  3607. // must ensure that the addresses all come out the same as
  3608. // they did the first time through.
  3609. bool has_relro = false;
  3610. const uint64_t old_addr = (*p)->vaddr();
  3611. const uint64_t old_end = old_addr + (*p)->memsz();
  3612. uint64_t new_addr = (*p)->set_section_addresses(target, this,
  3613. true, old_addr,
  3614. &increase_relro,
  3615. &has_relro,
  3616. &off,
  3617. &shndx_begin);
  3618. gold_assert(new_addr == old_end);
  3619. }
  3620. }
  3621. gold_assert(shndx_begin == shndx_load_seg);
  3622. }
  3623. // Handle the non-PT_LOAD segments, setting their offsets from their
  3624. // section's offsets.
  3625. for (Segment_list::iterator p = this->segment_list_.begin();
  3626. p != this->segment_list_.end();
  3627. ++p)
  3628. {
  3629. // PT_GNU_STACK was set up correctly when it was created.
  3630. if ((*p)->type() != elfcpp::PT_LOAD
  3631. && (*p)->type() != elfcpp::PT_GNU_STACK)
  3632. (*p)->set_offset((*p)->type() == elfcpp::PT_GNU_RELRO
  3633. ? increase_relro
  3634. : 0);
  3635. }
  3636. // Set the TLS offsets for each section in the PT_TLS segment.
  3637. if (this->tls_segment_ != NULL)
  3638. this->tls_segment_->set_tls_offsets();
  3639. return off;
  3640. }
  3641. // Set the offsets of all the allocated sections when doing a
  3642. // relocatable link. This does the same jobs as set_segment_offsets,
  3643. // only for a relocatable link.
  3644. off_t
  3645. Layout::set_relocatable_section_offsets(Output_data* file_header,
  3646. unsigned int* pshndx)
  3647. {
  3648. off_t off = 0;
  3649. file_header->set_address_and_file_offset(0, 0);
  3650. off += file_header->data_size();
  3651. for (Section_list::iterator p = this->section_list_.begin();
  3652. p != this->section_list_.end();
  3653. ++p)
  3654. {
  3655. // We skip unallocated sections here, except that group sections
  3656. // have to come first.
  3657. if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
  3658. && (*p)->type() != elfcpp::SHT_GROUP)
  3659. continue;
  3660. off = align_address(off, (*p)->addralign());
  3661. // The linker script might have set the address.
  3662. if (!(*p)->is_address_valid())
  3663. (*p)->set_address(0);
  3664. (*p)->set_file_offset(off);
  3665. (*p)->finalize_data_size();
  3666. if ((*p)->type() != elfcpp::SHT_NOBITS)
  3667. off += (*p)->data_size();
  3668. (*p)->set_out_shndx(*pshndx);
  3669. ++*pshndx;
  3670. }
  3671. return off;
  3672. }
  3673. // Set the file offset of all the sections not associated with a
  3674. // segment.
  3675. off_t
  3676. Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
  3677. {
  3678. off_t startoff = off;
  3679. off_t maxoff = off;
  3680. for (Section_list::iterator p = this->unattached_section_list_.begin();
  3681. p != this->unattached_section_list_.end();
  3682. ++p)
  3683. {
  3684. // The symtab section is handled in create_symtab_sections.
  3685. if (*p == this->symtab_section_)
  3686. continue;
  3687. // If we've already set the data size, don't set it again.
  3688. if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
  3689. continue;
  3690. if (pass == BEFORE_INPUT_SECTIONS_PASS
  3691. && (*p)->requires_postprocessing())
  3692. {
  3693. (*p)->create_postprocessing_buffer();
  3694. this->any_postprocessing_sections_ = true;
  3695. }
  3696. if (pass == BEFORE_INPUT_SECTIONS_PASS
  3697. && (*p)->after_input_sections())
  3698. continue;
  3699. else if (pass == POSTPROCESSING_SECTIONS_PASS
  3700. && (!(*p)->after_input_sections()
  3701. || (*p)->type() == elfcpp::SHT_STRTAB))
  3702. continue;
  3703. else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
  3704. && (!(*p)->after_input_sections()
  3705. || (*p)->type() != elfcpp::SHT_STRTAB))
  3706. continue;
  3707. if (!parameters->incremental_update())
  3708. {
  3709. off = align_address(off, (*p)->addralign());
  3710. (*p)->set_file_offset(off);
  3711. (*p)->finalize_data_size();
  3712. }
  3713. else
  3714. {
  3715. // Incremental update: allocate file space from free list.
  3716. (*p)->pre_finalize_data_size();
  3717. off_t current_size = (*p)->current_data_size();
  3718. off = this->allocate(current_size, (*p)->addralign(), startoff);
  3719. if (off == -1)
  3720. {
  3721. if (is_debugging_enabled(DEBUG_INCREMENTAL))
  3722. this->free_list_.dump();
  3723. gold_assert((*p)->output_section() != NULL);
  3724. gold_fallback(_("out of patch space for section %s; "
  3725. "relink with --incremental-full"),
  3726. (*p)->output_section()->name());
  3727. }
  3728. (*p)->set_file_offset(off);
  3729. (*p)->finalize_data_size();
  3730. if ((*p)->data_size() > current_size)
  3731. {
  3732. gold_assert((*p)->output_section() != NULL);
  3733. gold_fallback(_("%s: section changed size; "
  3734. "relink with --incremental-full"),
  3735. (*p)->output_section()->name());
  3736. }
  3737. gold_debug(DEBUG_INCREMENTAL,
  3738. "set_section_offsets: %08lx %08lx %s",
  3739. static_cast<long>(off),
  3740. static_cast<long>((*p)->data_size()),
  3741. ((*p)->output_section() != NULL
  3742. ? (*p)->output_section()->name() : "(special)"));
  3743. }
  3744. off += (*p)->data_size();
  3745. if (off > maxoff)
  3746. maxoff = off;
  3747. // At this point the name must be set.
  3748. if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
  3749. this->namepool_.add((*p)->name(), false, NULL);
  3750. }
  3751. return maxoff;
  3752. }
  3753. // Set the section indexes of all the sections not associated with a
  3754. // segment.
  3755. unsigned int
  3756. Layout::set_section_indexes(unsigned int shndx)
  3757. {
  3758. for (Section_list::iterator p = this->unattached_section_list_.begin();
  3759. p != this->unattached_section_list_.end();
  3760. ++p)
  3761. {
  3762. if (!(*p)->has_out_shndx())
  3763. {
  3764. (*p)->set_out_shndx(shndx);
  3765. ++shndx;
  3766. }
  3767. }
  3768. return shndx;
  3769. }
  3770. // Set the section addresses according to the linker script. This is
  3771. // only called when we see a SECTIONS clause. This returns the
  3772. // program segment which should hold the file header and segment
  3773. // headers, if any. It will return NULL if they should not be in a
  3774. // segment.
  3775. Output_segment*
  3776. Layout::set_section_addresses_from_script(Symbol_table* symtab)
  3777. {
  3778. Script_sections* ss = this->script_options_->script_sections();
  3779. gold_assert(ss->saw_sections_clause());
  3780. return this->script_options_->set_section_addresses(symtab, this);
  3781. }
  3782. // Place the orphan sections in the linker script.
  3783. void
  3784. Layout::place_orphan_sections_in_script()
  3785. {
  3786. Script_sections* ss = this->script_options_->script_sections();
  3787. gold_assert(ss->saw_sections_clause());
  3788. // Place each orphaned output section in the script.
  3789. for (Section_list::iterator p = this->section_list_.begin();
  3790. p != this->section_list_.end();
  3791. ++p)
  3792. {
  3793. if (!(*p)->found_in_sections_clause())
  3794. ss->place_orphan(*p);
  3795. }
  3796. }
  3797. // Count the local symbols in the regular symbol table and the dynamic
  3798. // symbol table, and build the respective string pools.
  3799. void
  3800. Layout::count_local_symbols(const Task* task,
  3801. const Input_objects* input_objects)
  3802. {
  3803. // First, figure out an upper bound on the number of symbols we'll
  3804. // be inserting into each pool. This helps us create the pools with
  3805. // the right size, to avoid unnecessary hashtable resizing.
  3806. unsigned int symbol_count = 0;
  3807. for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
  3808. p != input_objects->relobj_end();
  3809. ++p)
  3810. symbol_count += (*p)->local_symbol_count();
  3811. // Go from "upper bound" to "estimate." We overcount for two
  3812. // reasons: we double-count symbols that occur in more than one
  3813. // object file, and we count symbols that are dropped from the
  3814. // output. Add it all together and assume we overcount by 100%.
  3815. symbol_count /= 2;
  3816. // We assume all symbols will go into both the sympool and dynpool.
  3817. this->sympool_.reserve(symbol_count);
  3818. this->dynpool_.reserve(symbol_count);
  3819. for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
  3820. p != input_objects->relobj_end();
  3821. ++p)
  3822. {
  3823. Task_lock_obj<Object> tlo(task, *p);
  3824. (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
  3825. }
  3826. }
  3827. // Create the symbol table sections. Here we also set the final
  3828. // values of the symbols. At this point all the loadable sections are
  3829. // fully laid out. SHNUM is the number of sections so far.
  3830. void
  3831. Layout::create_symtab_sections(const Input_objects* input_objects,
  3832. Symbol_table* symtab,
  3833. unsigned int shnum,
  3834. off_t* poff,
  3835. unsigned int local_dynamic_count)
  3836. {
  3837. int symsize;
  3838. unsigned int align;
  3839. if (parameters->target().get_size() == 32)
  3840. {
  3841. symsize = elfcpp::Elf_sizes<32>::sym_size;
  3842. align = 4;
  3843. }
  3844. else if (parameters->target().get_size() == 64)
  3845. {
  3846. symsize = elfcpp::Elf_sizes<64>::sym_size;
  3847. align = 8;
  3848. }
  3849. else
  3850. gold_unreachable();
  3851. // Compute file offsets relative to the start of the symtab section.
  3852. off_t off = 0;
  3853. // Save space for the dummy symbol at the start of the section. We
  3854. // never bother to write this out--it will just be left as zero.
  3855. off += symsize;
  3856. unsigned int local_symbol_index = 1;
  3857. // Add STT_SECTION symbols for each Output section which needs one.
  3858. for (Section_list::iterator p = this->section_list_.begin();
  3859. p != this->section_list_.end();
  3860. ++p)
  3861. {
  3862. if (!(*p)->needs_symtab_index())
  3863. (*p)->set_symtab_index(-1U);
  3864. else
  3865. {
  3866. (*p)->set_symtab_index(local_symbol_index);
  3867. ++local_symbol_index;
  3868. off += symsize;
  3869. }
  3870. }
  3871. for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
  3872. p != input_objects->relobj_end();
  3873. ++p)
  3874. {
  3875. unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
  3876. off, symtab);
  3877. off += (index - local_symbol_index) * symsize;
  3878. local_symbol_index = index;
  3879. }
  3880. unsigned int local_symcount = local_symbol_index;
  3881. gold_assert(static_cast<off_t>(local_symcount * symsize) == off);
  3882. off_t dynoff;
  3883. size_t dyncount;
  3884. if (this->dynsym_section_ == NULL)
  3885. {
  3886. dynoff = 0;
  3887. dyncount = 0;
  3888. }
  3889. else
  3890. {
  3891. off_t locsize = local_dynamic_count * this->dynsym_section_->entsize();
  3892. dynoff = this->dynsym_section_->offset() + locsize;
  3893. dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
  3894. gold_assert(static_cast<off_t>(dyncount * symsize)
  3895. == this->dynsym_section_->data_size() - locsize);
  3896. }
  3897. off_t global_off = off;
  3898. off = symtab->finalize(off, dynoff, local_dynamic_count, dyncount,
  3899. &this->sympool_, &local_symcount);
  3900. if (!parameters->options().strip_all())
  3901. {
  3902. this->sympool_.set_string_offsets();
  3903. const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
  3904. Output_section* osymtab = this->make_output_section(symtab_name,
  3905. elfcpp::SHT_SYMTAB,
  3906. 0, ORDER_INVALID,
  3907. false);
  3908. this->symtab_section_ = osymtab;
  3909. Output_section_data* pos = new Output_data_fixed_space(off, align,
  3910. "** symtab");
  3911. osymtab->add_output_section_data(pos);
  3912. // We generate a .symtab_shndx section if we have more than
  3913. // SHN_LORESERVE sections. Technically it is possible that we
  3914. // don't need one, because it is possible that there are no
  3915. // symbols in any of sections with indexes larger than
  3916. // SHN_LORESERVE. That is probably unusual, though, and it is
  3917. // easier to always create one than to compute section indexes
  3918. // twice (once here, once when writing out the symbols).
  3919. if (shnum >= elfcpp::SHN_LORESERVE)
  3920. {
  3921. const char* symtab_xindex_name = this->namepool_.add(".symtab_shndx",
  3922. false, NULL);
  3923. Output_section* osymtab_xindex =
  3924. this->make_output_section(symtab_xindex_name,
  3925. elfcpp::SHT_SYMTAB_SHNDX, 0,
  3926. ORDER_INVALID, false);
  3927. size_t symcount = off / symsize;
  3928. this->symtab_xindex_ = new Output_symtab_xindex(symcount);
  3929. osymtab_xindex->add_output_section_data(this->symtab_xindex_);
  3930. osymtab_xindex->set_link_section(osymtab);
  3931. osymtab_xindex->set_addralign(4);
  3932. osymtab_xindex->set_entsize(4);
  3933. osymtab_xindex->set_after_input_sections();
  3934. // This tells the driver code to wait until the symbol table
  3935. // has written out before writing out the postprocessing
  3936. // sections, including the .symtab_shndx section.
  3937. this->any_postprocessing_sections_ = true;
  3938. }
  3939. const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
  3940. Output_section* ostrtab = this->make_output_section(strtab_name,
  3941. elfcpp::SHT_STRTAB,
  3942. 0, ORDER_INVALID,
  3943. false);
  3944. Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
  3945. ostrtab->add_output_section_data(pstr);
  3946. off_t symtab_off;
  3947. if (!parameters->incremental_update())
  3948. symtab_off = align_address(*poff, align);
  3949. else
  3950. {
  3951. symtab_off = this->allocate(off, align, *poff);
  3952. if (off == -1)
  3953. gold_fallback(_("out of patch space for symbol table; "
  3954. "relink with --incremental-full"));
  3955. gold_debug(DEBUG_INCREMENTAL,
  3956. "create_symtab_sections: %08lx %08lx .symtab",
  3957. static_cast<long>(symtab_off),
  3958. static_cast<long>(off));
  3959. }
  3960. symtab->set_file_offset(symtab_off + global_off);
  3961. osymtab->set_file_offset(symtab_off);
  3962. osymtab->finalize_data_size();
  3963. osymtab->set_link_section(ostrtab);
  3964. osymtab->set_info(local_symcount);
  3965. osymtab->set_entsize(symsize);
  3966. if (symtab_off + off > *poff)
  3967. *poff = symtab_off + off;
  3968. }
  3969. }
  3970. // Create the .shstrtab section, which holds the names of the
  3971. // sections. At the time this is called, we have created all the
  3972. // output sections except .shstrtab itself.
  3973. Output_section*
  3974. Layout::create_shstrtab()
  3975. {
  3976. // FIXME: We don't need to create a .shstrtab section if we are
  3977. // stripping everything.
  3978. const char* name = this->namepool_.add(".shstrtab", false, NULL);
  3979. Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0,
  3980. ORDER_INVALID, false);
  3981. if (strcmp(parameters->options().compress_debug_sections(), "none") != 0)
  3982. {
  3983. // We can't write out this section until we've set all the
  3984. // section names, and we don't set the names of compressed
  3985. // output sections until relocations are complete. FIXME: With
  3986. // the current names we use, this is unnecessary.
  3987. os->set_after_input_sections();
  3988. }
  3989. Output_section_data* posd = new Output_data_strtab(&this->namepool_);
  3990. os->add_output_section_data(posd);
  3991. return os;
  3992. }
  3993. // Create the section headers. SIZE is 32 or 64. OFF is the file
  3994. // offset.
  3995. void
  3996. Layout::create_shdrs(const Output_section* shstrtab_section, off_t* poff)
  3997. {
  3998. Output_section_headers* oshdrs;
  3999. oshdrs = new Output_section_headers(this,
  4000. &this->segment_list_,
  4001. &this->section_list_,
  4002. &this->unattached_section_list_,
  4003. &this->namepool_,
  4004. shstrtab_section);
  4005. off_t off;
  4006. if (!parameters->incremental_update())
  4007. off = align_address(*poff, oshdrs->addralign());
  4008. else
  4009. {
  4010. oshdrs->pre_finalize_data_size();
  4011. off = this->allocate(oshdrs->data_size(), oshdrs->addralign(), *poff);
  4012. if (off == -1)
  4013. gold_fallback(_("out of patch space for section header table; "
  4014. "relink with --incremental-full"));
  4015. gold_debug(DEBUG_INCREMENTAL,
  4016. "create_shdrs: %08lx %08lx (section header table)",
  4017. static_cast<long>(off),
  4018. static_cast<long>(off + oshdrs->data_size()));
  4019. }
  4020. oshdrs->set_address_and_file_offset(0, off);
  4021. off += oshdrs->data_size();
  4022. if (off > *poff)
  4023. *poff = off;
  4024. this->section_headers_ = oshdrs;
  4025. }
  4026. // Count the allocated sections.
  4027. size_t
  4028. Layout::allocated_output_section_count() const
  4029. {
  4030. size_t section_count = 0;
  4031. for (Segment_list::const_iterator p = this->segment_list_.begin();
  4032. p != this->segment_list_.end();
  4033. ++p)
  4034. section_count += (*p)->output_section_count();
  4035. return section_count;
  4036. }
  4037. // Create the dynamic symbol table.
  4038. // *PLOCAL_DYNAMIC_COUNT will be set to the number of local symbols
  4039. // from input objects, and *PFORCED_LOCAL_DYNAMIC_COUNT will be set
  4040. // to the number of global symbols that have been forced local.
  4041. // We need to remember the former because the forced-local symbols are
  4042. // written along with the global symbols in Symtab::write_globals().
  4043. void
  4044. Layout::create_dynamic_symtab(const Input_objects* input_objects,
  4045. Symbol_table* symtab,
  4046. Output_section** pdynstr,
  4047. unsigned int* plocal_dynamic_count,
  4048. unsigned int* pforced_local_dynamic_count,
  4049. std::vector<Symbol*>* pdynamic_symbols,
  4050. Versions* pversions)
  4051. {
  4052. // Count all the symbols in the dynamic symbol table, and set the
  4053. // dynamic symbol indexes.
  4054. // Skip symbol 0, which is always all zeroes.
  4055. unsigned int index = 1;
  4056. // Add STT_SECTION symbols for each Output section which needs one.
  4057. for (Section_list::iterator p = this->section_list_.begin();
  4058. p != this->section_list_.end();
  4059. ++p)
  4060. {
  4061. if (!(*p)->needs_dynsym_index())
  4062. (*p)->set_dynsym_index(-1U);
  4063. else
  4064. {
  4065. (*p)->set_dynsym_index(index);
  4066. ++index;
  4067. }
  4068. }
  4069. // Count the local symbols that need to go in the dynamic symbol table,
  4070. // and set the dynamic symbol indexes.
  4071. for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
  4072. p != input_objects->relobj_end();
  4073. ++p)
  4074. {
  4075. unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
  4076. index = new_index;
  4077. }
  4078. unsigned int local_symcount = index;
  4079. unsigned int forced_local_count = 0;
  4080. index = symtab->set_dynsym_indexes(index, &forced_local_count,
  4081. pdynamic_symbols, &this->dynpool_,
  4082. pversions);
  4083. *plocal_dynamic_count = local_symcount;
  4084. *pforced_local_dynamic_count = forced_local_count;
  4085. int symsize;
  4086. unsigned int align;
  4087. const int size = parameters->target().get_size();
  4088. if (size == 32)
  4089. {
  4090. symsize = elfcpp::Elf_sizes<32>::sym_size;
  4091. align = 4;
  4092. }
  4093. else if (size == 64)
  4094. {
  4095. symsize = elfcpp::Elf_sizes<64>::sym_size;
  4096. align = 8;
  4097. }
  4098. else
  4099. gold_unreachable();
  4100. // Create the dynamic symbol table section.
  4101. Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
  4102. elfcpp::SHT_DYNSYM,
  4103. elfcpp::SHF_ALLOC,
  4104. false,
  4105. ORDER_DYNAMIC_LINKER,
  4106. false, false, false);
  4107. // Check for NULL as a linker script may discard .dynsym.
  4108. if (dynsym != NULL)
  4109. {
  4110. Output_section_data* odata = new Output_data_fixed_space(index * symsize,
  4111. align,
  4112. "** dynsym");
  4113. dynsym->add_output_section_data(odata);
  4114. dynsym->set_info(local_symcount + forced_local_count);
  4115. dynsym->set_entsize(symsize);
  4116. dynsym->set_addralign(align);
  4117. this->dynsym_section_ = dynsym;
  4118. }
  4119. Output_data_dynamic* const odyn = this->dynamic_data_;
  4120. if (odyn != NULL)
  4121. {
  4122. odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
  4123. odyn->add_constant(elfcpp::DT_SYMENT, symsize);
  4124. }
  4125. // If there are more than SHN_LORESERVE allocated sections, we
  4126. // create a .dynsym_shndx section. It is possible that we don't
  4127. // need one, because it is possible that there are no dynamic
  4128. // symbols in any of the sections with indexes larger than
  4129. // SHN_LORESERVE. This is probably unusual, though, and at this
  4130. // time we don't know the actual section indexes so it is
  4131. // inconvenient to check.
  4132. if (this->allocated_output_section_count() >= elfcpp::SHN_LORESERVE)
  4133. {
  4134. Output_section* dynsym_xindex =
  4135. this->choose_output_section(NULL, ".dynsym_shndx",
  4136. elfcpp::SHT_SYMTAB_SHNDX,
  4137. elfcpp::SHF_ALLOC,
  4138. false, ORDER_DYNAMIC_LINKER, false, false,
  4139. false);
  4140. if (dynsym_xindex != NULL)
  4141. {
  4142. this->dynsym_xindex_ = new Output_symtab_xindex(index);
  4143. dynsym_xindex->add_output_section_data(this->dynsym_xindex_);
  4144. dynsym_xindex->set_link_section(dynsym);
  4145. dynsym_xindex->set_addralign(4);
  4146. dynsym_xindex->set_entsize(4);
  4147. dynsym_xindex->set_after_input_sections();
  4148. // This tells the driver code to wait until the symbol table
  4149. // has written out before writing out the postprocessing
  4150. // sections, including the .dynsym_shndx section.
  4151. this->any_postprocessing_sections_ = true;
  4152. }
  4153. }
  4154. // Create the dynamic string table section.
  4155. Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
  4156. elfcpp::SHT_STRTAB,
  4157. elfcpp::SHF_ALLOC,
  4158. false,
  4159. ORDER_DYNAMIC_LINKER,
  4160. false, false, false);
  4161. *pdynstr = dynstr;
  4162. if (dynstr != NULL)
  4163. {
  4164. Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
  4165. dynstr->add_output_section_data(strdata);
  4166. if (dynsym != NULL)
  4167. dynsym->set_link_section(dynstr);
  4168. if (this->dynamic_section_ != NULL)
  4169. this->dynamic_section_->set_link_section(dynstr);
  4170. if (odyn != NULL)
  4171. {
  4172. odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
  4173. odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
  4174. }
  4175. }
  4176. // Create the hash tables. The Gnu-style hash table must be
  4177. // built first, because it changes the order of the symbols
  4178. // in the dynamic symbol table.
  4179. if (strcmp(parameters->options().hash_style(), "gnu") == 0
  4180. || strcmp(parameters->options().hash_style(), "both") == 0)
  4181. {
  4182. unsigned char* phash;
  4183. unsigned int hashlen;
  4184. Dynobj::create_gnu_hash_table(*pdynamic_symbols,
  4185. local_symcount + forced_local_count,
  4186. &phash, &hashlen);
  4187. Output_section* hashsec =
  4188. this->choose_output_section(NULL, ".gnu.hash", elfcpp::SHT_GNU_HASH,
  4189. elfcpp::SHF_ALLOC, false,
  4190. ORDER_DYNAMIC_LINKER, false, false,
  4191. false);
  4192. Output_section_data* hashdata = new Output_data_const_buffer(phash,
  4193. hashlen,
  4194. align,
  4195. "** hash");
  4196. if (hashsec != NULL && hashdata != NULL)
  4197. hashsec->add_output_section_data(hashdata);
  4198. if (hashsec != NULL)
  4199. {
  4200. if (dynsym != NULL)
  4201. hashsec->set_link_section(dynsym);
  4202. // For a 64-bit target, the entries in .gnu.hash do not have
  4203. // a uniform size, so we only set the entry size for a
  4204. // 32-bit target.
  4205. if (parameters->target().get_size() == 32)
  4206. hashsec->set_entsize(4);
  4207. if (odyn != NULL)
  4208. odyn->add_section_address(elfcpp::DT_GNU_HASH, hashsec);
  4209. }
  4210. }
  4211. if (strcmp(parameters->options().hash_style(), "sysv") == 0
  4212. || strcmp(parameters->options().hash_style(), "both") == 0)
  4213. {
  4214. unsigned char* phash;
  4215. unsigned int hashlen;
  4216. Dynobj::create_elf_hash_table(*pdynamic_symbols,
  4217. local_symcount + forced_local_count,
  4218. &phash, &hashlen);
  4219. Output_section* hashsec =
  4220. this->choose_output_section(NULL, ".hash", elfcpp::SHT_HASH,
  4221. elfcpp::SHF_ALLOC, false,
  4222. ORDER_DYNAMIC_LINKER, false, false,
  4223. false);
  4224. Output_section_data* hashdata = new Output_data_const_buffer(phash,
  4225. hashlen,
  4226. align,
  4227. "** hash");
  4228. if (hashsec != NULL && hashdata != NULL)
  4229. hashsec->add_output_section_data(hashdata);
  4230. if (hashsec != NULL)
  4231. {
  4232. if (dynsym != NULL)
  4233. hashsec->set_link_section(dynsym);
  4234. hashsec->set_entsize(parameters->target().hash_entry_size() / 8);
  4235. }
  4236. if (odyn != NULL)
  4237. odyn->add_section_address(elfcpp::DT_HASH, hashsec);
  4238. }
  4239. }
  4240. // Assign offsets to each local portion of the dynamic symbol table.
  4241. void
  4242. Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
  4243. {
  4244. Output_section* dynsym = this->dynsym_section_;
  4245. if (dynsym == NULL)
  4246. return;
  4247. off_t off = dynsym->offset();
  4248. // Skip the dummy symbol at the start of the section.
  4249. off += dynsym->entsize();
  4250. for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
  4251. p != input_objects->relobj_end();
  4252. ++p)
  4253. {
  4254. unsigned int count = (*p)->set_local_dynsym_offset(off);
  4255. off += count * dynsym->entsize();
  4256. }
  4257. }
  4258. // Create the version sections.
  4259. void
  4260. Layout::create_version_sections(const Versions* versions,
  4261. const Symbol_table* symtab,
  4262. unsigned int local_symcount,
  4263. const std::vector<Symbol*>& dynamic_symbols,
  4264. const Output_section* dynstr)
  4265. {
  4266. if (!versions->any_defs() && !versions->any_needs())
  4267. return;
  4268. switch (parameters->size_and_endianness())
  4269. {
  4270. #ifdef HAVE_TARGET_32_LITTLE
  4271. case Parameters::TARGET_32_LITTLE:
  4272. this->sized_create_version_sections<32, false>(versions, symtab,
  4273. local_symcount,
  4274. dynamic_symbols, dynstr);
  4275. break;
  4276. #endif
  4277. #ifdef HAVE_TARGET_32_BIG
  4278. case Parameters::TARGET_32_BIG:
  4279. this->sized_create_version_sections<32, true>(versions, symtab,
  4280. local_symcount,
  4281. dynamic_symbols, dynstr);
  4282. break;
  4283. #endif
  4284. #ifdef HAVE_TARGET_64_LITTLE
  4285. case Parameters::TARGET_64_LITTLE:
  4286. this->sized_create_version_sections<64, false>(versions, symtab,
  4287. local_symcount,
  4288. dynamic_symbols, dynstr);
  4289. break;
  4290. #endif
  4291. #ifdef HAVE_TARGET_64_BIG
  4292. case Parameters::TARGET_64_BIG:
  4293. this->sized_create_version_sections<64, true>(versions, symtab,
  4294. local_symcount,
  4295. dynamic_symbols, dynstr);
  4296. break;
  4297. #endif
  4298. default:
  4299. gold_unreachable();
  4300. }
  4301. }
  4302. // Create the version sections, sized version.
  4303. template<int size, bool big_endian>
  4304. void
  4305. Layout::sized_create_version_sections(
  4306. const Versions* versions,
  4307. const Symbol_table* symtab,
  4308. unsigned int local_symcount,
  4309. const std::vector<Symbol*>& dynamic_symbols,
  4310. const Output_section* dynstr)
  4311. {
  4312. Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
  4313. elfcpp::SHT_GNU_versym,
  4314. elfcpp::SHF_ALLOC,
  4315. false,
  4316. ORDER_DYNAMIC_LINKER,
  4317. false, false, false);
  4318. // Check for NULL since a linker script may discard this section.
  4319. if (vsec != NULL)
  4320. {
  4321. unsigned char* vbuf;
  4322. unsigned int vsize;
  4323. versions->symbol_section_contents<size, big_endian>(symtab,
  4324. &this->dynpool_,
  4325. local_symcount,
  4326. dynamic_symbols,
  4327. &vbuf, &vsize);
  4328. Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2,
  4329. "** versions");
  4330. vsec->add_output_section_data(vdata);
  4331. vsec->set_entsize(2);
  4332. vsec->set_link_section(this->dynsym_section_);
  4333. }
  4334. Output_data_dynamic* const odyn = this->dynamic_data_;
  4335. if (odyn != NULL && vsec != NULL)
  4336. odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
  4337. if (versions->any_defs())
  4338. {
  4339. Output_section* vdsec;
  4340. vdsec = this->choose_output_section(NULL, ".gnu.version_d",
  4341. elfcpp::SHT_GNU_verdef,
  4342. elfcpp::SHF_ALLOC,
  4343. false, ORDER_DYNAMIC_LINKER, false,
  4344. false, false);
  4345. if (vdsec != NULL)
  4346. {
  4347. unsigned char* vdbuf;
  4348. unsigned int vdsize;
  4349. unsigned int vdentries;
  4350. versions->def_section_contents<size, big_endian>(&this->dynpool_,
  4351. &vdbuf, &vdsize,
  4352. &vdentries);
  4353. Output_section_data* vddata =
  4354. new Output_data_const_buffer(vdbuf, vdsize, 4, "** version defs");
  4355. vdsec->add_output_section_data(vddata);
  4356. vdsec->set_link_section(dynstr);
  4357. vdsec->set_info(vdentries);
  4358. if (odyn != NULL)
  4359. {
  4360. odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
  4361. odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
  4362. }
  4363. }
  4364. }
  4365. if (versions->any_needs())
  4366. {
  4367. Output_section* vnsec;
  4368. vnsec = this->choose_output_section(NULL, ".gnu.version_r",
  4369. elfcpp::SHT_GNU_verneed,
  4370. elfcpp::SHF_ALLOC,
  4371. false, ORDER_DYNAMIC_LINKER, false,
  4372. false, false);
  4373. if (vnsec != NULL)
  4374. {
  4375. unsigned char* vnbuf;
  4376. unsigned int vnsize;
  4377. unsigned int vnentries;
  4378. versions->need_section_contents<size, big_endian>(&this->dynpool_,
  4379. &vnbuf, &vnsize,
  4380. &vnentries);
  4381. Output_section_data* vndata =
  4382. new Output_data_const_buffer(vnbuf, vnsize, 4, "** version refs");
  4383. vnsec->add_output_section_data(vndata);
  4384. vnsec->set_link_section(dynstr);
  4385. vnsec->set_info(vnentries);
  4386. if (odyn != NULL)
  4387. {
  4388. odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
  4389. odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
  4390. }
  4391. }
  4392. }
  4393. }
  4394. // Create the .interp section and PT_INTERP segment.
  4395. void
  4396. Layout::create_interp(const Target* target)
  4397. {
  4398. gold_assert(this->interp_segment_ == NULL);
  4399. const char* interp = parameters->options().dynamic_linker();
  4400. if (interp == NULL)
  4401. {
  4402. interp = target->dynamic_linker();
  4403. gold_assert(interp != NULL);
  4404. }
  4405. size_t len = strlen(interp) + 1;
  4406. Output_section_data* odata = new Output_data_const(interp, len, 1);
  4407. Output_section* osec = this->choose_output_section(NULL, ".interp",
  4408. elfcpp::SHT_PROGBITS,
  4409. elfcpp::SHF_ALLOC,
  4410. false, ORDER_INTERP,
  4411. false, false, false);
  4412. if (osec != NULL)
  4413. osec->add_output_section_data(odata);
  4414. }
  4415. // Add dynamic tags for the PLT and the dynamic relocs. This is
  4416. // called by the target-specific code. This does nothing if not doing
  4417. // a dynamic link.
  4418. // USE_REL is true for REL relocs rather than RELA relocs.
  4419. // If PLT_GOT is not NULL, then DT_PLTGOT points to it.
  4420. // If PLT_REL is not NULL, it is used for DT_PLTRELSZ, and DT_JMPREL,
  4421. // and we also set DT_PLTREL. We use PLT_REL's output section, since
  4422. // some targets have multiple reloc sections in PLT_REL.
  4423. // If DYN_REL is not NULL, it is used for DT_REL/DT_RELA,
  4424. // DT_RELSZ/DT_RELASZ, DT_RELENT/DT_RELAENT. Again we use the output
  4425. // section.
  4426. // If ADD_DEBUG is true, we add a DT_DEBUG entry when generating an
  4427. // executable.
  4428. void
  4429. Layout::add_target_dynamic_tags(bool use_rel, const Output_data* plt_got,
  4430. const Output_data* plt_rel,
  4431. const Output_data_reloc_generic* dyn_rel,
  4432. bool add_debug, bool dynrel_includes_plt)
  4433. {
  4434. Output_data_dynamic* odyn = this->dynamic_data_;
  4435. if (odyn == NULL)
  4436. return;
  4437. if (plt_got != NULL && plt_got->output_section() != NULL)
  4438. odyn->add_section_address(elfcpp::DT_PLTGOT, plt_got);
  4439. if (plt_rel != NULL && plt_rel->output_section() != NULL)
  4440. {
  4441. odyn->add_section_size(elfcpp::DT_PLTRELSZ, plt_rel->output_section());
  4442. odyn->add_section_address(elfcpp::DT_JMPREL, plt_rel->output_section());
  4443. odyn->add_constant(elfcpp::DT_PLTREL,
  4444. use_rel ? elfcpp::DT_REL : elfcpp::DT_RELA);
  4445. }
  4446. if ((dyn_rel != NULL && dyn_rel->output_section() != NULL)
  4447. || (dynrel_includes_plt
  4448. && plt_rel != NULL
  4449. && plt_rel->output_section() != NULL))
  4450. {
  4451. bool have_dyn_rel = dyn_rel != NULL && dyn_rel->output_section() != NULL;
  4452. bool have_plt_rel = plt_rel != NULL && plt_rel->output_section() != NULL;
  4453. odyn->add_section_address(use_rel ? elfcpp::DT_REL : elfcpp::DT_RELA,
  4454. (have_dyn_rel
  4455. ? dyn_rel->output_section()
  4456. : plt_rel->output_section()));
  4457. elfcpp::DT size_tag = use_rel ? elfcpp::DT_RELSZ : elfcpp::DT_RELASZ;
  4458. if (have_dyn_rel && have_plt_rel && dynrel_includes_plt)
  4459. odyn->add_section_size(size_tag,
  4460. dyn_rel->output_section(),
  4461. plt_rel->output_section());
  4462. else if (have_dyn_rel)
  4463. odyn->add_section_size(size_tag, dyn_rel->output_section());
  4464. else
  4465. odyn->add_section_size(size_tag, plt_rel->output_section());
  4466. const int size = parameters->target().get_size();
  4467. elfcpp::DT rel_tag;
  4468. int rel_size;
  4469. if (use_rel)
  4470. {
  4471. rel_tag = elfcpp::DT_RELENT;
  4472. if (size == 32)
  4473. rel_size = Reloc_types<elfcpp::SHT_REL, 32, false>::reloc_size;
  4474. else if (size == 64)
  4475. rel_size = Reloc_types<elfcpp::SHT_REL, 64, false>::reloc_size;
  4476. else
  4477. gold_unreachable();
  4478. }
  4479. else
  4480. {
  4481. rel_tag = elfcpp::DT_RELAENT;
  4482. if (size == 32)
  4483. rel_size = Reloc_types<elfcpp::SHT_RELA, 32, false>::reloc_size;
  4484. else if (size == 64)
  4485. rel_size = Reloc_types<elfcpp::SHT_RELA, 64, false>::reloc_size;
  4486. else
  4487. gold_unreachable();
  4488. }
  4489. odyn->add_constant(rel_tag, rel_size);
  4490. if (parameters->options().combreloc() && have_dyn_rel)
  4491. {
  4492. size_t c = dyn_rel->relative_reloc_count();
  4493. if (c > 0)
  4494. odyn->add_constant((use_rel
  4495. ? elfcpp::DT_RELCOUNT
  4496. : elfcpp::DT_RELACOUNT),
  4497. c);
  4498. }
  4499. }
  4500. if (add_debug && !parameters->options().shared())
  4501. {
  4502. // The value of the DT_DEBUG tag is filled in by the dynamic
  4503. // linker at run time, and used by the debugger.
  4504. odyn->add_constant(elfcpp::DT_DEBUG, 0);
  4505. }
  4506. }
  4507. void
  4508. Layout::add_target_specific_dynamic_tag(elfcpp::DT tag, unsigned int val)
  4509. {
  4510. Output_data_dynamic* odyn = this->dynamic_data_;
  4511. if (odyn == NULL)
  4512. return;
  4513. odyn->add_constant(tag, val);
  4514. }
  4515. // Finish the .dynamic section and PT_DYNAMIC segment.
  4516. void
  4517. Layout::finish_dynamic_section(const Input_objects* input_objects,
  4518. const Symbol_table* symtab)
  4519. {
  4520. if (!this->script_options_->saw_phdrs_clause()
  4521. && this->dynamic_section_ != NULL)
  4522. {
  4523. Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
  4524. (elfcpp::PF_R
  4525. | elfcpp::PF_W));
  4526. oseg->add_output_section_to_nonload(this->dynamic_section_,
  4527. elfcpp::PF_R | elfcpp::PF_W);
  4528. }
  4529. Output_data_dynamic* const odyn = this->dynamic_data_;
  4530. if (odyn == NULL)
  4531. return;
  4532. for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
  4533. p != input_objects->dynobj_end();
  4534. ++p)
  4535. {
  4536. if (!(*p)->is_needed() && (*p)->as_needed())
  4537. {
  4538. // This dynamic object was linked with --as-needed, but it
  4539. // is not needed.
  4540. continue;
  4541. }
  4542. odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
  4543. }
  4544. if (parameters->options().shared())
  4545. {
  4546. const char* soname = parameters->options().soname();
  4547. if (soname != NULL)
  4548. odyn->add_string(elfcpp::DT_SONAME, soname);
  4549. }
  4550. Symbol* sym = symtab->lookup(parameters->options().init());
  4551. if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
  4552. odyn->add_symbol(elfcpp::DT_INIT, sym);
  4553. sym = symtab->lookup(parameters->options().fini());
  4554. if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
  4555. odyn->add_symbol(elfcpp::DT_FINI, sym);
  4556. // Look for .init_array, .preinit_array and .fini_array by checking
  4557. // section types.
  4558. for(Layout::Section_list::const_iterator p = this->section_list_.begin();
  4559. p != this->section_list_.end();
  4560. ++p)
  4561. switch((*p)->type())
  4562. {
  4563. case elfcpp::SHT_FINI_ARRAY:
  4564. odyn->add_section_address(elfcpp::DT_FINI_ARRAY, *p);
  4565. odyn->add_section_size(elfcpp::DT_FINI_ARRAYSZ, *p);
  4566. break;
  4567. case elfcpp::SHT_INIT_ARRAY:
  4568. odyn->add_section_address(elfcpp::DT_INIT_ARRAY, *p);
  4569. odyn->add_section_size(elfcpp::DT_INIT_ARRAYSZ, *p);
  4570. break;
  4571. case elfcpp::SHT_PREINIT_ARRAY:
  4572. odyn->add_section_address(elfcpp::DT_PREINIT_ARRAY, *p);
  4573. odyn->add_section_size(elfcpp::DT_PREINIT_ARRAYSZ, *p);
  4574. break;
  4575. default:
  4576. break;
  4577. }
  4578. // Add a DT_RPATH entry if needed.
  4579. const General_options::Dir_list& rpath(parameters->options().rpath());
  4580. if (!rpath.empty())
  4581. {
  4582. std::string rpath_val;
  4583. for (General_options::Dir_list::const_iterator p = rpath.begin();
  4584. p != rpath.end();
  4585. ++p)
  4586. {
  4587. if (rpath_val.empty())
  4588. rpath_val = p->name();
  4589. else
  4590. {
  4591. // Eliminate duplicates.
  4592. General_options::Dir_list::const_iterator q;
  4593. for (q = rpath.begin(); q != p; ++q)
  4594. if (q->name() == p->name())
  4595. break;
  4596. if (q == p)
  4597. {
  4598. rpath_val += ':';
  4599. rpath_val += p->name();
  4600. }
  4601. }
  4602. }
  4603. if (!parameters->options().enable_new_dtags())
  4604. odyn->add_string(elfcpp::DT_RPATH, rpath_val);
  4605. else
  4606. odyn->add_string(elfcpp::DT_RUNPATH, rpath_val);
  4607. }
  4608. // Look for text segments that have dynamic relocations.
  4609. bool have_textrel = false;
  4610. if (!this->script_options_->saw_sections_clause())
  4611. {
  4612. for (Segment_list::const_iterator p = this->segment_list_.begin();
  4613. p != this->segment_list_.end();
  4614. ++p)
  4615. {
  4616. if ((*p)->type() == elfcpp::PT_LOAD
  4617. && ((*p)->flags() & elfcpp::PF_W) == 0
  4618. && (*p)->has_dynamic_reloc())
  4619. {
  4620. have_textrel = true;
  4621. break;
  4622. }
  4623. }
  4624. }
  4625. else
  4626. {
  4627. // We don't know the section -> segment mapping, so we are
  4628. // conservative and just look for readonly sections with
  4629. // relocations. If those sections wind up in writable segments,
  4630. // then we have created an unnecessary DT_TEXTREL entry.
  4631. for (Section_list::const_iterator p = this->section_list_.begin();
  4632. p != this->section_list_.end();
  4633. ++p)
  4634. {
  4635. if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0
  4636. && ((*p)->flags() & elfcpp::SHF_WRITE) == 0
  4637. && (*p)->has_dynamic_reloc())
  4638. {
  4639. have_textrel = true;
  4640. break;
  4641. }
  4642. }
  4643. }
  4644. if (parameters->options().filter() != NULL)
  4645. odyn->add_string(elfcpp::DT_FILTER, parameters->options().filter());
  4646. if (parameters->options().any_auxiliary())
  4647. {
  4648. for (options::String_set::const_iterator p =
  4649. parameters->options().auxiliary_begin();
  4650. p != parameters->options().auxiliary_end();
  4651. ++p)
  4652. odyn->add_string(elfcpp::DT_AUXILIARY, *p);
  4653. }
  4654. // Add a DT_FLAGS entry if necessary.
  4655. unsigned int flags = 0;
  4656. if (have_textrel)
  4657. {
  4658. // Add a DT_TEXTREL for compatibility with older loaders.
  4659. odyn->add_constant(elfcpp::DT_TEXTREL, 0);
  4660. flags |= elfcpp::DF_TEXTREL;
  4661. if (parameters->options().text())
  4662. gold_error(_("read-only segment has dynamic relocations"));
  4663. else if (parameters->options().warn_shared_textrel()
  4664. && parameters->options().shared())
  4665. gold_warning(_("shared library text segment is not shareable"));
  4666. }
  4667. if (parameters->options().shared() && this->has_static_tls())
  4668. flags |= elfcpp::DF_STATIC_TLS;
  4669. if (parameters->options().origin())
  4670. flags |= elfcpp::DF_ORIGIN;
  4671. if (parameters->options().Bsymbolic()
  4672. && !parameters->options().have_dynamic_list())
  4673. {
  4674. flags |= elfcpp::DF_SYMBOLIC;
  4675. // Add DT_SYMBOLIC for compatibility with older loaders.
  4676. odyn->add_constant(elfcpp::DT_SYMBOLIC, 0);
  4677. }
  4678. if (parameters->options().now())
  4679. flags |= elfcpp::DF_BIND_NOW;
  4680. if (flags != 0)
  4681. odyn->add_constant(elfcpp::DT_FLAGS, flags);
  4682. flags = 0;
  4683. if (parameters->options().global())
  4684. flags |= elfcpp::DF_1_GLOBAL;
  4685. if (parameters->options().initfirst())
  4686. flags |= elfcpp::DF_1_INITFIRST;
  4687. if (parameters->options().interpose())
  4688. flags |= elfcpp::DF_1_INTERPOSE;
  4689. if (parameters->options().loadfltr())
  4690. flags |= elfcpp::DF_1_LOADFLTR;
  4691. if (parameters->options().nodefaultlib())
  4692. flags |= elfcpp::DF_1_NODEFLIB;
  4693. if (parameters->options().nodelete())
  4694. flags |= elfcpp::DF_1_NODELETE;
  4695. if (parameters->options().nodlopen())
  4696. flags |= elfcpp::DF_1_NOOPEN;
  4697. if (parameters->options().nodump())
  4698. flags |= elfcpp::DF_1_NODUMP;
  4699. if (!parameters->options().shared())
  4700. flags &= ~(elfcpp::DF_1_INITFIRST
  4701. | elfcpp::DF_1_NODELETE
  4702. | elfcpp::DF_1_NOOPEN);
  4703. if (parameters->options().origin())
  4704. flags |= elfcpp::DF_1_ORIGIN;
  4705. if (parameters->options().now())
  4706. flags |= elfcpp::DF_1_NOW;
  4707. if (parameters->options().Bgroup())
  4708. flags |= elfcpp::DF_1_GROUP;
  4709. if (parameters->options().pie())
  4710. flags |= elfcpp::DF_1_PIE;
  4711. if (flags != 0)
  4712. odyn->add_constant(elfcpp::DT_FLAGS_1, flags);
  4713. flags = 0;
  4714. if (parameters->options().unique())
  4715. flags |= elfcpp::DF_GNU_1_UNIQUE;
  4716. if (flags != 0)
  4717. odyn->add_constant(elfcpp::DT_GNU_FLAGS_1, flags);
  4718. }
  4719. // Set the size of the _DYNAMIC symbol table to be the size of the
  4720. // dynamic data.
  4721. void
  4722. Layout::set_dynamic_symbol_size(const Symbol_table* symtab)
  4723. {
  4724. Output_data_dynamic* const odyn = this->dynamic_data_;
  4725. if (odyn == NULL)
  4726. return;
  4727. odyn->finalize_data_size();
  4728. if (this->dynamic_symbol_ == NULL)
  4729. return;
  4730. off_t data_size = odyn->data_size();
  4731. const int size = parameters->target().get_size();
  4732. if (size == 32)
  4733. symtab->get_sized_symbol<32>(this->dynamic_symbol_)->set_symsize(data_size);
  4734. else if (size == 64)
  4735. symtab->get_sized_symbol<64>(this->dynamic_symbol_)->set_symsize(data_size);
  4736. else
  4737. gold_unreachable();
  4738. }
  4739. // The mapping of input section name prefixes to output section names.
  4740. // In some cases one prefix is itself a prefix of another prefix; in
  4741. // such a case the longer prefix must come first. These prefixes are
  4742. // based on the GNU linker default ELF linker script.
  4743. #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
  4744. #define MAPPING_INIT_EXACT(f, t) { f, 0, t, sizeof(t) - 1 }
  4745. const Layout::Section_name_mapping Layout::section_name_mapping[] =
  4746. {
  4747. MAPPING_INIT(".text.", ".text"),
  4748. MAPPING_INIT(".rodata.", ".rodata"),
  4749. MAPPING_INIT(".data.rel.ro.local.", ".data.rel.ro.local"),
  4750. MAPPING_INIT_EXACT(".data.rel.ro.local", ".data.rel.ro.local"),
  4751. MAPPING_INIT(".data.rel.ro.", ".data.rel.ro"),
  4752. MAPPING_INIT_EXACT(".data.rel.ro", ".data.rel.ro"),
  4753. MAPPING_INIT(".data.", ".data"),
  4754. MAPPING_INIT(".bss.", ".bss"),
  4755. MAPPING_INIT(".tdata.", ".tdata"),
  4756. MAPPING_INIT(".tbss.", ".tbss"),
  4757. MAPPING_INIT(".init_array.", ".init_array"),
  4758. MAPPING_INIT(".fini_array.", ".fini_array"),
  4759. MAPPING_INIT(".sdata.", ".sdata"),
  4760. MAPPING_INIT(".sbss.", ".sbss"),
  4761. // FIXME: In the GNU linker, .sbss2 and .sdata2 are handled
  4762. // differently depending on whether it is creating a shared library.
  4763. MAPPING_INIT(".sdata2.", ".sdata"),
  4764. MAPPING_INIT(".sbss2.", ".sbss"),
  4765. MAPPING_INIT(".lrodata.", ".lrodata"),
  4766. MAPPING_INIT(".ldata.", ".ldata"),
  4767. MAPPING_INIT(".lbss.", ".lbss"),
  4768. MAPPING_INIT(".gcc_except_table.", ".gcc_except_table"),
  4769. MAPPING_INIT(".gnu.linkonce.d.rel.ro.local.", ".data.rel.ro.local"),
  4770. MAPPING_INIT(".gnu.linkonce.d.rel.ro.", ".data.rel.ro"),
  4771. MAPPING_INIT(".gnu.linkonce.t.", ".text"),
  4772. MAPPING_INIT(".gnu.linkonce.r.", ".rodata"),
  4773. MAPPING_INIT(".gnu.linkonce.d.", ".data"),
  4774. MAPPING_INIT(".gnu.linkonce.b.", ".bss"),
  4775. MAPPING_INIT(".gnu.linkonce.s.", ".sdata"),
  4776. MAPPING_INIT(".gnu.linkonce.sb.", ".sbss"),
  4777. MAPPING_INIT(".gnu.linkonce.s2.", ".sdata"),
  4778. MAPPING_INIT(".gnu.linkonce.sb2.", ".sbss"),
  4779. MAPPING_INIT(".gnu.linkonce.wi.", ".debug_info"),
  4780. MAPPING_INIT(".gnu.linkonce.td.", ".tdata"),
  4781. MAPPING_INIT(".gnu.linkonce.tb.", ".tbss"),
  4782. MAPPING_INIT(".gnu.linkonce.lr.", ".lrodata"),
  4783. MAPPING_INIT(".gnu.linkonce.l.", ".ldata"),
  4784. MAPPING_INIT(".gnu.linkonce.lb.", ".lbss"),
  4785. MAPPING_INIT(".ARM.extab", ".ARM.extab"),
  4786. MAPPING_INIT(".gnu.linkonce.armextab.", ".ARM.extab"),
  4787. MAPPING_INIT(".ARM.exidx", ".ARM.exidx"),
  4788. MAPPING_INIT(".gnu.linkonce.armexidx.", ".ARM.exidx"),
  4789. MAPPING_INIT(".gnu.build.attributes.", ".gnu.build.attributes"),
  4790. };
  4791. // Mapping for ".text" section prefixes with -z,keep-text-section-prefix.
  4792. const Layout::Section_name_mapping Layout::text_section_name_mapping[] =
  4793. {
  4794. MAPPING_INIT(".text.hot.", ".text.hot"),
  4795. MAPPING_INIT_EXACT(".text.hot", ".text.hot"),
  4796. MAPPING_INIT(".text.unlikely.", ".text.unlikely"),
  4797. MAPPING_INIT_EXACT(".text.unlikely", ".text.unlikely"),
  4798. MAPPING_INIT(".text.startup.", ".text.startup"),
  4799. MAPPING_INIT_EXACT(".text.startup", ".text.startup"),
  4800. MAPPING_INIT(".text.exit.", ".text.exit"),
  4801. MAPPING_INIT_EXACT(".text.exit", ".text.exit"),
  4802. MAPPING_INIT(".text.", ".text"),
  4803. };
  4804. #undef MAPPING_INIT
  4805. #undef MAPPING_INIT_EXACT
  4806. const int Layout::section_name_mapping_count =
  4807. (sizeof(Layout::section_name_mapping)
  4808. / sizeof(Layout::section_name_mapping[0]));
  4809. const int Layout::text_section_name_mapping_count =
  4810. (sizeof(Layout::text_section_name_mapping)
  4811. / sizeof(Layout::text_section_name_mapping[0]));
  4812. // Find section name NAME in PSNM and return the mapped name if found
  4813. // with the length set in PLEN.
  4814. const char *
  4815. Layout::match_section_name(const Layout::Section_name_mapping* psnm,
  4816. const int count,
  4817. const char* name, size_t* plen)
  4818. {
  4819. for (int i = 0; i < count; ++i, ++psnm)
  4820. {
  4821. if (psnm->fromlen > 0)
  4822. {
  4823. if (strncmp(name, psnm->from, psnm->fromlen) == 0)
  4824. {
  4825. *plen = psnm->tolen;
  4826. return psnm->to;
  4827. }
  4828. }
  4829. else
  4830. {
  4831. if (strcmp(name, psnm->from) == 0)
  4832. {
  4833. *plen = psnm->tolen;
  4834. return psnm->to;
  4835. }
  4836. }
  4837. }
  4838. return NULL;
  4839. }
  4840. // Choose the output section name to use given an input section name.
  4841. // Set *PLEN to the length of the name. *PLEN is initialized to the
  4842. // length of NAME.
  4843. const char*
  4844. Layout::output_section_name(const Relobj* relobj, const char* name,
  4845. size_t* plen)
  4846. {
  4847. // gcc 4.3 generates the following sorts of section names when it
  4848. // needs a section name specific to a function:
  4849. // .text.FN
  4850. // .rodata.FN
  4851. // .sdata2.FN
  4852. // .data.FN
  4853. // .data.rel.FN
  4854. // .data.rel.local.FN
  4855. // .data.rel.ro.FN
  4856. // .data.rel.ro.local.FN
  4857. // .sdata.FN
  4858. // .bss.FN
  4859. // .sbss.FN
  4860. // .tdata.FN
  4861. // .tbss.FN
  4862. // The GNU linker maps all of those to the part before the .FN,
  4863. // except that .data.rel.local.FN is mapped to .data, and
  4864. // .data.rel.ro.local.FN is mapped to .data.rel.ro. The sections
  4865. // beginning with .data.rel.ro.local are grouped together.
  4866. // For an anonymous namespace, the string FN can contain a '.'.
  4867. // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
  4868. // GNU linker maps to .rodata.
  4869. // The .data.rel.ro sections are used with -z relro. The sections
  4870. // are recognized by name. We use the same names that the GNU
  4871. // linker does for these sections.
  4872. // It is hard to handle this in a principled way, so we don't even
  4873. // try. We use a table of mappings. If the input section name is
  4874. // not found in the table, we simply use it as the output section
  4875. // name.
  4876. if (parameters->options().keep_text_section_prefix()
  4877. && is_prefix_of(".text", name))
  4878. {
  4879. const char* match = match_section_name(text_section_name_mapping,
  4880. text_section_name_mapping_count,
  4881. name, plen);
  4882. if (match != NULL)
  4883. return match;
  4884. }
  4885. const char* match = match_section_name(section_name_mapping,
  4886. section_name_mapping_count, name, plen);
  4887. if (match != NULL)
  4888. return match;
  4889. // As an additional complication, .ctors sections are output in
  4890. // either .ctors or .init_array sections, and .dtors sections are
  4891. // output in either .dtors or .fini_array sections.
  4892. if (is_prefix_of(".ctors.", name) || is_prefix_of(".dtors.", name))
  4893. {
  4894. if (parameters->options().ctors_in_init_array())
  4895. {
  4896. *plen = 11;
  4897. return name[1] == 'c' ? ".init_array" : ".fini_array";
  4898. }
  4899. else
  4900. {
  4901. *plen = 6;
  4902. return name[1] == 'c' ? ".ctors" : ".dtors";
  4903. }
  4904. }
  4905. if (parameters->options().ctors_in_init_array()
  4906. && (strcmp(name, ".ctors") == 0 || strcmp(name, ".dtors") == 0))
  4907. {
  4908. // To make .init_array/.fini_array work with gcc we must exclude
  4909. // .ctors and .dtors sections from the crtbegin and crtend
  4910. // files.
  4911. if (relobj == NULL
  4912. || (!Layout::match_file_name(relobj, "crtbegin")
  4913. && !Layout::match_file_name(relobj, "crtend")))
  4914. {
  4915. *plen = 11;
  4916. return name[1] == 'c' ? ".init_array" : ".fini_array";
  4917. }
  4918. }
  4919. return name;
  4920. }
  4921. // Return true if RELOBJ is an input file whose base name matches
  4922. // FILE_NAME. The base name must have an extension of ".o", and must
  4923. // be exactly FILE_NAME.o or FILE_NAME, one character, ".o". This is
  4924. // to match crtbegin.o as well as crtbeginS.o without getting confused
  4925. // by other possibilities. Overall matching the file name this way is
  4926. // a dreadful hack, but the GNU linker does it in order to better
  4927. // support gcc, and we need to be compatible.
  4928. bool
  4929. Layout::match_file_name(const Relobj* relobj, const char* match)
  4930. {
  4931. const std::string& file_name(relobj->name());
  4932. const char* base_name = lbasename(file_name.c_str());
  4933. size_t match_len = strlen(match);
  4934. if (strncmp(base_name, match, match_len) != 0)
  4935. return false;
  4936. size_t base_len = strlen(base_name);
  4937. if (base_len != match_len + 2 && base_len != match_len + 3)
  4938. return false;
  4939. return memcmp(base_name + base_len - 2, ".o", 2) == 0;
  4940. }
  4941. // Check if a comdat group or .gnu.linkonce section with the given
  4942. // NAME is selected for the link. If there is already a section,
  4943. // *KEPT_SECTION is set to point to the existing section and the
  4944. // function returns false. Otherwise, OBJECT, SHNDX, IS_COMDAT, and
  4945. // IS_GROUP_NAME are recorded for this NAME in the layout object,
  4946. // *KEPT_SECTION is set to the internal copy and the function returns
  4947. // true.
  4948. bool
  4949. Layout::find_or_add_kept_section(const std::string& name,
  4950. Relobj* object,
  4951. unsigned int shndx,
  4952. bool is_comdat,
  4953. bool is_group_name,
  4954. Kept_section** kept_section)
  4955. {
  4956. // It's normal to see a couple of entries here, for the x86 thunk
  4957. // sections. If we see more than a few, we're linking a C++
  4958. // program, and we resize to get more space to minimize rehashing.
  4959. if (this->signatures_.size() > 4
  4960. && !this->resized_signatures_)
  4961. {
  4962. reserve_unordered_map(&this->signatures_,
  4963. this->number_of_input_files_ * 64);
  4964. this->resized_signatures_ = true;
  4965. }
  4966. Kept_section candidate;
  4967. std::pair<Signatures::iterator, bool> ins =
  4968. this->signatures_.insert(std::make_pair(name, candidate));
  4969. if (kept_section != NULL)
  4970. *kept_section = &ins.first->second;
  4971. if (ins.second)
  4972. {
  4973. // This is the first time we've seen this signature.
  4974. ins.first->second.set_object(object);
  4975. ins.first->second.set_shndx(shndx);
  4976. if (is_comdat)
  4977. ins.first->second.set_is_comdat();
  4978. if (is_group_name)
  4979. ins.first->second.set_is_group_name();
  4980. return true;
  4981. }
  4982. // We have already seen this signature.
  4983. if (ins.first->second.is_group_name())
  4984. {
  4985. // We've already seen a real section group with this signature.
  4986. // If the kept group is from a plugin object, and we're in the
  4987. // replacement phase, accept the new one as a replacement.
  4988. if (ins.first->second.object() == NULL
  4989. && parameters->options().plugins()->in_replacement_phase())
  4990. {
  4991. ins.first->second.set_object(object);
  4992. ins.first->second.set_shndx(shndx);
  4993. return true;
  4994. }
  4995. return false;
  4996. }
  4997. else if (is_group_name)
  4998. {
  4999. // This is a real section group, and we've already seen a
  5000. // linkonce section with this signature. Record that we've seen
  5001. // a section group, and don't include this section group.
  5002. ins.first->second.set_is_group_name();
  5003. return false;
  5004. }
  5005. else
  5006. {
  5007. // We've already seen a linkonce section and this is a linkonce
  5008. // section. These don't block each other--this may be the same
  5009. // symbol name with different section types.
  5010. return true;
  5011. }
  5012. }
  5013. // Store the allocated sections into the section list.
  5014. void
  5015. Layout::get_allocated_sections(Section_list* section_list) const
  5016. {
  5017. for (Section_list::const_iterator p = this->section_list_.begin();
  5018. p != this->section_list_.end();
  5019. ++p)
  5020. if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
  5021. section_list->push_back(*p);
  5022. }
  5023. // Store the executable sections into the section list.
  5024. void
  5025. Layout::get_executable_sections(Section_list* section_list) const
  5026. {
  5027. for (Section_list::const_iterator p = this->section_list_.begin();
  5028. p != this->section_list_.end();
  5029. ++p)
  5030. if (((*p)->flags() & (elfcpp::SHF_ALLOC | elfcpp::SHF_EXECINSTR))
  5031. == (elfcpp::SHF_ALLOC | elfcpp::SHF_EXECINSTR))
  5032. section_list->push_back(*p);
  5033. }
  5034. // Create an output segment.
  5035. Output_segment*
  5036. Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
  5037. {
  5038. gold_assert(!parameters->options().relocatable());
  5039. Output_segment* oseg = new Output_segment(type, flags);
  5040. this->segment_list_.push_back(oseg);
  5041. if (type == elfcpp::PT_TLS)
  5042. this->tls_segment_ = oseg;
  5043. else if (type == elfcpp::PT_GNU_RELRO)
  5044. this->relro_segment_ = oseg;
  5045. else if (type == elfcpp::PT_INTERP)
  5046. this->interp_segment_ = oseg;
  5047. return oseg;
  5048. }
  5049. // Return the file offset of the normal symbol table.
  5050. off_t
  5051. Layout::symtab_section_offset() const
  5052. {
  5053. if (this->symtab_section_ != NULL)
  5054. return this->symtab_section_->offset();
  5055. return 0;
  5056. }
  5057. // Return the section index of the normal symbol table. It may have
  5058. // been stripped by the -s/--strip-all option.
  5059. unsigned int
  5060. Layout::symtab_section_shndx() const
  5061. {
  5062. if (this->symtab_section_ != NULL)
  5063. return this->symtab_section_->out_shndx();
  5064. return 0;
  5065. }
  5066. // Write out the Output_sections. Most won't have anything to write,
  5067. // since most of the data will come from input sections which are
  5068. // handled elsewhere. But some Output_sections do have Output_data.
  5069. void
  5070. Layout::write_output_sections(Output_file* of) const
  5071. {
  5072. for (Section_list::const_iterator p = this->section_list_.begin();
  5073. p != this->section_list_.end();
  5074. ++p)
  5075. {
  5076. if (!(*p)->after_input_sections())
  5077. (*p)->write(of);
  5078. }
  5079. }
  5080. // Write out data not associated with a section or the symbol table.
  5081. void
  5082. Layout::write_data(const Symbol_table* symtab, Output_file* of) const
  5083. {
  5084. if (!parameters->options().strip_all())
  5085. {
  5086. const Output_section* symtab_section = this->symtab_section_;
  5087. for (Section_list::const_iterator p = this->section_list_.begin();
  5088. p != this->section_list_.end();
  5089. ++p)
  5090. {
  5091. if ((*p)->needs_symtab_index())
  5092. {
  5093. gold_assert(symtab_section != NULL);
  5094. unsigned int index = (*p)->symtab_index();
  5095. gold_assert(index > 0 && index != -1U);
  5096. off_t off = (symtab_section->offset()
  5097. + index * symtab_section->entsize());
  5098. symtab->write_section_symbol(*p, this->symtab_xindex_, of, off);
  5099. }
  5100. }
  5101. }
  5102. const Output_section* dynsym_section = this->dynsym_section_;
  5103. for (Section_list::const_iterator p = this->section_list_.begin();
  5104. p != this->section_list_.end();
  5105. ++p)
  5106. {
  5107. if ((*p)->needs_dynsym_index())
  5108. {
  5109. gold_assert(dynsym_section != NULL);
  5110. unsigned int index = (*p)->dynsym_index();
  5111. gold_assert(index > 0 && index != -1U);
  5112. off_t off = (dynsym_section->offset()
  5113. + index * dynsym_section->entsize());
  5114. symtab->write_section_symbol(*p, this->dynsym_xindex_, of, off);
  5115. }
  5116. }
  5117. // Write out the Output_data which are not in an Output_section.
  5118. for (Data_list::const_iterator p = this->special_output_list_.begin();
  5119. p != this->special_output_list_.end();
  5120. ++p)
  5121. (*p)->write(of);
  5122. // Write out the Output_data which are not in an Output_section
  5123. // and are regenerated in each iteration of relaxation.
  5124. for (Data_list::const_iterator p = this->relax_output_list_.begin();
  5125. p != this->relax_output_list_.end();
  5126. ++p)
  5127. (*p)->write(of);
  5128. }
  5129. // Write out the Output_sections which can only be written after the
  5130. // input sections are complete.
  5131. void
  5132. Layout::write_sections_after_input_sections(Output_file* of)
  5133. {
  5134. // Determine the final section offsets, and thus the final output
  5135. // file size. Note we finalize the .shstrab last, to allow the
  5136. // after_input_section sections to modify their section-names before
  5137. // writing.
  5138. if (this->any_postprocessing_sections_)
  5139. {
  5140. off_t off = this->output_file_size_;
  5141. off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
  5142. // Now that we've finalized the names, we can finalize the shstrab.
  5143. off =
  5144. this->set_section_offsets(off,
  5145. STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
  5146. if (off > this->output_file_size_)
  5147. {
  5148. of->resize(off);
  5149. this->output_file_size_ = off;
  5150. }
  5151. }
  5152. for (Section_list::const_iterator p = this->section_list_.begin();
  5153. p != this->section_list_.end();
  5154. ++p)
  5155. {
  5156. if ((*p)->after_input_sections())
  5157. (*p)->write(of);
  5158. }
  5159. this->section_headers_->write(of);
  5160. }
  5161. // If a tree-style build ID was requested, the parallel part of that computation
  5162. // is already done, and the final hash-of-hashes is computed here. For other
  5163. // types of build IDs, all the work is done here.
  5164. void
  5165. Layout::write_build_id(Output_file* of, unsigned char* array_of_hashes,
  5166. size_t size_of_hashes) const
  5167. {
  5168. if (this->build_id_note_ == NULL)
  5169. return;
  5170. unsigned char* ov = of->get_output_view(this->build_id_note_->offset(),
  5171. this->build_id_note_->data_size());
  5172. if (array_of_hashes == NULL)
  5173. {
  5174. const size_t output_file_size = this->output_file_size();
  5175. const unsigned char* iv = of->get_input_view(0, output_file_size);
  5176. const char* style = parameters->options().build_id();
  5177. // If we get here with style == "tree" then the output must be
  5178. // too small for chunking, and we use SHA-1 in that case.
  5179. if ((strcmp(style, "sha1") == 0) || (strcmp(style, "tree") == 0))
  5180. sha1_buffer(reinterpret_cast<const char*>(iv), output_file_size, ov);
  5181. else if (strcmp(style, "md5") == 0)
  5182. md5_buffer(reinterpret_cast<const char*>(iv), output_file_size, ov);
  5183. else
  5184. gold_unreachable();
  5185. of->free_input_view(0, output_file_size, iv);
  5186. }
  5187. else
  5188. {
  5189. // Non-overlapping substrings of the output file have been hashed.
  5190. // Compute SHA-1 hash of the hashes.
  5191. sha1_buffer(reinterpret_cast<const char*>(array_of_hashes),
  5192. size_of_hashes, ov);
  5193. delete[] array_of_hashes;
  5194. }
  5195. of->write_output_view(this->build_id_note_->offset(),
  5196. this->build_id_note_->data_size(),
  5197. ov);
  5198. }
  5199. // Write out a binary file. This is called after the link is
  5200. // complete. IN is the temporary output file we used to generate the
  5201. // ELF code. We simply walk through the segments, read them from
  5202. // their file offset in IN, and write them to their load address in
  5203. // the output file. FIXME: with a bit more work, we could support
  5204. // S-records and/or Intel hex format here.
  5205. void
  5206. Layout::write_binary(Output_file* in) const
  5207. {
  5208. gold_assert(parameters->options().oformat_enum()
  5209. == General_options::OBJECT_FORMAT_BINARY);
  5210. // Get the size of the binary file.
  5211. uint64_t max_load_address = 0;
  5212. for (Segment_list::const_iterator p = this->segment_list_.begin();
  5213. p != this->segment_list_.end();
  5214. ++p)
  5215. {
  5216. if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
  5217. {
  5218. uint64_t max_paddr = (*p)->paddr() + (*p)->filesz();
  5219. if (max_paddr > max_load_address)
  5220. max_load_address = max_paddr;
  5221. }
  5222. }
  5223. Output_file out(parameters->options().output_file_name());
  5224. out.open(max_load_address);
  5225. for (Segment_list::const_iterator p = this->segment_list_.begin();
  5226. p != this->segment_list_.end();
  5227. ++p)
  5228. {
  5229. if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
  5230. {
  5231. const unsigned char* vin = in->get_input_view((*p)->offset(),
  5232. (*p)->filesz());
  5233. unsigned char* vout = out.get_output_view((*p)->paddr(),
  5234. (*p)->filesz());
  5235. memcpy(vout, vin, (*p)->filesz());
  5236. out.write_output_view((*p)->paddr(), (*p)->filesz(), vout);
  5237. in->free_input_view((*p)->offset(), (*p)->filesz(), vin);
  5238. }
  5239. }
  5240. out.close();
  5241. }
  5242. // Print the output sections to the map file.
  5243. void
  5244. Layout::print_to_mapfile(Mapfile* mapfile) const
  5245. {
  5246. for (Segment_list::const_iterator p = this->segment_list_.begin();
  5247. p != this->segment_list_.end();
  5248. ++p)
  5249. (*p)->print_sections_to_mapfile(mapfile);
  5250. for (Section_list::const_iterator p = this->unattached_section_list_.begin();
  5251. p != this->unattached_section_list_.end();
  5252. ++p)
  5253. (*p)->print_to_mapfile(mapfile);
  5254. }
  5255. // Print statistical information to stderr. This is used for --stats.
  5256. void
  5257. Layout::print_stats() const
  5258. {
  5259. this->namepool_.print_stats("section name pool");
  5260. this->sympool_.print_stats("output symbol name pool");
  5261. this->dynpool_.print_stats("dynamic name pool");
  5262. for (Section_list::const_iterator p = this->section_list_.begin();
  5263. p != this->section_list_.end();
  5264. ++p)
  5265. (*p)->print_merge_stats();
  5266. }
  5267. // Write_sections_task methods.
  5268. // We can always run this task.
  5269. Task_token*
  5270. Write_sections_task::is_runnable()
  5271. {
  5272. return NULL;
  5273. }
  5274. // We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
  5275. // when finished.
  5276. void
  5277. Write_sections_task::locks(Task_locker* tl)
  5278. {
  5279. tl->add(this, this->output_sections_blocker_);
  5280. if (this->input_sections_blocker_ != NULL)
  5281. tl->add(this, this->input_sections_blocker_);
  5282. tl->add(this, this->final_blocker_);
  5283. }
  5284. // Run the task--write out the data.
  5285. void
  5286. Write_sections_task::run(Workqueue*)
  5287. {
  5288. this->layout_->write_output_sections(this->of_);
  5289. }
  5290. // Write_data_task methods.
  5291. // We can always run this task.
  5292. Task_token*
  5293. Write_data_task::is_runnable()
  5294. {
  5295. return NULL;
  5296. }
  5297. // We need to unlock FINAL_BLOCKER when finished.
  5298. void
  5299. Write_data_task::locks(Task_locker* tl)
  5300. {
  5301. tl->add(this, this->final_blocker_);
  5302. }
  5303. // Run the task--write out the data.
  5304. void
  5305. Write_data_task::run(Workqueue*)
  5306. {
  5307. this->layout_->write_data(this->symtab_, this->of_);
  5308. }
  5309. // Write_symbols_task methods.
  5310. // We can always run this task.
  5311. Task_token*
  5312. Write_symbols_task::is_runnable()
  5313. {
  5314. return NULL;
  5315. }
  5316. // We need to unlock FINAL_BLOCKER when finished.
  5317. void
  5318. Write_symbols_task::locks(Task_locker* tl)
  5319. {
  5320. tl->add(this, this->final_blocker_);
  5321. }
  5322. // Run the task--write out the symbols.
  5323. void
  5324. Write_symbols_task::run(Workqueue*)
  5325. {
  5326. this->symtab_->write_globals(this->sympool_, this->dynpool_,
  5327. this->layout_->symtab_xindex(),
  5328. this->layout_->dynsym_xindex(), this->of_);
  5329. }
  5330. // Write_after_input_sections_task methods.
  5331. // We can only run this task after the input sections have completed.
  5332. Task_token*
  5333. Write_after_input_sections_task::is_runnable()
  5334. {
  5335. if (this->input_sections_blocker_->is_blocked())
  5336. return this->input_sections_blocker_;
  5337. return NULL;
  5338. }
  5339. // We need to unlock FINAL_BLOCKER when finished.
  5340. void
  5341. Write_after_input_sections_task::locks(Task_locker* tl)
  5342. {
  5343. tl->add(this, this->final_blocker_);
  5344. }
  5345. // Run the task.
  5346. void
  5347. Write_after_input_sections_task::run(Workqueue*)
  5348. {
  5349. this->layout_->write_sections_after_input_sections(this->of_);
  5350. }
  5351. // Build IDs can be computed as a "flat" sha1 or md5 of a string of bytes,
  5352. // or as a "tree" where each chunk of the string is hashed and then those
  5353. // hashes are put into a (much smaller) string which is hashed with sha1.
  5354. // We compute a checksum over the entire file because that is simplest.
  5355. void
  5356. Build_id_task_runner::run(Workqueue* workqueue, const Task*)
  5357. {
  5358. Task_token* post_hash_tasks_blocker = new Task_token(true);
  5359. const Layout* layout = this->layout_;
  5360. Output_file* of = this->of_;
  5361. const size_t filesize = (layout->output_file_size() <= 0 ? 0
  5362. : static_cast<size_t>(layout->output_file_size()));
  5363. unsigned char* array_of_hashes = NULL;
  5364. size_t size_of_hashes = 0;
  5365. if (strcmp(this->options_->build_id(), "tree") == 0
  5366. && this->options_->build_id_chunk_size_for_treehash() > 0
  5367. && filesize > 0
  5368. && (filesize >= this->options_->build_id_min_file_size_for_treehash()))
  5369. {
  5370. static const size_t MD5_OUTPUT_SIZE_IN_BYTES = 16;
  5371. const size_t chunk_size =
  5372. this->options_->build_id_chunk_size_for_treehash();
  5373. const size_t num_hashes = ((filesize - 1) / chunk_size) + 1;
  5374. post_hash_tasks_blocker->add_blockers(num_hashes);
  5375. size_of_hashes = num_hashes * MD5_OUTPUT_SIZE_IN_BYTES;
  5376. array_of_hashes = new unsigned char[size_of_hashes];
  5377. unsigned char *dst = array_of_hashes;
  5378. for (size_t i = 0, src_offset = 0; i < num_hashes;
  5379. i++, dst += MD5_OUTPUT_SIZE_IN_BYTES, src_offset += chunk_size)
  5380. {
  5381. size_t size = std::min(chunk_size, filesize - src_offset);
  5382. workqueue->queue(new Hash_task(of,
  5383. src_offset,
  5384. size,
  5385. dst,
  5386. post_hash_tasks_blocker));
  5387. }
  5388. }
  5389. // Queue the final task to write the build id and close the output file.
  5390. workqueue->queue(new Task_function(new Close_task_runner(this->options_,
  5391. layout,
  5392. of,
  5393. array_of_hashes,
  5394. size_of_hashes),
  5395. post_hash_tasks_blocker,
  5396. "Task_function Close_task_runner"));
  5397. }
  5398. // Close_task_runner methods.
  5399. // Finish up the build ID computation, if necessary, and write a binary file,
  5400. // if necessary. Then close the output file.
  5401. void
  5402. Close_task_runner::run(Workqueue*, const Task*)
  5403. {
  5404. // At this point the multi-threaded part of the build ID computation,
  5405. // if any, is done. See Build_id_task_runner.
  5406. this->layout_->write_build_id(this->of_, this->array_of_hashes_,
  5407. this->size_of_hashes_);
  5408. // If we've been asked to create a binary file, we do so here.
  5409. if (this->options_->oformat_enum() != General_options::OBJECT_FORMAT_ELF)
  5410. this->layout_->write_binary(this->of_);
  5411. if (this->options_->dependency_file())
  5412. File_read::write_dependency_file(this->options_->dependency_file(),
  5413. this->options_->output_file_name());
  5414. this->of_->close();
  5415. }
  5416. // Instantiate the templates we need. We could use the configure
  5417. // script to restrict this to only the ones for implemented targets.
  5418. #ifdef HAVE_TARGET_32_LITTLE
  5419. template
  5420. Output_section*
  5421. Layout::init_fixed_output_section<32, false>(
  5422. const char* name,
  5423. elfcpp::Shdr<32, false>& shdr);
  5424. #endif
  5425. #ifdef HAVE_TARGET_32_BIG
  5426. template
  5427. Output_section*
  5428. Layout::init_fixed_output_section<32, true>(
  5429. const char* name,
  5430. elfcpp::Shdr<32, true>& shdr);
  5431. #endif
  5432. #ifdef HAVE_TARGET_64_LITTLE
  5433. template
  5434. Output_section*
  5435. Layout::init_fixed_output_section<64, false>(
  5436. const char* name,
  5437. elfcpp::Shdr<64, false>& shdr);
  5438. #endif
  5439. #ifdef HAVE_TARGET_64_BIG
  5440. template
  5441. Output_section*
  5442. Layout::init_fixed_output_section<64, true>(
  5443. const char* name,
  5444. elfcpp::Shdr<64, true>& shdr);
  5445. #endif
  5446. #ifdef HAVE_TARGET_32_LITTLE
  5447. template
  5448. Output_section*
  5449. Layout::layout<32, false>(Sized_relobj_file<32, false>* object,
  5450. unsigned int shndx,
  5451. const char* name,
  5452. const elfcpp::Shdr<32, false>& shdr,
  5453. unsigned int, unsigned int, unsigned int, off_t*);
  5454. #endif
  5455. #ifdef HAVE_TARGET_32_BIG
  5456. template
  5457. Output_section*
  5458. Layout::layout<32, true>(Sized_relobj_file<32, true>* object,
  5459. unsigned int shndx,
  5460. const char* name,
  5461. const elfcpp::Shdr<32, true>& shdr,
  5462. unsigned int, unsigned int, unsigned int, off_t*);
  5463. #endif
  5464. #ifdef HAVE_TARGET_64_LITTLE
  5465. template
  5466. Output_section*
  5467. Layout::layout<64, false>(Sized_relobj_file<64, false>* object,
  5468. unsigned int shndx,
  5469. const char* name,
  5470. const elfcpp::Shdr<64, false>& shdr,
  5471. unsigned int, unsigned int, unsigned int, off_t*);
  5472. #endif
  5473. #ifdef HAVE_TARGET_64_BIG
  5474. template
  5475. Output_section*
  5476. Layout::layout<64, true>(Sized_relobj_file<64, true>* object,
  5477. unsigned int shndx,
  5478. const char* name,
  5479. const elfcpp::Shdr<64, true>& shdr,
  5480. unsigned int, unsigned int, unsigned int, off_t*);
  5481. #endif
  5482. #ifdef HAVE_TARGET_32_LITTLE
  5483. template
  5484. Output_section*
  5485. Layout::layout_reloc<32, false>(Sized_relobj_file<32, false>* object,
  5486. unsigned int reloc_shndx,
  5487. const elfcpp::Shdr<32, false>& shdr,
  5488. Output_section* data_section,
  5489. Relocatable_relocs* rr);
  5490. #endif
  5491. #ifdef HAVE_TARGET_32_BIG
  5492. template
  5493. Output_section*
  5494. Layout::layout_reloc<32, true>(Sized_relobj_file<32, true>* object,
  5495. unsigned int reloc_shndx,
  5496. const elfcpp::Shdr<32, true>& shdr,
  5497. Output_section* data_section,
  5498. Relocatable_relocs* rr);
  5499. #endif
  5500. #ifdef HAVE_TARGET_64_LITTLE
  5501. template
  5502. Output_section*
  5503. Layout::layout_reloc<64, false>(Sized_relobj_file<64, false>* object,
  5504. unsigned int reloc_shndx,
  5505. const elfcpp::Shdr<64, false>& shdr,
  5506. Output_section* data_section,
  5507. Relocatable_relocs* rr);
  5508. #endif
  5509. #ifdef HAVE_TARGET_64_BIG
  5510. template
  5511. Output_section*
  5512. Layout::layout_reloc<64, true>(Sized_relobj_file<64, true>* object,
  5513. unsigned int reloc_shndx,
  5514. const elfcpp::Shdr<64, true>& shdr,
  5515. Output_section* data_section,
  5516. Relocatable_relocs* rr);
  5517. #endif
  5518. #ifdef HAVE_TARGET_32_LITTLE
  5519. template
  5520. void
  5521. Layout::layout_group<32, false>(Symbol_table* symtab,
  5522. Sized_relobj_file<32, false>* object,
  5523. unsigned int,
  5524. const char* group_section_name,
  5525. const char* signature,
  5526. const elfcpp::Shdr<32, false>& shdr,
  5527. elfcpp::Elf_Word flags,
  5528. std::vector<unsigned int>* shndxes);
  5529. #endif
  5530. #ifdef HAVE_TARGET_32_BIG
  5531. template
  5532. void
  5533. Layout::layout_group<32, true>(Symbol_table* symtab,
  5534. Sized_relobj_file<32, true>* object,
  5535. unsigned int,
  5536. const char* group_section_name,
  5537. const char* signature,
  5538. const elfcpp::Shdr<32, true>& shdr,
  5539. elfcpp::Elf_Word flags,
  5540. std::vector<unsigned int>* shndxes);
  5541. #endif
  5542. #ifdef HAVE_TARGET_64_LITTLE
  5543. template
  5544. void
  5545. Layout::layout_group<64, false>(Symbol_table* symtab,
  5546. Sized_relobj_file<64, false>* object,
  5547. unsigned int,
  5548. const char* group_section_name,
  5549. const char* signature,
  5550. const elfcpp::Shdr<64, false>& shdr,
  5551. elfcpp::Elf_Word flags,
  5552. std::vector<unsigned int>* shndxes);
  5553. #endif
  5554. #ifdef HAVE_TARGET_64_BIG
  5555. template
  5556. void
  5557. Layout::layout_group<64, true>(Symbol_table* symtab,
  5558. Sized_relobj_file<64, true>* object,
  5559. unsigned int,
  5560. const char* group_section_name,
  5561. const char* signature,
  5562. const elfcpp::Shdr<64, true>& shdr,
  5563. elfcpp::Elf_Word flags,
  5564. std::vector<unsigned int>* shndxes);
  5565. #endif
  5566. #ifdef HAVE_TARGET_32_LITTLE
  5567. template
  5568. Output_section*
  5569. Layout::layout_eh_frame<32, false>(Sized_relobj_file<32, false>* object,
  5570. const unsigned char* symbols,
  5571. off_t symbols_size,
  5572. const unsigned char* symbol_names,
  5573. off_t symbol_names_size,
  5574. unsigned int shndx,
  5575. const elfcpp::Shdr<32, false>& shdr,
  5576. unsigned int reloc_shndx,
  5577. unsigned int reloc_type,
  5578. off_t* off);
  5579. #endif
  5580. #ifdef HAVE_TARGET_32_BIG
  5581. template
  5582. Output_section*
  5583. Layout::layout_eh_frame<32, true>(Sized_relobj_file<32, true>* object,
  5584. const unsigned char* symbols,
  5585. off_t symbols_size,
  5586. const unsigned char* symbol_names,
  5587. off_t symbol_names_size,
  5588. unsigned int shndx,
  5589. const elfcpp::Shdr<32, true>& shdr,
  5590. unsigned int reloc_shndx,
  5591. unsigned int reloc_type,
  5592. off_t* off);
  5593. #endif
  5594. #ifdef HAVE_TARGET_64_LITTLE
  5595. template
  5596. Output_section*
  5597. Layout::layout_eh_frame<64, false>(Sized_relobj_file<64, false>* object,
  5598. const unsigned char* symbols,
  5599. off_t symbols_size,
  5600. const unsigned char* symbol_names,
  5601. off_t symbol_names_size,
  5602. unsigned int shndx,
  5603. const elfcpp::Shdr<64, false>& shdr,
  5604. unsigned int reloc_shndx,
  5605. unsigned int reloc_type,
  5606. off_t* off);
  5607. #endif
  5608. #ifdef HAVE_TARGET_64_BIG
  5609. template
  5610. Output_section*
  5611. Layout::layout_eh_frame<64, true>(Sized_relobj_file<64, true>* object,
  5612. const unsigned char* symbols,
  5613. off_t symbols_size,
  5614. const unsigned char* symbol_names,
  5615. off_t symbol_names_size,
  5616. unsigned int shndx,
  5617. const elfcpp::Shdr<64, true>& shdr,
  5618. unsigned int reloc_shndx,
  5619. unsigned int reloc_type,
  5620. off_t* off);
  5621. #endif
  5622. #ifdef HAVE_TARGET_32_LITTLE
  5623. template
  5624. void
  5625. Layout::add_to_gdb_index(bool is_type_unit,
  5626. Sized_relobj<32, false>* object,
  5627. const unsigned char* symbols,
  5628. off_t symbols_size,
  5629. unsigned int shndx,
  5630. unsigned int reloc_shndx,
  5631. unsigned int reloc_type);
  5632. #endif
  5633. #ifdef HAVE_TARGET_32_BIG
  5634. template
  5635. void
  5636. Layout::add_to_gdb_index(bool is_type_unit,
  5637. Sized_relobj<32, true>* object,
  5638. const unsigned char* symbols,
  5639. off_t symbols_size,
  5640. unsigned int shndx,
  5641. unsigned int reloc_shndx,
  5642. unsigned int reloc_type);
  5643. #endif
  5644. #ifdef HAVE_TARGET_64_LITTLE
  5645. template
  5646. void
  5647. Layout::add_to_gdb_index(bool is_type_unit,
  5648. Sized_relobj<64, false>* object,
  5649. const unsigned char* symbols,
  5650. off_t symbols_size,
  5651. unsigned int shndx,
  5652. unsigned int reloc_shndx,
  5653. unsigned int reloc_type);
  5654. #endif
  5655. #ifdef HAVE_TARGET_64_BIG
  5656. template
  5657. void
  5658. Layout::add_to_gdb_index(bool is_type_unit,
  5659. Sized_relobj<64, true>* object,
  5660. const unsigned char* symbols,
  5661. off_t symbols_size,
  5662. unsigned int shndx,
  5663. unsigned int reloc_shndx,
  5664. unsigned int reloc_type);
  5665. #endif
  5666. } // End namespace gold.