ogelf.pas 114 KB

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