ogelf.pas 116 KB

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