ogelf.pas 121 KB

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