ogelf.pas 121 KB

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