ogelf.pas 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475
  1. {
  2. Copyright (c) 1998-2006 by Peter Vreman
  3. Contains the binary elf writer
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit ogelf;
  18. {$i fpcdefs.inc}
  19. interface
  20. uses
  21. { common }
  22. cclasses,globtype,
  23. { target }
  24. systems,
  25. { assembler }
  26. aasmbase,assemble,
  27. { ELF definitions }
  28. elfbase,
  29. { output }
  30. ogbase,
  31. owbase;
  32. type
  33. {$ifdef cpu64bitaddr}
  34. TElfsechdr = TElf64sechdr;
  35. {$else cpu64bitaddr}
  36. TElfsechdr = TElf32sechdr;
  37. {$endif cpu64bitaddr}
  38. TElfObjSection = class(TObjSection)
  39. public
  40. shstridx,
  41. shtype,
  42. shflags,
  43. shlink,
  44. shinfo,
  45. shentsize : longint;
  46. constructor create(AList:TFPHashObjectList;const Aname:string;Aalign:longint;Aoptions:TObjSectionOptions);override;
  47. constructor create_ext(aobjdata:TObjData;const Aname:string;Ashtype,Ashflags:longint;Aalign:longint;Aentsize:longint);
  48. constructor create_reloc(aobjdata:TObjData;const Aname:string;allocflag:boolean);
  49. procedure writeReloc_internal(aTarget:TObjSection;offset:aword;len:byte;reltype:TObjRelocationType);override;
  50. end;
  51. TElfSymtabKind = (esk_obj,esk_exe,esk_dyn);
  52. TElfSymtab = class(TElfObjSection)
  53. public
  54. kind: TElfSymtabKind;
  55. fstrsec: TObjSection;
  56. symidx: longint;
  57. tlsbase: aword;
  58. constructor create(aObjData:TObjData;aKind:TElfSymtabKind);reintroduce;
  59. procedure writeSymbol(objsym:TObjSymbol;nameidx:longword=0);
  60. procedure writeInternalSymbol(avalue:aword;astridx:longword;ainfo:byte;ashndx:word);
  61. end;
  62. TElfObjData = class(TObjData)
  63. public
  64. ident: TElfIdent;
  65. flags: longword;
  66. {$ifdef mips}
  67. gp_value: longword;
  68. {$endif mips}
  69. constructor create(const n:string);override;
  70. function sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;override;
  71. procedure CreateDebugSections;override;
  72. procedure writereloc(data:aint;len:aword;p:TObjSymbol;reltype:TObjRelocationType);override;
  73. end;
  74. TElfObjectOutput = class(tObjOutput)
  75. private
  76. symtabsect: TElfSymtab;
  77. shstrtabsect: TElfObjSection;
  78. procedure createrelocsection(s:TElfObjSection;data:TObjData);
  79. procedure createshstrtab(data:TObjData);
  80. procedure createsymtab(data: TObjData);
  81. procedure writesectionheader(s:TElfObjSection);
  82. procedure section_write_symbol(p:TObject;arg:pointer);
  83. procedure section_count_sections(p:TObject;arg:pointer);
  84. procedure section_create_relocsec(p:TObject;arg:pointer);
  85. procedure section_write_sechdr(p:TObject;arg:pointer);
  86. protected
  87. function writedata(data:TObjData):boolean;override;
  88. public
  89. constructor Create(AWriter:TObjectWriter);override;
  90. end;
  91. TElfAssembler = class(tinternalassembler)
  92. constructor create(info: pasminfo; smart:boolean);override;
  93. end;
  94. PSectionRec=^TSectionRec;
  95. TSectionRec=record
  96. sec: TObjSection;
  97. relocpos: aword;
  98. relocs: longint;
  99. relentsize: longint;
  100. end;
  101. TElfsecheaderarray=array of TElfsechdr;
  102. TObjSymbolClass=class of TObjSymbol;
  103. TElfObjInput=class(TObjInput)
  104. private
  105. FSecTbl: PSectionRec;
  106. FSymTbl: PPointer;
  107. FLoaded: PBoolean;
  108. shdrs: TElfsecheaderarray;
  109. nsects: longword;
  110. shoffset: aword;
  111. shstrndx: longword;
  112. symtabndx: longword;
  113. shstrtab: PChar;
  114. strtab: PChar;
  115. shstrtablen: longword;
  116. strtablen: longword;
  117. symtaboffset: aword;
  118. syms: longword;
  119. localsyms: longword;
  120. symversions: PWord;
  121. dynobj: boolean;
  122. CObjSymbol: TObjSymbolClass;
  123. verdefs: TFPHashObjectList;
  124. function LoadHeader(out objdata:TObjData):boolean;
  125. procedure LoadSection(const shdr:TElfsechdr;index:longint;objdata:TObjData);
  126. procedure LoadRelocations(const secrec:TSectionRec);
  127. procedure LoadSymbols(objdata:TObjData;count,locals:longword);
  128. procedure LoadDynamic(const shdr:TElfsechdr;objdata:TObjData);
  129. public
  130. constructor Create;override;
  131. destructor Destroy;override;
  132. function ReadObjData(AReader:TObjectreader;out objdata:TObjData):boolean;override;
  133. class function CanReadObjData(AReader:TObjectreader):boolean;override;
  134. function CreateSection(const shdr:TElfsechdr;index:longint;objdata:TObjData;
  135. out secname:string):TElfObjSection;
  136. function ReadBytes(offs:longint;out buf;len:longint):boolean;
  137. end;
  138. TElfVersionDef = class(TFPHashObject)
  139. public
  140. index: longword;
  141. end;
  142. TElfDynamicObjData = class(TElfObjData)
  143. private
  144. FVersionDefs: TFPHashObjectList;
  145. public
  146. soname_strofs: longword;
  147. vernaux_count: longword;
  148. constructor create(const n:string);override;
  149. destructor destroy;override;
  150. property versiondefs:TFPHashObjectList read FVersionDefs;
  151. end;
  152. TVersionedObjSymbol = class(TObjSymbol)
  153. private
  154. FVersion: TElfVersionDef;
  155. public
  156. property version: TElfVersionDef read FVersion write FVersion;
  157. end;
  158. TRelocNameProc=function(reltyp:byte):string;
  159. TEncodeRelocProc=function(objrel:TObjRelocation):byte;
  160. TLoadRelocProc=procedure(objrel:TObjRelocation);
  161. TLoadSectionProc=function(objinput:TElfObjInput;objdata:TObjData;const shdr:TElfsechdr;shindex:longint):boolean;
  162. TEncodeFlagsProc=function:longword;
  163. TDynamicReloc=(
  164. dr_relative,
  165. dr_glob_dat,
  166. dr_jump_slot,
  167. dr_copy,
  168. dr_irelative
  169. );
  170. TElfTarget=record
  171. max_page_size: longword;
  172. exe_image_base: longword;
  173. machine_code: word;
  174. relocs_use_addend: boolean;
  175. dyn_reloc_codes: array[TDynamicReloc] of byte;
  176. relocname: TRelocNameProc;
  177. encodereloc: TEncodeRelocProc;
  178. loadreloc: TLoadRelocProc;
  179. loadsection: TLoadSectionProc;
  180. encodeflags: TEncodeFlagsProc;
  181. end;
  182. TElfExeSection=class(TExeSection)
  183. public
  184. secshidx : longword; { index of the section header }
  185. shstridx,
  186. shtype,
  187. shflags,
  188. shlink,
  189. shinfo,
  190. shentsize : longword;
  191. procedure AddObjSection(objsec:TObjSection;ignoreprops:boolean=false);override;
  192. end;
  193. TElfSegment=class
  194. public
  195. ptype: longword;
  196. pflags: longword;
  197. DataPos: aword;
  198. DataSize: aword;
  199. MemPos: aword;
  200. MemSize: aword;
  201. align: longword;
  202. //physaddr: aword;
  203. FSectionList: TFPObjectList;
  204. constructor Create(atype,aflags,aalign:longword);
  205. destructor Destroy; override;
  206. procedure Add(exesec:TExeSection);
  207. end;
  208. TElfExeOutput=class(TExeOutput)
  209. private
  210. segmentlist: TFPObjectList;
  211. textseg,
  212. dataseg,
  213. noteseg,
  214. phdrseg: TElfSegment;
  215. shstrtabsect: TElfObjSection;
  216. symtab: TElfSymtab;
  217. shoffset: aword;
  218. gotwritten: boolean;
  219. { dynamic linking }
  220. dynsymnames: Plongword;
  221. dynsymtable: TElfSymtab;
  222. interpobjsec: TObjSection;
  223. FInterpreter: pshortstring;
  224. verneedcount,
  225. verdefcount: longword;
  226. symversec,
  227. verdefsec,
  228. verneedsec,
  229. hashobjsec: TElfObjSection;
  230. neededlist: TFPHashList;
  231. dyncopysyms: TFPObjectList;
  232. preinitarraysec,
  233. initarraysec,
  234. finiarraysec: TObjSection;
  235. function AttachSection(objsec:TObjSection):TElfExeSection;
  236. function CreateSegment(atype,aflags,aalign:longword):TElfSegment;
  237. procedure WriteHeader;
  238. procedure WriteDynamicSymbolsHash;
  239. procedure WriteVersionSections;
  240. procedure WriteDynamicTags;
  241. procedure FinishDynamicTags;
  242. procedure exesection_write_header(p:TObject;arg:Pointer);
  243. procedure segment_write_header(p:TObject;arg:Pointer);
  244. procedure mempos_segment(seg:TElfSegment);
  245. procedure datapos_segment(seg:TElfSegment);
  246. procedure MapSectionsToSegments;
  247. procedure WriteStaticSymtable;
  248. procedure WriteShstrtab;
  249. procedure FixupSectionLinks;
  250. procedure InitDynlink;
  251. procedure OrderOrphanSections;
  252. protected
  253. dynamiclink: boolean;
  254. hastextrelocs: boolean;
  255. gotsymbol: TObjSymbol;
  256. dynsymlist: TFPObjectList;
  257. dynamicsec,
  258. gotobjsec: TObjSection;
  259. dynbssobjsec,
  260. pltobjsec,
  261. gotpltobjsec,
  262. pltrelocsec,
  263. ipltrelocsec,
  264. dynrelocsec: TElfObjSection;
  265. dynreloclist: TFPObjectList;
  266. tlsseg: TElfSegment;
  267. relative_reloc_count: longint;
  268. gotsize: aword;
  269. dynrelsize: aword;
  270. procedure PrepareGOT;virtual;
  271. function AllocGOTSlot(objsym: TObjSymbol):boolean;virtual;
  272. procedure CreateGOTSection;virtual;
  273. procedure make_dynamic_if_undefweak(exesym:TExeSymbol);
  274. procedure WriteDynRelocEntry(dataofs:aword;typ:byte;symidx:aword;addend:aword);
  275. procedure CreatePLT;virtual;
  276. procedure WriteFirstPLTEntry;virtual;abstract;
  277. procedure WritePLTEntry(exesym:TExeSymbol);virtual;
  278. procedure WriteIndirectPLTEntry(exesym:TExeSymbol);virtual;
  279. procedure WriteTargetDynamicTags;virtual;
  280. procedure GOTRelocPass1(objsec:TObjSection;var idx:longint);virtual;abstract;
  281. procedure ReportNonDSOReloc(reltyp:byte;objsec:TObjSection;ObjReloc:TObjRelocation);
  282. procedure ReportRelocOverflow(reltyp:byte;objsec:TObjSection;ObjReloc:TObjRelocation);
  283. procedure WriteDynTag(aTag:longword;aValue:longword);
  284. procedure WriteDynTag(aTag:longword;aSection:TObjSection;aOffs:aword=0);
  285. procedure Do_Mempos;virtual;
  286. public
  287. constructor Create;override;
  288. destructor Destroy;override;
  289. procedure Load_Start;override;
  290. procedure Load_DynamicObject(ObjData:TObjData;asneeded:boolean);override;
  291. procedure Order_Start;override;
  292. procedure Order_end;override;
  293. procedure AfterUnusedSectionRemoval;override;
  294. procedure MemPos_Start;override;
  295. procedure MemPos_ExeSection(const aname:string);override;
  296. procedure DataPos_Start;override;
  297. procedure DataPos_ExeSection(const aname:string);override;
  298. function writeData:boolean;override;
  299. procedure GenerateLibraryImports(ImportLibraryList:TFPHashObjectList);override;
  300. property interpreter:pshortstring read FInterpreter write FInterpreter;
  301. end;
  302. var
  303. ElfExeOutputClass: TExeOutputClass;
  304. ElfTarget: TElfTarget;
  305. const
  306. { Bits of TObjSymbol.refs field }
  307. symref_plt = 1;
  308. symref_from_text = 2;
  309. implementation
  310. uses
  311. SysUtils,
  312. verbose,
  313. export,expunix,
  314. cutils,globals,fmodule,owar;
  315. const
  316. symbolresize = 200*18;
  317. {$ifdef cpu64bitaddr}
  318. const
  319. ELFCLASS = ELFCLASS64;
  320. type
  321. telfheader = telf64header;
  322. telfreloc = telf64reloc;
  323. telfsymbol = telf64symbol;
  324. telfproghdr = telf64proghdr;
  325. telfdyn = telf64dyn;
  326. function ELF_R_INFO(sym:longword;typ:byte):qword;inline;
  327. begin
  328. result:=(qword(sym) shl 32) or typ;
  329. end;
  330. {$else cpu64bitaddr}
  331. const
  332. ELFCLASS = ELFCLASS32;
  333. type
  334. telfheader = telf32header;
  335. telfreloc = telf32reloc;
  336. telfsymbol = telf32symbol;
  337. telfproghdr = telf32proghdr;
  338. telfdyn = telf32dyn;
  339. function ELF_R_INFO(sym:longword;typ:byte):longword;inline;
  340. begin
  341. result:=(sym shl 8) or typ;
  342. end;
  343. {$endif cpu64bitaddr}
  344. procedure MayBeSwapHeader(var h : telf32header);
  345. begin
  346. if source_info.endian<>target_info.endian then
  347. with h do
  348. begin
  349. e_type:=swapendian(e_type);
  350. e_machine:=swapendian(e_machine);
  351. e_version:=swapendian(e_version);
  352. e_entry:=swapendian(e_entry);
  353. e_phoff:=swapendian(e_phoff);
  354. e_shoff:=swapendian(e_shoff);
  355. e_flags:=swapendian(e_flags);
  356. e_ehsize:=swapendian(e_ehsize);
  357. e_phentsize:=swapendian(e_phentsize);
  358. e_phnum:=swapendian(e_phnum);
  359. e_shentsize:=swapendian(e_shentsize);
  360. e_shnum:=swapendian(e_shnum);
  361. e_shstrndx:=swapendian(e_shstrndx);
  362. end;
  363. end;
  364. procedure MayBeSwapHeader(var h : telf64header);
  365. begin
  366. if source_info.endian<>target_info.endian then
  367. with h do
  368. begin
  369. e_type:=swapendian(e_type);
  370. e_machine:=swapendian(e_machine);
  371. e_version:=swapendian(e_version);
  372. e_entry:=swapendian(e_entry);
  373. e_phoff:=swapendian(e_phoff);
  374. e_shoff:=swapendian(e_shoff);
  375. e_flags:=swapendian(e_flags);
  376. e_ehsize:=swapendian(e_ehsize);
  377. e_phentsize:=swapendian(e_phentsize);
  378. e_phnum:=swapendian(e_phnum);
  379. e_shentsize:=swapendian(e_shentsize);
  380. e_shnum:=swapendian(e_shnum);
  381. e_shstrndx:=swapendian(e_shstrndx);
  382. end;
  383. end;
  384. procedure MayBeSwapHeader(var h : telf32proghdr);
  385. begin
  386. if source_info.endian<>target_info.endian then
  387. with h do
  388. begin
  389. p_align:=swapendian(p_align);
  390. p_filesz:=swapendian(p_filesz);
  391. p_flags:=swapendian(p_flags);
  392. p_memsz:=swapendian(p_memsz);
  393. p_offset:=swapendian(p_offset);
  394. p_paddr:=swapendian(p_paddr);
  395. p_type:=swapendian(p_type);
  396. p_vaddr:=swapendian(p_vaddr);
  397. end;
  398. end;
  399. procedure MayBeSwapHeader(var h : telf64proghdr);
  400. begin
  401. if source_info.endian<>target_info.endian then
  402. with h do
  403. begin
  404. p_align:=swapendian(p_align);
  405. p_filesz:=swapendian(p_filesz);
  406. p_flags:=swapendian(p_flags);
  407. p_memsz:=swapendian(p_memsz);
  408. p_offset:=swapendian(p_offset);
  409. p_paddr:=swapendian(p_paddr);
  410. p_type:=swapendian(p_type);
  411. p_vaddr:=swapendian(p_vaddr);
  412. end;
  413. end;
  414. procedure MaybeSwapSecHeader(var h : telf32sechdr);
  415. begin
  416. if source_info.endian<>target_info.endian then
  417. with h do
  418. begin
  419. sh_name:=swapendian(sh_name);
  420. sh_type:=swapendian(sh_type);
  421. sh_flags:=swapendian(sh_flags);
  422. sh_addr:=swapendian(sh_addr);
  423. sh_offset:=swapendian(sh_offset);
  424. sh_size:=swapendian(sh_size);
  425. sh_link:=swapendian(sh_link);
  426. sh_info:=swapendian(sh_info);
  427. sh_addralign:=swapendian(sh_addralign);
  428. sh_entsize:=swapendian(sh_entsize);
  429. end;
  430. end;
  431. procedure MaybeSwapSecHeader(var h : telf64sechdr);
  432. begin
  433. if source_info.endian<>target_info.endian then
  434. with h do
  435. begin
  436. sh_name:=swapendian(sh_name);
  437. sh_type:=swapendian(sh_type);
  438. sh_flags:=swapendian(sh_flags);
  439. sh_addr:=swapendian(sh_addr);
  440. sh_offset:=swapendian(sh_offset);
  441. sh_size:=swapendian(sh_size);
  442. sh_link:=swapendian(sh_link);
  443. sh_info:=swapendian(sh_info);
  444. sh_addralign:=swapendian(sh_addralign);
  445. sh_entsize:=swapendian(sh_entsize);
  446. end;
  447. end;
  448. procedure MaybeSwapElfSymbol(var h : telf32symbol);
  449. begin
  450. if source_info.endian<>target_info.endian then
  451. with h do
  452. begin
  453. st_name:=swapendian(st_name);
  454. st_value:=swapendian(st_value);
  455. st_size:=swapendian(st_size);
  456. st_shndx:=swapendian(st_shndx);
  457. end;
  458. end;
  459. procedure MaybeSwapElfSymbol(var h : telf64symbol);
  460. begin
  461. if source_info.endian<>target_info.endian then
  462. with h do
  463. begin
  464. st_name:=swapendian(st_name);
  465. st_value:=swapendian(st_value);
  466. st_size:=swapendian(st_size);
  467. st_shndx:=swapendian(st_shndx);
  468. end;
  469. end;
  470. procedure MaybeSwapElfReloc(var h : telf32reloc);
  471. begin
  472. if source_info.endian<>target_info.endian then
  473. with h do
  474. begin
  475. address:=swapendian(address);
  476. info:=swapendian(info);
  477. addend:=swapendian(addend);
  478. end;
  479. end;
  480. procedure MaybeSwapElfReloc(var h : telf64reloc);
  481. begin
  482. if source_info.endian<>target_info.endian then
  483. with h do
  484. begin
  485. address:=swapendian(address);
  486. info:=swapendian(info);
  487. addend:=swapendian(addend);
  488. end;
  489. end;
  490. procedure MaybeSwapElfDyn(var h : telf32dyn);
  491. begin
  492. if source_info.endian<>target_info.endian then
  493. with h do
  494. begin
  495. d_tag:=swapendian(d_tag);
  496. d_val:=swapendian(d_val);
  497. end;
  498. end;
  499. procedure MaybeSwapElfDyn(var h : telf64dyn);
  500. begin
  501. if source_info.endian<>target_info.endian then
  502. with h do
  503. begin
  504. d_tag:=swapendian(d_tag);
  505. d_val:=swapendian(d_val);
  506. end;
  507. end;
  508. procedure MaybeSwapElfverdef(var h: TElfverdef);
  509. begin
  510. if source_info.endian<>target_info.endian then
  511. with h do
  512. begin
  513. vd_version:=swapendian(vd_version);
  514. vd_flags:=swapendian(vd_flags);
  515. vd_ndx:=swapendian(vd_ndx);
  516. vd_cnt:=swapendian(vd_cnt);
  517. vd_hash:=swapendian(vd_hash);
  518. vd_aux:=swapendian(vd_aux);
  519. vd_next:=swapendian(vd_next);
  520. end;
  521. end;
  522. procedure MaybeSwapElfverdaux(var h: TElfverdaux);
  523. begin
  524. if source_info.endian<>target_info.endian then
  525. with h do
  526. begin
  527. vda_name:=swapendian(vda_name);
  528. vda_next:=swapendian(vda_next);
  529. end;
  530. end;
  531. procedure MaybeSwapElfverneed(var h: TElfverneed);
  532. begin
  533. if source_info.endian<>target_info.endian then
  534. with h do
  535. begin
  536. vn_version:=swapendian(vn_version);
  537. vn_cnt:=swapendian(vn_cnt);
  538. vn_file:=swapendian(vn_file);
  539. vn_aux:=swapendian(vn_aux);
  540. vn_next:=swapendian(vn_next);
  541. end;
  542. end;
  543. procedure MaybeSwapElfvernaux(var h: TElfvernaux);
  544. begin
  545. if source_info.endian<>target_info.endian then
  546. with h do
  547. begin
  548. vna_hash:=swapendian(vna_hash);
  549. vna_flags:=swapendian(vna_flags);
  550. vna_other:=swapendian(vna_other);
  551. vna_name:=swapendian(vna_name);
  552. vna_next:=swapendian(vna_next);
  553. end;
  554. end;
  555. {****************************************************************************
  556. Helpers
  557. ****************************************************************************}
  558. procedure encodesechdrflags(aoptions:TObjSectionOptions;out AshType:longint;out Ashflags:longint);
  559. begin
  560. { Section Type }
  561. AshType:=SHT_PROGBITS;
  562. if oso_strings in aoptions then
  563. AshType:=SHT_STRTAB
  564. else if not(oso_data in aoptions) then
  565. AshType:=SHT_NOBITS;
  566. { Section Flags }
  567. Ashflags:=0;
  568. if oso_load in aoptions then
  569. Ashflags:=Ashflags or SHF_ALLOC;
  570. if oso_executable in aoptions then
  571. Ashflags:=Ashflags or SHF_EXECINSTR;
  572. if oso_write in aoptions then
  573. Ashflags:=Ashflags or SHF_WRITE;
  574. end;
  575. procedure decodesechdrflags(AshType:longint;Ashflags:longint;out aoptions:TObjSectionOptions);
  576. begin
  577. aoptions:=[];
  578. { Section Type }
  579. if AshType<>SHT_NOBITS then
  580. include(aoptions,oso_data);
  581. if AshType=SHT_STRTAB then
  582. include(aoptions,oso_strings);
  583. { Section Flags }
  584. if Ashflags and SHF_ALLOC<>0 then
  585. include(aoptions,oso_load);
  586. if Ashflags and SHF_WRITE<>0 then
  587. include(aoptions,oso_write);
  588. if Ashflags and SHF_EXECINSTR<>0 then
  589. include(aoptions,oso_executable);
  590. end;
  591. {****************************************************************************
  592. TElfObjSection
  593. ****************************************************************************}
  594. constructor TElfObjSection.create(AList:TFPHashObjectList;const Aname:string;Aalign:longint;Aoptions:TObjSectionOptions);
  595. begin
  596. inherited create(AList,Aname,Aalign,aoptions);
  597. index:=0;
  598. shstridx:=0;
  599. encodesechdrflags(aoptions,shtype,shflags);
  600. shlink:=0;
  601. shinfo:=0;
  602. if name='.stab' then
  603. shentsize:=sizeof(TObjStabEntry);
  604. end;
  605. constructor TElfObjSection.create_ext(aobjdata:TObjData;const Aname:string;Ashtype,Ashflags:longint;Aalign:longint;Aentsize:longint);
  606. var
  607. aoptions : TObjSectionOptions;
  608. begin
  609. decodesechdrflags(Ashtype,Ashflags,aoptions);
  610. inherited create(aobjdata.ObjSectionList,Aname,Aalign,aoptions);
  611. objdata:=aobjdata;
  612. index:=0;
  613. shstridx:=0;
  614. shtype:=AshType;
  615. shflags:=AshFlags;
  616. shentsize:=Aentsize;
  617. end;
  618. const
  619. relsec_prefix:array[boolean] of string[5] = ('.rel','.rela');
  620. relsec_shtype:array[boolean] of longword = (SHT_REL,SHT_RELA);
  621. constructor TElfObjSection.create_reloc(aobjdata:TObjData;const Aname:string;allocflag:boolean);
  622. begin
  623. create_ext(aobjdata,
  624. relsec_prefix[ElfTarget.relocs_use_addend]+aname,
  625. relsec_shtype[ElfTarget.relocs_use_addend],
  626. SHF_ALLOC*ord(allocflag),
  627. sizeof(pint),
  628. (2+ord(ElfTarget.relocs_use_addend))*sizeof(pint));
  629. end;
  630. procedure TElfObjSection.writeReloc_internal(aTarget:TObjSection;offset:aword;len:byte;reltype:TObjRelocationType);
  631. var
  632. reloc: TObjRelocation;
  633. begin
  634. reloc:=TObjRelocation.CreateSection(Size,aTarget,reltype);
  635. reloc.size:=len;
  636. ObjRelocations.Add(reloc);
  637. if reltype=RELOC_RELATIVE then
  638. { ARM does not require this adjustment, other CPUs must be checked }
  639. {$if defined(i386) or defined(x86_64)}
  640. dec(offset,len)
  641. {$endif i386 or x86_64}
  642. else if reltype<>RELOC_ABSOLUTE then
  643. InternalError(2012062401);
  644. if ElfTarget.relocs_use_addend then
  645. begin
  646. reloc.orgsize:=offset;
  647. offset:=0;
  648. end;
  649. write(offset,len);
  650. end;
  651. {****************************************************************************
  652. TElfObjData
  653. ****************************************************************************}
  654. constructor TElfObjData.create(const n:string);
  655. begin
  656. inherited create(n);
  657. CObjSection:=TElfObjSection;
  658. end;
  659. function TElfObjData.sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;
  660. const
  661. secnames : array[TAsmSectiontype] of string[length('__DATA, __datacoal_nt,coalesced')] = ('','',
  662. { TODO: sec_rodata is still writable }
  663. '.text','.data','.data','.rodata','.bss','.threadvar',
  664. '.pdata',
  665. '.text', { darwin stubs }
  666. '__DATA,__nl_symbol_ptr',
  667. '__DATA,__la_symbol_ptr',
  668. '__DATA,__mod_init_func',
  669. '__DATA,__mod_term_func',
  670. '.stab','.stabstr',
  671. '.idata$2','.idata$4','.idata$5','.idata$6','.idata$7','.edata',
  672. '.eh_frame',
  673. '.debug_frame','.debug_info','.debug_line','.debug_abbrev','.debug_aranges','.debug_ranges',
  674. '.fpc',
  675. '.toc',
  676. '.init',
  677. '.fini',
  678. '.objc_class',
  679. '.objc_meta_class',
  680. '.objc_cat_cls_meth',
  681. '.objc_cat_inst_meth',
  682. '.objc_protocol',
  683. '.objc_string_object',
  684. '.objc_cls_meth',
  685. '.objc_inst_meth',
  686. '.objc_cls_refs',
  687. '.objc_message_refs',
  688. '.objc_symbols',
  689. '.objc_category',
  690. '.objc_class_vars',
  691. '.objc_instance_vars',
  692. '.objc_module_info',
  693. '.objc_class_names',
  694. '.objc_meth_var_types',
  695. '.objc_meth_var_names',
  696. '.objc_selector_strs',
  697. '.objc_protocol_ext',
  698. '.objc_class_ext',
  699. '.objc_property',
  700. '.objc_image_info',
  701. '.objc_cstring_object',
  702. '.objc_sel_fixup',
  703. '__DATA,__objc_data',
  704. '__DATA,__objc_const',
  705. '.objc_superrefs',
  706. '__DATA, __datacoal_nt,coalesced',
  707. '.objc_classlist',
  708. '.objc_nlclasslist',
  709. '.objc_catlist',
  710. '.obcj_nlcatlist',
  711. '.objc_protolist',
  712. '.stack',
  713. '.heap'
  714. );
  715. var
  716. sep : string[3];
  717. secname : string;
  718. begin
  719. { section type user gives the user full controll on the section name }
  720. if atype=sec_user then
  721. result:=aname
  722. else
  723. begin
  724. secname:=secnames[atype];
  725. if (atype=sec_fpc) and (Copy(aname,1,3)='res') then
  726. begin
  727. result:=secname+'.'+aname;
  728. exit;
  729. end;
  730. if create_smartlink_sections and (aname<>'') then
  731. begin
  732. case aorder of
  733. secorder_begin :
  734. sep:='.b_';
  735. secorder_end :
  736. sep:='.z_';
  737. else
  738. sep:='.n_';
  739. end;
  740. result:=secname+sep+aname
  741. end
  742. else
  743. result:=secname;
  744. end;
  745. end;
  746. procedure TElfObjData.CreateDebugSections;
  747. begin
  748. if target_dbg.id=dbg_stabs then
  749. begin
  750. stabssec:=createsection(sec_stab);
  751. stabstrsec:=createsection(sec_stabstr);
  752. end;
  753. end;
  754. procedure TElfObjData.writereloc(data:aint;len:aword;p:TObjSymbol;reltype:TObjRelocationType);
  755. var
  756. symaddr : aint;
  757. objreloc: TObjRelocation;
  758. begin
  759. if CurrObjSec=nil then
  760. internalerror(200403292);
  761. objreloc:=nil;
  762. if assigned(p) then
  763. begin
  764. { real address of the symbol }
  765. symaddr:=p.address;
  766. { Local ObjSymbols can be resolved already or need a section reloc }
  767. if (p.bind=AB_LOCAL) and
  768. (reltype in [RELOC_RELATIVE,RELOC_ABSOLUTE{$ifdef x86_64},RELOC_ABSOLUTE32{$endif x86_64}{$ifdef arm},RELOC_RELATIVE_24,RELOC_RELATIVE_CALL{$endif arm}]) then
  769. begin
  770. {$ifdef ARM}
  771. if (reltype in [RELOC_RELATIVE_24,RELOC_RELATIVE_CALL]) and
  772. (p.objsection=CurrObjSec) then
  773. begin
  774. data:=aint((data and $ff000000) or (((((data and $ffffff) shl 2)+(symaddr-CurrObjSec.Size)) shr 2) and $FFFFFF)); // TODO: Check overflow
  775. end
  776. else
  777. {$endif ARM}
  778. { For a reltype relocation in the same section the
  779. value can be calculated }
  780. if (p.objsection=CurrObjSec) and
  781. (reltype=RELOC_RELATIVE) then
  782. inc(data,symaddr-len-CurrObjSec.Size)
  783. else
  784. begin
  785. objreloc:=TObjRelocation.CreateSection(CurrObjSec.Size,p.objsection,reltype);
  786. CurrObjSec.ObjRelocations.Add(objreloc);
  787. inc(data,symaddr);
  788. end;
  789. end
  790. else
  791. begin
  792. objreloc:=TObjRelocation.CreateSymbol(CurrObjSec.Size,p,reltype);
  793. CurrObjSec.ObjRelocations.Add(objreloc);
  794. { If target is a local label and it isn't handled above,
  795. patch its type in order to get it written to symtable.
  796. This may happen e.g. when taking address of Pascal label in PIC mode. }
  797. if (p.bind=AB_LOCAL) and (p.typ=AT_LABEL) then
  798. p.typ:=AT_ADDR;
  799. end;
  800. end;
  801. if assigned(objreloc) then
  802. begin
  803. objreloc.size:=len;
  804. if reltype in [RELOC_RELATIVE{$ifdef x86},RELOC_PLT32{$endif}{$ifdef x86_64},RELOC_GOTPCREL{$endif}] then
  805. dec(data,len);
  806. if ElfTarget.relocs_use_addend then
  807. begin
  808. objreloc.orgsize:=aword(data);
  809. data:=0;
  810. end;
  811. end;
  812. CurrObjSec.write(data,len);
  813. end;
  814. {****************************************************************************
  815. TElfDynamicObjData
  816. ****************************************************************************}
  817. constructor TElfDynamicObjData.create(const n:string);
  818. begin
  819. inherited Create(n);
  820. FVersionDefs:=TFPHashObjectList.create(true);
  821. { Default symversions with indices 0 and 1 }
  822. TElfVersionDef.create(FVersionDefs,'*local*');
  823. TElfVersionDef.create(FVersionDefs,'*global*');
  824. end;
  825. destructor TElfDynamicObjData.destroy;
  826. begin
  827. FVersionDefs.free;
  828. inherited Destroy;
  829. end;
  830. {****************************************************************************
  831. TElfSymtab
  832. ****************************************************************************}
  833. const
  834. symsecnames: array[boolean] of string[8] = ('.symtab','.dynsym');
  835. strsecnames: array[boolean] of string[8] = ('.strtab','.dynstr');
  836. symsectypes: array[boolean] of longword = (SHT_SYMTAB,SHT_DYNSYM);
  837. symsecattrs: array[boolean] of longword = (0,SHF_ALLOC);
  838. constructor TElfSymtab.create(aObjData:TObjData;aKind:TElfSymtabKind);
  839. var
  840. dyn:boolean;
  841. begin
  842. dyn:=(aKind=esk_dyn);
  843. create_ext(aObjData,symsecnames[dyn],symsectypes[dyn],symsecattrs[dyn],sizeof(pint),sizeof(TElfSymbol));
  844. fstrsec:=TElfObjSection.create_ext(aObjData,strsecnames[dyn],SHT_STRTAB,symsecattrs[dyn],1,0);
  845. fstrsec.writezeros(1);
  846. writezeros(sizeof(TElfSymbol));
  847. symidx:=1;
  848. shinfo:=1;
  849. kind:=aKind;
  850. end;
  851. procedure TElfSymtab.writeInternalSymbol(avalue:aword;astridx:longword;ainfo:byte;ashndx:word);
  852. var
  853. elfsym:TElfSymbol;
  854. begin
  855. fillchar(elfsym,sizeof(elfsym),0);
  856. elfsym.st_value:=avalue;
  857. elfsym.st_name:=astridx;
  858. elfsym.st_info:=ainfo;
  859. elfsym.st_shndx:=ashndx;
  860. inc(symidx);
  861. inc(shinfo);
  862. MaybeSwapElfSymbol(elfsym);
  863. write(elfsym,sizeof(elfsym));
  864. end;
  865. procedure TElfSymtab.writeSymbol(objsym:TObjSymbol;nameidx:longword);
  866. var
  867. elfsym:TElfSymbol;
  868. begin
  869. fillchar(elfsym,sizeof(elfsym),0);
  870. if nameidx=0 then
  871. elfsym.st_name:=fstrsec.writestr(objsym.name)
  872. else
  873. elfsym.st_name:=nameidx;
  874. elfsym.st_size:=objsym.size;
  875. elfsym.st_value:=objsym.address;
  876. {$ifdef ARM}
  877. if objsym.ThumbFunc then
  878. inc(elfsym.st_value);
  879. {$endif ARM}
  880. case objsym.bind of
  881. AB_LOCAL :
  882. begin
  883. elfsym.st_info:=STB_LOCAL shl 4;
  884. inc(shinfo);
  885. end;
  886. AB_COMMON :
  887. begin
  888. elfsym.st_value:=size_2_align(objsym.size);
  889. elfsym.st_info:=STB_GLOBAL shl 4;
  890. elfsym.st_shndx:=SHN_COMMON;
  891. end;
  892. AB_EXTERNAL :
  893. elfsym.st_info:=STB_GLOBAL shl 4;
  894. AB_WEAK_EXTERNAL :
  895. elfsym.st_info:=STB_WEAK shl 4;
  896. AB_GLOBAL :
  897. elfsym.st_info:=STB_GLOBAL shl 4;
  898. else
  899. InternalError(2012111801);
  900. end;
  901. { External symbols must be NOTYPE in relocatable files }
  902. if (objsym.bind<>AB_EXTERNAL) or (kind<>esk_obj) then
  903. begin
  904. case objsym.typ of
  905. AT_FUNCTION :
  906. elfsym.st_info:=elfsym.st_info or STT_FUNC;
  907. AT_DATA,
  908. AT_METADATA:
  909. elfsym.st_info:=elfsym.st_info or STT_OBJECT;
  910. AT_TLS:
  911. elfsym.st_info:=elfsym.st_info or STT_TLS;
  912. AT_GNU_IFUNC:
  913. elfsym.st_info:=elfsym.st_info or STT_GNU_IFUNC;
  914. { other types are implicitly mapped to STT_NOTYPE }
  915. end;
  916. end;
  917. if objsym.bind<>AB_COMMON then
  918. begin
  919. if kind<>esk_obj then
  920. begin
  921. if assigned(objsym.objsection) and assigned(objsym.objsection.ExeSection) then
  922. begin
  923. if (objsym.typ=AT_TLS) then
  924. elfsym.st_value:=elfsym.st_value-tlsbase
  925. else if (oso_plt in objsym.objsection.SecOptions) then
  926. elfsym.st_value:=0
  927. else
  928. elfsym.st_shndx:=TElfExeSection(objsym.objsection.ExeSection).secshidx;
  929. end;
  930. end
  931. else
  932. begin
  933. if assigned(objsym.objsection) then
  934. elfsym.st_shndx:=objsym.objsection.index
  935. else
  936. elfsym.st_shndx:=SHN_UNDEF;
  937. objsym.symidx:=symidx;
  938. end;
  939. end;
  940. inc(symidx);
  941. MaybeSwapElfSymbol(elfsym);
  942. write(elfsym,sizeof(TElfSymbol));
  943. end;
  944. {****************************************************************************
  945. TElfObjectOutput
  946. ****************************************************************************}
  947. constructor TElfObjectOutput.create(AWriter:TObjectWriter);
  948. begin
  949. inherited Create(AWriter);
  950. CObjData:=TElfObjData;
  951. end;
  952. procedure TElfObjectOutput.createrelocsection(s:TElfObjSection;data:TObjData);
  953. var
  954. i : longint;
  955. rel : telfreloc;
  956. objreloc : TObjRelocation;
  957. relsym : longint;
  958. relocsect : TElfObjSection;
  959. begin
  960. { create the reloc section }
  961. relocsect:=TElfObjSection.create_reloc(data,s.name,false);
  962. relocsect.shlink:=symtabsect.index;
  963. relocsect.shinfo:=s.index;
  964. { add the relocations }
  965. for i:=0 to s.Objrelocations.count-1 do
  966. begin
  967. objreloc:=TObjRelocation(s.Objrelocations[i]);
  968. { Symbol }
  969. if assigned(objreloc.symbol) then
  970. begin
  971. if objreloc.symbol.symidx=-1 then
  972. begin
  973. writeln(objreloc.symbol.Name);
  974. internalerror(200603012);
  975. end;
  976. relsym:=objreloc.symbol.symidx;
  977. end
  978. else
  979. begin
  980. if objreloc.objsection<>nil then
  981. relsym:=objreloc.objsection.secsymidx
  982. else
  983. relsym:=SHN_UNDEF;
  984. end;
  985. rel.address:=objreloc.dataoffset;
  986. rel.info:=ELF_R_INFO(relsym,ElfTarget.encodereloc(objreloc));
  987. {$push}{$r-}
  988. rel.addend:=objreloc.orgsize;
  989. {$pop}
  990. { write reloc }
  991. { ElfXX_Rel is essentially ElfXX_Rela without the addend field. }
  992. MaybeSwapElfReloc(rel);
  993. relocsect.write(rel,relocsect.shentsize);
  994. end;
  995. end;
  996. procedure TElfObjectOutput.section_write_symbol(p:TObject;arg:pointer);
  997. begin
  998. { Must not write symbols for internal sections like .symtab }
  999. { TODO: maybe use inclusive list of section types instead }
  1000. if (TElfObjSection(p).shtype in [SHT_SYMTAB,SHT_STRTAB,SHT_REL,SHT_RELA]) then
  1001. exit;
  1002. TObjSection(p).secsymidx:=symtabsect.symidx;
  1003. symtabsect.writeInternalSymbol(0,0,STT_SECTION,TObjSection(p).index);
  1004. end;
  1005. procedure TElfObjectOutput.createsymtab(data: TObjData);
  1006. var
  1007. i : longint;
  1008. objsym : TObjSymbol;
  1009. begin
  1010. with data do
  1011. begin
  1012. { section symbols }
  1013. ObjSectionList.ForEachCall(@section_write_symbol,nil);
  1014. { First the Local Symbols, this is required by ELF. The localsyms
  1015. count stored in shinfo is used to skip the local symbols
  1016. when traversing the symtab }
  1017. for i:=0 to ObjSymbolList.Count-1 do
  1018. begin
  1019. objsym:=TObjSymbol(ObjSymbolList[i]);
  1020. if (objsym.bind=AB_LOCAL) and (objsym.typ<>AT_LABEL) then
  1021. symtabsect.WriteSymbol(objsym);
  1022. end;
  1023. { Global Symbols }
  1024. for i:=0 to ObjSymbolList.Count-1 do
  1025. begin
  1026. objsym:=TObjSymbol(ObjSymbolList[i]);
  1027. if (objsym.bind<>AB_LOCAL) then
  1028. symtabsect.WriteSymbol(objsym);
  1029. end;
  1030. { update the .symtab section header }
  1031. symtabsect.shlink:=symtabsect.fstrsec.index;
  1032. end;
  1033. end;
  1034. procedure TElfObjectOutput.createshstrtab(data: TObjData);
  1035. var
  1036. i,prefixlen:longint;
  1037. objsec,target:TElfObjSection;
  1038. begin
  1039. shstrtabsect.writezeros(1);
  1040. prefixlen:=length('.rel')+ord(ElfTarget.relocs_use_addend);
  1041. for i:=0 to data.ObjSectionList.Count-1 do
  1042. begin
  1043. objsec:=TElfObjSection(data.ObjSectionList[i]);
  1044. { Alias section names into names of corresponding reloc sections,
  1045. this is allowed by ELF specs and saves good half of .shstrtab space. }
  1046. if objsec.shtype=relsec_shtype[ElfTarget.relocs_use_addend] then
  1047. begin
  1048. target:=TElfObjSection(data.ObjSectionList[objsec.shinfo-1]);
  1049. if (target.ObjRelocations.Count=0) or
  1050. (target.shstridx<prefixlen) then
  1051. InternalError(2012101204);
  1052. objsec.shstridx:=target.shstridx-prefixlen;
  1053. end
  1054. else
  1055. begin
  1056. if objsec.ObjRelocations.Count<>0 then
  1057. shstrtabsect.write(relsec_prefix[true][1],prefixlen);
  1058. objsec.shstridx:=shstrtabsect.writestr(objsec.name);
  1059. end;
  1060. end;
  1061. end;
  1062. procedure TElfObjectOutput.writesectionheader(s:TElfObjSection);
  1063. var
  1064. sechdr : telfsechdr;
  1065. begin
  1066. fillchar(sechdr,sizeof(sechdr),0);
  1067. sechdr.sh_name:=s.shstridx;
  1068. sechdr.sh_type:=s.shtype;
  1069. sechdr.sh_flags:=s.shflags;
  1070. sechdr.sh_offset:=s.datapos;
  1071. sechdr.sh_size:=s.Size;
  1072. sechdr.sh_link:=s.shlink;
  1073. sechdr.sh_info:=s.shinfo;
  1074. sechdr.sh_addralign:=s.secalign;
  1075. sechdr.sh_entsize:=s.shentsize;
  1076. MaybeSwapSecHeader(sechdr);
  1077. writer.write(sechdr,sizeof(sechdr));
  1078. end;
  1079. procedure TElfObjectOutput.section_count_sections(p:TObject;arg:pointer);
  1080. begin
  1081. TElfObjSection(p).index:=pword(arg)^;
  1082. inc(pword(arg)^);
  1083. end;
  1084. procedure TElfObjectOutput.section_create_relocsec(p:TObject;arg:pointer);
  1085. begin
  1086. if (TElfObjSection(p).ObjRelocations.count>0) then
  1087. createrelocsection(TElfObjSection(p),TObjData(arg));
  1088. end;
  1089. procedure TElfObjectOutput.section_write_sechdr(p:TObject;arg:pointer);
  1090. begin
  1091. writesectionheader(TElfObjSection(p));
  1092. end;
  1093. function TElfObjectOutput.writedata(data:TObjData):boolean;
  1094. var
  1095. header : telfheader;
  1096. shoffset,
  1097. datapos : aword;
  1098. nsections : word;
  1099. begin
  1100. result:=false;
  1101. with data do
  1102. begin
  1103. { default sections }
  1104. symtabsect:=TElfSymtab.create(data,esk_obj);
  1105. shstrtabsect:=TElfObjSection.create_ext(data,'.shstrtab',SHT_STRTAB,0,1,0);
  1106. { "no executable stack" marker }
  1107. { TODO: used by OpenBSD/NetBSD as well? }
  1108. if (target_info.system in (systems_linux + systems_android + systems_freebsd + systems_dragonfly)) and
  1109. not(cs_executable_stack in current_settings.moduleswitches) then
  1110. TElfObjSection.create_ext(data,'.note.GNU-stack',SHT_PROGBITS,0,1,0);
  1111. { symbol for filename }
  1112. symtabsect.fstrsec.writestr(ExtractFileName(current_module.mainsource));
  1113. symtabsect.writeInternalSymbol(0,1,STT_FILE,SHN_ABS);
  1114. { calc amount of sections we have }
  1115. nsections:=1;
  1116. { also create the index in the section header table }
  1117. ObjSectionList.ForEachCall(@section_count_sections,@nsections);
  1118. { create .symtab and .strtab }
  1119. createsymtab(data);
  1120. { Create the relocation sections, this needs valid secidx and symidx }
  1121. ObjSectionList.ForEachCall(@section_create_relocsec,data);
  1122. { recalc nsections to incude the reloc sections }
  1123. nsections:=1;
  1124. ObjSectionList.ForEachCall(@section_count_sections,@nsections);
  1125. { create .shstrtab }
  1126. createshstrtab(data);
  1127. { Calculate the filepositions }
  1128. datapos:=$40; { elfheader + alignment }
  1129. { section data }
  1130. layoutsections(datapos);
  1131. { section headers }
  1132. shoffset:=align(datapos,dword(Sizeof(AInt)));
  1133. inc(datapos,(nsections+1)*sizeof(telfsechdr));
  1134. { Write ELF Header }
  1135. fillchar(header,sizeof(header),0);
  1136. header.e_ident[EI_MAG0]:=ELFMAG0; { = #127'ELF' }
  1137. header.e_ident[EI_MAG1]:=ELFMAG1;
  1138. header.e_ident[EI_MAG2]:=ELFMAG2;
  1139. header.e_ident[EI_MAG3]:=ELFMAG3;
  1140. header.e_ident[EI_CLASS]:=ELFCLASS;
  1141. if target_info.endian=endian_big then
  1142. header.e_ident[EI_DATA]:=ELFDATA2MSB
  1143. else
  1144. header.e_ident[EI_DATA]:=ELFDATA2LSB;
  1145. header.e_ident[EI_VERSION]:=1;
  1146. if target_info.system in systems_openbsd then
  1147. header.e_ident[EI_OSABI]:=ELFOSABI_OPENBSD
  1148. else if target_info.system in systems_freebsd then
  1149. header.e_ident[EI_OSABI]:=ELFOSABI_FREEBSD
  1150. else if target_info.system in systems_dragonfly then
  1151. header.e_ident[EI_OSABI]:=ELFOSABI_NONE;
  1152. header.e_type:=ET_REL;
  1153. header.e_machine:=ElfTarget.machine_code;
  1154. header.e_version:=1;
  1155. header.e_shoff:=shoffset;
  1156. header.e_shstrndx:=shstrtabsect.index;
  1157. header.e_shnum:=nsections;
  1158. header.e_ehsize:=sizeof(telfheader);
  1159. header.e_shentsize:=sizeof(telfsechdr);
  1160. if assigned(ElfTarget.encodeflags) then
  1161. header.e_flags:=ElfTarget.encodeflags();
  1162. MaybeSwapHeader(header);
  1163. writer.write(header,sizeof(header));
  1164. writer.writezeros($40-sizeof(header)); { align }
  1165. { Sections }
  1166. WriteSectionContent(data);
  1167. { Align header }
  1168. Writer.Writezeros(Align(Writer.Size,Sizeof(AInt))-Writer.Size);
  1169. { section headers, start with an empty header for sh_undef }
  1170. writer.writezeros(sizeof(telfsechdr));
  1171. ObjSectionList.ForEachCall(@section_write_sechdr,nil);
  1172. end;
  1173. result:=true;
  1174. end;
  1175. {****************************************************************************
  1176. TELFAssembler
  1177. ****************************************************************************}
  1178. constructor TElfAssembler.Create(info: pasminfo; smart:boolean);
  1179. begin
  1180. inherited;
  1181. CObjOutput:=TElfObjectOutput;
  1182. CInternalAr:=tarobjectwriter;
  1183. end;
  1184. {****************************************************************************
  1185. TELFObjectInput
  1186. ****************************************************************************}
  1187. constructor TElfObjInput.Create;
  1188. begin
  1189. inherited Create;
  1190. CObjData:=TElfObjData;
  1191. CObjSymbol:=TObjSymbol;
  1192. end;
  1193. destructor TElfObjInput.Destroy;
  1194. begin
  1195. if Assigned(FSymTbl) then
  1196. FreeMem(FSymTbl);
  1197. if Assigned(FSecTbl) then
  1198. FreeMem(FSecTbl);
  1199. if Assigned(strtab) then
  1200. FreeMem(strtab);
  1201. if Assigned(shstrtab) then
  1202. FreeMem(shstrtab);
  1203. if Assigned(symversions) then
  1204. FreeMem(symversions);
  1205. inherited Destroy;
  1206. end;
  1207. procedure TElfObjInput.LoadRelocations(const secrec:TSectionRec);
  1208. var
  1209. i: longint;
  1210. rel: TElfReloc;
  1211. reltyp: byte;
  1212. relsym: longint;
  1213. objrel: TObjRelocation;
  1214. p: TObjSymbol;
  1215. begin
  1216. FReader.Seek(secrec.relocpos);
  1217. if secrec.sec=nil then
  1218. InternalError(2012060203);
  1219. if (secrec.relentsize=3*sizeof(pint)) then
  1220. with secrec.sec do SecOptions:=SecOptions+[oso_rela_relocs];
  1221. for i:=0 to secrec.relocs-1 do
  1222. begin
  1223. FReader.Read(rel,secrec.relentsize);
  1224. MaybeSwapElfReloc(rel);
  1225. reltyp:=rel.info and $FF;
  1226. {$ifdef cpu64bitaddr}
  1227. relsym:=rel.info shr 32;
  1228. {$else cpu64bitaddr}
  1229. relsym:=(rel.info shr 8) and $FFFFFF;
  1230. {$endif cpu64bitaddr}
  1231. if relsym>=syms then
  1232. InternalError(2012060204);
  1233. p:=TObjSymbol(FSymTbl[relsym]);
  1234. { Some relocations (e.g. R_ARM_V4BX) don't use a symbol at all }
  1235. if assigned(p) or (relsym=0) then
  1236. begin
  1237. objrel:=TObjRelocation.CreateRaw(rel.address-secrec.sec.mempos,p,reltyp);
  1238. if (secrec.relentsize=3*sizeof(pint)) then
  1239. objrel.orgsize:=rel.addend;
  1240. { perform target-specific actions }
  1241. if Assigned(ElfTarget.loadreloc) then
  1242. ElfTarget.loadreloc(objrel);
  1243. secrec.sec.ObjRelocations.add(objrel);
  1244. end
  1245. else
  1246. begin
  1247. InputError('Unable to resolve symbol of relocation');
  1248. exit;
  1249. end;
  1250. end;
  1251. end;
  1252. procedure TElfObjInput.LoadSymbols(objdata:TObjData;count,locals:longword);
  1253. var
  1254. i: longint;
  1255. sym: TElfSymbol;
  1256. bind: TAsmSymBind;
  1257. typ: TAsmSymType;
  1258. objsym: TObjSymbol;
  1259. ver: word;
  1260. begin
  1261. FSymTbl:=AllocMem(count*sizeof(Pointer));
  1262. for i:=1 to count-1 do
  1263. begin
  1264. FReader.Read(sym,sizeof(TElfSymbol));
  1265. MaybeSwapElfSymbol(sym);
  1266. if sym.st_name>=strtablen then
  1267. InternalError(2012060205);
  1268. if sym.st_shndx=SHN_ABS then { ignore absolute symbols (should we really do it???) }
  1269. Continue
  1270. else if sym.st_shndx=SHN_COMMON then
  1271. bind:=AB_COMMON
  1272. else if (sym.st_shndx>=nsects) then
  1273. InternalError(2012060206)
  1274. else
  1275. case (sym.st_info shr 4) of
  1276. STB_LOCAL:
  1277. bind:=AB_LOCAL;
  1278. STB_GLOBAL:
  1279. if sym.st_shndx=SHN_UNDEF then
  1280. bind:=AB_EXTERNAL
  1281. else
  1282. bind:=AB_GLOBAL;
  1283. STB_WEAK:
  1284. bind:=AB_WEAK_EXTERNAL;
  1285. else
  1286. InternalError(2012060207);
  1287. end;
  1288. { Ignore section symbol if we didn't create the corresponding objsection
  1289. (examples are SHT_GROUP or .note.GNU-stack sections). }
  1290. if (sym.st_shndx>0) and (sym.st_shndx<SHN_LORESERVE) and
  1291. (FSecTbl[sym.st_shndx].sec=nil) and
  1292. (not dynobj) then
  1293. if ((sym.st_info and $0F)=STT_SECTION) then
  1294. Continue
  1295. else
  1296. begin
  1297. writeln(objdata.name,' ',i);
  1298. InternalError(2012110701)
  1299. end;
  1300. case (sym.st_info and $0F) of
  1301. STT_NOTYPE:
  1302. typ:=AT_NONE;
  1303. STT_OBJECT:
  1304. typ:=AT_DATA;
  1305. STT_FUNC:
  1306. typ:=AT_FUNCTION;
  1307. STT_SECTION:
  1308. typ:=AT_SECTION;
  1309. STT_FILE:
  1310. continue;
  1311. STT_TLS:
  1312. typ:=AT_TLS;
  1313. STT_GNU_IFUNC:
  1314. typ:=AT_GNU_IFUNC;
  1315. else
  1316. writeln(objdata.name,' ',sym.st_info and $0F);
  1317. InternalError(2012060208);
  1318. end;
  1319. { If reading DSO, we're interested only in global symbols defined there.
  1320. Symbols with non-current version should also be ignored. }
  1321. ver:=0;
  1322. if dynobj then
  1323. begin
  1324. if assigned(symversions) then
  1325. begin
  1326. ver:=symversions[i];
  1327. if (ver=VER_NDX_LOCAL) or (ver>VERSYM_VERSION) then
  1328. continue;
  1329. end;
  1330. if (bind=AB_LOCAL) or (sym.st_shndx=SHN_UNDEF) then
  1331. continue;
  1332. if ver>=verdefs.count then
  1333. InternalError(2012120505);
  1334. end;
  1335. { validity of name and objsection has been checked above }
  1336. { !! all AT_SECTION symbols have duplicate (null) name,
  1337. therefore TObjSection.CreateSymbol cannot be used here }
  1338. objsym:=CObjSymbol.Create(objdata.ObjSymbolList,string(PChar(@strtab[sym.st_name])));
  1339. objsym.bind:=bind;
  1340. objsym.typ:=typ;
  1341. if bind<>AB_COMMON then
  1342. objsym.objsection:=FSecTbl[sym.st_shndx].sec;
  1343. objsym.offset:=sym.st_value;
  1344. objsym.size:=sym.st_size;
  1345. FSymTbl[i]:=objsym;
  1346. if (ver>VER_NDX_GLOBAL) then
  1347. TVersionedObjSymbol(objsym).version:=TElfVersionDef(verdefs[ver]);
  1348. end;
  1349. end;
  1350. function TElfObjInput.CreateSection(const shdr:TElfsechdr;index:longint;objdata:tobjdata;
  1351. out secname:string):TElfObjSection;
  1352. begin
  1353. secname:=string(PChar(@shstrtab[shdr.sh_name]));
  1354. result:=TElfObjSection.create_ext(objdata,secname,
  1355. shdr.sh_type,shdr.sh_flags,shdr.sh_addralign,shdr.sh_entsize);
  1356. result.index:=index;
  1357. result.DataPos:=shdr.sh_offset;
  1358. result.MemPos:=shdr.sh_addr;
  1359. result.Size:=shdr.sh_size;
  1360. FSecTbl[index].sec:=result;
  1361. end;
  1362. function TElfObjInput.ReadBytes(offs:longint;out buf;len:longint):boolean;
  1363. begin
  1364. FReader.Seek(offs);
  1365. result:=FReader.Read(buf,len);
  1366. end;
  1367. procedure TElfObjInput.LoadSection(const shdr:TElfsechdr;index:longint;objdata:tobjdata);
  1368. var
  1369. sec: TElfObjSection;
  1370. sym: TElfSymbol;
  1371. secname: string;
  1372. begin
  1373. if shdr.sh_name>=shstrtablen then
  1374. InternalError(2012060210);
  1375. case shdr.sh_type of
  1376. SHT_NULL:
  1377. {ignore};
  1378. { SHT_STRTAB may appear for .stabstr and other debug sections.
  1379. .shstrtab and .strtab are processed separately and don't appear here. }
  1380. SHT_PROGBITS,SHT_NOBITS,SHT_NOTE,SHT_STRTAB,
  1381. SHT_INIT_ARRAY,SHT_FINI_ARRAY,SHT_PREINIT_ARRAY:
  1382. begin
  1383. sec:=CreateSection(shdr,index,objdata,secname);
  1384. if (Length(secname)>3) and (secname[2] in ['d','f','n','s']) then
  1385. begin
  1386. if (Pos('.stub',secname)=1) or
  1387. (Pos('.fpc',secname)=1) then
  1388. sec.SecOptions:=[oso_keep]
  1389. { ELF does not have any flags specific to debug sections,
  1390. but reserves names starting with '.debug' for this purpose }
  1391. else if (Pos('.debug',secname)=1) or
  1392. (secname='.stab') or
  1393. (secname='.stabstr') then
  1394. sec.SecOptions:=[oso_debug]
  1395. else if (secname='.note.GNU-stack') and (shdr.sh_type=SHT_PROGBITS) then
  1396. begin
  1397. if (shdr.sh_flags and SHF_EXECINSTR)=0 then
  1398. objdata.ExecStack:=False;
  1399. end;
  1400. end;
  1401. if (shdr.sh_type=SHT_NOTE) and (shdr.sh_size<>0) then
  1402. sec.SecOptions:=[oso_keep];
  1403. end;
  1404. SHT_REL,SHT_RELA:
  1405. begin
  1406. if shdr.sh_info>=nsects then
  1407. InternalError(2012060211);
  1408. if shdr.sh_entsize<>longword((2+ord(shdr.sh_type=SHT_RELA))*sizeof(pint)) then
  1409. InternalError(2012060212);
  1410. with FSecTbl[shdr.sh_info] do
  1411. begin
  1412. relocpos:=shdr.sh_offset;
  1413. relocs:=shdr.sh_size div shdr.sh_entsize;
  1414. relentsize:=shdr.sh_entsize;
  1415. end;
  1416. end;
  1417. SHT_GROUP:
  1418. if (shdr.sh_size>=2*sizeof(longword)) and
  1419. (shdr.sh_entsize=sizeof(longword)) and
  1420. ((shdr.sh_size mod shdr.sh_entsize)=0) then
  1421. begin
  1422. { Groups are identified by name of symbol pointed to by
  1423. sh_link and sh_info, not by sh_name. This symbol
  1424. may as well be STT_SECTION symbol of this section,
  1425. in which case we end up using sh_name. }
  1426. if dynobj then
  1427. InternalError(2012110801);
  1428. if (shdr.sh_link<>symtabndx) then
  1429. InternalError(2012110703);
  1430. if (shdr.sh_info>=syms) then
  1431. InternalError(2012110704);
  1432. FReader.Seek(symtaboffset+shdr.sh_info*sizeof(TElfSymbol));
  1433. FReader.Read(sym,sizeof(TElfSymbol));
  1434. MaybeSwapElfSymbol(sym);
  1435. if sym.st_name>=strtablen then
  1436. InternalError(2012110705);
  1437. if (sym.st_shndx=index) and (sym.st_info=((STB_LOCAL shl 4) or STT_SECTION)) then
  1438. secname:=string(PChar(@shstrtab[shdr.sh_name]))
  1439. else
  1440. secname:=string(PChar(@strtab[sym.st_name]));
  1441. { Postpone further processing until all sections are loaded,
  1442. we'll need to access correct section header.
  1443. Since ABI requires SHT_GROUP sections to come first in the file,
  1444. we assume that group number x has header index x+1.
  1445. If we ever encounter files where this is not true, we'll have
  1446. to maintain a separate index. }
  1447. objdata.CreateSectionGroup(secname);
  1448. if (index<>objdata.GroupsList.Count) then
  1449. InternalError(2012110802);
  1450. end
  1451. else
  1452. InternalError(2012110706);
  1453. SHT_GNU_ATTRIBUTES:
  1454. { TODO: must not be ignored };
  1455. else
  1456. if not (assigned(ElfTarget.loadsection) and
  1457. ElfTarget.loadsection(self,objdata,shdr,index)) then
  1458. InternalError(2012072603);
  1459. end;
  1460. FLoaded[index]:=True;
  1461. end;
  1462. function TElfObjInput.LoadHeader(out objdata:TObjData):boolean;
  1463. var
  1464. header:TElfHeader;
  1465. begin
  1466. result:=false;
  1467. if not FReader.read(header,sizeof(header)) then
  1468. begin
  1469. InputError('Can''t read ELF header');
  1470. exit;
  1471. end;
  1472. if (header.e_ident[EI_MAG0]<>ELFMAG0) or (header.e_ident[EI_MAG1]<>ELFMAG1) or
  1473. (header.e_ident[EI_MAG2]<>ELFMAG2) or (header.e_ident[EI_MAG3]<>ELFMAG3) then
  1474. begin
  1475. InputError('Illegal ELF magic');
  1476. exit;
  1477. end;
  1478. if (header.e_ident[EI_VERSION]<>1) then
  1479. begin
  1480. InputError('Unknown ELF file version');
  1481. exit;
  1482. end;
  1483. if (header.e_ident[EI_CLASS]<>ELFCLASS) then
  1484. begin
  1485. InputError('Wrong ELF file class (32/64 bit mismatch)');
  1486. exit;
  1487. end;
  1488. if (header.e_ident[EI_DATA]<>1+ord(target_info.endian=endian_big)) then
  1489. begin
  1490. InputError('ELF endianness does not match target');
  1491. exit;
  1492. end;
  1493. MaybeSwapHeader(header);
  1494. if (header.e_version<>1) then
  1495. begin
  1496. InputError('Unknown ELF data version');
  1497. exit;
  1498. end;
  1499. if (header.e_machine<>ElfTarget.machine_code) then
  1500. begin
  1501. InputError('ELF file is for different CPU');
  1502. exit;
  1503. end;
  1504. if (header.e_type<>ET_REL) and (header.e_type<>ET_DYN) then
  1505. begin
  1506. InputError('Not a relocatable or dynamic ELF file');
  1507. exit;
  1508. end;
  1509. if header.e_shentsize<>sizeof(TElfsechdr) then
  1510. InternalError(2012062701);
  1511. nsects:=header.e_shnum;
  1512. dynobj:=(header.e_type=ET_DYN);
  1513. shoffset:=header.e_shoff;
  1514. shstrndx:=header.e_shstrndx;
  1515. if dynobj then
  1516. begin
  1517. objdata:=TElfDynamicObjData.Create(InputFilename);
  1518. verdefs:=TElfDynamicObjData(objdata).versiondefs;
  1519. CObjSymbol:=TVersionedObjSymbol;
  1520. end
  1521. else
  1522. objdata:=CObjData.Create(InputFilename);
  1523. TElfObjData(objdata).ident:=header.e_ident;
  1524. TElfObjData(objdata).flags:=header.e_flags;
  1525. result:=true;
  1526. end;
  1527. procedure TElfObjInput.LoadDynamic(const shdr:TElfsechdr;objdata:TObjData);
  1528. var
  1529. dt: TElfDyn;
  1530. i: longint;
  1531. begin
  1532. if (shdr.sh_entsize<>sizeof(TElfDyn)) then
  1533. InternalError(2012071403);
  1534. FReader.Seek(shdr.sh_offset);
  1535. for i:=0 to (shdr.sh_size div shdr.sh_entsize)-1 do
  1536. begin
  1537. FReader.Read(dt,sizeof(TElfDyn));
  1538. MaybeSwapElfDyn(dt);
  1539. case dt.d_tag of
  1540. DT_NULL:
  1541. break;
  1542. DT_SONAME:
  1543. TElfObjData(objdata).FName:=string(PChar(@strtab[dt.d_ptr]));
  1544. DT_NEEDED:
  1545. ;
  1546. end;
  1547. end;
  1548. end;
  1549. function TElfObjInput.ReadObjData(AReader:TObjectreader;out objdata:TObjData):boolean;
  1550. var
  1551. i,j,strndx,dynndx,
  1552. versymndx,verdefndx,verneedndx: longint;
  1553. objsec: TObjSection;
  1554. grp: TObjSectionGroup;
  1555. tmp: longword;
  1556. count: longint;
  1557. vd: TElfverdef;
  1558. vda: TElfverdaux;
  1559. vdoffset: aword;
  1560. begin
  1561. FReader:=AReader;
  1562. InputFileName:=AReader.FileName;
  1563. result:=false;
  1564. strndx:=0;
  1565. if not LoadHeader(objData) then
  1566. exit;
  1567. FSecTbl:=AllocMem(nsects*sizeof(TSectionRec));
  1568. FLoaded:=AllocMem(nsects*sizeof(boolean));
  1569. SetLength(shdrs,nsects);
  1570. FReader.Seek(shoffset);
  1571. if not FReader.Read(shdrs[0],nsects*sizeof(TElfsechdr)) then
  1572. begin
  1573. InputError('Can''t read ELF section headers');
  1574. exit;
  1575. end;
  1576. if source_info.endian<>target_info.endian then
  1577. for i:=0 to nsects-1 do
  1578. MaybeSwapSecHeader(shdrs[i]);
  1579. { First, load the .shstrtab section }
  1580. if shstrndx>=nsects then
  1581. InternalError(2012060201);
  1582. if shdrs[shstrndx].sh_type<>SHT_STRTAB then
  1583. InternalError(2012060202);
  1584. shstrtablen:=shdrs[shstrndx].sh_size;
  1585. GetMem(shstrtab,shstrtablen);
  1586. FReader.seek(shdrs[shstrndx].sh_offset);
  1587. FReader.read(shstrtab^,shstrtablen);
  1588. FLoaded[shstrndx]:=True;
  1589. { Locate the symtable, it is typically at the end so loop backwards.
  1590. Load the strings, postpone symtable itself until done with sections.
  1591. Note that is is legal to have no symtable.
  1592. For DSO, locate .dynsym instead, this one is near the beginning, but
  1593. overall number of sections won't be big. }
  1594. symtabndx:=0;
  1595. for i:=nsects-1 downto 1 do
  1596. begin
  1597. if (shdrs[i].sh_type<>symsectypes[dynobj]) then
  1598. continue;
  1599. if (shdrs[i].sh_entsize<>sizeof(TElfSymbol)) then
  1600. InternalError(2012060213);
  1601. if shdrs[i].sh_link>=nsects then
  1602. InternalError(2012062702);
  1603. strndx:=shdrs[i].sh_link;
  1604. if shdrs[strndx].sh_type<>SHT_STRTAB then
  1605. InternalError(2012062703);
  1606. strtablen:=shdrs[strndx].sh_size;
  1607. GetMem(strtab,strtablen);
  1608. FReader.seek(shdrs[strndx].sh_offset);
  1609. FReader.read(strtab^,strtablen);
  1610. symtaboffset:=shdrs[i].sh_offset;
  1611. syms:=shdrs[i].sh_size div sizeof(TElfSymbol);
  1612. localsyms:=shdrs[i].sh_info;
  1613. FLoaded[i]:=True;
  1614. FLoaded[strndx]:=True;
  1615. symtabndx:=i;
  1616. break;
  1617. end;
  1618. if dynobj then
  1619. begin
  1620. if symtabndx=0 then
  1621. InternalError(2012110707);
  1622. { Locate .dynamic and version sections. Expect a single one of a kind. }
  1623. dynndx:=0;
  1624. versymndx:=0;
  1625. verdefndx:=0;
  1626. verneedndx:=0;
  1627. for i:=nsects-1 downto 0 do
  1628. begin
  1629. case shdrs[i].sh_type of
  1630. SHT_DYNAMIC:
  1631. begin
  1632. if dynndx<>0 then
  1633. InternalError(2012102001);
  1634. dynndx:=i;
  1635. if (shdrs[dynndx].sh_link<>strndx) then
  1636. InternalError(2012071402);
  1637. LoadDynamic(shdrs[dynndx],objdata);
  1638. end;
  1639. SHT_GNU_versym:
  1640. begin
  1641. if versymndx<>0 then
  1642. InternalError(2012102002);
  1643. versymndx:=i;
  1644. if shdrs[i].sh_entsize<>sizeof(word) then
  1645. InternalError(2012102003);
  1646. if shdrs[i].sh_link<>symtabndx then
  1647. InternalError(2012102004);
  1648. if shdrs[i].sh_size<>syms*sizeof(word) then
  1649. InternalError(2012102005);
  1650. GetMem(symversions,shdrs[i].sh_size);
  1651. FReader.seek(shdrs[i].sh_offset);
  1652. FReader.read(symversions^,shdrs[i].sh_size);
  1653. if source_info.endian<>target_info.endian then
  1654. for j:=0 to syms-1 do
  1655. symversions[j]:=SwapEndian(symversions[j]);
  1656. end;
  1657. SHT_GNU_verdef:
  1658. begin
  1659. if verdefndx<>0 then
  1660. InternalError(2012102006);
  1661. verdefndx:=i;
  1662. if shdrs[i].sh_link<>strndx then
  1663. InternalError(2012120501);
  1664. vdoffset:=shdrs[i].sh_offset;
  1665. { TODO: can we rely on sh_info, or must read until vd_next=0? }
  1666. for j:=1 to shdrs[i].sh_info do
  1667. begin
  1668. FReader.seek(vdoffset);
  1669. FReader.Read(vd,sizeof(TElfverdef));
  1670. MaybeSwapElfverdef(vd);
  1671. if vd.vd_version<>VER_DEF_CURRENT then
  1672. InternalError(2012120502);
  1673. FReader.seek(vdoffset+vd.vd_aux);
  1674. vdoffset:=vdoffset+vd.vd_next;
  1675. { First verdaux entry holds name of version (unless VER_FLG_BASE flag is set),
  1676. subsequent one(s) point to parent(s). For our purposes, version hierarchy
  1677. looks irrelevant. }
  1678. FReader.Read(vda,sizeof(TElfverdaux));
  1679. MaybeSwapElfverdaux(vda);
  1680. if vda.vda_name>=strtablen then
  1681. InternalError(2012120503);
  1682. if (vd.vd_flags and VER_FLG_BASE)<>0 then
  1683. continue;
  1684. { Assuming verdef indices assigned continuously starting from 2,
  1685. at least BFD produces files that way. }
  1686. if verdefs.count<>vd.vd_ndx then
  1687. InternalError(2012120504);
  1688. TElfVersionDef.Create(verdefs,string(PChar(@strtab[vda.vda_name])));
  1689. end;
  1690. end;
  1691. SHT_GNU_verneed:
  1692. begin
  1693. if verneedndx<>0 then
  1694. InternalError(2012102007);
  1695. verneedndx:=i;
  1696. //sh_link->.dynstr
  1697. //sh_info->number of entries
  1698. end;
  1699. end;
  1700. end;
  1701. if dynndx=0 then
  1702. InternalError(2012071401);
  1703. { load the symtable }
  1704. FReader.Seek(symtaboffset+sizeof(TElfSymbol));
  1705. LoadSymbols(objdata,syms,localsyms);
  1706. result:=True;
  1707. exit;
  1708. end;
  1709. { assume stack is executable until proven otherwise }
  1710. objdata.ExecStack:=True;
  1711. { Process section headers }
  1712. for i:=1 to nsects-1 do
  1713. if not FLoaded[i] then
  1714. LoadSection(shdrs[i],i,objdata);
  1715. { load the content }
  1716. ReadSectionContent(objdata);
  1717. { load the symtable }
  1718. FReader.Seek(symtaboffset+sizeof(TElfSymbol));
  1719. LoadSymbols(objdata,syms,localsyms);
  1720. { finish relocations }
  1721. for i:=0 to objdata.ObjSectionList.Count-1 do
  1722. begin
  1723. objsec:=TObjSection(objdata.ObjsectionList[i]);
  1724. { skip debug sections }
  1725. if (oso_debug in objsec.SecOptions) and
  1726. (cs_link_strip in current_settings.globalswitches) and
  1727. not(cs_link_separate_dbg_file in current_settings.globalswitches) then
  1728. continue;
  1729. if FSecTbl[objsec.index].relocpos>0 then
  1730. LoadRelocations(FSecTbl[objsec.index]);
  1731. end;
  1732. { finish processing section groups, if any }
  1733. if Assigned(objdata.GroupsList) then
  1734. begin
  1735. for i:=0 to objdata.GroupsList.Count-1 do
  1736. begin
  1737. grp:=TObjSectionGroup(objData.GroupsList[i]);
  1738. FReader.Seek(shdrs[i+1].sh_offset);
  1739. { first dword is flags }
  1740. FReader.Read(tmp,sizeof(longword));
  1741. if source_info.endian<>target_info.endian then
  1742. tmp:=SwapEndian(tmp);
  1743. if (tmp and GRP_COMDAT)<>0 then
  1744. grp.IsComdat:=true;
  1745. count:=(shdrs[i+1].sh_size div sizeof(longword))-1;
  1746. SetLength(grp.members,count);
  1747. for j:=0 to count-1 do
  1748. begin
  1749. FReader.Read(tmp,sizeof(longword));
  1750. if source_info.endian<>target_info.endian then
  1751. tmp:=SwapEndian(tmp);
  1752. if (tmp>=nsects) then
  1753. InternalError(2012110805);
  1754. objsec:=FSecTbl[tmp].sec;
  1755. if (objsec=nil) then
  1756. InternalError(2012110806);
  1757. if (TElfObjSection(objsec).shflags and SHF_GROUP)=0 then
  1758. InternalError(2012110807);
  1759. grp.members[j]:=objsec;
  1760. objsec.Group:=grp;
  1761. end;
  1762. end;
  1763. end;
  1764. result:=True;
  1765. end;
  1766. class function TElfObjInput.CanReadObjData(AReader:TObjectreader):boolean;
  1767. var
  1768. header: TElfHeader;
  1769. begin
  1770. result:=false;
  1771. if AReader.Read(header,sizeof(header)) then
  1772. begin;
  1773. if (header.e_ident[EI_MAG0]=ELFMAG0) and (header.e_ident[EI_MAG1]=ELFMAG1) and
  1774. (header.e_ident[EI_MAG2]=ELFMAG2) and (header.e_ident[EI_MAG3]=ELFMAG3) then
  1775. { TODO: check additional fields }
  1776. result:=true;
  1777. end;
  1778. AReader.Seek(0);
  1779. end;
  1780. {*****************************************************************************
  1781. TElfExeOutput
  1782. *****************************************************************************}
  1783. constructor TElfExeOutput.Create;
  1784. begin
  1785. inherited Create;
  1786. CObjData:=TElfObjData;
  1787. CExeSection:=TElfExeSection;
  1788. {$ifdef cpu64}
  1789. MaxMemPos:=Qword($FFFFFFFFFFFFFFFF);
  1790. //MaxMemPos:=$7EFFFFFF; { As specified by SysV AMD64 ABI for small memory model }
  1791. {$else cpu64}
  1792. MaxMemPos:=$7FFFFFFF;
  1793. {$endif cpu64}
  1794. SectionMemAlign:=$20;
  1795. SectionDataAlign:=$20;
  1796. segmentlist:=TFPObjectList.Create(True);
  1797. neededlist:=TFPHashList.Create;
  1798. end;
  1799. destructor TElfExeOutput.Destroy;
  1800. begin
  1801. dyncopysyms.Free;
  1802. neededlist.Free;
  1803. segmentlist.Free;
  1804. dynsymlist.Free;
  1805. dynreloclist.Free;
  1806. if assigned(dynsymnames) then
  1807. FreeMem(dynsymnames);
  1808. stringdispose(FInterpreter);
  1809. inherited Destroy;
  1810. end;
  1811. function TElfExeOutput.AttachSection(objsec:TObjSection):TElfExeSection;
  1812. begin
  1813. objsec.SecOptions:=[oso_keep];
  1814. result:=TElfExeSection(FindExeSection(objsec.name));
  1815. if result=nil then
  1816. result:=TElfExeSection.Create(ExeSectionList,objsec.name);
  1817. result.AddObjSection(objsec);
  1818. end;
  1819. function TElfExeOutput.CreateSegment(atype,aflags,aalign:longword):TElfSegment;
  1820. begin
  1821. result:=TElfSegment.Create(atype,aflags,aalign);
  1822. segmentlist.add(result);
  1823. end;
  1824. procedure TElfExeOutput.WriteHeader;
  1825. var
  1826. header: TElfHeader;
  1827. begin
  1828. FillChar(header,sizeof(header),0);
  1829. header.e_ident[EI_MAG0]:=ELFMAG0; { = #127'ELF' }
  1830. header.e_ident[EI_MAG1]:=ELFMAG1;
  1831. header.e_ident[EI_MAG2]:=ELFMAG2;
  1832. header.e_ident[EI_MAG3]:=ELFMAG3;
  1833. header.e_ident[EI_CLASS]:=ELFCLASS;
  1834. if target_info.endian=endian_big then
  1835. header.e_ident[EI_DATA]:=ELFDATA2MSB
  1836. else
  1837. header.e_ident[EI_DATA]:=ELFDATA2LSB;
  1838. header.e_ident[EI_VERSION]:=1;
  1839. if target_info.system in systems_openbsd then
  1840. header.e_ident[EI_OSABI]:=ELFOSABI_OPENBSD
  1841. else if target_info.system in systems_freebsd then
  1842. header.e_ident[EI_OSABI]:=ELFOSABI_FREEBSD
  1843. else if target_info.system in systems_dragonfly then
  1844. header.e_ident[EI_OSABI]:=ELFOSABI_NONE;
  1845. if IsSharedLibrary then
  1846. header.e_type:=ET_DYN
  1847. else
  1848. header.e_type:=ET_EXEC;
  1849. header.e_machine:=ElfTarget.machine_code;
  1850. header.e_version:=1;
  1851. header.e_phoff:=sizeof(TElfHeader);
  1852. header.e_shoff:=shoffset;
  1853. header.e_shstrndx:=ExeSectionList.IndexOf(shstrtabsect.ExeSection)+1;
  1854. header.e_shnum:=ExeSectionList.Count+1;
  1855. header.e_phnum:=segmentlist.count;
  1856. header.e_ehsize:=sizeof(telfheader);
  1857. if assigned(ElfTarget.encodeflags) then
  1858. header.e_flags:=ElfTarget.encodeflags();
  1859. if assigned(EntrySym) then
  1860. header.e_entry:=EntrySym.Address;
  1861. header.e_shentsize:=sizeof(telfsechdr);
  1862. header.e_phentsize:=sizeof(telfproghdr);
  1863. MaybeSwapHeader(header);
  1864. FWriter.Write(header,sizeof(header));
  1865. end;
  1866. procedure TElfExeOutput.exesection_write_header(p:TObject;arg:Pointer);
  1867. var
  1868. shdr: TElfsechdr;
  1869. exesec: TElfExeSection absolute p;
  1870. begin
  1871. FillChar(shdr,sizeof(shdr),0);
  1872. shdr.sh_name:=exesec.shstridx;
  1873. if (ExeWriteMode=ewm_dbgonly) and
  1874. (exesec.SecOptions*[oso_debug,oso_debug_copy]=[]) then
  1875. shdr.sh_type:=SHT_NOBITS
  1876. else
  1877. shdr.sh_type:=exesec.shtype;
  1878. shdr.sh_flags:=exesec.shflags;
  1879. if (oso_load in exesec.SecOptions) then
  1880. shdr.sh_addr:=exesec.MemPos;
  1881. shdr.sh_offset:=exesec.DataPos;
  1882. shdr.sh_size:=exesec.Size;
  1883. shdr.sh_link:=exesec.shlink;
  1884. shdr.sh_info:=exesec.shinfo;
  1885. shdr.sh_addralign:=exesec.SecAlign;
  1886. shdr.sh_entsize:=exesec.shentsize;
  1887. MaybeSwapSecHeader(shdr);
  1888. FWriter.Write(shdr,sizeof(shdr));
  1889. end;
  1890. procedure TElfExeOutput.segment_write_header(p:TObject;arg:Pointer);
  1891. var
  1892. phdr: TElfproghdr;
  1893. seg: TElfSegment absolute p;
  1894. begin
  1895. FillChar(phdr,sizeof(phdr),0);
  1896. phdr.p_type:=seg.ptype;
  1897. phdr.p_flags:=seg.pflags;
  1898. phdr.p_align:=seg.align;
  1899. phdr.p_offset:=seg.DataPos;
  1900. phdr.p_filesz:=seg.DataSize;
  1901. phdr.p_memsz:=seg.MemSize;
  1902. phdr.p_vaddr:=seg.MemPos;
  1903. phdr.p_paddr:=seg.MemPos;
  1904. MaybeSwapHeader(phdr);
  1905. FWriter.Write(phdr,sizeof(phdr));
  1906. end;
  1907. procedure TElfExeOutput.WriteStaticSymtable;
  1908. var
  1909. i: longint;
  1910. sec: TElfExeSection;
  1911. exesym: TExeSymbol;
  1912. begin
  1913. if assigned(tlsseg) then
  1914. symtab.tlsbase:=tlsseg.MemPos;
  1915. for i:=0 to ExeSectionList.Count-1 do
  1916. begin
  1917. sec:=TElfExeSection(ExeSectionList[i]);
  1918. { Must not write symbols for internal sections like .symtab }
  1919. if (sec.shtype in [SHT_SYMTAB,SHT_STRTAB,SHT_REL,SHT_RELA]) then
  1920. continue;
  1921. sec.secsymidx:=symtab.symidx;
  1922. symtab.writeInternalSymbol(sec.mempos,0,STT_SECTION,sec.secshidx);
  1923. end;
  1924. { local symbols first }
  1925. for i:=0 to ExeSymbolList.Count-1 do
  1926. begin
  1927. exesym:=TExeSymbol(ExeSymbolList[i]);
  1928. if (exesym.objsymbol.bind=AB_LOCAL) and (exesym.objsymbol.typ<>AT_LABEL) then
  1929. symtab.WriteSymbol(exesym.objsymbol);
  1930. end;
  1931. { Global Symbols }
  1932. for i:=0 to ExeSymbolList.Count-1 do
  1933. begin
  1934. exesym:=TExeSymbol(ExeSymbolList[i]);
  1935. if (exesym.objsymbol.bind<>AB_LOCAL) then
  1936. symtab.WriteSymbol(exesym.objsymbol);
  1937. end;
  1938. { update exe section properties }
  1939. symtab.ExeSection.size:=symtab.size;
  1940. TElfExeSection(symtab.ExeSection).shinfo:=symtab.shinfo;
  1941. TElfExeSection(symtab.ExeSection).shlink:=ExeSectionList.IndexOf(symtab.fstrsec.ExeSection)+1;
  1942. symtab.fstrsec.ExeSection.Size:=symtab.fstrsec.size;
  1943. end;
  1944. procedure TElfExeOutput.MapSectionsToSegments;
  1945. var
  1946. seg: TElfSegment;
  1947. exesec: TExeSection;
  1948. i: longint;
  1949. begin
  1950. if (not IsSharedLibrary) and assigned(interpobjsec) then
  1951. begin
  1952. phdrseg:=CreateSegment(PT_PHDR,PF_R or PF_X,sizeof(pint));
  1953. seg:=CreateSegment(PT_INTERP,PF_R,1);
  1954. seg.Add(interpobjsec.ExeSection);
  1955. end;
  1956. textseg:=CreateSegment(PT_LOAD,PF_X or PF_R,ElfTarget.max_page_size);
  1957. dataseg:=CreateSegment(PT_LOAD,PF_R or PF_W,ElfTarget.max_page_size);
  1958. for i:=0 to ExeSectionList.Count-1 do
  1959. begin
  1960. exesec:=TExeSection(ExeSectionList[i]);
  1961. if (oso_load in exesec.SecOptions) then
  1962. begin
  1963. if (TElfExeSection(exesec).shflags and SHF_TLS)<>0 then
  1964. begin
  1965. if tlsseg=nil then
  1966. tlsseg:=CreateSegment(PT_TLS,PF_R,sizeof(pint));
  1967. tlsseg.add(exesec);
  1968. end;
  1969. { TODO: at least on Linux, ld seems to drop .note.ABI-tag for static executables.
  1970. (Logic is as follows: there is no .note.ABI-tag section in ld script, so it
  1971. is processed as orphan section. As such, it is placed after .interp.
  1972. For static executables .interp is dropped, and it looks like there's nowhere to
  1973. place .note.ABI-tag in this case)
  1974. Always including it doesn't harm though (except increasing file size). }
  1975. if TElfExeSection(exesec).shtype=SHT_NOTE then
  1976. begin
  1977. if noteseg=nil then
  1978. noteseg:=CreateSegment(PT_NOTE,PF_R,4);
  1979. noteseg.Add(exesec);
  1980. Include(exesec.SecOptions,oso_debug_copy);
  1981. end;
  1982. if (oso_executable in exesec.SecOptions) or
  1983. not (oso_write in exesec.SecOptions) then
  1984. textseg.add(exesec)
  1985. else
  1986. dataseg.add(exesec);
  1987. end;
  1988. end;
  1989. if dynamiclink then
  1990. begin
  1991. seg:=CreateSegment(PT_DYNAMIC,PF_R or PF_W,sizeof(pint));
  1992. seg.add(dynamicsec.ExeSection);
  1993. end;
  1994. { stack flags }
  1995. CreateSegment(PT_GNU_STACK,PF_R or PF_W or (PF_X*ord(ExecStack)),sizeof(pint));
  1996. end;
  1997. procedure TElfExeOutput.make_dynamic_if_undefweak(exesym:TExeSymbol);
  1998. begin
  1999. if (exesym.dynindex=0) and (exesym.state=symstate_undefweak) and
  2000. not (cs_link_staticflag in current_settings.globalswitches) then
  2001. exesym.dynindex:=dynsymlist.add(exesym)+1;
  2002. end;
  2003. function TElfExeOutput.AllocGOTSlot(objsym:TObjSymbol):boolean;
  2004. var
  2005. exesym: TExeSymbol;
  2006. begin
  2007. result:=false;
  2008. exesym:=objsym.exesymbol;
  2009. { Although local symbols should not be accessed through GOT,
  2010. this isn't strictly forbidden. In this case we need to fake up
  2011. the exesym to store the GOT offset in it.
  2012. TODO: name collision; maybe use a different symbol list object? }
  2013. if exesym=nil then
  2014. begin
  2015. exesym:=TExeSymbol.Create(ExeSymbolList,objsym.name+'*local*');
  2016. exesym.objsymbol:=objsym;
  2017. objsym.exesymbol:=exesym;
  2018. end;
  2019. if exesym.GotOffset>0 then
  2020. exit;
  2021. gotobjsec.alloc(sizeof(pint));
  2022. exesym.GotOffset:=gotobjsec.size;
  2023. make_dynamic_if_undefweak(exesym);
  2024. { In shared library, every GOT entry needs a RELATIVE dynamic reloc,
  2025. imported/exported symbols need GLOB_DAT instead. For executables,
  2026. only the latter applies. }
  2027. if IsSharedLibrary or (exesym.dynindex>0) then
  2028. dynrelocsec.alloc(dynrelocsec.shentsize);
  2029. result:=true;
  2030. end;
  2031. procedure TElfExeOutput.PrepareGOT;
  2032. var
  2033. i,j,k: longint;
  2034. objsec: TElfObjSection;
  2035. exesec: TExeSection;
  2036. begin
  2037. for i:=0 to ExeSectionList.Count-1 do
  2038. begin
  2039. exesec:=TExeSection(ExeSectionList[i]);
  2040. for j:=0 to exesec.ObjSectionlist.count-1 do
  2041. begin
  2042. objsec:=TElfObjSection(exesec.ObjSectionlist[j]);
  2043. { ignore linker-generated and debug sections }
  2044. if (objsec.objdata=internalobjdata) or (oso_debug in objsec.SecOptions) then
  2045. continue;
  2046. if not objsec.Used then
  2047. internalerror(2012060901);
  2048. k:=0;
  2049. while k<objsec.ObjRelocations.Count do
  2050. begin
  2051. GOTRelocPass1(objsec,k);
  2052. inc(k);
  2053. end;
  2054. end;
  2055. end;
  2056. { remember sizes for sanity checking }
  2057. gotsize:=gotobjsec.size;
  2058. if assigned(dynrelocsec) then
  2059. dynrelsize:=dynrelocsec.size
  2060. else
  2061. dynrelsize:=0;
  2062. end;
  2063. procedure TElfExeOutput.CreateGOTSection;
  2064. begin
  2065. gotpltobjsec:=TElfObjSection.create_ext(internalObjData,'.got.plt',
  2066. SHT_PROGBITS,SHF_ALLOC or SHF_WRITE,sizeof(pint),sizeof(pint));
  2067. gotobjsec:=TElfObjSection.create_ext(internalObjData,'.got',
  2068. SHT_PROGBITS,SHF_ALLOC or SHF_WRITE,sizeof(pint),sizeof(pint));
  2069. gotobjsec.SecOptions:=[oso_keep];
  2070. { GOT symbol and reserved .got.plt entries }
  2071. internalObjData.SetSection(gotpltobjsec);
  2072. gotsymbol:=internalObjData.SymbolDefine('_GLOBAL_OFFSET_TABLE_',AB_GLOBAL,AT_DATA);
  2073. gotpltobjsec.writeZeros(3*sizeof(pint));
  2074. end;
  2075. procedure TElfExeOutput.Load_Start;
  2076. begin
  2077. inherited Load_Start;
  2078. dynsymlist:=TFPObjectList.Create(False);
  2079. CreateGOTSection;
  2080. end;
  2081. procedure TElfExeOutput.Load_DynamicObject(objdata:TObjData;asneeded:boolean);
  2082. var
  2083. i: longint;
  2084. exesym: TExeSymbol;
  2085. objsym: TObjSymbol;
  2086. needed: boolean;
  2087. begin
  2088. Comment(v_debug,'Dynamic object: '+objdata.name);
  2089. needed:=false;
  2090. for i:=0 to UnresolvedExeSymbols.Count-1 do
  2091. begin
  2092. exesym:=TExeSymbol(UnresolvedExeSymbols[i]);
  2093. if not (exesym.State in [symstate_undefined,symstate_undefweak]) then
  2094. continue;
  2095. objsym:=TObjSymbol(objdata.ObjSymbolList.Find(exesym.name));
  2096. if assigned(objsym) then
  2097. begin
  2098. exesym.State:=symstate_defined;
  2099. exesym.dynindex:=dynsymlist.Add(exesym)+1;
  2100. { The original binding, value and section of external symbol
  2101. must be preserved, therefore resolving directly to .so symbol
  2102. hurts more than it helps. Copy type and size, and store .so
  2103. symbol in objsym.indsymbol for later use. }
  2104. exesym.ObjSymbol.typ:=objsym.typ;
  2105. if objsym.typ<>AT_FUNCTION then
  2106. exesym.ObjSymbol.size:=objsym.size;
  2107. exesym.ObjSymbol.indsymbol:=objsym;
  2108. objsym.ExeSymbol:=exesym;
  2109. needed:=true;
  2110. end;
  2111. end;
  2112. if (needed or (not asneeded)) and
  2113. (neededlist.Find(objdata.name)=nil) then
  2114. neededlist.Add(objdata.name,objdata);
  2115. end;
  2116. procedure TElfExeOutput.Order_Start;
  2117. begin
  2118. inherited Order_Start;
  2119. dynamiclink:=IsSharedLibrary or (dynsymlist.count>0) or
  2120. (
  2121. (UnresolvedExeSymbols.Count>0) and
  2122. not (cs_link_staticflag in current_settings.globalswitches)
  2123. );
  2124. if dynamiclink then
  2125. InitDynlink;
  2126. if dynamiclink or (IndirectObjSymbols.Count>0) then
  2127. CreatePLT;
  2128. end;
  2129. procedure TElfExeOutput.Order_end;
  2130. procedure set_oso_keep(const s:string;out firstsec:TObjSection);
  2131. var
  2132. exesec:TExeSection;
  2133. objsec:TObjSection;
  2134. i:longint;
  2135. sz: aword;
  2136. begin
  2137. firstsec:=nil;
  2138. sz:=0;
  2139. exesec:=TExeSection(ExeSectionList.Find(s));
  2140. if assigned(exesec) then
  2141. begin
  2142. for i:=0 to exesec.ObjSectionList.Count-1 do
  2143. begin
  2144. objsec:=TObjSection(exesec.ObjSectionList[i]);
  2145. { ignore sections used for symbol definition }
  2146. if oso_data in objsec.SecOptions then
  2147. begin
  2148. if firstsec=nil then
  2149. firstsec:=objsec;
  2150. objsec.SecOptions:=[oso_keep];
  2151. inc(sz,objsec.size);
  2152. end;
  2153. end;
  2154. exesec.size:=sz;
  2155. end;
  2156. end;
  2157. var
  2158. dummy: TObjSection;
  2159. begin
  2160. OrderOrphanSections;
  2161. inherited Order_end;
  2162. set_oso_keep('.init',dummy);
  2163. set_oso_keep('.fini',dummy);
  2164. set_oso_keep('.jcr',dummy);
  2165. set_oso_keep('.ctors',dummy);
  2166. set_oso_keep('.dtors',dummy);
  2167. set_oso_keep('.preinit_array',preinitarraysec);
  2168. if assigned(preinitarraysec) and IsSharedLibrary then
  2169. Comment(v_error,'.preinit_array section is not allowed in shared libraries');
  2170. set_oso_keep('.init_array',initarraysec);
  2171. set_oso_keep('.fini_array',finiarraysec);
  2172. set_oso_keep('.eh_frame',dummy);
  2173. { let .dynamic reference other dynamic sections so they aren't marked
  2174. for removal as unused }
  2175. if dynamiclink then
  2176. WriteDynamicTags;
  2177. end;
  2178. procedure TElfExeOutput.OrderOrphanSections;
  2179. var
  2180. i,j:longint;
  2181. objdata:TObjData;
  2182. objsec:TObjSection;
  2183. exesec:TExeSection;
  2184. opts:TObjSectionOptions;
  2185. s:string;
  2186. newsections:TFPHashObjectList;
  2187. allsections:TFPList;
  2188. inserts:array[0..6] of TExeSection;
  2189. idx,inspos:longint;
  2190. begin
  2191. newsections:=TFPHashObjectList.Create(false);
  2192. allsections:=TFPList.Create;
  2193. { copy existing sections }
  2194. for i:=0 to ExeSectionList.Count-1 do
  2195. allsections.add(ExeSectionList[i]);
  2196. inserts[0]:=FindExeSection('.comment');
  2197. inserts[1]:=nil;
  2198. inserts[2]:=FindExeSection('.interp');
  2199. inserts[3]:=FindExeSection('.bss');
  2200. inserts[4]:=FindExeSection('.data');
  2201. inserts[5]:=FindExeSection('.rodata');
  2202. inserts[6]:=FindExeSection('.text');
  2203. for i:=0 to ObjDataList.Count-1 do
  2204. begin
  2205. ObjData:=TObjData(ObjDataList[i]);
  2206. for j:=0 to ObjData.ObjSectionList.Count-1 do
  2207. begin
  2208. objsec:=TObjSection(ObjData.ObjSectionList[j]);
  2209. if objsec.Used then
  2210. continue;
  2211. s:=objsec.name;
  2212. exesec:=TExeSection(newsections.Find(s));
  2213. if assigned(exesec) then
  2214. begin
  2215. exesec.AddObjSection(objsec);
  2216. continue;
  2217. end;
  2218. opts:=objsec.SecOptions*[oso_data,oso_load,oso_write,oso_executable];
  2219. if (objsec.SecOptions*[oso_load,oso_debug]=[]) then
  2220. { non-alloc, after .comment
  2221. GNU ld places .comment between stabs and dwarf debug info }
  2222. inspos:=0
  2223. else if not (oso_load in objsec.SecOptions) then
  2224. inspos:=1 { debugging, skip }
  2225. else if (oso_load in objsec.SecOptions) and
  2226. (TElfObjSection(objsec).shtype=SHT_NOTE) then
  2227. inspos:=2 { after .interp }
  2228. else if (opts=[oso_load,oso_write]) then
  2229. inspos:=3 { after .bss }
  2230. else if (opts=[oso_data,oso_load,oso_write]) then
  2231. inspos:=4 { after .data }
  2232. else if (opts=[oso_data,oso_load]) then
  2233. inspos:=5 { rodata, relocs=??? }
  2234. else if (opts=[oso_data,oso_load,oso_executable]) then
  2235. inspos:=6 { text }
  2236. else
  2237. begin
  2238. Comment(v_debug,'Orphan section '+objsec.fullname+' has attributes that are not handled!');
  2239. continue;
  2240. end;
  2241. if (inserts[inspos]=nil) then
  2242. begin
  2243. Comment(v_debug,'Orphan section '+objsec.fullname+': nowhere to insert, ignored');
  2244. continue;
  2245. end;
  2246. idx:=allsections.IndexOf(inserts[inspos]);
  2247. exesec:=CExeSection.Create(newsections,s);
  2248. allsections.Insert(idx+1,exesec);
  2249. inserts[inspos]:=exesec;
  2250. exesec.AddObjSection(objsec);
  2251. end;
  2252. end;
  2253. { Now replace the ExeSectionList with content of allsections }
  2254. if (newsections.count<>0) then
  2255. ReplaceExeSectionList(allsections);
  2256. newsections.Free;
  2257. allsections.Free;
  2258. end;
  2259. procedure TElfExeOutput.AfterUnusedSectionRemoval;
  2260. var
  2261. i:longint;
  2262. exesym:TExeSymbol;
  2263. objsym:TObjSymbol;
  2264. objsec: TObjSection;
  2265. begin
  2266. { Unused section removal sets Used property of referenced exesymbols.
  2267. Remaining ones can be removed. }
  2268. for i:=0 to dynsymlist.count-1 do
  2269. begin
  2270. exesym:=TExeSymbol(dynsymlist[i]);
  2271. if assigned(exesym.ObjSymbol.ObjSection) then // an exported symbol
  2272. continue;
  2273. if not exesym.used then
  2274. begin
  2275. dynsymlist[i]:=nil;
  2276. exesym.dynindex:=0;
  2277. end;
  2278. end;
  2279. dynsymlist.Pack;
  2280. { reindex }
  2281. for i:=0 to dynsymlist.count-1 do
  2282. TExeSymbol(dynsymlist[i]).dynindex:=i+1;
  2283. { Drop unresolved symbols that aren't referenced, assign dynamic
  2284. indices to remaining ones, but not if linking with -Xt.
  2285. TODO: behavior of .so with -Xt ? }
  2286. if (cs_link_staticflag in current_settings.globalswitches) then
  2287. UnresolvedExeSymbols.Clear
  2288. else
  2289. for i:=0 to UnresolvedExeSymbols.Count-1 do
  2290. begin
  2291. exesym:=TExeSymbol(UnresolvedExeSymbols[i]);
  2292. if exesym.used then
  2293. begin
  2294. if exesym.dynindex<>0 then
  2295. InternalError(2012062301);
  2296. { Weak-referenced symbols are changed into dynamic ones
  2297. only if referenced through GOT or PLT (this is BFD-compatible) }
  2298. if exesym.state<>symstate_undefweak then
  2299. exesym.dynindex:=dynsymlist.add(exesym)+1;
  2300. end
  2301. else
  2302. UnresolvedExeSymbols[i]:=nil;
  2303. end;
  2304. UnresolvedExeSymbols.Pack;
  2305. { Scan relocations to determine size of GOT, dynamic reloc section, etc. }
  2306. PrepareGOT;
  2307. { Write required PLT entries }
  2308. for i:=0 to dynsymlist.Count-1 do
  2309. begin
  2310. exesym:=TExeSymbol(dynsymlist[i]);
  2311. if assigned(exesym.ObjSymbol.objsection) then // an exported symbol
  2312. continue;
  2313. if ((exesym.ObjSymbol.refs and symref_plt)<>0) or
  2314. ((exesym.ObjSymbol.typ in [AT_FUNCTION,AT_GNU_IFUNC]) and (not IsSharedLibrary)) then
  2315. begin
  2316. make_dynamic_if_undefweak(exesym);
  2317. { This symbol has a valid address to which relocations are resolved,
  2318. but it remains (weak)external when written to dynamic symtable. }
  2319. objsym:=internalobjdata.CreateSymbol(exesym.name);
  2320. objsym.typ:=AT_FUNCTION;
  2321. objsym.bind:=exesym.ObjSymbol.bind; { AB_EXTERNAL or AB_WEAK_EXTERNAL }
  2322. objsym.indsymbol:=exesym.ObjSymbol.indsymbol;
  2323. objsym.offset:=pltobjsec.size;
  2324. objsym.objsection:=pltobjsec;
  2325. objsym.exesymbol:=exesym;
  2326. exesym.ObjSymbol:=objsym;
  2327. WritePLTEntry(exesym);
  2328. end
  2329. else if ((exesym.ObjSymbol.refs and symref_from_text)<>0) and
  2330. (exesym.ObjSymbol.typ<>AT_FUNCTION) and (not IsSharedLibrary) and
  2331. (exesym.state<>symstate_undefweak) then
  2332. begin
  2333. if exesym.ObjSymbol.size=0 then
  2334. Comment(v_error,'Dynamic variable '+exesym.name+' has zero size');
  2335. internalobjdata.setSection(dynbssobjsec);
  2336. internalobjdata.allocalign(size_2_align(exesym.ObjSymbol.size));
  2337. objsym:=internalobjdata.SymbolDefine(exesym.name,AB_GLOBAL,AT_DATA);
  2338. objsym.size:=exesym.ObjSymbol.size;
  2339. objsym.indsymbol:=exesym.ObjSymbol.indsymbol;
  2340. exesym.ObjSymbol:=objsym;
  2341. objsym.exesymbol:=exesym;
  2342. dynbssobjsec.alloc(objsym.size);
  2343. { allocate space for R_xx_COPY relocation for this symbol;
  2344. we'll create it later, to be consistent with "-z combreloc" semantics }
  2345. dyncopysyms.add(objsym);
  2346. dynrelocsec.alloc(dynrelocsec.shentsize);
  2347. inc(dynrelsize,dynrelocsec.shentsize);
  2348. end;
  2349. end;
  2350. { Handle indirect symbols }
  2351. for i:=0 to IndirectObjSymbols.Count-1 do
  2352. begin
  2353. objsym:=TObjSymbol(IndirectObjSymbols[i]);
  2354. objsec:=objsym.ExeSymbol.ObjSymbol.objsection;
  2355. objsym.bind:=AB_EXTERNAL; { cheat FixupSymbols }
  2356. if (oso_plt in objsec.SecOptions) then
  2357. continue;
  2358. WriteIndirectPLTEntry(objsym.ExeSymbol);
  2359. end;
  2360. FixupSymbols;
  2361. if dynamiclink then
  2362. begin
  2363. WriteVersionSections;
  2364. WriteDynamicSymbolsHash;
  2365. end;
  2366. { Create .shstrtab section, which is needed in both exe and .dbg files }
  2367. shstrtabsect:=TElfObjSection.Create_ext(internalObjData,'.shstrtab',SHT_STRTAB,0,1,0);
  2368. shstrtabsect.SecOptions:=[oso_debug_copy];
  2369. AttachSection(shstrtabsect);
  2370. { Create the static symtable (.symtab and .strtab) }
  2371. if (cs_link_separate_dbg_file in current_settings.globalswitches) or
  2372. not(cs_link_strip in current_settings.globalswitches) then
  2373. begin
  2374. symtab:=TElfSymtab.Create(internalObjData,esk_exe);
  2375. symtab.SecOptions:=[oso_debug];
  2376. symtab.fstrsec.SecOptions:=[oso_debug];
  2377. AttachSection(symtab);
  2378. AttachSection(symtab.fstrsec);
  2379. end;
  2380. { Re-enable sections which end up to contain some data
  2381. (.got, .rel[a].dyn, .rel[a].plt (includes .rel[a].iplt) and .hash }
  2382. if gotobjsec.size<>0 then
  2383. gotobjsec.ExeSection.Disabled:=false;
  2384. if assigned(dynrelocsec) and
  2385. ((dynrelocsec.size<>0) or (dyncopysyms.count<>0)) then
  2386. dynrelocsec.ExeSection.Disabled:=false;
  2387. if assigned(pltrelocsec) and (pltrelocsec.size>0) then
  2388. pltrelocsec.ExeSection.Disabled:=false;
  2389. if assigned(ipltrelocsec) and (ipltrelocsec.size>0) then
  2390. ipltrelocsec.ExeSection.Disabled:=false;
  2391. if assigned(hashobjsec) then
  2392. hashobjsec.ExeSection.Disabled:=false;
  2393. if assigned(symversec) and (symversec.size<>0) then
  2394. symversec.ExeSection.Disabled:=false;
  2395. if assigned(verneedsec) and (verneedsec.size<>0) then
  2396. verneedsec.ExeSection.Disabled:=false;
  2397. if assigned(verdefsec) and (verdefsec.size<>0) then
  2398. verdefsec.ExeSection.Disabled:=false;
  2399. RemoveDisabledSections;
  2400. MapSectionsToSegments;
  2401. if dynamiclink then
  2402. FinishDynamicTags;
  2403. end;
  2404. procedure TElfExeOutput.WriteShStrtab;
  2405. var
  2406. i: longint;
  2407. exesec: TElfExeSection;
  2408. begin
  2409. { Remove any existing .shstrtab contents }
  2410. if (shstrtabsect.size>0) then
  2411. begin
  2412. shstrtabsect.ReleaseData;
  2413. shstrtabsect.Size:=0;
  2414. shstrtabsect.SecOptions:=[oso_data];
  2415. end;
  2416. shstrtabsect.writezeros(1);
  2417. for i:=0 to ExeSectionList.Count-1 do
  2418. begin
  2419. exesec:=TElfExeSection(ExeSectionList[i]);
  2420. exesec.shstridx:=shstrtabsect.writestr(exesec.Name);
  2421. exesec.secshidx:=i+1;
  2422. end;
  2423. end;
  2424. procedure TElfExeOutput.FixupSectionLinks;
  2425. var
  2426. dynstrndx,dynsymndx: longword;
  2427. begin
  2428. if dynamiclink then
  2429. begin
  2430. dynstrndx:=TElfExeSection(dynsymtable.fstrsec.ExeSection).secshidx;
  2431. dynsymndx:=TElfExeSection(dynsymtable.ExeSection).secshidx;
  2432. TElfExeSection(hashobjsec.ExeSection).shlink:=dynsymndx;
  2433. TElfExeSection(dynamicsec.ExeSection).shlink:=dynstrndx;
  2434. TElfExeSection(dynsymtable.ExeSection).shlink:=dynstrndx;
  2435. if assigned(pltrelocsec) then
  2436. begin
  2437. TElfExeSection(pltrelocsec.ExeSection).shlink:=dynsymndx;
  2438. TElfExeSection(pltrelocsec.ExeSection).shinfo:=TElfExeSection(pltobjsec.ExeSection).secshidx;
  2439. end;
  2440. if assigned(dynrelocsec) and assigned(dynrelocsec.ExeSection) then
  2441. TElfExeSection(dynrelocsec.ExeSection).shlink:=dynsymndx;
  2442. if symversec.size>0 then
  2443. TElfExeSection(symversec.ExeSection).shlink:=dynsymndx;
  2444. if verdefsec.size>0 then
  2445. TElfExeSection(verdefsec.ExeSection).shlink:=dynstrndx;
  2446. if verneedsec.size>0 then
  2447. TElfExeSection(verneedsec.ExeSection).shlink:=dynstrndx;
  2448. end
  2449. else if assigned(ipltrelocsec) then
  2450. TElfExeSection(ipltrelocsec.ExeSection).shinfo:=TElfExeSection(pltobjsec.ExeSection).secshidx;
  2451. end;
  2452. procedure TElfExeOutput.Do_Mempos;
  2453. var
  2454. i,j: longint;
  2455. seg: TElfSegment;
  2456. exesec: TElfExeSection;
  2457. objsec: TObjSection;
  2458. tempmempos: qword;
  2459. begin
  2460. if IsSharedLibrary then
  2461. CurrMemPos:=0
  2462. else
  2463. CurrMemPos:=ElfTarget.exe_image_base;
  2464. textseg.MemPos:=CurrMemPos;
  2465. if assigned(phdrseg) then
  2466. begin
  2467. phdrseg.Mempos:=CurrMemPos+sizeof(TElfHeader);
  2468. phdrseg.Memsize:=sizeof(TElfproghdr)*segmentlist.count;
  2469. end;
  2470. CurrMemPos:=CurrMemPos+sizeof(TElfHeader)+segmentlist.count*sizeof(TElfproghdr);
  2471. MemPos_Segment(textseg);
  2472. CurrMemPos:=Align(CurrMemPos,SectionDataAlign); {! Data,not MemAlign}
  2473. CurrMemPos:=CurrMemPos+ElfTarget.max_page_size;
  2474. dataseg.MemPos:=CurrMemPos;
  2475. MemPos_Segment(dataseg);
  2476. { Mempos of unmapped sections is forced to zero, but we have to set positions
  2477. of its objsections and update sizes }
  2478. for i:=0 to ExeSectionList.Count-1 do
  2479. begin
  2480. exesec:=TElfExeSection(ExeSectionList[i]);
  2481. if not (oso_load in exesec.SecOptions) then
  2482. begin
  2483. tempmempos:=0;
  2484. exesec.MemPos:=tempmempos;
  2485. for j:=0 to exesec.ObjSectionList.Count-1 do
  2486. begin
  2487. objsec:=TObjSection(exesec.ObjSectionList[j]);
  2488. tempmempos:=objsec.setmempos(tempmempos);
  2489. end;
  2490. exesec.Size:=tempmempos;
  2491. end;
  2492. end;
  2493. { Update MemPos and MemSize of non-load segments,
  2494. in particular, TLS sizes are needed to resolve relocations }
  2495. for i:=0 to segmentlist.count-1 do
  2496. begin
  2497. seg:=TElfSegment(segmentlist[i]);
  2498. if (seg.ptype=PT_LOAD) or (seg.FSectionList.Count=0) then
  2499. continue;
  2500. seg.MemPos:=TExeSection(seg.FSectionList.First).MemPos;
  2501. for j:=0 to seg.FSectionList.Count-1 do
  2502. begin
  2503. exesec:=TElfExeSection(seg.FSectionList[j]);
  2504. seg.MemSize:=exesec.MemPos+exesec.Size-seg.MemPos;
  2505. end;
  2506. end;
  2507. end;
  2508. procedure TElfExeOutput.MemPos_Start;
  2509. var
  2510. i: longint;
  2511. begin
  2512. { Assign section indices and fill .shstrtab
  2513. List of sections cannot be modified after this point. }
  2514. WriteShStrtab;
  2515. { fixup sh_link/sh_info members of various dynamic sections }
  2516. FixupSectionLinks;
  2517. { The actual layout }
  2518. Do_Mempos;
  2519. if (not gotwritten) then
  2520. begin
  2521. { Reset size of .got and .rel[a].dyn, they will be refilled while fixing up relocations.
  2522. For .got, consider already written reserved entries. }
  2523. if assigned(gotobjsec) then
  2524. gotobjsec.size:=gotobjsec.data.size;
  2525. if assigned(dynrelocsec) then
  2526. begin
  2527. dynrelocsec.size:=0;
  2528. { write actual .dynsym content (needs valid symbol addresses) }
  2529. if assigned(tlsseg) then
  2530. dynsymtable.tlsbase:=tlsseg.MemPos;
  2531. dynsymtable.size:=sizeof(TElfsymbol);
  2532. for i:=0 to dynsymlist.count-1 do
  2533. dynsymtable.writeSymbol(TExeSymbol(dynsymlist[i]).objsymbol,dynsymnames[i]);
  2534. end;
  2535. end;
  2536. end;
  2537. procedure TElfExeOutput.MemPos_Segment(seg:TElfSegment);
  2538. var
  2539. i: longint;
  2540. exesec: TElfExeSection;
  2541. begin
  2542. for i:=0 to seg.FSectionList.Count-1 do
  2543. begin
  2544. exesec:=TElfExeSection(seg.FSectionList[i]);
  2545. inherited MemPos_ExeSection(exesec);
  2546. { .tbss should not contribute to address space }
  2547. if (exesec.shtype=SHT_NOBITS) and ((exesec.shflags and SHF_TLS)<>0) then
  2548. CurrMemPos:=exesec.MemPos;
  2549. end;
  2550. { calculate size of the segment }
  2551. seg.MemSize:=CurrMemPos-seg.MemPos;
  2552. end;
  2553. procedure TElfExeOutput.MemPos_ExeSection(const aname:string);
  2554. begin
  2555. // Ignore. All layout is done in mempos_start
  2556. end;
  2557. procedure TElfExeOutput.DataPos_Start;
  2558. var
  2559. i,j: longint;
  2560. exesec: TExeSection;
  2561. seg: TElfSegment;
  2562. objreloc: TObjRelocation;
  2563. objsym: TObjSymbol;
  2564. begin
  2565. gotwritten:=true;
  2566. { If target does not support sorted relocations, it is expected to write the
  2567. entire .rel[a].dyn section during FixupRelocations, and leave dynreloclist empty.
  2568. Otherwise, only RELATIVE ones should be written, space for non-relative relocations
  2569. should remain. }
  2570. if assigned(dynrelocsec) then
  2571. begin
  2572. { Append R_xx_COPY relocations }
  2573. for i:=0 to dyncopysyms.count-1 do
  2574. begin
  2575. objsym:=TObjSymbol(dyncopysyms[i]);
  2576. dynreloclist.Add(TObjRelocation.CreateRaw(objsym.address,objsym,ElfTarget.dyn_reloc_codes[dr_copy]));
  2577. end;
  2578. dyncopysyms.Clear;
  2579. if (dynrelocsec.size+(dynreloclist.count*dynrelocsec.shentsize)<>dynrelsize) then
  2580. InternalError(2012110601);
  2581. { Write out non-RELATIVE dynamic relocations
  2582. TODO: additional sorting? }
  2583. for i:=0 to dynreloclist.count-1 do
  2584. begin
  2585. objreloc:=TObjRelocation(dynreloclist[i]);
  2586. WriteDynRelocEntry(objreloc.dataoffset,objreloc.ftype,objreloc.symbol.exesymbol.dynindex,0);
  2587. end;
  2588. end;
  2589. { sanity checks }
  2590. if assigned(gotobjsec) and (gotsize<>gotobjsec.size) then
  2591. InternalError(2012092501);
  2592. if assigned(dynrelocsec) and (dynrelsize<>dynrelocsec.size) then
  2593. InternalError(2012092502);
  2594. if (ExeWriteMode=ewm_dbgonly) or
  2595. (
  2596. (ExeWriteMode=ewm_exefull) and
  2597. not(cs_link_strip in current_settings.globalswitches)
  2598. ) then
  2599. WriteStaticSymtable;
  2600. { first handle primary segments }
  2601. textseg.DataPos:=0;
  2602. CurrDataPos:=sizeof(TElfHeader)+sizeof(TElfproghdr)*segmentlist.count;
  2603. if assigned(phdrseg) then
  2604. begin
  2605. phdrseg.DataPos:=sizeof(TElfHeader);
  2606. phdrseg.DataSize:=sizeof(TElfproghdr)*segmentlist.count;
  2607. end;
  2608. DataPos_Segment(textseg);
  2609. CurrDataPos:=align(CurrDataPos,SectionDataAlign);
  2610. dataseg.DataPos:=CurrDataPos;
  2611. DataPos_Segment(dataseg);
  2612. { then unmapped sections }
  2613. for i:=0 to ExeSectionList.Count-1 do
  2614. begin
  2615. exesec:=TExeSection(ExeSectionList[i]);
  2616. if not (oso_load in exesec.SecOptions) then
  2617. inherited DataPos_ExeSection(exesec);
  2618. end;
  2619. { finally, update size/position of non-load segments }
  2620. for i:=0 to segmentlist.count-1 do
  2621. begin
  2622. seg:=TElfSegment(segmentlist[i]);
  2623. if (seg.ptype=PT_LOAD) or (seg.FSectionList.Count=0) then
  2624. continue;
  2625. seg.DataPos:=TExeSection(seg.FSectionList.First).DataPos;
  2626. for j:=0 to seg.FSectionList.Count-1 do
  2627. begin
  2628. exesec:=TExeSection(seg.FSectionList[j]);
  2629. if oso_data in exesec.SecOptions then
  2630. seg.DataSize:=exesec.DataPos+exesec.Size-seg.DataPos;
  2631. end;
  2632. end;
  2633. { place section headers after the data }
  2634. shoffset:=CurrDataPos;
  2635. CurrDataPos:=CurrDataPos+ExeSectionList.Count*sizeof(TElfsechdr);
  2636. end;
  2637. procedure TElfExeOutput.DataPos_Segment(seg:TElfSegment);
  2638. var
  2639. i: longint;
  2640. exesec: TElfExeSection;
  2641. begin
  2642. for i:=0 to seg.FSectionList.Count-1 do
  2643. begin
  2644. exesec:=TElfExeSection(seg.FSectionList[i]);
  2645. { ELF needs DataPos set to 'would-be' value for sections that
  2646. don't have data, and for non-debug sections in .dbg file, too.
  2647. This slightly differs from generic approach. }
  2648. if not (oso_data in exesec.SecOptions) or
  2649. (
  2650. (ExeWriteMode=ewm_dbgonly) and
  2651. (exesec.SecOptions*[oso_debug,oso_debug_copy]=[])
  2652. ) then
  2653. begin
  2654. CurrDataPos:=align(CurrDataPos,SectionDataAlign);
  2655. exesec.DataPos:=CurrDataPos;
  2656. end
  2657. else
  2658. inherited DataPos_ExeSection(exesec);
  2659. end;
  2660. { calculate size of the segment }
  2661. seg.DataSize:=CurrDataPos-seg.DataPos;
  2662. end;
  2663. procedure TElfExeOutput.DataPos_ExeSection(const aname:string);
  2664. begin
  2665. // Ignore. Work is done entirely in datapos_start.
  2666. end;
  2667. procedure TElfExeOutput.InitDynlink;
  2668. begin
  2669. if not IsSharedLibrary then
  2670. begin
  2671. interpobjsec:=internalObjData.createsection('.interp',1,[oso_data,oso_load,oso_keep]);
  2672. interpobjsec.writestr(interpreter^);
  2673. end;
  2674. hashobjsec:=TElfObjSection.create_ext(internalObjData,'.hash',
  2675. SHT_HASH,SHF_ALLOC,sizeof(pint),4);
  2676. hashobjsec.secoptions:=[oso_keep];
  2677. dynsymtable:=TElfSymtab.create(internalObjData,esk_dyn);
  2678. dynamicsec:=TElfObjSection.create_ext(internalObjData,'.dynamic',
  2679. SHT_DYNAMIC,SHF_ALLOC or SHF_WRITE,sizeof(pint),sizeof(TElfDyn));
  2680. dynamicsec.SecOptions:=[oso_keep];
  2681. dynrelocsec:=TElfObjSection.create_reloc(internalObjData,'.dyn',true);
  2682. dynrelocsec.SecOptions:=[oso_keep];
  2683. dynbssobjsec:=TElfObjSection.create_ext(internalObjData,'.dynbss',
  2684. SHT_NOBITS,SHF_ALLOC or SHF_WRITE,sizeof(pint){16??},0);
  2685. dynbssobjsec.SecOptions:=[oso_keep];
  2686. dynreloclist:=TFPObjectList.Create(true);
  2687. symversec:=TElfObjSection.create_ext(internalObjData,'.gnu.version',
  2688. SHT_GNU_VERSYM,SHF_ALLOC,sizeof(word),sizeof(word));
  2689. symversec.SecOptions:=[oso_keep];
  2690. verdefsec:=TElfObjSection.create_ext(internalObjData,'.gnu.version_d',
  2691. SHT_GNU_VERDEF,SHF_ALLOC,sizeof(pint),0);
  2692. verdefsec.SecOptions:=[oso_keep];
  2693. verneedsec:=TElfObjSection.create_ext(internalObjData,'.gnu.version_r',
  2694. SHT_GNU_VERNEED,SHF_ALLOC,sizeof(pint),0);
  2695. verneedsec.SecOptions:=[oso_keep];
  2696. dyncopysyms:=TFPObjectList.Create(False);
  2697. end;
  2698. const
  2699. hashbuckets: array[0..15] of longint=(
  2700. 1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
  2701. 16411, 32771);
  2702. {$push}{$r-,q-}
  2703. function elfhash(const name:string):longword;
  2704. var
  2705. g: longword;
  2706. i: longint;
  2707. begin
  2708. result:=0;
  2709. for i:=1 to length(name) do
  2710. begin
  2711. result:=(result shl 4)+ord(name[i]);
  2712. g:=result and $F0000000;
  2713. if g>0 then
  2714. result:=result xor (g shr 24);
  2715. result:=result and (not g);
  2716. end;
  2717. end;
  2718. {$pop}
  2719. procedure TElfExeOutput.WriteDynamicSymbolsHash;
  2720. var
  2721. nchains,nbuckets: longint;
  2722. i,j: longint;
  2723. hashdata: plongint;
  2724. sym: TExeSymbol;
  2725. begin
  2726. dynsymnames:=AllocMem(dynsymlist.count*sizeof(longword));
  2727. nchains:=dynsymlist.Count+1;
  2728. { determine suitable bucket count }
  2729. i:=high(hashbuckets);
  2730. while (i>=0) and (nchains<hashbuckets[i]) do
  2731. dec(i);
  2732. nbuckets:=hashbuckets[i];
  2733. hashdata:=AllocMem((2+nchains+nbuckets)*sizeof(longint));
  2734. hashdata[0]:=nbuckets;
  2735. hashdata[1]:=nchains;
  2736. { The contents of .dynsym can be written only after mempos pass
  2737. because it needs valid symbol virtual addresses and section indices.
  2738. Here we preset .dynsym size and write names, in order to get
  2739. correct size of .dynstr section. }
  2740. dynsymtable.size:=(dynsymlist.count+1)*sizeof(TElfsymbol);
  2741. for i:=0 to dynsymlist.Count-1 do
  2742. begin
  2743. sym:=TExeSymbol(dynsymlist[i]);
  2744. dynsymnames[i]:=dynsymtable.fstrsec.writestr(sym.objsymbol.name);
  2745. j:=(elfhash(sym.objsymbol.name) mod nbuckets)+2;
  2746. while hashdata[j]<>0 do
  2747. j:=2+nbuckets+hashdata[j];
  2748. hashdata[j]:=i+1;
  2749. end;
  2750. if source_info.endian<>target_info.endian then
  2751. for i:=0 to nchains+nbuckets+1 do
  2752. hashdata[i]:=swapendian(hashdata[i]);
  2753. hashobjsec.write(hashdata^,(2+nchains+nbuckets)*sizeof(longint));
  2754. freemem(hashdata);
  2755. end;
  2756. procedure TElfExeOutput.WriteVersionSections;
  2757. var
  2758. i,j: longint;
  2759. idx,auxidx: longword;
  2760. exesym: TExeSymbol;
  2761. dynobj: TElfDynamicObjData;
  2762. ver: TElfVersionDef;
  2763. vn: TElfverneed;
  2764. vna: TElfvernaux;
  2765. symversions: pword;
  2766. begin
  2767. symversions:=AllocMem((dynsymlist.count+1)*sizeof(word));
  2768. { Assign version indices }
  2769. idx:=VER_NDX_GLOBAL+1;
  2770. for i:=0 to dynsymlist.count-1 do
  2771. begin
  2772. exesym:=TExeSymbol(dynsymlist[i]);
  2773. if (exesym.objsymbol.indsymbol is TVersionedObjSymbol) then
  2774. ver:=TVersionedObjSymbol(exesym.objsymbol.indsymbol).version
  2775. else
  2776. ver:=nil;
  2777. if assigned(ver) then
  2778. begin
  2779. if ver.index=0 then
  2780. begin
  2781. ver.index:=idx;
  2782. inc(idx);
  2783. end;
  2784. symversions[i+1]:=ver.index;
  2785. end
  2786. else if exesym.state in [symstate_undefined,symstate_undefweak] then
  2787. symversions[i+1]:=VER_NDX_LOCAL
  2788. else
  2789. symversions[i+1]:=VER_NDX_GLOBAL;
  2790. end;
  2791. { Count entries to be written }
  2792. verneedcount:=0;
  2793. for i:=0 to neededlist.count-1 do
  2794. begin
  2795. dynobj:=TElfDynamicObjData(neededlist[i]);
  2796. dynobj.vernaux_count:=0;
  2797. for j:=2 to dynobj.versiondefs.count-1 do
  2798. begin
  2799. ver:=TElfVersionDef(dynobj.versiondefs[j]);
  2800. if ver.index>VER_NDX_GLOBAL then
  2801. inc(dynobj.vernaux_count);
  2802. end;
  2803. if (dynobj.vernaux_count>0) then
  2804. inc(verneedcount);
  2805. end;
  2806. { Now write }
  2807. idx:=0;
  2808. for i:=0 to neededlist.count-1 do
  2809. begin
  2810. dynobj:=TElfDynamicObjData(neededlist[i]);
  2811. if dynobj.vernaux_count=0 then
  2812. continue;
  2813. inc(idx);
  2814. vn.vn_version:=VER_NEED_CURRENT;
  2815. vn.vn_cnt:=dynobj.vernaux_count;
  2816. vn.vn_file:=dynobj.soname_strofs;
  2817. vn.vn_aux:=sizeof(TElfverneed);
  2818. vn.vn_next:=ord(idx<verneedcount)*(sizeof(TElfverneed)+vn.vn_cnt*sizeof(TElfvernaux));
  2819. MaybeSwapElfverneed(vn);
  2820. verneedsec.write(vn,sizeof(TElfverneed));
  2821. auxidx:=0;
  2822. for j:=2 to dynobj.versiondefs.count-1 do
  2823. begin
  2824. ver:=TElfVersionDef(dynobj.versiondefs[j]);
  2825. if ver.index<=VER_NDX_GLOBAL then
  2826. continue;
  2827. inc(auxidx);
  2828. vna.vna_hash:=elfhash(ver.name);
  2829. vna.vna_flags:=0; { BFD copies this from verdef.vd_flags?? }
  2830. vna.vna_other:=ver.index;
  2831. vna.vna_name:=dynsymtable.fstrsec.writestr(ver.name);
  2832. vna.vna_next:=ord(auxidx<dynobj.vernaux_count)*sizeof(TElfvernaux);
  2833. MaybeSwapElfvernaux(vna);
  2834. verneedsec.write(vna,sizeof(TElfvernaux));
  2835. end;
  2836. end;
  2837. TElfExeSection(verneedsec.ExeSection).shinfo:=verneedcount;
  2838. { If there are no needed versions, .gnu.version section is not needed }
  2839. if verneedcount>0 then
  2840. begin
  2841. if source_info.endian<>target_info.endian then
  2842. for i:=0 to dynsymlist.count+1 do
  2843. symversions[i]:=swapendian(symversions[i]);
  2844. symversec.write(symversions^,(dynsymlist.count+1)*sizeof(word));
  2845. end;
  2846. FreeMem(symversions);
  2847. end;
  2848. procedure TElfExeOutput.WriteDynRelocEntry(dataofs:aword;typ:byte;symidx:aword;addend:aword);
  2849. var
  2850. rel:telfreloc;
  2851. begin
  2852. rel.address:=dataofs;
  2853. rel.info:=ELF_R_INFO(symidx,typ);
  2854. {$push}{$r-}
  2855. rel.addend:=addend;
  2856. {$pop}
  2857. MaybeSwapElfReloc(rel);
  2858. dynrelocsec.write(rel,dynrelocsec.shentsize);
  2859. end;
  2860. procedure TElfExeOutput.WriteDynTag(aTag:longword;aValue:longword);
  2861. var
  2862. d: TElfDyn;
  2863. begin
  2864. d.d_tag:=aTag;
  2865. d.d_val:=aValue;
  2866. MaybeSwapElfDyn(d);
  2867. dynamicsec.write(d,sizeof(TElfDyn));
  2868. end;
  2869. procedure TElfExeOutput.WriteDynTag(aTag:longword;aSection:TObjSection;aOffs:aword);
  2870. var
  2871. d: TElfDyn;
  2872. begin
  2873. d.d_tag:=aTag;
  2874. if source_info.endian<>target_info.endian then
  2875. d.d_tag:=swapendian(d.d_tag);
  2876. dynamicsec.write(d.d_tag,sizeof(d.d_tag));
  2877. { TODO: ignores endianness! }
  2878. dynamicsec.writeReloc_internal(aSection,aOffs,sizeof(d.d_ptr),RELOC_ABSOLUTE);
  2879. end;
  2880. procedure TElfExeOutput.WriteTargetDynamicTags;
  2881. begin
  2882. { to be overridden by CPU-specific descendants }
  2883. end;
  2884. procedure TElfExeOutput.WriteDynamicTags;
  2885. var
  2886. s: aword;
  2887. i: longint;
  2888. sym: TExeSymbol;
  2889. hs:string;
  2890. dynobj: TElfDynamicObjData;
  2891. begin
  2892. for i:=0 to neededlist.Count-1 do
  2893. begin
  2894. dynobj:=TElfDynamicObjData(neededlist[i]);
  2895. s:=dynsymtable.fstrsec.writestr(dynobj.name);
  2896. dynobj.soname_strofs:=s;
  2897. WriteDynTag(DT_NEEDED,s);
  2898. end;
  2899. if IsSharedLibrary then
  2900. begin
  2901. s:=dynsymtable.fstrsec.writestr(ExtractFileName(current_module.sharedlibfilename));
  2902. WriteDynTag(DT_SONAME,s);
  2903. { TODO: names hardcoded here }
  2904. sym:=TExeSymbol(ExeSymbolList.Find('FPC_SHARED_LIB_START'));
  2905. if assigned(sym) then
  2906. WriteDynTag(DT_INIT,sym.objsymbol.objsection,sym.objsymbol.offset);
  2907. sym:=TExeSymbol(ExeSymbolList.Find('FPC_LIB_EXIT'));
  2908. if assigned(sym) then
  2909. WriteDynTag(DT_FINI,sym.objsymbol.objsection,sym.objsymbol.offset);
  2910. end;
  2911. { TODO: we need a dedicated parameter to pass runpath, instead of this hack
  2912. (-Xr is a different thing, it passes "-rpath-link"). }
  2913. if (ParaLinkOptions<>'') then
  2914. begin
  2915. hs:=ParaLinkOptions;
  2916. while (hs<>'') do
  2917. begin
  2918. if (GetToken(hs,' ')='-rpath') then
  2919. begin
  2920. s:=dynsymtable.fstrsec.writestr(GetToken(hs,' '));
  2921. WriteDynTag(DT_RPATH,s);
  2922. end;
  2923. end;
  2924. end;
  2925. if assigned(preinitarraysec) then
  2926. begin
  2927. WriteDynTag(DT_PREINIT_ARRAY,preinitarraysec,0);
  2928. WriteDynTag(DT_PREINIT_ARRAYSZ,preinitarraysec.exesection.size);
  2929. end;
  2930. if assigned(initarraysec) then
  2931. begin
  2932. WriteDynTag(DT_INIT_ARRAY,initarraysec,0);
  2933. WriteDynTag(DT_INIT_ARRAYSZ,initarraysec.exesection.size);
  2934. end;
  2935. if assigned(finiarraysec) then
  2936. begin
  2937. WriteDynTag(DT_FINI_ARRAY,finiarraysec,0);
  2938. WriteDynTag(DT_FINI_ARRAYSZ,finiarraysec.exesection.size);
  2939. end;
  2940. writeDynTag(DT_HASH,hashobjsec);
  2941. writeDynTag(DT_STRTAB,dynsymtable.fstrsec);
  2942. writeDynTag(DT_SYMTAB,dynsymtable);
  2943. writeDynTag(DT_SYMENT,sizeof(TElfSymbol));
  2944. if Assigned(gotpltobjsec) then
  2945. writeDynTag(DT_PLTGOT,gotpltobjsec);
  2946. end;
  2947. const
  2948. pltreltags: array[boolean] of longword=(DT_REL,DT_RELA);
  2949. relsztags: array[boolean] of longword=(DT_RELSZ,DT_RELASZ);
  2950. relenttags: array[boolean] of longword=(DT_RELENT,DT_RELAENT);
  2951. {$ifndef MIPS}
  2952. relcnttags: array[boolean] of longword=(DT_RELCOUNT,DT_RELACOUNT);
  2953. {$endif MIPS}
  2954. procedure TElfExeOutput.FinishDynamicTags;
  2955. var
  2956. rela: boolean;
  2957. begin
  2958. if assigned(dynsymtable) then
  2959. writeDynTag(DT_STRSZ,dynsymtable.fstrsec.size);
  2960. if hastextrelocs then
  2961. writeDynTag(DT_TEXTREL,0);
  2962. if Assigned(pltrelocsec) and (pltrelocsec.size>0) then
  2963. begin
  2964. writeDynTag(DT_PLTRELSZ,pltrelocsec.Size);
  2965. writeDynTag(DT_PLTREL,pltreltags[pltrelocsec.shtype=SHT_RELA]);
  2966. writeDynTag(DT_JMPREL,pltrelocsec);
  2967. end;
  2968. if Assigned(dynrelocsec) and (dynrelocsec.size>0) then
  2969. begin
  2970. rela:=(dynrelocsec.shtype=SHT_RELA);
  2971. writeDynTag(pltreltags[rela],dynrelocsec);
  2972. writeDynTag(relsztags[rela],dynrelocsec.Size);
  2973. writeDynTag(relenttags[rela],dynrelocsec.shentsize);
  2974. {$ifndef MIPS}
  2975. if (relative_reloc_count>0) then
  2976. writeDynTag(relcnttags[rela],relative_reloc_count);
  2977. {$endif MIPS}
  2978. end;
  2979. WriteTargetDynamicTags;
  2980. if (verdefcount>0) or (verneedcount>0) then
  2981. begin
  2982. if (verdefcount>0) then
  2983. begin
  2984. writeDynTag(DT_VERDEF,verdefsec);
  2985. writeDynTag(DT_VERDEFNUM,verdefcount);
  2986. end;
  2987. if (verneedcount>0) then
  2988. begin
  2989. writeDynTag(DT_VERNEED,verneedsec);
  2990. writeDynTag(DT_VERNEEDNUM,verneedcount);
  2991. end;
  2992. writeDynTag(DT_VERSYM,symversec);
  2993. end;
  2994. writeDynTag(DT_NULL,0);
  2995. end;
  2996. procedure TElfExeOutput.CreatePLT;
  2997. var
  2998. reloc: TObjRelocation;
  2999. begin
  3000. pltobjsec:=TElfObjSection.create_ext(internalObjData,'.plt',
  3001. SHT_PROGBITS,SHF_ALLOC or SHF_EXECINSTR,4,16);
  3002. pltobjsec.SecOptions:=[oso_keep,oso_plt];
  3003. pltrelocsec:=TElfObjSection.create_reloc(internalObjData,'.plt',true);
  3004. pltrelocsec.SecOptions:=[oso_keep];
  3005. ipltrelocsec:=TElfObjSection.create_reloc(internalObjData,'.iplt',true);
  3006. ipltrelocsec.SecOptions:=[oso_keep];
  3007. { reference .dynamic from .got.plt, this isn't necessary if linking statically }
  3008. { TODO: maybe move writing initial .got.plt entries here completely
  3009. (needs testing --- GOT symbol may get lost if .got.plt is empty)}
  3010. if dynamiclink then
  3011. begin
  3012. reloc:=TObjRelocation.CreateSection(0,dynamicsec,RELOC_ABSOLUTE);
  3013. reloc.size:=sizeof(pint);
  3014. gotpltobjsec.ObjRelocations.Add(reloc);
  3015. end;
  3016. { Initial PLT entry, CPU-specific }
  3017. WriteFirstPLTEntry;
  3018. end;
  3019. procedure TElfExeOutput.WritePLTEntry(exesym:TExeSymbol);
  3020. begin
  3021. // must be implemented by CPU-specific descendant
  3022. InternalError(2012092102);
  3023. end;
  3024. procedure TElfExeOutput.WriteIndirectPLTEntry(exesym:TExeSymbol);
  3025. begin
  3026. // must be implemented by CPU-specific descendant
  3027. InternalError(2012092101);
  3028. end;
  3029. function TElfExeOutput.WriteData:boolean;
  3030. begin
  3031. WriteHeader;
  3032. segmentlist.ForEachCall(@segment_write_header,nil);
  3033. WriteExeSectionContent;
  3034. FWriter.WriteZeros(sizeof(TElfsechdr));
  3035. ExeSectionList.ForEachCall(@exesection_write_header,nil);
  3036. result:=true;
  3037. end;
  3038. procedure TElfExeOutput.GenerateLibraryImports(ImportLibraryList:TFPHashObjectList);
  3039. var
  3040. exportlist: TCmdStrList;
  3041. sym: TExeSymbol;
  3042. begin
  3043. AllowUndefinedSymbols:=IsSharedLibrary;
  3044. { add exported symbols to dynamic list }
  3045. exportlist:=texportlibunix(exportlib).exportedsymnames;
  3046. if not exportlist.empty then
  3047. repeat
  3048. sym:=TExeSymbol(ExeSymbolList.Find(exportlist.getfirst));
  3049. if assigned(sym) then
  3050. begin
  3051. if assigned(sym.objsymbol.objsection) then
  3052. sym.objsymbol.objsection.SecOptions:=[oso_keep];
  3053. sym.dynindex:=dynsymlist.add(sym)+1
  3054. end
  3055. else
  3056. InternalError(2012071801);
  3057. until exportlist.empty;
  3058. end;
  3059. procedure TElfExeOutput.ReportNonDSOReloc(reltyp:byte;objsec:TObjSection;ObjReloc:TObjRelocation);
  3060. begin
  3061. { TODO: include objsec properties into message }
  3062. Comment(v_error,'Relocation '+ElfTarget.RelocName(reltyp)+' against '''+objreloc.TargetName+''' cannot be used when linking a shared object; recompile with -Cg');
  3063. end;
  3064. procedure TElfExeOutput.ReportRelocOverflow(reltyp:byte;objsec:TObjSection;ObjReloc:TObjRelocation);
  3065. begin
  3066. { TODO: include objsec properties into message }
  3067. Comment(v_error,'Relocation truncated to fit: '+ElfTarget.RelocName(reltyp)+' against '''+objreloc.TargetName+'''');
  3068. end;
  3069. {****************************************************************************
  3070. TElfExeSection
  3071. ****************************************************************************}
  3072. procedure TElfExeSection.AddObjSection(objsec:TObjSection;ignoreprops:boolean);
  3073. begin
  3074. inherited AddObjSection(objsec,ignoreprops);
  3075. if ignoreprops then
  3076. exit;
  3077. if (shtype=SHT_NULL) then
  3078. begin
  3079. shtype:=TElfObjSection(objsec).shtype;
  3080. shflags:=TElfObjSection(objsec).shflags;
  3081. shentsize:=TElfObjSection(objsec).shentsize;
  3082. end;
  3083. end;
  3084. {****************************************************************************
  3085. TElfSegment
  3086. ****************************************************************************}
  3087. constructor TElfSegment.Create(atype,aflags,aalign:longword);
  3088. begin
  3089. ptype:=atype;
  3090. pflags:=aflags;
  3091. align:=aalign;
  3092. FSectionList:=TFPObjectList.Create(false);
  3093. end;
  3094. destructor TElfSegment.Destroy;
  3095. begin
  3096. FSectionList.Free;
  3097. inherited Destroy;
  3098. end;
  3099. procedure TElfSegment.Add(exesec:TExeSection);
  3100. begin
  3101. FSectionList.Add(exesec);
  3102. end;
  3103. end.