ogelf.pas 100 KB

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