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: TAnsiCharDynarray;
  114. strtab: TAnsiCharDynarray;
  115. shstrtablen: longword;
  116. strtablen: longword;
  117. symtaboffset: aword;
  118. syms: longword;
  119. localsyms: longword;
  120. symversions: TWordDynArray;
  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. '.note'
  515. );
  516. var
  517. sep : string[3];
  518. secname : string;
  519. begin
  520. { section type user gives the user full controll on the section name }
  521. if atype=sec_user then
  522. result:=aname
  523. else
  524. begin
  525. secname:=secnames[atype];
  526. if (atype=sec_fpc) and (Copy(aname,1,3)='res') then
  527. begin
  528. result:=secname+'.'+aname;
  529. exit;
  530. end;
  531. if atype=sec_threadvar then
  532. begin
  533. if (target_info.system in (systems_windows+systems_wince)) then
  534. secname:='.tls'
  535. else if (target_info.system in systems_linux) then
  536. secname:='.tbss';
  537. end;
  538. if create_smartlink_sections and (aname<>'') then
  539. begin
  540. case aorder of
  541. secorder_begin :
  542. sep:='.b_';
  543. secorder_end :
  544. sep:='.z_';
  545. else
  546. sep:='.n_';
  547. end;
  548. result:=secname+sep+aname
  549. end
  550. else
  551. result:=secname;
  552. end;
  553. end;
  554. procedure TElfObjData.CreateDebugSections;
  555. begin
  556. if target_dbg.id=dbg_stabs then
  557. begin
  558. stabssec:=createsection(sec_stab);
  559. stabstrsec:=createsection(sec_stabstr);
  560. end;
  561. end;
  562. procedure TElfObjData.writereloc(data:aint;len:aword;p:TObjSymbol;reltype:TObjRelocationType);
  563. type
  564. multi = record
  565. case integer of
  566. 0 : (ba : array[0..sizeof(aint)-1] of byte);
  567. 1 : (b : byte);
  568. 2 : (w : word);
  569. 4 : (d : dword);
  570. 8 : (q : qword);
  571. end;
  572. var
  573. symaddr : aint;
  574. ba : multi;
  575. b : byte;
  576. objreloc: TObjRelocation;
  577. begin
  578. if CurrObjSec=nil then
  579. internalerror(200403292);
  580. objreloc:=nil;
  581. if assigned(p) then
  582. begin
  583. { real address of the symbol }
  584. symaddr:=p.address;
  585. { Local ObjSymbols can be resolved already or need a section reloc }
  586. if (p.bind=AB_LOCAL) and
  587. (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
  588. begin
  589. {$ifdef ARM}
  590. if (reltype in [RELOC_RELATIVE_24,RELOC_RELATIVE_CALL]) and
  591. (p.objsection=CurrObjSec) then
  592. begin
  593. data:=aint((data and $ff000000) or (((((data and $ffffff) shl 2)+(symaddr-CurrObjSec.Size)) shr 2) and $FFFFFF)); // TODO: Check overflow
  594. end
  595. else
  596. {$endif ARM}
  597. { For a reltype relocation in the same section the
  598. value can be calculated }
  599. if (p.objsection=CurrObjSec) and
  600. (reltype=RELOC_RELATIVE) then
  601. inc(data,symaddr-len-CurrObjSec.Size)
  602. else
  603. begin
  604. objreloc:=TObjRelocation.CreateSection(CurrObjSec.Size,p.objsection,reltype);
  605. CurrObjSec.ObjRelocations.Add(objreloc);
  606. inc(data,symaddr);
  607. end;
  608. end
  609. else
  610. begin
  611. objreloc:=TObjRelocation.CreateSymbol(CurrObjSec.Size,p,reltype);
  612. CurrObjSec.ObjRelocations.Add(objreloc);
  613. { If target is a local label and it isn't handled above,
  614. patch its type in order to get it written to symtable.
  615. This may happen e.g. when taking address of Pascal label in PIC mode. }
  616. if (p.bind=AB_LOCAL) and (p.typ=AT_LABEL) then
  617. p.typ:=AT_ADDR;
  618. end;
  619. end;
  620. if assigned(objreloc) then
  621. begin
  622. objreloc.size:=len;
  623. { RELOC_GOTPCREL, RELOC_REX_GOTPCRELX, RELOC_GOTPCRELX] need special handling
  624. this is done in x86/aasmcpu unit }
  625. if reltype in [RELOC_RELATIVE{$ifdef x86},RELOC_PLT32{$endif}
  626. {$ifdef x86_64}, RELOC_GOTPCREL, RELOC_REX_GOTPCRELX, RELOC_GOTPCRELX,RELOC_TLSGD{$endif}] then
  627. dec(data,len);
  628. if ElfTarget.relocs_use_addend then
  629. begin
  630. objreloc.orgsize:=aword(data);
  631. data:=0;
  632. end;
  633. end;
  634. if target_info.endian<>source_info.endian then
  635. begin
  636. ba.q:=0;
  637. if (len<=sizeof(data)) then
  638. case len of
  639. 1 : ba.b:=byte(data);
  640. 2 : begin
  641. ba.w:=word(data);
  642. ba.w:=swapendian(ba.w);
  643. end;
  644. 4 : begin
  645. ba.d:=dword(data);
  646. ba.d:=swapendian(ba.d);
  647. end;
  648. 8 : begin
  649. ba.q:=qword(data);
  650. ba.q:=swapendian(ba.q);
  651. end;
  652. else
  653. internalerror(2024012501);
  654. end;
  655. CurrObjSec.write(ba,len);
  656. end
  657. else
  658. CurrObjSec.write(data,len);
  659. end;
  660. {****************************************************************************
  661. TElfDynamicObjData
  662. ****************************************************************************}
  663. constructor TElfDynamicObjData.create(const n:string);
  664. begin
  665. inherited Create(n);
  666. FVersionDefs:=TFPHashObjectList.create(true);
  667. { Default symversions with indices 0 and 1 }
  668. TElfVersionDef.create(FVersionDefs,'*local*');
  669. TElfVersionDef.create(FVersionDefs,'*global*');
  670. end;
  671. destructor TElfDynamicObjData.destroy;
  672. begin
  673. FVersionDefs.free;
  674. inherited Destroy;
  675. end;
  676. {****************************************************************************
  677. TElfSymtab
  678. ****************************************************************************}
  679. const
  680. symsecnames: array[boolean] of string[8] = ('.symtab','.dynsym');
  681. strsecnames: array[boolean] of string[8] = ('.strtab','.dynstr');
  682. symsectypes: array[boolean] of longword = (SHT_SYMTAB,SHT_DYNSYM);
  683. symsecattrs: array[boolean] of longword = (0,SHF_ALLOC);
  684. constructor TElfSymtab.create(aObjData:TObjData;aKind:TElfSymtabKind);
  685. var
  686. dyn:boolean;
  687. begin
  688. dyn:=(aKind=esk_dyn);
  689. create_ext(aObjData,symsecnames[dyn],symsectypes[dyn],symsecattrs[dyn],sizeof(pint),sizeof(TElfSymbol));
  690. fstrsec:=TElfObjSection.create_ext(aObjData,strsecnames[dyn],SHT_STRTAB,symsecattrs[dyn],1,0);
  691. fstrsec.writezeros(1);
  692. writezeros(sizeof(TElfSymbol));
  693. symidx:=1;
  694. shinfo:=1;
  695. kind:=aKind;
  696. end;
  697. procedure TElfSymtab.writeInternalSymbol(avalue:aword;astridx:longword;ainfo:byte;ashndx:word);
  698. var
  699. elfsym:TElfSymbol;
  700. begin
  701. fillchar(elfsym,sizeof(elfsym),0);
  702. elfsym.st_value:=avalue;
  703. elfsym.st_name:=astridx;
  704. elfsym.st_info:=ainfo;
  705. elfsym.st_shndx:=ashndx;
  706. inc(symidx);
  707. inc(shinfo);
  708. MaybeSwapElfSymbol(elfsym);
  709. write(elfsym,sizeof(elfsym));
  710. end;
  711. procedure TElfSymtab.writeSymbol(objsym:TObjSymbol;nameidx:longword);
  712. var
  713. elfsym:TElfSymbol;
  714. begin
  715. fillchar(elfsym,sizeof(elfsym),0);
  716. if nameidx=0 then
  717. elfsym.st_name:=fstrsec.writestr(objsym.name)
  718. else
  719. elfsym.st_name:=nameidx;
  720. elfsym.st_size:=objsym.size;
  721. elfsym.st_value:=objsym.address;
  722. {$ifdef ARM}
  723. if objsym.ThumbFunc then
  724. inc(elfsym.st_value);
  725. {$endif ARM}
  726. { hidden symbols should have been converted to local symbols in
  727. the linking pass in case we're writing an exe/library; don't
  728. convert them to local here as well, as that would potentially
  729. hide a bug there. }
  730. case objsym.bind of
  731. AB_LOCAL :
  732. begin
  733. elfsym.st_info:=STB_LOCAL shl 4;
  734. inc(shinfo);
  735. end;
  736. AB_COMMON :
  737. begin
  738. elfsym.st_value:=size_2_align(objsym.size);
  739. elfsym.st_info:=STB_GLOBAL shl 4;
  740. elfsym.st_shndx:=SHN_COMMON;
  741. end;
  742. AB_EXTERNAL :
  743. elfsym.st_info:=STB_GLOBAL shl 4;
  744. AB_WEAK_EXTERNAL :
  745. elfsym.st_info:=STB_WEAK shl 4;
  746. AB_GLOBAL :
  747. elfsym.st_info:=STB_GLOBAL shl 4;
  748. AB_PRIVATE_EXTERN :
  749. begin
  750. elfsym.st_info:=STB_GLOBAL shl 4;
  751. SetElfSymbolVisibility(elfsym.st_other,STV_HIDDEN);
  752. end
  753. else
  754. InternalError(2012111801);
  755. end;
  756. { External symbols must be NOTYPE in relocatable files except if they are TLS symbols }
  757. if (objsym.bind<>AB_EXTERNAL) or (kind<>esk_obj) or (objsym.typ=AT_TLS) then
  758. begin
  759. case objsym.typ of
  760. AT_FUNCTION :
  761. elfsym.st_info:=elfsym.st_info or STT_FUNC;
  762. AT_DATA,
  763. AT_METADATA:
  764. elfsym.st_info:=elfsym.st_info or STT_OBJECT;
  765. AT_TLS:
  766. elfsym.st_info:=elfsym.st_info or STT_TLS;
  767. AT_GNU_IFUNC:
  768. elfsym.st_info:=elfsym.st_info or STT_GNU_IFUNC;
  769. { other types are implicitly mapped to STT_NOTYPE }
  770. else
  771. ;
  772. end;
  773. end;
  774. if objsym.bind<>AB_COMMON then
  775. begin
  776. if kind<>esk_obj then
  777. begin
  778. if assigned(objsym.objsection) and assigned(objsym.objsection.ExeSection) then
  779. begin
  780. if (objsym.typ=AT_TLS) then
  781. elfsym.st_value:=elfsym.st_value-tlsbase
  782. else if (oso_plt in objsym.objsection.SecOptions) then
  783. elfsym.st_value:=0
  784. else
  785. elfsym.st_shndx:=TElfExeSection(objsym.objsection.ExeSection).secshidx;
  786. end;
  787. end
  788. else
  789. begin
  790. if assigned(objsym.objsection) then
  791. elfsym.st_shndx:=objsym.objsection.index
  792. else
  793. elfsym.st_shndx:=SHN_UNDEF;
  794. objsym.symidx:=symidx;
  795. end;
  796. end;
  797. inc(symidx);
  798. MaybeSwapElfSymbol(elfsym);
  799. write(elfsym,sizeof(TElfSymbol));
  800. end;
  801. {****************************************************************************
  802. TElfObjectOutput
  803. ****************************************************************************}
  804. constructor TElfObjectOutput.create(AWriter:TObjectWriter);
  805. begin
  806. inherited Create(AWriter);
  807. CObjData:=TElfObjData;
  808. end;
  809. procedure TElfObjectOutput.createrelocsection(s:TElfObjSection;data:TObjData);
  810. var
  811. i : longint;
  812. rel : telfreloc;
  813. objreloc : TObjRelocation;
  814. relsym : longint;
  815. relocsect : TElfObjSection;
  816. begin
  817. { create the reloc section }
  818. relocsect:=TElfObjSection.create_reloc(data,s.name,false);
  819. relocsect.shlink:=symtabsect.index;
  820. relocsect.shinfo:=s.index;
  821. { add the relocations }
  822. for i:=0 to s.Objrelocations.count-1 do
  823. begin
  824. objreloc:=TObjRelocation(s.Objrelocations[i]);
  825. { Symbol }
  826. if assigned(objreloc.symbol) then
  827. begin
  828. if objreloc.symbol.symidx=-1 then
  829. begin
  830. writeln(objreloc.symbol.Name);
  831. internalerror(200603012);
  832. end;
  833. relsym:=objreloc.symbol.symidx;
  834. end
  835. else
  836. begin
  837. if objreloc.objsection<>nil then
  838. relsym:=objreloc.objsection.secsymidx
  839. else
  840. relsym:=SHN_UNDEF;
  841. end;
  842. rel.address:=objreloc.dataoffset;
  843. rel.info:=ELF_R_INFO(relsym,ElfTarget.encodereloc(objreloc));
  844. {$push}{$r-}
  845. rel.addend:=objreloc.orgsize;
  846. {$pop}
  847. { write reloc }
  848. { ElfXX_Rel is essentially ElfXX_Rela without the addend field. }
  849. MaybeSwapElfReloc(rel);
  850. relocsect.write(rel,relocsect.shentsize);
  851. end;
  852. end;
  853. procedure TElfObjectOutput.section_write_symbol(p:TObject;arg:pointer);
  854. begin
  855. { Must not write symbols for internal sections like .symtab }
  856. { TODO: maybe use inclusive list of section types instead }
  857. if (TElfObjSection(p).shtype in [SHT_SYMTAB,SHT_STRTAB,SHT_REL,SHT_RELA]) then
  858. exit;
  859. TObjSection(p).secsymidx:=symtabsect.symidx;
  860. symtabsect.writeInternalSymbol(0,0,STT_SECTION,TObjSection(p).index);
  861. end;
  862. procedure TElfObjectOutput.createsymtab(data: TObjData);
  863. var
  864. i : longint;
  865. objsym : TObjSymbol;
  866. begin
  867. with data do
  868. begin
  869. { section symbols }
  870. ObjSectionList.ForEachCall(@section_write_symbol,nil);
  871. { First the Local Symbols, this is required by ELF. The localsyms
  872. count stored in shinfo is used to skip the local symbols
  873. when traversing the symtab }
  874. for i:=0 to ObjSymbolList.Count-1 do
  875. begin
  876. objsym:=TObjSymbol(ObjSymbolList[i]);
  877. if (objsym.bind=AB_LOCAL) and (objsym.typ<>AT_LABEL) then
  878. symtabsect.WriteSymbol(objsym);
  879. end;
  880. { Global Symbols }
  881. for i:=0 to ObjSymbolList.Count-1 do
  882. begin
  883. objsym:=TObjSymbol(ObjSymbolList[i]);
  884. if (objsym.bind<>AB_LOCAL) then
  885. symtabsect.WriteSymbol(objsym);
  886. end;
  887. { update the .symtab section header }
  888. symtabsect.shlink:=symtabsect.fstrsec.index;
  889. end;
  890. end;
  891. procedure TElfObjectOutput.createshstrtab(data: TObjData);
  892. var
  893. i,prefixlen:longint;
  894. objsec,target:TElfObjSection;
  895. begin
  896. shstrtabsect.writezeros(1);
  897. prefixlen:=length('.rel')+ord(ElfTarget.relocs_use_addend);
  898. for i:=0 to data.ObjSectionList.Count-1 do
  899. begin
  900. objsec:=TElfObjSection(data.ObjSectionList[i]);
  901. { Alias section names into names of corresponding reloc sections,
  902. this is allowed by ELF specs and saves good half of .shstrtab space. }
  903. if objsec.shtype=relsec_shtype[ElfTarget.relocs_use_addend] then
  904. begin
  905. target:=TElfObjSection(data.ObjSectionList[objsec.shinfo-1]);
  906. if (target.ObjRelocations.Count=0) or
  907. (target.shstridx<prefixlen) then
  908. InternalError(2012101204);
  909. objsec.shstridx:=target.shstridx-prefixlen;
  910. end
  911. else
  912. begin
  913. if objsec.ObjRelocations.Count<>0 then
  914. shstrtabsect.write(relsec_prefix[true][1],prefixlen);
  915. objsec.shstridx:=shstrtabsect.writestr(objsec.name);
  916. end;
  917. end;
  918. end;
  919. procedure TElfObjectOutput.writesectionheader(s:TElfObjSection);
  920. var
  921. sechdr : telfsechdr;
  922. begin
  923. fillchar(sechdr,sizeof(sechdr),0);
  924. sechdr.sh_name:=s.shstridx;
  925. sechdr.sh_type:=s.shtype;
  926. sechdr.sh_flags:=s.shflags;
  927. sechdr.sh_offset:=s.datapos;
  928. sechdr.sh_size:=s.Size;
  929. sechdr.sh_link:=s.shlink;
  930. sechdr.sh_info:=s.shinfo;
  931. sechdr.sh_addralign:=s.secalign;
  932. sechdr.sh_entsize:=s.shentsize;
  933. MaybeSwapSecHeader(sechdr);
  934. writer.write(sechdr,sizeof(sechdr));
  935. end;
  936. procedure TElfObjectOutput.section_count_sections(p:TObject;arg:pointer);
  937. begin
  938. TElfObjSection(p).index:=pword(arg)^;
  939. inc(pword(arg)^);
  940. end;
  941. procedure TElfObjectOutput.section_create_relocsec(p:TObject;arg:pointer);
  942. begin
  943. if (TElfObjSection(p).ObjRelocations.count>0) then
  944. createrelocsection(TElfObjSection(p),TObjData(arg));
  945. end;
  946. procedure TElfObjectOutput.section_write_sechdr(p:TObject;arg:pointer);
  947. begin
  948. writesectionheader(TElfObjSection(p));
  949. end;
  950. function TElfObjectOutput.writedata(data:TObjData):boolean;
  951. var
  952. header : telfheader;
  953. shoffset,
  954. datapos : aword;
  955. nsections : word;
  956. begin
  957. result:=false;
  958. with data do
  959. begin
  960. { default sections }
  961. symtabsect:=TElfSymtab.create(data,esk_obj);
  962. shstrtabsect:=TElfObjSection.create_ext(data,'.shstrtab',SHT_STRTAB,0,1,0);
  963. { "no executable stack" marker }
  964. { TODO: used by OpenBSD/NetBSD as well? }
  965. if (target_info.system in (systems_linux + systems_android + systems_freebsd + systems_dragonfly)) and
  966. not(cs_executable_stack in current_settings.moduleswitches) then
  967. TElfObjSection.create_ext(data,'.note.GNU-stack',SHT_PROGBITS,0,1,0);
  968. { symbol for filename }
  969. symtabsect.fstrsec.writestr(ExtractFileName(current_module.mainsource));
  970. symtabsect.writeInternalSymbol(0,1,STT_FILE,SHN_ABS);
  971. { calc amount of sections we have }
  972. nsections:=1;
  973. { also create the index in the section header table }
  974. ObjSectionList.ForEachCall(@section_count_sections,@nsections);
  975. { create .symtab and .strtab }
  976. createsymtab(data);
  977. { Create the relocation sections, this needs valid secidx and symidx }
  978. ObjSectionList.ForEachCall(@section_create_relocsec,data);
  979. { recalc nsections to incude the reloc sections }
  980. nsections:=1;
  981. ObjSectionList.ForEachCall(@section_count_sections,@nsections);
  982. { create .shstrtab }
  983. createshstrtab(data);
  984. { Calculate the filepositions }
  985. datapos:=$40; { elfheader + alignment }
  986. { section data }
  987. layoutsections(datapos);
  988. { section headers }
  989. shoffset:=align(datapos,dword(Sizeof(AInt)));
  990. inc(datapos,(nsections+1)*sizeof(telfsechdr));
  991. { Write ELF Header }
  992. fillchar(header,sizeof(header),0);
  993. header.e_ident[EI_MAG0]:=ELFMAG0; { = #127'ELF' }
  994. header.e_ident[EI_MAG1]:=ELFMAG1;
  995. header.e_ident[EI_MAG2]:=ELFMAG2;
  996. header.e_ident[EI_MAG3]:=ELFMAG3;
  997. header.e_ident[EI_CLASS]:=ELFCLASS;
  998. if target_info.endian=endian_big then
  999. header.e_ident[EI_DATA]:=ELFDATA2MSB
  1000. else
  1001. header.e_ident[EI_DATA]:=ELFDATA2LSB;
  1002. header.e_ident[EI_VERSION]:=1;
  1003. if target_info.system in systems_openbsd then
  1004. header.e_ident[EI_OSABI]:=ELFOSABI_OPENBSD
  1005. else if target_info.system in systems_freebsd then
  1006. header.e_ident[EI_OSABI]:=ELFOSABI_FREEBSD
  1007. else if target_info.system in systems_dragonfly then
  1008. header.e_ident[EI_OSABI]:=ELFOSABI_NONE;
  1009. header.e_type:=ET_REL;
  1010. header.e_machine:=ElfTarget.machine_code;
  1011. header.e_version:=1;
  1012. header.e_shoff:=shoffset;
  1013. header.e_shstrndx:=shstrtabsect.index;
  1014. header.e_shnum:=nsections;
  1015. header.e_ehsize:=sizeof(telfheader);
  1016. header.e_shentsize:=sizeof(telfsechdr);
  1017. if assigned(ElfTarget.encodeflags) then
  1018. header.e_flags:=ElfTarget.encodeflags();
  1019. MaybeSwapHeader(header);
  1020. writer.write(header,sizeof(header));
  1021. writer.writezeros($40-sizeof(header)); { align }
  1022. { Sections }
  1023. WriteSectionContent(data);
  1024. { Align header }
  1025. Writer.Writezeros(Align(Writer.Size,Sizeof(AInt))-Writer.Size);
  1026. { section headers, start with an empty header for sh_undef }
  1027. writer.writezeros(sizeof(telfsechdr));
  1028. ObjSectionList.ForEachCall(@section_write_sechdr,nil);
  1029. end;
  1030. result:=true;
  1031. end;
  1032. {****************************************************************************
  1033. TELFAssembler
  1034. ****************************************************************************}
  1035. constructor TElfAssembler.Create(info: pasminfo; smart:boolean);
  1036. begin
  1037. inherited;
  1038. CObjOutput:=TElfObjectOutput;
  1039. CInternalAr:=tarobjectwriter;
  1040. end;
  1041. {****************************************************************************
  1042. TELFObjectInput
  1043. ****************************************************************************}
  1044. constructor TElfObjInput.Create;
  1045. begin
  1046. inherited Create;
  1047. CObjData:=TElfObjData;
  1048. CObjSymbol:=TObjSymbol;
  1049. end;
  1050. destructor TElfObjInput.Destroy;
  1051. begin
  1052. if Assigned(FSymTbl) then
  1053. FreeMem(FSymTbl);
  1054. if Assigned(FSecTbl) then
  1055. FreeMem(FSecTbl);
  1056. strtab:=nil;
  1057. shstrtab:=nil;
  1058. symversions:=nil;
  1059. inherited Destroy;
  1060. end;
  1061. procedure TElfObjInput.LoadRelocations(const secrec:TSectionRec);
  1062. var
  1063. i: longint;
  1064. rel: TElfReloc;
  1065. reltyp: byte;
  1066. relsym: longint;
  1067. objrel: TObjRelocation;
  1068. p: TObjSymbol;
  1069. begin
  1070. FReader.Seek(secrec.relocpos);
  1071. if secrec.sec=nil then
  1072. InternalError(2012060203);
  1073. if (secrec.relentsize=3*sizeof(pint)) then
  1074. with secrec.sec do SecOptions:=SecOptions+[oso_rela_relocs];
  1075. for i:=0 to secrec.relocs-1 do
  1076. begin
  1077. FReader.Read(rel,secrec.relentsize);
  1078. MaybeSwapElfReloc(rel);
  1079. reltyp:=rel.info and $FF;
  1080. {$ifdef cpu64bitaddr}
  1081. relsym:=rel.info shr 32;
  1082. {$else cpu64bitaddr}
  1083. relsym:=(rel.info shr 8) and $FFFFFF;
  1084. {$endif cpu64bitaddr}
  1085. if relsym>=syms then
  1086. InternalError(2012060204);
  1087. p:=TObjSymbol(FSymTbl[relsym]);
  1088. { Some relocations (e.g. R_ARM_V4BX) don't use a symbol at all }
  1089. if assigned(p) or (relsym=0) then
  1090. begin
  1091. objrel:=TObjRelocation.CreateRaw(rel.address-secrec.sec.mempos,p,reltyp);
  1092. if (secrec.relentsize=3*sizeof(pint)) then
  1093. objrel.orgsize:=rel.addend;
  1094. { perform target-specific actions }
  1095. if Assigned(ElfTarget.loadreloc) then
  1096. ElfTarget.loadreloc(objrel);
  1097. secrec.sec.ObjRelocations.add(objrel);
  1098. end
  1099. else
  1100. begin
  1101. InputError('Unable to resolve symbol of relocation');
  1102. exit;
  1103. end;
  1104. end;
  1105. end;
  1106. procedure TElfObjInput.LoadSymbols(objdata:TObjData;count,locals:longword);
  1107. var
  1108. i: longint;
  1109. sym: TElfSymbol;
  1110. bind: TAsmSymBind;
  1111. typ: TAsmSymType;
  1112. objsym: TObjSymbol;
  1113. ver: word;
  1114. begin
  1115. FSymTbl:=AllocMem(count*sizeof(Pointer));
  1116. for i:=1 to count-1 do
  1117. begin
  1118. FReader.Read(sym,sizeof(TElfSymbol));
  1119. MaybeSwapElfSymbol(sym);
  1120. if sym.st_name>=strtablen then
  1121. InternalError(2012060205);
  1122. if sym.st_shndx=SHN_ABS then { ignore absolute symbols (should we really do it???) }
  1123. Continue
  1124. else if sym.st_shndx=SHN_COMMON then
  1125. bind:=AB_COMMON
  1126. else if (sym.st_shndx>=nsects) then
  1127. InternalError(2012060206)
  1128. else
  1129. case (sym.st_info shr 4) of
  1130. STB_LOCAL:
  1131. bind:=AB_LOCAL;
  1132. STB_GLOBAL:
  1133. if sym.st_shndx=SHN_UNDEF then
  1134. bind:=AB_EXTERNAL
  1135. else if GetElfSymbolVisibility(sym.st_other)=STV_HIDDEN then
  1136. bind:=AB_PRIVATE_EXTERN
  1137. else
  1138. bind:=AB_GLOBAL;
  1139. STB_WEAK:
  1140. bind:=AB_WEAK_EXTERNAL;
  1141. else
  1142. InternalError(2012060207);
  1143. end;
  1144. { Ignore section symbol if we didn't create the corresponding objsection
  1145. (examples are SHT_GROUP or .note.GNU-stack sections). }
  1146. if (sym.st_shndx>0) and (sym.st_shndx<SHN_LORESERVE) and
  1147. (FSecTbl[sym.st_shndx].sec=nil) and
  1148. (not dynobj) then
  1149. if ((sym.st_info and $0F)=STT_SECTION) then
  1150. Continue
  1151. else
  1152. begin
  1153. writeln(objdata.name,' ',i);
  1154. InternalError(2012110701)
  1155. end;
  1156. case (sym.st_info and $0F) of
  1157. STT_NOTYPE:
  1158. typ:=AT_NONE;
  1159. STT_OBJECT:
  1160. typ:=AT_DATA;
  1161. STT_FUNC:
  1162. typ:=AT_FUNCTION;
  1163. STT_SECTION:
  1164. typ:=AT_SECTION;
  1165. STT_FILE:
  1166. continue;
  1167. STT_TLS:
  1168. typ:=AT_TLS;
  1169. STT_GNU_IFUNC:
  1170. typ:=AT_GNU_IFUNC;
  1171. else
  1172. writeln(objdata.name,' ',sym.st_info and $0F);
  1173. InternalError(2012060208);
  1174. end;
  1175. { If reading DSO, we're interested only in global symbols defined there.
  1176. Symbols with non-current version should also be ignored. }
  1177. ver:=0;
  1178. if dynobj then
  1179. begin
  1180. if assigned(symversions) then
  1181. begin
  1182. ver:=symversions[i];
  1183. if (ver=VER_NDX_LOCAL) or (ver>VERSYM_VERSION) then
  1184. continue;
  1185. end;
  1186. if (bind=AB_LOCAL) or (sym.st_shndx=SHN_UNDEF) then
  1187. continue;
  1188. if ver>=verdefs.count then
  1189. InternalError(2012120505);
  1190. end;
  1191. { validity of name and objsection has been checked above }
  1192. { !! all AT_SECTION symbols have duplicate (null) name,
  1193. therefore TObjSection.CreateSymbol cannot be used here }
  1194. objsym:=CObjSymbol.Create(objdata.ObjSymbolList,string(PChar(@strtab[sym.st_name])));
  1195. objsym.bind:=bind;
  1196. objsym.typ:=typ;
  1197. if bind<>AB_COMMON then
  1198. objsym.objsection:=FSecTbl[sym.st_shndx].sec;
  1199. objsym.offset:=sym.st_value;
  1200. objsym.size:=sym.st_size;
  1201. FSymTbl[i]:=objsym;
  1202. if (ver>VER_NDX_GLOBAL) then
  1203. TVersionedObjSymbol(objsym).version:=TElfVersionDef(verdefs[ver]);
  1204. end;
  1205. end;
  1206. function TElfObjInput.CreateSection(const shdr:TElfsechdr;index:longint;objdata:tobjdata;
  1207. out secname:string):TElfObjSection;
  1208. begin
  1209. secname:=string(PChar(@shstrtab[shdr.sh_name]));
  1210. result:=TElfObjSection.create_ext(objdata,secname,
  1211. shdr.sh_type,shdr.sh_flags,shdr.sh_addralign,shdr.sh_entsize);
  1212. result.index:=index;
  1213. result.DataPos:=shdr.sh_offset;
  1214. result.MemPos:=shdr.sh_addr;
  1215. result.Size:=shdr.sh_size;
  1216. FSecTbl[index].sec:=result;
  1217. end;
  1218. function TElfObjInput.ReadBytes(offs:longint;out buf;len:longint):boolean;
  1219. begin
  1220. FReader.Seek(offs);
  1221. result:=FReader.Read(buf,len);
  1222. end;
  1223. procedure TElfObjInput.LoadSection(const shdr:TElfsechdr;index:longint;objdata:tobjdata);
  1224. var
  1225. sec: TElfObjSection;
  1226. sym: TElfSymbol;
  1227. secname: string;
  1228. begin
  1229. if shdr.sh_name>=shstrtablen then
  1230. InternalError(2012060210);
  1231. case shdr.sh_type of
  1232. SHT_NULL:
  1233. {ignore};
  1234. { SHT_STRTAB may appear for .stabstr and other debug sections.
  1235. .shstrtab and .strtab are processed separately and don't appear here. }
  1236. SHT_PROGBITS,SHT_NOBITS,SHT_NOTE,SHT_STRTAB,
  1237. SHT_INIT_ARRAY,SHT_FINI_ARRAY,SHT_PREINIT_ARRAY:
  1238. begin
  1239. sec:=CreateSection(shdr,index,objdata,secname);
  1240. if (Length(secname)>3) and (secname[2] in ['d','f','n','s']) then
  1241. begin
  1242. if (Pos('.stub',secname)=1) or
  1243. (Pos('.fpc',secname)=1) then
  1244. sec.SecOptions:=[oso_keep]
  1245. { ELF does not have any flags specific to debug sections,
  1246. but reserves names starting with '.debug' for this purpose }
  1247. else if (Pos('.debug',secname)=1) or
  1248. (secname='.stab') or
  1249. (secname='.stabstr') then
  1250. sec.SecOptions:=[oso_debug]
  1251. else if (secname='.note.GNU-stack') and (shdr.sh_type=SHT_PROGBITS) then
  1252. begin
  1253. if (shdr.sh_flags and SHF_EXECINSTR)=0 then
  1254. objdata.ExecStack:=False;
  1255. end;
  1256. end;
  1257. if (shdr.sh_type=SHT_NOTE) and (shdr.sh_size<>0) then
  1258. sec.SecOptions:=[oso_keep];
  1259. end;
  1260. SHT_REL,SHT_RELA:
  1261. begin
  1262. if shdr.sh_info>=nsects then
  1263. InternalError(2012060211);
  1264. if shdr.sh_entsize<>longword((2+ord(shdr.sh_type=SHT_RELA))*sizeof(pint)) then
  1265. InternalError(2012060212);
  1266. with FSecTbl[shdr.sh_info] do
  1267. begin
  1268. relocpos:=shdr.sh_offset;
  1269. relocs:=shdr.sh_size div shdr.sh_entsize;
  1270. relentsize:=shdr.sh_entsize;
  1271. end;
  1272. end;
  1273. SHT_GROUP:
  1274. if (shdr.sh_size>=2*sizeof(longword)) and
  1275. (shdr.sh_entsize=sizeof(longword)) and
  1276. ((shdr.sh_size mod shdr.sh_entsize)=0) then
  1277. begin
  1278. { Groups are identified by name of symbol pointed to by
  1279. sh_link and sh_info, not by sh_name. This symbol
  1280. may as well be STT_SECTION symbol of this section,
  1281. in which case we end up using sh_name. }
  1282. if dynobj then
  1283. InternalError(2012110801);
  1284. if (shdr.sh_link<>symtabndx) then
  1285. InternalError(2012110703);
  1286. if (shdr.sh_info>=syms) then
  1287. InternalError(2012110704);
  1288. FReader.Seek(symtaboffset+shdr.sh_info*sizeof(TElfSymbol));
  1289. FReader.Read(sym,sizeof(TElfSymbol));
  1290. MaybeSwapElfSymbol(sym);
  1291. if sym.st_name>=strtablen then
  1292. InternalError(2012110705);
  1293. if (sym.st_shndx=index) and (sym.st_info=((STB_LOCAL shl 4) or STT_SECTION)) then
  1294. secname:=string(PChar(@shstrtab[shdr.sh_name]))
  1295. else
  1296. secname:=string(PChar(@strtab[sym.st_name]));
  1297. { Postpone further processing until all sections are loaded,
  1298. we'll need to access correct section header.
  1299. Since ABI requires SHT_GROUP sections to come first in the file,
  1300. we assume that group number x has header index x+1.
  1301. If we ever encounter files where this is not true, we'll have
  1302. to maintain a separate index. }
  1303. objdata.CreateSectionGroup(secname);
  1304. if (index<>objdata.GroupsList.Count) then
  1305. InternalError(2012110802);
  1306. end
  1307. else
  1308. InternalError(2012110706);
  1309. SHT_GNU_ATTRIBUTES:
  1310. { TODO: must not be ignored };
  1311. else
  1312. if not (assigned(ElfTarget.loadsection) and
  1313. ElfTarget.loadsection(self,objdata,shdr,index)) then
  1314. InternalError(2012072603);
  1315. end;
  1316. FLoaded[index]:=True;
  1317. end;
  1318. function TElfObjInput.LoadHeader(out objdata:TObjData):boolean;
  1319. var
  1320. header:TElfHeader;
  1321. begin
  1322. result:=false;
  1323. if not FReader.read(header,sizeof(header)) then
  1324. begin
  1325. InputError('Can''t read ELF header');
  1326. exit;
  1327. end;
  1328. if (header.e_ident[EI_MAG0]<>ELFMAG0) or (header.e_ident[EI_MAG1]<>ELFMAG1) or
  1329. (header.e_ident[EI_MAG2]<>ELFMAG2) or (header.e_ident[EI_MAG3]<>ELFMAG3) then
  1330. begin
  1331. InputError('Illegal ELF magic');
  1332. exit;
  1333. end;
  1334. if (header.e_ident[EI_VERSION]<>1) then
  1335. begin
  1336. InputError('Unknown ELF file version');
  1337. exit;
  1338. end;
  1339. if (header.e_ident[EI_CLASS]<>ELFCLASS) then
  1340. begin
  1341. InputError('Wrong ELF file class (32/64 bit mismatch)');
  1342. exit;
  1343. end;
  1344. if (header.e_ident[EI_DATA]<>1+ord(target_info.endian=endian_big)) then
  1345. begin
  1346. InputError('ELF endianness does not match target');
  1347. exit;
  1348. end;
  1349. MaybeSwapHeader(header);
  1350. if (header.e_version<>1) then
  1351. begin
  1352. InputError('Unknown ELF data version');
  1353. exit;
  1354. end;
  1355. if (header.e_machine<>ElfTarget.machine_code) then
  1356. begin
  1357. InputError('ELF file is for different CPU');
  1358. exit;
  1359. end;
  1360. if (header.e_type<>ET_REL) and (header.e_type<>ET_DYN) then
  1361. begin
  1362. InputError('Not a relocatable or dynamic ELF file');
  1363. exit;
  1364. end;
  1365. if header.e_shentsize<>sizeof(TElfsechdr) then
  1366. InternalError(2012062701);
  1367. nsects:=header.e_shnum;
  1368. dynobj:=(header.e_type=ET_DYN);
  1369. shoffset:=header.e_shoff;
  1370. shstrndx:=header.e_shstrndx;
  1371. if dynobj then
  1372. begin
  1373. objdata:=TElfDynamicObjData.Create(InputFilename);
  1374. verdefs:=TElfDynamicObjData(objdata).versiondefs;
  1375. CObjSymbol:=TVersionedObjSymbol;
  1376. end
  1377. else
  1378. objdata:=CObjData.Create(InputFilename);
  1379. TElfObjData(objdata).ident:=header.e_ident;
  1380. TElfObjData(objdata).flags:=header.e_flags;
  1381. result:=true;
  1382. end;
  1383. procedure TElfObjInput.LoadDynamic(const shdr:TElfsechdr;objdata:TObjData);
  1384. var
  1385. dt: TElfDyn;
  1386. i: longint;
  1387. begin
  1388. if (shdr.sh_entsize<>sizeof(TElfDyn)) then
  1389. InternalError(2012071403);
  1390. FReader.Seek(shdr.sh_offset);
  1391. for i:=0 to (shdr.sh_size div shdr.sh_entsize)-1 do
  1392. begin
  1393. FReader.Read(dt,sizeof(TElfDyn));
  1394. MaybeSwapElfDyn(dt);
  1395. case dt.d_tag of
  1396. DT_NULL:
  1397. break;
  1398. DT_SONAME:
  1399. TElfObjData(objdata).FName:=string(PChar(@strtab[dt.d_ptr]));
  1400. DT_NEEDED:
  1401. ;
  1402. end;
  1403. end;
  1404. end;
  1405. function TElfObjInput.ReadObjData(AReader:TObjectreader;out objdata:TObjData):boolean;
  1406. var
  1407. i,j,strndx,dynndx,
  1408. versymndx,verdefndx,verneedndx: longint;
  1409. objsec: TObjSection;
  1410. grp: TObjSectionGroup;
  1411. tmp: longword;
  1412. count: longint;
  1413. vd: TElfverdef;
  1414. vda: TElfverdaux;
  1415. vdoffset: aword;
  1416. begin
  1417. FReader:=AReader;
  1418. InputFileName:=AReader.FileName;
  1419. result:=false;
  1420. strndx:=0;
  1421. if not LoadHeader(objData) then
  1422. exit;
  1423. FSecTbl:=AllocMem(nsects*sizeof(TSectionRec));
  1424. FLoaded:=AllocMem(nsects*sizeof(boolean));
  1425. SetLength(shdrs,nsects);
  1426. FReader.Seek(shoffset);
  1427. if not FReader.Read(shdrs[0],nsects*sizeof(TElfsechdr)) then
  1428. begin
  1429. InputError('Can''t read ELF section headers');
  1430. exit;
  1431. end;
  1432. if source_info.endian<>target_info.endian then
  1433. for i:=0 to nsects-1 do
  1434. MaybeSwapSecHeader(shdrs[i]);
  1435. { First, load the .shstrtab section }
  1436. if shstrndx>=nsects then
  1437. InternalError(2012060201);
  1438. if shdrs[shstrndx].sh_type<>SHT_STRTAB then
  1439. InternalError(2012060202);
  1440. shstrtablen:=shdrs[shstrndx].sh_size;
  1441. SetLength(shstrtab,shstrtablen);
  1442. FReader.seek(shdrs[shstrndx].sh_offset);
  1443. FReader.read(shstrtab[0],shstrtablen);
  1444. FLoaded[shstrndx]:=True;
  1445. { Locate the symtable, it is typically at the end so loop backwards.
  1446. Load the strings, postpone symtable itself until done with sections.
  1447. Note that is is legal to have no symtable.
  1448. For DSO, locate .dynsym instead, this one is near the beginning, but
  1449. overall number of sections won't be big. }
  1450. symtabndx:=0;
  1451. for i:=nsects-1 downto 1 do
  1452. begin
  1453. if (shdrs[i].sh_type<>symsectypes[dynobj]) then
  1454. continue;
  1455. if (shdrs[i].sh_entsize<>sizeof(TElfSymbol)) then
  1456. InternalError(2012060213);
  1457. if shdrs[i].sh_link>=nsects then
  1458. InternalError(2012062702);
  1459. strndx:=shdrs[i].sh_link;
  1460. if shdrs[strndx].sh_type<>SHT_STRTAB then
  1461. InternalError(2012062703);
  1462. strtablen:=shdrs[strndx].sh_size;
  1463. setLength(strtab,strtablen);
  1464. FReader.seek(shdrs[strndx].sh_offset);
  1465. FReader.read(strtab[0],strtablen);
  1466. symtaboffset:=shdrs[i].sh_offset;
  1467. syms:=shdrs[i].sh_size div sizeof(TElfSymbol);
  1468. localsyms:=shdrs[i].sh_info;
  1469. FLoaded[i]:=True;
  1470. FLoaded[strndx]:=True;
  1471. symtabndx:=i;
  1472. break;
  1473. end;
  1474. if dynobj then
  1475. begin
  1476. if symtabndx=0 then
  1477. InternalError(2012110707);
  1478. { Locate .dynamic and version sections. Expect a single one of a kind. }
  1479. dynndx:=0;
  1480. versymndx:=0;
  1481. verdefndx:=0;
  1482. verneedndx:=0;
  1483. for i:=nsects-1 downto 0 do
  1484. begin
  1485. case shdrs[i].sh_type of
  1486. SHT_DYNAMIC:
  1487. begin
  1488. if dynndx<>0 then
  1489. InternalError(2012102001);
  1490. dynndx:=i;
  1491. if (shdrs[dynndx].sh_link<>strndx) then
  1492. InternalError(2012071402);
  1493. LoadDynamic(shdrs[dynndx],objdata);
  1494. end;
  1495. SHT_GNU_versym:
  1496. begin
  1497. if versymndx<>0 then
  1498. InternalError(2012102002);
  1499. versymndx:=i;
  1500. if shdrs[i].sh_entsize<>sizeof(word) then
  1501. InternalError(2012102003);
  1502. if shdrs[i].sh_link<>symtabndx then
  1503. InternalError(2012102004);
  1504. if shdrs[i].sh_size<>syms*sizeof(word) then
  1505. InternalError(2012102005);
  1506. SetLength(symversions,shdrs[i].sh_size);
  1507. FReader.seek(shdrs[i].sh_offset);
  1508. FReader.read(symversions[0],shdrs[i].sh_size);
  1509. if source_info.endian<>target_info.endian then
  1510. for j:=0 to syms-1 do
  1511. symversions[j]:=SwapEndian(symversions[j]);
  1512. end;
  1513. SHT_GNU_verdef:
  1514. begin
  1515. if verdefndx<>0 then
  1516. InternalError(2012102006);
  1517. verdefndx:=i;
  1518. if shdrs[i].sh_link<>strndx then
  1519. InternalError(2012120501);
  1520. vdoffset:=shdrs[i].sh_offset;
  1521. { TODO: can we rely on sh_info, or must read until vd_next=0? }
  1522. for j:=1 to shdrs[i].sh_info do
  1523. begin
  1524. FReader.seek(vdoffset);
  1525. FReader.Read(vd,sizeof(TElfverdef));
  1526. MaybeSwapElfverdef(vd);
  1527. if vd.vd_version<>VER_DEF_CURRENT then
  1528. InternalError(2012120502);
  1529. FReader.seek(vdoffset+vd.vd_aux);
  1530. vdoffset:=vdoffset+vd.vd_next;
  1531. { First verdaux entry holds name of version (unless VER_FLG_BASE flag is set),
  1532. subsequent one(s) point to parent(s). For our purposes, version hierarchy
  1533. looks irrelevant. }
  1534. FReader.Read(vda,sizeof(TElfverdaux));
  1535. MaybeSwapElfverdaux(vda);
  1536. if vda.vda_name>=strtablen then
  1537. InternalError(2012120503);
  1538. if (vd.vd_flags and VER_FLG_BASE)<>0 then
  1539. continue;
  1540. { Assuming verdef indices assigned continuously starting from 2,
  1541. at least BFD produces files that way. }
  1542. if verdefs.count<>vd.vd_ndx then
  1543. InternalError(2012120504);
  1544. TElfVersionDef.Create(verdefs,string(PChar(@strtab[vda.vda_name])));
  1545. end;
  1546. end;
  1547. SHT_GNU_verneed:
  1548. begin
  1549. if verneedndx<>0 then
  1550. InternalError(2012102007);
  1551. verneedndx:=i;
  1552. //sh_link->.dynstr
  1553. //sh_info->number of entries
  1554. end;
  1555. end;
  1556. end;
  1557. if dynndx=0 then
  1558. InternalError(2012071401);
  1559. { load the symtable }
  1560. FReader.Seek(symtaboffset+sizeof(TElfSymbol));
  1561. LoadSymbols(objdata,syms,localsyms);
  1562. result:=True;
  1563. exit;
  1564. end;
  1565. { assume stack is executable until proven otherwise }
  1566. objdata.ExecStack:=True;
  1567. { Process section headers }
  1568. for i:=1 to nsects-1 do
  1569. if not FLoaded[i] then
  1570. LoadSection(shdrs[i],i,objdata);
  1571. { load the content }
  1572. ReadSectionContent(objdata);
  1573. { load the symtable }
  1574. FReader.Seek(symtaboffset+sizeof(TElfSymbol));
  1575. LoadSymbols(objdata,syms,localsyms);
  1576. { finish relocations }
  1577. for i:=0 to objdata.ObjSectionList.Count-1 do
  1578. begin
  1579. objsec:=TObjSection(objdata.ObjsectionList[i]);
  1580. { skip debug sections }
  1581. if (oso_debug in objsec.SecOptions) and
  1582. (cs_link_strip in current_settings.globalswitches) and
  1583. not(cs_link_separate_dbg_file in current_settings.globalswitches) then
  1584. continue;
  1585. if FSecTbl[objsec.index].relocpos>0 then
  1586. LoadRelocations(FSecTbl[objsec.index]);
  1587. end;
  1588. { finish processing section groups, if any }
  1589. if Assigned(objdata.GroupsList) then
  1590. begin
  1591. for i:=0 to objdata.GroupsList.Count-1 do
  1592. begin
  1593. grp:=TObjSectionGroup(objData.GroupsList[i]);
  1594. FReader.Seek(shdrs[i+1].sh_offset);
  1595. { first dword is flags }
  1596. FReader.Read(tmp,sizeof(longword));
  1597. if source_info.endian<>target_info.endian then
  1598. tmp:=SwapEndian(tmp);
  1599. if (tmp and GRP_COMDAT)<>0 then
  1600. grp.IsComdat:=true;
  1601. count:=(shdrs[i+1].sh_size div sizeof(longword))-1;
  1602. SetLength(grp.members,count);
  1603. for j:=0 to count-1 do
  1604. begin
  1605. FReader.Read(tmp,sizeof(longword));
  1606. if source_info.endian<>target_info.endian then
  1607. tmp:=SwapEndian(tmp);
  1608. if (tmp>=nsects) then
  1609. InternalError(2012110805);
  1610. objsec:=FSecTbl[tmp].sec;
  1611. if (objsec=nil) then
  1612. InternalError(2012110806);
  1613. if (TElfObjSection(objsec).shflags and SHF_GROUP)=0 then
  1614. InternalError(2012110807);
  1615. grp.members[j]:=objsec;
  1616. objsec.Group:=grp;
  1617. end;
  1618. end;
  1619. end;
  1620. result:=True;
  1621. end;
  1622. class function TElfObjInput.CanReadObjData(AReader:TObjectreader):boolean;
  1623. var
  1624. header: TElfHeader;
  1625. begin
  1626. result:=false;
  1627. if AReader.Read(header,sizeof(header)) then
  1628. begin;
  1629. if (header.e_ident[EI_MAG0]=ELFMAG0) and (header.e_ident[EI_MAG1]=ELFMAG1) and
  1630. (header.e_ident[EI_MAG2]=ELFMAG2) and (header.e_ident[EI_MAG3]=ELFMAG3) then
  1631. { TODO: check additional fields }
  1632. result:=true;
  1633. end;
  1634. AReader.Seek(0);
  1635. end;
  1636. {*****************************************************************************
  1637. TElfExeOutput
  1638. *****************************************************************************}
  1639. constructor TElfExeOutput.Create;
  1640. begin
  1641. inherited Create;
  1642. CObjData:=TElfObjData;
  1643. CExeSection:=TElfExeSection;
  1644. {$ifdef cpu64}
  1645. MaxMemPos:=Qword($FFFFFFFFFFFFFFFF);
  1646. //MaxMemPos:=$7EFFFFFF; { As specified by SysV AMD64 ABI for small memory model }
  1647. {$else cpu64}
  1648. MaxMemPos:=$7FFFFFFF;
  1649. {$endif cpu64}
  1650. SectionMemAlign:=$20;
  1651. SectionDataAlign:=$20;
  1652. segmentlist:=TFPObjectList.Create(True);
  1653. neededlist:=TFPHashList.Create;
  1654. end;
  1655. destructor TElfExeOutput.Destroy;
  1656. begin
  1657. dyncopysyms.Free;
  1658. neededlist.Free;
  1659. segmentlist.Free;
  1660. dynsymlist.Free;
  1661. dynreloclist.Free;
  1662. if assigned(dynsymnames) then
  1663. FreeMem(dynsymnames);
  1664. stringdispose(FInterpreter);
  1665. inherited Destroy;
  1666. end;
  1667. function TElfExeOutput.AttachSection(objsec:TObjSection):TElfExeSection;
  1668. begin
  1669. objsec.SecOptions:=[oso_keep];
  1670. result:=TElfExeSection(FindExeSection(objsec.name));
  1671. if result=nil then
  1672. result:=TElfExeSection.Create(ExeSectionList,objsec.name);
  1673. result.AddObjSection(objsec);
  1674. end;
  1675. function TElfExeOutput.CreateSegment(atype,aflags,aalign:longword):TElfSegment;
  1676. begin
  1677. result:=TElfSegment.Create(atype,aflags,aalign);
  1678. segmentlist.add(result);
  1679. end;
  1680. procedure TElfExeOutput.WriteHeader;
  1681. var
  1682. header: TElfHeader;
  1683. begin
  1684. FillChar(header,sizeof(header),0);
  1685. header.e_ident[EI_MAG0]:=ELFMAG0; { = #127'ELF' }
  1686. header.e_ident[EI_MAG1]:=ELFMAG1;
  1687. header.e_ident[EI_MAG2]:=ELFMAG2;
  1688. header.e_ident[EI_MAG3]:=ELFMAG3;
  1689. header.e_ident[EI_CLASS]:=ELFCLASS;
  1690. if target_info.endian=endian_big then
  1691. header.e_ident[EI_DATA]:=ELFDATA2MSB
  1692. else
  1693. header.e_ident[EI_DATA]:=ELFDATA2LSB;
  1694. header.e_ident[EI_VERSION]:=1;
  1695. if target_info.system in systems_openbsd then
  1696. header.e_ident[EI_OSABI]:=ELFOSABI_OPENBSD
  1697. else if target_info.system in systems_freebsd then
  1698. header.e_ident[EI_OSABI]:=ELFOSABI_FREEBSD
  1699. else if target_info.system in systems_dragonfly then
  1700. header.e_ident[EI_OSABI]:=ELFOSABI_NONE;
  1701. if IsSharedLibrary then
  1702. header.e_type:=ET_DYN
  1703. else
  1704. header.e_type:=ET_EXEC;
  1705. header.e_machine:=ElfTarget.machine_code;
  1706. header.e_version:=1;
  1707. header.e_phoff:=sizeof(TElfHeader);
  1708. header.e_shoff:=shoffset;
  1709. header.e_shstrndx:=ExeSectionList.IndexOf(shstrtabsect.ExeSection)+1;
  1710. header.e_shnum:=ExeSectionList.Count+1;
  1711. header.e_phnum:=segmentlist.count;
  1712. header.e_ehsize:=sizeof(telfheader);
  1713. if assigned(ElfTarget.encodeflags) then
  1714. header.e_flags:=ElfTarget.encodeflags();
  1715. if assigned(EntrySym) then
  1716. header.e_entry:=EntrySym.Address;
  1717. header.e_shentsize:=sizeof(telfsechdr);
  1718. header.e_phentsize:=sizeof(telfproghdr);
  1719. MaybeSwapHeader(header);
  1720. FWriter.Write(header,sizeof(header));
  1721. end;
  1722. procedure TElfExeOutput.exesection_write_header(p:TObject;arg:Pointer);
  1723. var
  1724. shdr: TElfsechdr;
  1725. exesec: TElfExeSection absolute p;
  1726. begin
  1727. FillChar(shdr,sizeof(shdr),0);
  1728. shdr.sh_name:=exesec.shstridx;
  1729. if (ExeWriteMode=ewm_dbgonly) and
  1730. (exesec.SecOptions*[oso_debug,oso_debug_copy]=[]) then
  1731. shdr.sh_type:=SHT_NOBITS
  1732. else
  1733. shdr.sh_type:=exesec.shtype;
  1734. shdr.sh_flags:=exesec.shflags;
  1735. if (oso_load in exesec.SecOptions) then
  1736. shdr.sh_addr:=exesec.MemPos;
  1737. shdr.sh_offset:=exesec.DataPos;
  1738. shdr.sh_size:=exesec.Size;
  1739. shdr.sh_link:=exesec.shlink;
  1740. shdr.sh_info:=exesec.shinfo;
  1741. shdr.sh_addralign:=exesec.SecAlign;
  1742. shdr.sh_entsize:=exesec.shentsize;
  1743. MaybeSwapSecHeader(shdr);
  1744. FWriter.Write(shdr,sizeof(shdr));
  1745. end;
  1746. procedure TElfExeOutput.segment_write_header(p:TObject;arg:Pointer);
  1747. var
  1748. phdr: TElfproghdr;
  1749. seg: TElfSegment absolute p;
  1750. begin
  1751. FillChar(phdr,sizeof(phdr),0);
  1752. phdr.p_type:=seg.ptype;
  1753. phdr.p_flags:=seg.pflags;
  1754. phdr.p_align:=seg.align;
  1755. phdr.p_offset:=seg.DataPos;
  1756. phdr.p_filesz:=seg.DataSize;
  1757. phdr.p_memsz:=seg.MemSize;
  1758. phdr.p_vaddr:=seg.MemPos;
  1759. phdr.p_paddr:=seg.MemPos;
  1760. MaybeSwapHeader(phdr);
  1761. FWriter.Write(phdr,sizeof(phdr));
  1762. end;
  1763. procedure TElfExeOutput.WriteStaticSymtable;
  1764. var
  1765. i: longint;
  1766. sec: TElfExeSection;
  1767. exesym: TExeSymbol;
  1768. begin
  1769. if assigned(tlsseg) then
  1770. symtab.tlsbase:=tlsseg.MemPos;
  1771. for i:=0 to ExeSectionList.Count-1 do
  1772. begin
  1773. sec:=TElfExeSection(ExeSectionList[i]);
  1774. { Must not write symbols for internal sections like .symtab }
  1775. if (sec.shtype in [SHT_SYMTAB,SHT_STRTAB,SHT_REL,SHT_RELA]) then
  1776. continue;
  1777. sec.secsymidx:=symtab.symidx;
  1778. symtab.writeInternalSymbol(sec.mempos,0,STT_SECTION,sec.secshidx);
  1779. end;
  1780. { local symbols first }
  1781. for i:=0 to ExeSymbolList.Count-1 do
  1782. begin
  1783. exesym:=TExeSymbol(ExeSymbolList[i]);
  1784. if (exesym.objsymbol.bind=AB_LOCAL) and (exesym.objsymbol.typ<>AT_LABEL) then
  1785. symtab.WriteSymbol(exesym.objsymbol);
  1786. end;
  1787. { Global Symbols }
  1788. for i:=0 to ExeSymbolList.Count-1 do
  1789. begin
  1790. exesym:=TExeSymbol(ExeSymbolList[i]);
  1791. if (exesym.objsymbol.bind<>AB_LOCAL) then
  1792. symtab.WriteSymbol(exesym.objsymbol);
  1793. end;
  1794. { update exe section properties }
  1795. symtab.ExeSection.size:=symtab.size;
  1796. TElfExeSection(symtab.ExeSection).shinfo:=symtab.shinfo;
  1797. TElfExeSection(symtab.ExeSection).shlink:=ExeSectionList.IndexOf(symtab.fstrsec.ExeSection)+1;
  1798. symtab.fstrsec.ExeSection.Size:=symtab.fstrsec.size;
  1799. end;
  1800. procedure TElfExeOutput.MapSectionsToSegments;
  1801. var
  1802. seg: TElfSegment;
  1803. exesec: TExeSection;
  1804. i: longint;
  1805. begin
  1806. if (not IsSharedLibrary) and assigned(interpobjsec) then
  1807. begin
  1808. phdrseg:=CreateSegment(PT_PHDR,PF_R or PF_X,sizeof(pint));
  1809. seg:=CreateSegment(PT_INTERP,PF_R,1);
  1810. seg.Add(interpobjsec.ExeSection);
  1811. end;
  1812. textseg:=CreateSegment(PT_LOAD,PF_X or PF_R,ElfTarget.max_page_size);
  1813. dataseg:=CreateSegment(PT_LOAD,PF_R or PF_W,ElfTarget.max_page_size);
  1814. for i:=0 to ExeSectionList.Count-1 do
  1815. begin
  1816. exesec:=TExeSection(ExeSectionList[i]);
  1817. if (oso_load in exesec.SecOptions) then
  1818. begin
  1819. if (TElfExeSection(exesec).shflags and SHF_TLS)<>0 then
  1820. begin
  1821. if tlsseg=nil then
  1822. tlsseg:=CreateSegment(PT_TLS,PF_R,sizeof(pint));
  1823. tlsseg.add(exesec);
  1824. end;
  1825. { TODO: at least on Linux, ld seems to drop .note.ABI-tag for static executables.
  1826. (Logic is as follows: there is no .note.ABI-tag section in ld script, so it
  1827. is processed as orphan section. As such, it is placed after .interp.
  1828. For static executables .interp is dropped, and it looks like there's nowhere to
  1829. place .note.ABI-tag in this case)
  1830. Always including it doesn't harm though (except increasing file size). }
  1831. if TElfExeSection(exesec).shtype=SHT_NOTE then
  1832. begin
  1833. if noteseg=nil then
  1834. noteseg:=CreateSegment(PT_NOTE,PF_R,4);
  1835. noteseg.Add(exesec);
  1836. Include(exesec.SecOptions,oso_debug_copy);
  1837. end;
  1838. if (oso_executable in exesec.SecOptions) or
  1839. not (oso_write in exesec.SecOptions) then
  1840. textseg.add(exesec)
  1841. else
  1842. dataseg.add(exesec);
  1843. end;
  1844. end;
  1845. if dynamiclink then
  1846. begin
  1847. seg:=CreateSegment(PT_DYNAMIC,PF_R or PF_W,sizeof(pint));
  1848. seg.add(dynamicsec.ExeSection);
  1849. end;
  1850. { stack flags }
  1851. CreateSegment(PT_GNU_STACK,PF_R or PF_W or (PF_X*ord(ExecStack)),sizeof(pint));
  1852. end;
  1853. procedure TElfExeOutput.make_dynamic_if_undefweak(exesym:TExeSymbol);
  1854. begin
  1855. if (exesym.dynindex=0) and (exesym.state=symstate_undefweak) and
  1856. not (cs_link_staticflag in current_settings.globalswitches) then
  1857. exesym.dynindex:=dynsymlist.add(exesym)+1;
  1858. end;
  1859. function TElfExeOutput.AllocGOTSlot(objsym:TObjSymbol):boolean;
  1860. var
  1861. exesym: TExeSymbol;
  1862. begin
  1863. result:=false;
  1864. exesym:=objsym.exesymbol;
  1865. { Although local symbols should not be accessed through GOT,
  1866. this isn't strictly forbidden. In this case we need to fake up
  1867. the exesym to store the GOT offset in it.
  1868. TODO: name collision; maybe use a different symbol list object? }
  1869. if exesym=nil then
  1870. begin
  1871. exesym:=TExeSymbol.Create(ExeSymbolList,objsym.name+'*local*');
  1872. exesym.objsymbol:=objsym;
  1873. objsym.exesymbol:=exesym;
  1874. end;
  1875. if exesym.GotOffset>0 then
  1876. exit;
  1877. gotobjsec.alloc(sizeof(pint));
  1878. exesym.GotOffset:=gotobjsec.size;
  1879. make_dynamic_if_undefweak(exesym);
  1880. { In shared library, every GOT entry needs a RELATIVE dynamic reloc,
  1881. imported/exported symbols need GLOB_DAT instead. For executables,
  1882. only the latter applies. }
  1883. if IsSharedLibrary or (exesym.dynindex>0) then
  1884. dynrelocsec.alloc(dynrelocsec.shentsize);
  1885. result:=true;
  1886. end;
  1887. procedure TElfExeOutput.PrepareGOT;
  1888. var
  1889. i,j,k: longint;
  1890. objsec: TElfObjSection;
  1891. exesec: TExeSection;
  1892. begin
  1893. for i:=0 to ExeSectionList.Count-1 do
  1894. begin
  1895. exesec:=TExeSection(ExeSectionList[i]);
  1896. for j:=0 to exesec.ObjSectionlist.count-1 do
  1897. begin
  1898. objsec:=TElfObjSection(exesec.ObjSectionlist[j]);
  1899. { ignore linker-generated and debug sections }
  1900. if (objsec.objdata=internalobjdata) or (oso_debug in objsec.SecOptions) then
  1901. continue;
  1902. if not objsec.Used then
  1903. internalerror(2012060901);
  1904. k:=0;
  1905. while k<objsec.ObjRelocations.Count do
  1906. begin
  1907. GOTRelocPass1(objsec,k);
  1908. inc(k);
  1909. end;
  1910. end;
  1911. end;
  1912. { remember sizes for sanity checking }
  1913. gotsize:=gotobjsec.size;
  1914. if assigned(dynrelocsec) then
  1915. dynrelsize:=dynrelocsec.size
  1916. else
  1917. dynrelsize:=0;
  1918. end;
  1919. procedure TElfExeOutput.CreateGOTSection;
  1920. begin
  1921. gotpltobjsec:=TElfObjSection.create_ext(internalObjData,'.got.plt',
  1922. SHT_PROGBITS,SHF_ALLOC or SHF_WRITE,sizeof(pint),sizeof(pint));
  1923. gotobjsec:=TElfObjSection.create_ext(internalObjData,'.got',
  1924. SHT_PROGBITS,SHF_ALLOC or SHF_WRITE,sizeof(pint),sizeof(pint));
  1925. gotobjsec.SecOptions:=[oso_keep];
  1926. { GOT symbol and reserved .got.plt entries }
  1927. internalObjData.SetSection(gotpltobjsec);
  1928. gotsymbol:=internalObjData.SymbolDefine('_GLOBAL_OFFSET_TABLE_',AB_GLOBAL,AT_DATA);
  1929. gotpltobjsec.writeZeros(3*sizeof(pint));
  1930. end;
  1931. procedure TElfExeOutput.Load_Start;
  1932. begin
  1933. inherited Load_Start;
  1934. dynsymlist:=TFPObjectList.Create(False);
  1935. CreateGOTSection;
  1936. end;
  1937. procedure TElfExeOutput.Load_DynamicObject(objdata:TObjData;asneeded:boolean);
  1938. var
  1939. i: longint;
  1940. exesym: TExeSymbol;
  1941. objsym: TObjSymbol;
  1942. needed: boolean;
  1943. begin
  1944. Comment(v_debug,'Dynamic object: '+objdata.name);
  1945. needed:=false;
  1946. for i:=0 to UnresolvedExeSymbols.Count-1 do
  1947. begin
  1948. exesym:=TExeSymbol(UnresolvedExeSymbols[i]);
  1949. if not (exesym.State in [symstate_undefined,symstate_undefweak]) then
  1950. continue;
  1951. objsym:=TObjSymbol(objdata.ObjSymbolList.Find(exesym.name));
  1952. if assigned(objsym) then
  1953. begin
  1954. exesym.State:=symstate_defined;
  1955. exesym.dynindex:=dynsymlist.Add(exesym)+1;
  1956. { The original binding, value and section of external symbol
  1957. must be preserved, therefore resolving directly to .so symbol
  1958. hurts more than it helps. Copy type and size, and store .so
  1959. symbol in objsym.indsymbol for later use. }
  1960. exesym.ObjSymbol.typ:=objsym.typ;
  1961. if objsym.typ<>AT_FUNCTION then
  1962. exesym.ObjSymbol.size:=objsym.size;
  1963. exesym.ObjSymbol.indsymbol:=objsym;
  1964. objsym.ExeSymbol:=exesym;
  1965. needed:=true;
  1966. end;
  1967. end;
  1968. if (needed or (not asneeded)) and
  1969. (neededlist.Find(objdata.name)=nil) then
  1970. neededlist.Add(objdata.name,objdata);
  1971. end;
  1972. procedure TElfExeOutput.Order_Start;
  1973. begin
  1974. inherited Order_Start;
  1975. dynamiclink:=IsSharedLibrary or (dynsymlist.count>0) or
  1976. (
  1977. (UnresolvedExeSymbols.Count>0) and
  1978. not (cs_link_staticflag in current_settings.globalswitches)
  1979. );
  1980. if dynamiclink then
  1981. InitDynlink;
  1982. if dynamiclink or (IndirectObjSymbols.Count>0) then
  1983. CreatePLT;
  1984. end;
  1985. procedure TElfExeOutput.Order_end;
  1986. procedure set_oso_keep(const s:string;out firstsec:TObjSection);
  1987. var
  1988. exesec:TExeSection;
  1989. objsec:TObjSection;
  1990. i:longint;
  1991. sz: aword;
  1992. begin
  1993. firstsec:=nil;
  1994. sz:=0;
  1995. exesec:=TExeSection(ExeSectionList.Find(s));
  1996. if assigned(exesec) then
  1997. begin
  1998. for i:=0 to exesec.ObjSectionList.Count-1 do
  1999. begin
  2000. objsec:=TObjSection(exesec.ObjSectionList[i]);
  2001. { ignore sections used for symbol definition }
  2002. if oso_data in objsec.SecOptions then
  2003. begin
  2004. if firstsec=nil then
  2005. firstsec:=objsec;
  2006. objsec.SecOptions:=[oso_keep];
  2007. inc(sz,objsec.size);
  2008. end;
  2009. end;
  2010. exesec.size:=sz;
  2011. end;
  2012. end;
  2013. var
  2014. dummy: TObjSection;
  2015. begin
  2016. OrderOrphanSections;
  2017. inherited Order_end;
  2018. set_oso_keep('.init',dummy);
  2019. set_oso_keep('.fini',dummy);
  2020. set_oso_keep('.jcr',dummy);
  2021. set_oso_keep('.ctors',dummy);
  2022. set_oso_keep('.dtors',dummy);
  2023. set_oso_keep('.preinit_array',preinitarraysec);
  2024. if assigned(preinitarraysec) and IsSharedLibrary then
  2025. Comment(v_error,'.preinit_array section is not allowed in shared libraries');
  2026. set_oso_keep('.init_array',initarraysec);
  2027. set_oso_keep('.fini_array',finiarraysec);
  2028. set_oso_keep('.eh_frame',dummy);
  2029. { let .dynamic reference other dynamic sections so they aren't marked
  2030. for removal as unused }
  2031. if dynamiclink then
  2032. WriteDynamicTags;
  2033. end;
  2034. procedure TElfExeOutput.OrderOrphanSections;
  2035. var
  2036. i,j:longint;
  2037. objdata:TObjData;
  2038. objsec:TObjSection;
  2039. exesec:TExeSection;
  2040. opts:TObjSectionOptions;
  2041. s:string;
  2042. newsections:TFPHashObjectList;
  2043. allsections:TFPList;
  2044. inserts:array[0..6] of TExeSection;
  2045. idx,inspos:longint;
  2046. begin
  2047. newsections:=TFPHashObjectList.Create(false);
  2048. allsections:=TFPList.Create;
  2049. { copy existing sections }
  2050. allsections.Capacity:=ExeSectionList.Count;
  2051. for i:=0 to ExeSectionList.Count-1 do
  2052. allsections.add(ExeSectionList[i]);
  2053. inserts[0]:=FindExeSection('.comment');
  2054. inserts[1]:=nil;
  2055. inserts[2]:=FindExeSection('.interp');
  2056. inserts[3]:=FindExeSection('.bss');
  2057. inserts[4]:=FindExeSection('.data');
  2058. inserts[5]:=FindExeSection('.rodata');
  2059. inserts[6]:=FindExeSection('.text');
  2060. for i:=0 to ObjDataList.Count-1 do
  2061. begin
  2062. ObjData:=TObjData(ObjDataList[i]);
  2063. for j:=0 to ObjData.ObjSectionList.Count-1 do
  2064. begin
  2065. objsec:=TObjSection(ObjData.ObjSectionList[j]);
  2066. if objsec.Used then
  2067. continue;
  2068. s:=objsec.name;
  2069. exesec:=TExeSection(newsections.Find(s));
  2070. if assigned(exesec) then
  2071. begin
  2072. exesec.AddObjSection(objsec);
  2073. continue;
  2074. end;
  2075. opts:=objsec.SecOptions*[oso_data,oso_load,oso_write,oso_executable];
  2076. if (objsec.SecOptions*[oso_load,oso_debug]=[]) then
  2077. { non-alloc, after .comment
  2078. GNU ld places .comment between stabs and dwarf debug info }
  2079. inspos:=0
  2080. else if not (oso_load in objsec.SecOptions) then
  2081. inspos:=1 { debugging, skip }
  2082. else if (oso_load in objsec.SecOptions) and
  2083. (TElfObjSection(objsec).shtype=SHT_NOTE) then
  2084. inspos:=2 { after .interp }
  2085. else if (opts=[oso_load,oso_write]) then
  2086. inspos:=3 { after .bss }
  2087. else if (opts=[oso_data,oso_load,oso_write]) then
  2088. inspos:=4 { after .data }
  2089. else if (opts=[oso_data,oso_load]) then
  2090. inspos:=5 { rodata, relocs=??? }
  2091. else if (opts=[oso_data,oso_load,oso_executable]) then
  2092. inspos:=6 { text }
  2093. else
  2094. begin
  2095. Comment(v_debug,'Orphan section '+objsec.fullname+' has attributes that are not handled!');
  2096. continue;
  2097. end;
  2098. if (inserts[inspos]=nil) then
  2099. begin
  2100. Comment(v_debug,'Orphan section '+objsec.fullname+': nowhere to insert, ignored');
  2101. continue;
  2102. end;
  2103. idx:=allsections.IndexOf(inserts[inspos]);
  2104. exesec:=CExeSection.Create(newsections,s);
  2105. allsections.Insert(idx+1,exesec);
  2106. inserts[inspos]:=exesec;
  2107. exesec.AddObjSection(objsec);
  2108. end;
  2109. end;
  2110. { Now replace the ExeSectionList with content of allsections }
  2111. if (newsections.count<>0) then
  2112. ReplaceExeSectionList(allsections);
  2113. newsections.Free;
  2114. allsections.Free;
  2115. end;
  2116. procedure TElfExeOutput.AfterUnusedSectionRemoval;
  2117. var
  2118. i:longint;
  2119. exesym:TExeSymbol;
  2120. objsym:TObjSymbol;
  2121. objsec: TObjSection;
  2122. begin
  2123. { Unused section removal sets Used property of referenced exesymbols.
  2124. Remaining ones can be removed. }
  2125. for i:=0 to dynsymlist.count-1 do
  2126. begin
  2127. exesym:=TExeSymbol(dynsymlist[i]);
  2128. if assigned(exesym.ObjSymbol.ObjSection) then // an exported symbol
  2129. continue;
  2130. if not exesym.used then
  2131. begin
  2132. dynsymlist[i]:=nil;
  2133. exesym.dynindex:=0;
  2134. end;
  2135. end;
  2136. dynsymlist.Pack;
  2137. { reindex }
  2138. for i:=0 to dynsymlist.count-1 do
  2139. TExeSymbol(dynsymlist[i]).dynindex:=i+1;
  2140. { Drop unresolved symbols that aren't referenced, assign dynamic
  2141. indices to remaining ones, but not if linking with -Xt.
  2142. TODO: behavior of .so with -Xt ? }
  2143. if (cs_link_staticflag in current_settings.globalswitches) then
  2144. UnresolvedExeSymbols.Clear
  2145. else
  2146. for i:=0 to UnresolvedExeSymbols.Count-1 do
  2147. begin
  2148. exesym:=TExeSymbol(UnresolvedExeSymbols[i]);
  2149. if exesym.used then
  2150. begin
  2151. if exesym.dynindex<>0 then
  2152. InternalError(2012062301);
  2153. { Weak-referenced symbols are changed into dynamic ones
  2154. only if referenced through GOT or PLT (this is BFD-compatible) }
  2155. if exesym.state<>symstate_undefweak then
  2156. exesym.dynindex:=dynsymlist.add(exesym)+1;
  2157. end
  2158. else
  2159. UnresolvedExeSymbols[i]:=nil;
  2160. end;
  2161. UnresolvedExeSymbols.Pack;
  2162. { Scan relocations to determine size of GOT, dynamic reloc section, etc. }
  2163. PrepareGOT;
  2164. { Write required PLT entries }
  2165. for i:=0 to dynsymlist.Count-1 do
  2166. begin
  2167. exesym:=TExeSymbol(dynsymlist[i]);
  2168. if assigned(exesym.ObjSymbol.objsection) then // an exported symbol
  2169. continue;
  2170. if ((exesym.ObjSymbol.refs and symref_plt)<>0) or
  2171. ((exesym.ObjSymbol.typ in [AT_FUNCTION,AT_GNU_IFUNC]) and (not IsSharedLibrary)) then
  2172. begin
  2173. make_dynamic_if_undefweak(exesym);
  2174. { This symbol has a valid address to which relocations are resolved,
  2175. but it remains (weak)external when written to dynamic symtable. }
  2176. objsym:=internalobjdata.CreateSymbol(exesym.name);
  2177. objsym.typ:=AT_FUNCTION;
  2178. objsym.bind:=exesym.ObjSymbol.bind; { AB_EXTERNAL or AB_WEAK_EXTERNAL }
  2179. objsym.indsymbol:=exesym.ObjSymbol.indsymbol;
  2180. objsym.offset:=pltobjsec.size;
  2181. objsym.objsection:=pltobjsec;
  2182. objsym.exesymbol:=exesym;
  2183. exesym.ObjSymbol:=objsym;
  2184. WritePLTEntry(exesym);
  2185. end
  2186. else if ((exesym.ObjSymbol.refs and symref_from_text)<>0) and
  2187. (exesym.ObjSymbol.typ<>AT_FUNCTION) and (not IsSharedLibrary) and
  2188. (exesym.state<>symstate_undefweak) then
  2189. begin
  2190. if exesym.ObjSymbol.size=0 then
  2191. Comment(v_error,'Dynamic variable '+exesym.name+' has zero size');
  2192. internalobjdata.setSection(dynbssobjsec);
  2193. internalobjdata.allocalign(size_2_align(exesym.ObjSymbol.size));
  2194. objsym:=internalobjdata.SymbolDefine(exesym.name,AB_GLOBAL,AT_DATA);
  2195. objsym.size:=exesym.ObjSymbol.size;
  2196. objsym.indsymbol:=exesym.ObjSymbol.indsymbol;
  2197. exesym.ObjSymbol:=objsym;
  2198. objsym.exesymbol:=exesym;
  2199. dynbssobjsec.alloc(objsym.size);
  2200. { allocate space for R_xx_COPY relocation for this symbol;
  2201. we'll create it later, to be consistent with "-z combreloc" semantics }
  2202. dyncopysyms.add(objsym);
  2203. dynrelocsec.alloc(dynrelocsec.shentsize);
  2204. inc(dynrelsize,dynrelocsec.shentsize);
  2205. end;
  2206. end;
  2207. { Handle indirect symbols }
  2208. for i:=0 to IndirectObjSymbols.Count-1 do
  2209. begin
  2210. objsym:=TObjSymbol(IndirectObjSymbols[i]);
  2211. objsec:=objsym.ExeSymbol.ObjSymbol.objsection;
  2212. objsym.bind:=AB_EXTERNAL; { cheat FixupSymbols }
  2213. if (oso_plt in objsec.SecOptions) then
  2214. continue;
  2215. WriteIndirectPLTEntry(objsym.ExeSymbol);
  2216. end;
  2217. FixupSymbols;
  2218. if dynamiclink then
  2219. begin
  2220. WriteVersionSections;
  2221. WriteDynamicSymbolsHash;
  2222. end;
  2223. { Create .shstrtab section, which is needed in both exe and .dbg files }
  2224. shstrtabsect:=TElfObjSection.Create_ext(internalObjData,'.shstrtab',SHT_STRTAB,0,1,0);
  2225. shstrtabsect.SecOptions:=[oso_debug_copy];
  2226. AttachSection(shstrtabsect);
  2227. { Create the static symtable (.symtab and .strtab) }
  2228. if (cs_link_separate_dbg_file in current_settings.globalswitches) or
  2229. not(cs_link_strip in current_settings.globalswitches) then
  2230. begin
  2231. symtab:=TElfSymtab.Create(internalObjData,esk_exe);
  2232. symtab.SecOptions:=[oso_debug];
  2233. symtab.fstrsec.SecOptions:=[oso_debug];
  2234. AttachSection(symtab);
  2235. AttachSection(symtab.fstrsec);
  2236. end;
  2237. { Re-enable sections which end up to contain some data
  2238. (.got, .rel[a].dyn, .rel[a].plt (includes .rel[a].iplt) and .hash }
  2239. if gotobjsec.size<>0 then
  2240. gotobjsec.ExeSection.Disabled:=false;
  2241. if assigned(dynrelocsec) and
  2242. ((dynrelocsec.size<>0) or (dyncopysyms.count<>0)) then
  2243. dynrelocsec.ExeSection.Disabled:=false;
  2244. if assigned(pltrelocsec) and (pltrelocsec.size>0) then
  2245. pltrelocsec.ExeSection.Disabled:=false;
  2246. if assigned(ipltrelocsec) and (ipltrelocsec.size>0) then
  2247. ipltrelocsec.ExeSection.Disabled:=false;
  2248. if assigned(hashobjsec) then
  2249. hashobjsec.ExeSection.Disabled:=false;
  2250. if assigned(symversec) and (symversec.size<>0) then
  2251. symversec.ExeSection.Disabled:=false;
  2252. if assigned(verneedsec) and (verneedsec.size<>0) then
  2253. verneedsec.ExeSection.Disabled:=false;
  2254. if assigned(verdefsec) and (verdefsec.size<>0) then
  2255. verdefsec.ExeSection.Disabled:=false;
  2256. RemoveDisabledSections;
  2257. MapSectionsToSegments;
  2258. if dynamiclink then
  2259. FinishDynamicTags;
  2260. end;
  2261. procedure TElfExeOutput.WriteShStrtab;
  2262. var
  2263. i: longint;
  2264. exesec: TElfExeSection;
  2265. begin
  2266. { Remove any existing .shstrtab contents }
  2267. if (shstrtabsect.size>0) then
  2268. begin
  2269. shstrtabsect.ReleaseData;
  2270. shstrtabsect.Size:=0;
  2271. shstrtabsect.SecOptions:=[oso_data];
  2272. end;
  2273. shstrtabsect.writezeros(1);
  2274. for i:=0 to ExeSectionList.Count-1 do
  2275. begin
  2276. exesec:=TElfExeSection(ExeSectionList[i]);
  2277. exesec.shstridx:=shstrtabsect.writestr(exesec.Name);
  2278. exesec.secshidx:=i+1;
  2279. end;
  2280. end;
  2281. procedure TElfExeOutput.FixupSectionLinks;
  2282. var
  2283. dynstrndx,dynsymndx: longword;
  2284. begin
  2285. if dynamiclink then
  2286. begin
  2287. dynstrndx:=TElfExeSection(dynsymtable.fstrsec.ExeSection).secshidx;
  2288. dynsymndx:=TElfExeSection(dynsymtable.ExeSection).secshidx;
  2289. TElfExeSection(hashobjsec.ExeSection).shlink:=dynsymndx;
  2290. TElfExeSection(dynamicsec.ExeSection).shlink:=dynstrndx;
  2291. TElfExeSection(dynsymtable.ExeSection).shlink:=dynstrndx;
  2292. if assigned(pltrelocsec) then
  2293. begin
  2294. TElfExeSection(pltrelocsec.ExeSection).shlink:=dynsymndx;
  2295. TElfExeSection(pltrelocsec.ExeSection).shinfo:=TElfExeSection(pltobjsec.ExeSection).secshidx;
  2296. end;
  2297. if assigned(dynrelocsec) and assigned(dynrelocsec.ExeSection) then
  2298. TElfExeSection(dynrelocsec.ExeSection).shlink:=dynsymndx;
  2299. if symversec.size>0 then
  2300. TElfExeSection(symversec.ExeSection).shlink:=dynsymndx;
  2301. if verdefsec.size>0 then
  2302. TElfExeSection(verdefsec.ExeSection).shlink:=dynstrndx;
  2303. if verneedsec.size>0 then
  2304. TElfExeSection(verneedsec.ExeSection).shlink:=dynstrndx;
  2305. end
  2306. else if assigned(ipltrelocsec) then
  2307. TElfExeSection(ipltrelocsec.ExeSection).shinfo:=TElfExeSection(pltobjsec.ExeSection).secshidx;
  2308. end;
  2309. procedure TElfExeOutput.Do_Mempos;
  2310. var
  2311. i,j: longint;
  2312. seg: TElfSegment;
  2313. exesec: TElfExeSection;
  2314. objsec: TObjSection;
  2315. tempmempos: qword;
  2316. begin
  2317. if IsSharedLibrary then
  2318. CurrMemPos:=0
  2319. else
  2320. CurrMemPos:=ElfTarget.exe_image_base;
  2321. textseg.MemPos:=CurrMemPos;
  2322. if assigned(phdrseg) then
  2323. begin
  2324. phdrseg.Mempos:=CurrMemPos+sizeof(TElfHeader);
  2325. phdrseg.Memsize:=sizeof(TElfproghdr)*segmentlist.count;
  2326. end;
  2327. CurrMemPos:=CurrMemPos+sizeof(TElfHeader)+segmentlist.count*sizeof(TElfproghdr);
  2328. MemPos_Segment(textseg);
  2329. CurrMemPos:=Align(CurrMemPos,SectionDataAlign); {! Data,not MemAlign}
  2330. CurrMemPos:=CurrMemPos+ElfTarget.max_page_size;
  2331. dataseg.MemPos:=CurrMemPos;
  2332. MemPos_Segment(dataseg);
  2333. { Mempos of unmapped sections is forced to zero, but we have to set positions
  2334. of its objsections and update sizes }
  2335. for i:=0 to ExeSectionList.Count-1 do
  2336. begin
  2337. exesec:=TElfExeSection(ExeSectionList[i]);
  2338. if not (oso_load in exesec.SecOptions) then
  2339. begin
  2340. tempmempos:=0;
  2341. exesec.MemPos:=tempmempos;
  2342. for j:=0 to exesec.ObjSectionList.Count-1 do
  2343. begin
  2344. objsec:=TObjSection(exesec.ObjSectionList[j]);
  2345. tempmempos:=objsec.setmempos(tempmempos);
  2346. end;
  2347. exesec.Size:=tempmempos;
  2348. end;
  2349. end;
  2350. { Update MemPos and MemSize of non-load segments,
  2351. in particular, TLS sizes are needed to resolve relocations }
  2352. for i:=0 to segmentlist.count-1 do
  2353. begin
  2354. seg:=TElfSegment(segmentlist[i]);
  2355. if (seg.ptype=PT_LOAD) or (seg.FSectionList.Count=0) then
  2356. continue;
  2357. seg.MemPos:=TExeSection(seg.FSectionList.First).MemPos;
  2358. for j:=0 to seg.FSectionList.Count-1 do
  2359. begin
  2360. exesec:=TElfExeSection(seg.FSectionList[j]);
  2361. seg.MemSize:=exesec.MemPos+exesec.Size-seg.MemPos;
  2362. end;
  2363. end;
  2364. end;
  2365. procedure TElfExeOutput.MemPos_Start;
  2366. var
  2367. i: longint;
  2368. begin
  2369. { Assign section indices and fill .shstrtab
  2370. List of sections cannot be modified after this point. }
  2371. WriteShStrtab;
  2372. { fixup sh_link/sh_info members of various dynamic sections }
  2373. FixupSectionLinks;
  2374. { The actual layout }
  2375. Do_Mempos;
  2376. if (not gotwritten) then
  2377. begin
  2378. { Reset size of .got and .rel[a].dyn, they will be refilled while fixing up relocations.
  2379. For .got, consider already written reserved entries. }
  2380. if assigned(gotobjsec) then
  2381. gotobjsec.size:=gotobjsec.data.size;
  2382. if assigned(dynrelocsec) then
  2383. begin
  2384. dynrelocsec.size:=0;
  2385. { write actual .dynsym content (needs valid symbol addresses) }
  2386. if assigned(tlsseg) then
  2387. dynsymtable.tlsbase:=tlsseg.MemPos;
  2388. dynsymtable.size:=sizeof(TElfsymbol);
  2389. for i:=0 to dynsymlist.count-1 do
  2390. dynsymtable.writeSymbol(TExeSymbol(dynsymlist[i]).objsymbol,dynsymnames[i]);
  2391. end;
  2392. end;
  2393. end;
  2394. procedure TElfExeOutput.MemPos_Segment(seg:TElfSegment);
  2395. var
  2396. i: longint;
  2397. exesec: TElfExeSection;
  2398. begin
  2399. for i:=0 to seg.FSectionList.Count-1 do
  2400. begin
  2401. exesec:=TElfExeSection(seg.FSectionList[i]);
  2402. inherited MemPos_ExeSection(exesec);
  2403. { .tbss should not contribute to address space }
  2404. if (exesec.shtype=SHT_NOBITS) and ((exesec.shflags and SHF_TLS)<>0) then
  2405. CurrMemPos:=exesec.MemPos;
  2406. end;
  2407. { calculate size of the segment }
  2408. seg.MemSize:=CurrMemPos-seg.MemPos;
  2409. end;
  2410. procedure TElfExeOutput.MemPos_ExeSection(const aname:string);
  2411. begin
  2412. // Ignore. All layout is done in mempos_start
  2413. end;
  2414. procedure TElfExeOutput.DataPos_Start;
  2415. var
  2416. i,j: longint;
  2417. exesec: TExeSection;
  2418. seg: TElfSegment;
  2419. objreloc: TObjRelocation;
  2420. objsym: TObjSymbol;
  2421. begin
  2422. gotwritten:=true;
  2423. { If target does not support sorted relocations, it is expected to write the
  2424. entire .rel[a].dyn section during FixupRelocations, and leave dynreloclist empty.
  2425. Otherwise, only RELATIVE ones should be written, space for non-relative relocations
  2426. should remain. }
  2427. if assigned(dynrelocsec) then
  2428. begin
  2429. { Append R_xx_COPY relocations }
  2430. dynreloclist.capacity:=dynreloclist.count+dyncopysyms.count;
  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: TWordDynArray;
  2624. begin
  2625. SetLength(symversions,(dynsymlist.count+1));
  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[0],(dynsymlist.count+1)*sizeof(word));
  2703. end;
  2704. symversions:=nil;
  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.