ogelf.pas 106 KB

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