ogelf.pas 103 KB

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